Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: set line for columns and table constraints in CREATE TABLE statements (#2305)

rebeliceb17c09698e0f
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index 4a5de58cdc..823249d3f1 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -9,9 +9,11 @@ import (
)
type testData struct {
- stmt string
- want []ast.Node
- statementList []parser.SingleSQL
+ stmt string
+ want []ast.Node
+ statementList []parser.SingleSQL
+ columnLine [][]int
+ constraintLine [][]int
}
func runTests(t *testing.T, tests []testData) {
@@ -23,6 +25,15 @@ func runTests(t *testing.T, tests []testData) {
for i := range test.want {
test.want[i].SetText(test.statementList[i].Text)
test.want[i].SetLine(test.statementList[i].Line)
+
+ if createTable, ok := test.want[i].(*ast.CreateTableStmt); ok {
+ for j, col := range createTable.ColumnList {
+ col.SetLine(test.columnLine[i][j])
+ }
+ for j, cons := range createTable.ConstraintList {
+ cons.SetLine(test.constraintLine[i][j])
+ }
+ }
}
require.Equal(t, test.want, res, test.stmt)
}
@@ -68,6 +79,9 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
Line: 1,
},
},
+ columnLine: [][]int{
+ {1, 1},
+ },
},
{
stmt: "CREATE TABLE IF NOT EXISTS techBook (\"A\" int, b int)",
@@ -90,6 +104,9 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
Line: 1,
},
},
+ columnLine: [][]int{
+ {1, 1},
+ },
},
{
stmt: "CREATE TABLE tech_book(a INT CONSTRAINT t_pk_a PRIMARY KEY)",
@@ -119,6 +136,9 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
Line: 1,
},
},
+ columnLine: [][]int{
+ {1},
+ },
},
{
stmt: "CREATE TABLE tech_book(a INT, b int CONSTRAINT uk_b UNIQUE, CONSTRAINT t_pk_a PRIMARY KEY(a))",
@@ -158,6 +178,12 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
Line: 1,
},
},
+ columnLine: [][]int{
+ {1, 1},
+ },
+ constraintLine: [][]int{
+ {1},
+ },
},
{
stmt: "CREATE TABLE tech_book(a INT CONSTRAINT fk_a REFERENCES people(id), CONSTRAINT fk_a_people_b FOREIGN KEY (a) REFERENCES people(b))",
@@ -208,6 +234,12 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
Line: 1,
},
},
+ columnLine: [][]int{
+ {1},
+ },
+ constraintLine: [][]int{
+ {1},
+ },
},
}
diff --git a/plugin/parser/engine/pg/parser.go b/plugin/parser/engine/pg/parser.go
index c3229b55db..78cacbbe8d 100644
--- a/plugin/parser/engine/pg/parser.go
+++ b/plugin/parser/engine/pg/parser.go
@@ -46,6 +46,11 @@ func (*PostgreSQLParser) Parse(_ parser.Context, statement string) ([]ast.Node,
if err != nil {
return nil, err
}
+ if createTable, ok := node.(*ast.CreateTableStmt); ok {
+ if err := parser.SetLineForCreateTableStmt(parser.Postgres, createTable); err != nil {
+ return nil, err
+ }
+ }
nodeList = append(nodeList, node)
}
return nodeList, nil
diff --git a/plugin/parser/set_line_for_create_table_test.go b/plugin/parser/set_line_for_create_table_test.go
new file mode 100644
index 0000000000..59531211b1
--- /dev/null
+++ b/plugin/parser/set_line_for_create_table_test.go
@@ -0,0 +1,81 @@
+package parser_test
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/parser"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+ "github.com/stretchr/testify/require"
+
+ // Register postgres parser driver.
+ _ "github.com/bytebase/bytebase/plugin/parser/engine/pg"
+)
+
+type setLineTestData struct {
+ statement string
+ columnLineList []int
+ constraintLineList []int
+}
+
+func TestPGCreateTableSetLine(t *testing.T) {
+ tests := []setLineTestData{
+ {
+ statement: `
+ CREATE TABLE t(
+ a int, B int,
+ C int,
+ "D" int NOT NULL,
+ 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, 8, 10},
+ },
+ {
+ // 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: `
+ CREATE TABLE t(
+ a int PRIMARY KEY,
+ b int CHECK(b>1), c int UNIQUE
+ )
+ `,
+ columnLineList: []int{3, 4, 4},
+ constraintLineList: []int{},
+ },
+ }
+
+ for _, test := range tests {
+ nodeList, err := parser.Parse(parser.Postgres, parser.Context{}, test.statement)
+ require.NoError(t, err)
+ require.Len(t, nodeList, 1)
+ node, ok := nodeList[0].(*ast.CreateTableStmt)
+ require.True(t, ok)
+ require.Equal(t, len(test.columnLineList), len(node.ColumnList))
+ require.Equal(t, len(test.constraintLineList), len(node.ConstraintList))
+ for i, col := range node.ColumnList {
+ require.Equal(t, col.Line(), test.columnLineList[i], i)
+ }
+ for i, cons := range node.ConstraintList {
+ require.Equal(t, cons.Line(), test.constraintLineList[i], i)
+ }
+ }
+}
diff --git a/plugin/parser/tokenizer.go b/plugin/parser/tokenizer.go
index b9a710bc44..f2903f8394 100644
--- a/plugin/parser/tokenizer.go
+++ b/plugin/parser/tokenizer.go
@@ -1,8 +1,10 @@
package parser
import (
+ "strings"
"unicode"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
"github.com/pkg/errors"
)
@@ -38,6 +40,96 @@ func newTokenizer(statement string) *tokenizer {
return t
}
+// setLineForCreateTableStmt sets the line for columns and table constraints in CREATE TABLE statements.
+func (t *tokenizer) setLineForCreateTableStmt(node *ast.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.ColumnList {
+ col.SetLine(node.Line())
+ }
+ for _, cons := range node.ConstraintList {
+ cons.SetLine(node.Line())
+ }
+
+ 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 '(':
+ 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.ColumnList) &&
+ strings.Contains(def, strings.ToLower(node.ColumnList[columnPos].ColumnName)) {
+ node.ColumnList[columnPos].SetLine(t.startLine + node.Line() - 1)
+ } else if constraintPos < len(node.ConstraintList) &&
+ matchTableConstraint(def, node.ConstraintList[constraintPos]) {
+ node.ConstraintList[constraintPos].SetLine(t.startLine + node.Line() - 1)
+ }
+ return nil
+ }
+ t.skip(1)
+ case ',':
+ def := strings.ToLower(t.getString(startPos, t.pos()-startPos))
+ if columnPos < len(node.ColumnList) &&
+ strings.Contains(def, strings.ToLower(node.ColumnList[columnPos].ColumnName)) {
+ node.ColumnList[columnPos].SetLine(t.startLine + node.Line() - 1)
+ columnPos++
+ } else if constraintPos < len(node.ConstraintList) &&
+ matchTableConstraint(def, node.ConstraintList[constraintPos]) {
+ node.ConstraintList[constraintPos].SetLine(t.startLine + node.Line() - 1)
+ constraintPos++
+ }
+ t.skip(1)
+ t.skipBlank()
+ startPos = t.pos()
+ t.startLine = t.line
+ case eofRune:
+ return nil
+ default:
+ t.skip(1)
+ }
+ }
+}
+
+// matchTableConstraint matches text as lowercase.
+func matchTableConstraint(text string, cons *ast.ConstraintDef) bool {
+ text = strings.ToLower(text)
+ if cons.Name != "" {
+ return strings.Contains(text, strings.ToLower(cons.Name))
+ }
+ switch cons.Type {
+ case ast.ConstraintTypeCheck:
+ return strings.Contains(text, "check")
+ case ast.ConstraintTypeUnique:
+ return strings.Contains(text, "unique")
+ case ast.ConstraintTypePrimary:
+ return strings.Contains(text, "primary key")
+ case ast.ConstraintTypeForeign:
+ return strings.Contains(text, "foreign key")
+ }
+ return false
+}
+
// splitPostgreSQLMultiSQL splits the statement to a string slice.
// We mainly considered:
// - comments
diff --git a/plugin/parser/utils.go b/plugin/parser/utils.go
index da0e06e990..54669b7d48 100644
--- a/plugin/parser/utils.go
+++ b/plugin/parser/utils.go
@@ -1,6 +1,9 @@
package parser
-import "github.com/pkg/errors"
+import (
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+ "github.com/pkg/errors"
+)
// SingleSQL is a separate SQL split from multi-SQL.
type SingleSQL struct {
@@ -18,3 +21,14 @@ func SplitMultiSQL(engineType EngineType, statement string) ([]SingleSQL, error)
return nil, errors.Errorf("engine type is not supported: %s", engineType)
}
}
+
+// SetLineForCreateTableStmt sets the line for columns and table constraints in CREATE TABLE statements.
+func SetLineForCreateTableStmt(engineType EngineType, node *ast.CreateTableStmt) error {
+ switch engineType {
+ case Postgres:
+ t := newTokenizer(node.Text())
+ return t.setLineForCreateTableStmt(node)
+ default:
+ return errors.Errorf("engine type is not supported: %s", engineType)
+ }
+}