Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: set line for MySQL CREATE TABLE statement (#2361)
rebelice531b6a579e15
diff --git a/plugin/parser/set_line_for_create_table_test.go b/plugin/parser/set_line_for_create_table_test.goindex 3fd2c44858..1cb4b33d97 100644--- a/plugin/parser/set_line_for_create_table_test.go+++ b/plugin/parser/set_line_for_create_table_test.go@@ -5,10 +5,14 @@ import ("github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/ast"+ tidbparser "github.com/pingcap/tidb/parser"+ tidbast "github.com/pingcap/tidb/parser/ast""github.com/stretchr/testify/require"// Register postgres parser driver._ "github.com/bytebase/bytebase/plugin/parser/engine/pg"+ // Register pingcap parser driver.+ _ "github.com/pingcap/tidb/types/parser_driver")type setLineTestData struct {@@ -94,3 +98,85 @@ func TestPGCreateTableSetLine(t *testing.T) {}}}++func TestMySQLCreateTableSetLine(t *testing.T) {+ tests := []setLineTestData{+ {+ statement: `-- this is the first line.+ CREATE TABLE t(+ a int, B int,+ C int,+ D int NOT NULL,+ INDEX (a),+ KEY (a),+ CONSTRAINT unique_a UNIQUE (a),+ UNIQUE (b, c),+ PRIMARY KEY (d),CHECK (a > 0),++ FOREIGN KEY (a, b, c) REFERENCES t1(a, b, c)+ )+ `,+ columnLineList: []int{3, 3, 4, 5},+ constraintLineList: []int{6, 7, 8, 9, 10, 10, 12},+ },+ {+ // test for Windows.+ statement: "\r\n" ++ "CREATE TABLE t(" + "\r\n" ++ "a int, B int," + "\r\n" ++ "C int," + "\r\n" ++ `D int NOT NULL,` + "\r\n" ++ "CONSTRAINT unique_a UNIQUE (a)," + "\r\n" ++ "UNIQUE (b, c)," + "\r\n" ++ "PRIMARY KEY (d),CHECK (a > 0)," + "\r\n" ++ "\r\n" ++ "FOREIGN KEY (a, b, c) REFERENCES t1(a, b, c)" + "\r\n" ++ ")",+ columnLineList: []int{3, 3, 4, 5},+ constraintLineList: []int{6, 7, 8, 8, 10},+ },+ {+ statement: `-- this is the first line.+ CREATE TABLE t(+ a int PRIMARY KEY,+ b int CHECK(b>1), c int UNIQUE+ )+ `,+ columnLineList: []int{3, 4, 4},+ constraintLineList: []int{},+ },+ {+ statement: `-- complex example+ CREATE TABLE t(+ a int PRIMARY KEY,+ name varchar(255) DEFAULT 'UNIQUE on (a, b, c)(',+ UNIQUE(a, name),+ UNIQUE(name)+ )+ `,+ columnLineList: []int{3, 4},+ constraintLineList: []int{5, 6},+ },+ }++ for _, test := range tests {+ p := tidbparser.New()+ p.EnableWindowFunc(true)+ nodeList, _, err := p.Parse(test.statement, "", "")+ require.NoError(t, err)+ require.Len(t, nodeList, 1)+ node, ok := nodeList[0].(*tidbast.CreateTableStmt)+ require.True(t, ok)+ require.Equal(t, len(test.columnLineList), len(node.Cols))+ require.Equal(t, len(test.constraintLineList), len(node.Constraints))+ node.SetOriginTextPosition(1)+ err = parser.SetLineForMySQLCreateTableStmt(node)+ require.NoError(t, err)+ for i, col := range node.Cols {+ require.Equal(t, col.OriginTextPosition(), test.columnLineList[i], i)+ }+ for i, cons := range node.Constraints {+ require.Equal(t, cons.OriginTextPosition(), test.constraintLineList[i], i)+ }+ }+}diff --git a/plugin/parser/tokenizer.go b/plugin/parser/tokenizer.goindex d3b0196a27..6c2bc69a23 100644--- a/plugin/parser/tokenizer.go+++ b/plugin/parser/tokenizer.go@@ -8,6 +8,7 @@ import ("unicode""github.com/bytebase/bytebase/plugin/parser/ast"+ tidbast "github.com/pingcap/tidb/parser/ast""github.com/pkg/errors")@@ -80,6 +81,115 @@ func newStreamTokenizer(src io.Reader) *tokenizer {return t}+func (t *tokenizer) setLineForMySQLCreateTableStmt(node *tidbast.CreateTableStmt) error {+ // We assume that the parser will parse the columns and table constraints according to the order of the raw SQL statements+ // and the identifiers don't equal any keywords in CREATE TABLE statements.+ // If it breaks our assumption, we set the line for columns and table constraints to the first line of the CREATE TABLE statement.+ for _, col := range node.Cols {+ col.SetOriginTextPosition(node.OriginTextPosition())+ }+ for _, cons := range node.Constraints {+ cons.SetOriginTextPosition(node.OriginTextPosition())+ }++ columnPos := 0+ constraintPos := 0+ // find the '(' for CREATE TABLE ... ( ... )+ if err := t.scanTo([]rune{'('}); err != nil {+ return err+ }++ // parentheses is the flag for matching parentheses.+ parentheses := 1+ t.skipBlank()+ startPos := t.pos()+ t.startLine = t.line+ for {+ switch t.char(0) {+ case '\n':+ t.line+++ t.skip(1)+ case '\'', '"':+ if err := t.scanString(t.char(0)); err != nil {+ return err+ }+ case '(':+ parentheses+++ t.skip(1)+ case ')':+ parentheses--+ if parentheses == 0 {+ // This means we find the corresponding ')' for the first '(' in CREATE TABLE statements.+ // We need to check the definition and return.+ def := strings.ToLower(t.getString(startPos, t.pos()-startPos))+ if columnPos < len(node.Cols) &&+ strings.Contains(def, node.Cols[columnPos].Name.Name.L) {+ node.Cols[columnPos].SetOriginTextPosition(t.startLine + node.OriginTextPosition() - 1)+ } else if constraintPos < len(node.Constraints) &&+ matchMySQLTableConstraint(def, node.Constraints[constraintPos]) {+ node.Constraints[constraintPos].SetOriginTextPosition(t.startLine + node.OriginTextPosition() - 1)+ }+ return nil+ }+ t.skip(1)+ case ',':+ // e.g. CREATE TABLE t(+ // a int,+ // b int,+ // UNIQUE(a, b),+ // UNIQUE(b)+ // )+ // We don't need to consider the ',' in UNIQUE(a, b)+ if parentheses > 1 {+ t.skip(1)+ continue+ }+ def := strings.ToLower(t.getString(startPos, t.pos()-startPos))+ if columnPos < len(node.Cols) &&+ strings.Contains(def, node.Cols[columnPos].Name.Name.L) {+ node.Cols[columnPos].SetOriginTextPosition(t.startLine + node.OriginTextPosition() - 1)+ columnPos+++ } else if constraintPos < len(node.Constraints) &&+ matchMySQLTableConstraint(def, node.Constraints[constraintPos]) {+ node.Constraints[constraintPos].SetOriginTextPosition(t.startLine + node.OriginTextPosition() - 1)+ constraintPos+++ }+ t.skip(1)+ t.skipBlank()+ startPos = t.pos()+ t.startLine = t.line+ case eofRune:+ return nil+ default:+ t.skip(1)+ }+ }+}++func matchMySQLTableConstraint(text string, cons *tidbast.Constraint) bool {+ text = strings.ToLower(text)+ if cons.Name != "" {+ return strings.Contains(text, strings.ToLower(cons.Name))+ }+ switch cons.Tp {+ case tidbast.ConstraintCheck:+ return strings.Contains(text, "check")+ case tidbast.ConstraintUniq, tidbast.ConstraintUniqKey, tidbast.ConstraintUniqIndex:+ return strings.Contains(text, "unique")+ case tidbast.ConstraintPrimaryKey:+ return strings.Contains(text, "primary key")+ case tidbast.ConstraintForeignKey:+ return strings.Contains(text, "foreign key")+ case tidbast.ConstraintIndex:+ notUnique := !strings.Contains(text, "unique")+ notPrimary := !strings.Contains(text, "primary key")+ notForeign := !strings.Contains(text, "foreign key")+ isIndex := strings.Contains(text, "index") || strings.Contains(text, "key")+ return notUnique && notPrimary && notForeign && isIndex+ }+ return false+}+// setLineForPGCreateTableStmt sets the line for columns and table constraints in CREATE TABLE statements.func (t *tokenizer) setLineForPGCreateTableStmt(node *ast.CreateTableStmt) error {// We assume that the parser will parse the columns and table constraints according to the order of the raw SQL statementsdiff --git a/plugin/parser/utils.go b/plugin/parser/utils.goindex 90366ad423..6a5066cf74 100644--- a/plugin/parser/utils.go+++ b/plugin/parser/utils.go@@ -4,6 +4,7 @@ import ("io""github.com/bytebase/bytebase/plugin/parser/ast"+ tidbast "github.com/pingcap/tidb/parser/ast""github.com/pkg/errors")@@ -51,3 +52,10 @@ func SetLineForCreateTableStmt(engineType EngineType, node *ast.CreateTableStmt)return errors.Errorf("engine type is not supported: %s", engineType)}}++// SetLineForMySQLCreateTableStmt sets the line for columns and table constraints in MySQL CREATE TABLE statments.+// This is a temporary function. Because we do not convert tidb AST to our AST. So we have to implement this.+// TODO(rebelice): remove it.+func SetLineForMySQLCreateTableStmt(node *tidbast.CreateTableStmt) error {+ return newTokenizer(node.Text()).setLineForMySQLCreateTableStmt(node)+}