GolangsqlsqlsqlsqlGolangsql
sql
xwb1989/sqlparserDDLtidbparsertidbparsersqlDDL
DDL
ALTER TABLE Persons DROP COLUMN DateOfBirth, DROP COLUMN ID;
xwb1989/sqlparsertidbparser
package sqlcheck

import (
    "fmt"
    "github.com/blastrain/vitess-sqlparser/tidbparser/ast"
    "github.com/blastrain/vitess-sqlparser/tidbparser/parser"
    "testing"
)

// 定义一个可以访问SQL解析树节点的Visitor
type DropColumnVisitor struct {
    TableName string
    Columns   []string
}

func (v *DropColumnVisitor) IsValid() bool {
    return v.TableName != "" && len(v.Columns) > 0
}

func (v *DropColumnVisitor) Enter(in ast.Node) (out ast.Node, skipChildren bool) {
    fmt.Printf("%T\n", in)
    // 识别了ALTER就直接访问子节点,看是不是DropColumn
    switch in.(type) {
    case *ast.AlterTableStmt:
        if v.TableName != "" {
            break
        }
        node := in.(*ast.AlterTableStmt)
        v.TableName = node.Table.Name.String()
        for _, spec := range node.Specs {
            // 看解析的Tp枚举是不是ast.AlterTableDropColumn对应的枚举
            if spec.Tp == ast.AlterTableDropColumn {
                v.Columns = append(v.Columns, spec.OldColumnName.OrigColName())
            }
        }
    default:
        break
    }
    // 不需要访问子节点
    return in, true
}

func (v *DropColumnVisitor) Leave(in ast.Node) (out ast.Node, ok bool) {
    return in, true
}

func TestParseDropColumn(t *testing.T) {
    sql := "ALTER TABLE Persons DROP COLUMN DateOfBirth, DROP COLUMN ID;"
    sqlParser := parser.New()
    stmtNodes, err := sqlParser.Parse(sql, "", "")
    if err != nil {
        t.Fatalf("Parse error: %v", err)
    }
    t.Logf("stmt: %s", JsonDump(stmtNodes))

    v := &DropColumnVisitor{
        TableName: "",
        Columns:   []string{},
    }
    // 每个根节点开始起访问
    for _, stmtNode := range stmtNodes {
        stmtNode.Accept(v)
    }
    t.Logf("visitor: %s", JsonDump(v))

    if !v.IsValid() {
        t.Fatalf("invalid drop column ddl")
    }
    t.Logf("drop columns %v at table %s", v.Columns, v.TableName)
}
sqlEnterLeaveVisitorinterfacesqlinterface*ast.AlterTableStmtALTERSpecsDROP COLUMN

我们打印整个解析树,就能够清晰的看到结果:

=== RUN   TestParseDropColumn
    vitess_sqlparser_test.go:50: stmt: [
          {
            "Table": {
              "Schema": {
                "O": "",
                "L": ""
              },
              "Name": {
                "O": "Persons",
                "L": "persons"
              },
              "DBInfo": null,
              "TableInfo": null,
              "IndexHints": null
            },
            "Specs": [
              {
                "Tp": 4,
                "Name": "",
                "Constraint": null,
                "Options": null,
                "NewTable": null,
                "NewColumns": null,
                "OldColumnName": {
                  "Schema": {
                    "O": "",
                    "L": ""
                  },
                  "Table": {
                    "O": "",
                    "L": ""
                  },
                  "Name": {
                    "O": "DateOfBirth",
                    "L": "dateofbirth"
                  }
                },
                "Position": null,
                "LockType": 0
              },
              {
                "Tp": 4,
                "Name": "",
                "Constraint": null,
                "Options": null,
                "NewTable": null,
                "NewColumns": null,
                "OldColumnName": {
                  "Schema": {
                    "O": "",
                    "L": ""
                  },
                  "Table": {
                    "O": "",
                    "L": ""
                  },
                  "Name": {
                    "O": "ID",
                    "L": "id"
                  }
                },
                "Position": null,
                "LockType": 0
              }
            ]
          }
        ]

    vitess_sqlparser_test.go:59: visitor: {
          "TableName": "Persons",
          "Columns": [
            "DateOfBirth",
            "ID"
          ]
        }
    vitess_sqlparser_test.go:64: drop columns [DateOfBirth ID] at table Persons
--- PASS: TestParseDropColumn (0.00s)
PASS
ALTERPersonsDROPDateOfBirthID
sqlsql