parser
parser copied to clipboard
Would like to replace all table names. Any examples?
e.g. select * from t123_terms inner join t123_abc ... inner join t123_xyz;
how do i replace t123... with abc.t123_...?
please help. thx
@gitmko0 Sorry for the late reply. You can define your own visitor that implemented(ast.Visitor). In the function Enter() or Leave(), try to do a type conversion:
type myVisitor struct{}
func (v *myVisitor) Enter(in ast.Node) (ast.Node, bool) {
if name, ok := in.(*ast.TableName); ok {
name.Schema = model.NewCIStr("abc")
}
return in, false
}
func (v *myVisitor) Leave(in ast.Node) (ast.Node, bool) {
return in, true
}
Here is a quick and dirty example:
func main() {
p := New()
stmtNodes, _, err := p.Parse("select * from t", "", "")
root := stmtNodes[0]
var sb strings.Builder
flags := format.DefaultRestoreFlags
err = root.Restore(format.NewRestoreCtx(flags, &sb))
fmt.Println(err)
fmt.Println(sb.String())
vis := &myVisitor{}
root.Accept(vis)
sb.Reset()
err = root.Restore(format.NewRestoreCtx(flags, &sb))
fmt.Println(err)
fmt.Println(sb.String())
}
<nil>
SELECT * FROM `t`
<nil>
SELECT * FROM `abc`.`t`
Hope it works :)