github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/schema/visitor.go (about)

     1  // Copyright 2022 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package schema
    15  
    16  import (
    17  	"github.com/pingcap/tidb/pkg/parser/ast"
    18  	"github.com/pingcap/tidb/pkg/parser/model"
    19  )
    20  
    21  type currentDBSetter struct {
    22  	currentDB string
    23  }
    24  
    25  func (c currentDBSetter) Enter(n ast.Node) (node ast.Node, skipChildren bool) {
    26  	// mimic preprocessor in TiDB
    27  	switch v := n.(type) {
    28  	case *ast.CreateTableStmt:
    29  		for _, val := range v.Constraints {
    30  			if val.Refer != nil && val.Refer.Table.Schema.String() == "" {
    31  				val.Refer.Table.Schema = v.Table.Schema
    32  			}
    33  		}
    34  	case *ast.AlterTableStmt:
    35  		for _, spec := range v.Specs {
    36  			if spec.Tp == ast.AlterTableAddConstraint && spec.Constraint.Refer != nil {
    37  				table := spec.Constraint.Refer.Table
    38  				if table.Schema.L == "" && v.Table.Schema.L != "" {
    39  					table.Schema = model.NewCIStr(v.Table.Schema.L)
    40  				}
    41  			}
    42  		}
    43  	}
    44  	return n, false
    45  }
    46  
    47  func (c currentDBSetter) Leave(n ast.Node) (node ast.Node, ok bool) {
    48  	v, ok := n.(*ast.TableName)
    49  	if !ok {
    50  		return n, true
    51  	}
    52  	if v.Schema.O == "" {
    53  		v.Schema = model.NewCIStr(c.currentDB)
    54  	}
    55  	return n, true
    56  }