pingcap / parser

A MySQL Compatible SQL Parser
Apache License 2.0
1.41k stars 489 forks source link

is there any easy to change the select field? #1285

Closed cjphaha closed 3 years ago

cjphaha commented 3 years ago

for example: The original sql statement is:

SELECT  name, user, password  FROM info;

I want to convert it to:

SELECT  name,user,password_encrypted  FROM info;

how to change the password field to password_encrypted? i need help, thx!

cjphaha commented 3 years ago

I tried to use setTest but failed

type FingerprintVisitor struct{}

func (f *FingerprintVisitor) Enter(in ast.Node) (node ast.Node, skipChildren bool) {
    if v, ok := in.(*ast.SelectField);ok {
        v.SetText("replaced_num")
    }
    return in, false
}

func (f *FingerprintVisitor) Leave(in ast.Node) (node ast.Node, ok bool) {
    return in, true
}
tangenta commented 3 years ago
func (f *FingerprintVisitor) Enter(in ast.Node) (node ast.Node, skipChildren bool) {
    if sf, ok := in.(*ast.SelectField); ok {
        if cn, ok := sf.Expr.(*ast.ColumnNameExpr); ok {
            if cn.Name.Name.L == "password" {
                cn.Name.Name = model.NewCIStr("password_encrypted")
            }
        }
    }
    return in, false
}

@cjphaha You can check the rules in the parser.y to peek at the possible structs.

cjphaha commented 3 years ago
func (f *FingerprintVisitor) Enter(in ast.Node) (node ast.Node, skipChildren bool) {
  if sf, ok := in.(*ast.SelectField); ok {
      if cn, ok := sf.Expr.(*ast.ColumnNameExpr); ok {
          if cn.Name.Name.L == "password" {
              cn.Name.Name = model.NewCIStr("password_encrypted")
          }
      }
  }
  return in, false
}

@cjphaha You can check the rules in the parser.y to peek at the possible structs.

thx!

cjphaha commented 3 years ago
func (f *FingerprintVisitor) Enter(in ast.Node) (node ast.Node, skipChildren bool) {
  if sf, ok := in.(*ast.SelectField); ok {
      if cn, ok := sf.Expr.(*ast.ColumnNameExpr); ok {
          if cn.Name.Name.L == "password" {
              cn.Name.Name = model.NewCIStr("password_encrypted")
          }
      }
  }
  return in, false
}

@cjphaha You can check the rules in the parser.y to peek at the possible structs.

Sorry, I have another question to consult you, is there easy way totransfer this insert sql

INSERT INTO `account` (`name`,`password_plain`) VALUES (?,?)

to

INSERT INTO `account` (`name`,`password`, `password_plain`, `password_enctryped`) VALUES (?,?)
tangenta commented 3 years ago

Please take a look at InsertStmt.Columns. You can use a similar visitor to change it.

cjphaha commented 3 years ago

Please take a look at InsertStmt.Columns. You can use a similar visitor to change it.

thank you very very much!