Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement antlr-based pg split multi-sqls (#9788)
rebelicedad803f6b329
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.goindex 3215653e07..46745fabe3 100644--- a/backend/plugin/db/mysql/mysql.go+++ b/backend/plugin/db/mysql/mysql.go@@ -185,7 +185,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ bool, optif err != nil {return 0, errors.Wrapf(err, "failed to split sql")}- list = filterEmptySQL(list)+ list = base.FilterEmptySQL(list)if len(list) == 0 {return 0, nil}@@ -276,7 +276,7 @@ func (driver *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement sif err != nil {return nil, err}- singleSQLs = filterEmptySQL(singleSQLs)+ singleSQLs = base.FilterEmptySQL(singleSQLs)if len(singleSQLs) == 0 {return nil, nil}@@ -342,13 +342,3 @@ func (driver *Driver) querySingleSQL(ctx context.Context, conn *sql.Conn, singlefunc (*Driver) RunStatement(ctx context.Context, conn *sql.Conn, statement string) ([]*v1pb.QueryResult, error) {return util.RunStatement(ctx, storepb.Engine_MYSQL, conn, statement)}--func filterEmptySQL(list []base.SingleSQL) []base.SingleSQL {- var result []base.SingleSQL- for _, sql := range list {- if !sql.Empty {- result = append(result, sql)- }- }- return result-}diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex 6b00539fc7..742d602258 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -456,6 +456,7 @@ func (driver *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement sif err != nil {return nil, err}+ singleSQLs = base.FilterEmptySQL(singleSQLs)if len(singleSQLs) == 0 {return nil, nil}diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.goindex 3c62c38312..cbee1c8759 100644--- a/backend/plugin/db/redshift/redshift.go+++ b/backend/plugin/db/redshift/redshift.go@@ -351,6 +351,7 @@ func (driver *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement sif err != nil {return nil, err}+ singleSQLs = base.FilterEmptySQL(singleSQLs)if len(singleSQLs) == 0 {return nil, nil}diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.goindex dc7c0b78ff..fd03e51b6c 100644--- a/backend/plugin/db/risingwave/risingwave.go+++ b/backend/plugin/db/risingwave/risingwave.go@@ -402,6 +402,7 @@ func (driver *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement sif err != nil {return nil, err}+ singleSQLs = base.FilterEmptySQL(singleSQLs)if len(singleSQLs) == 0 {return nil, nil}diff --git a/backend/plugin/parser/base/base.go b/backend/plugin/parser/base/base.goindex e6417168cd..e2a3138b55 100644--- a/backend/plugin/parser/base/base.go+++ b/backend/plugin/parser/base/base.go@@ -83,3 +83,13 @@ func (*ParseErrorListener) ReportAttemptingFullContext(recognizer antlr.Parser,func (*ParseErrorListener) ReportContextSensitivity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex, prediction int, configs *antlr.ATNConfigSet) {antlr.ConsoleErrorListenerINSTANCE.ReportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs)}++func FilterEmptySQL(list []SingleSQL) []SingleSQL {+ var result []SingleSQL+ for _, sql := range list {+ if !sql.Empty {+ result = append(result, sql)+ }+ }+ return result+}diff --git a/backend/plugin/parser/base/lexer.go b/backend/plugin/parser/base/lexer.gonew file mode 100644index 0000000000..78e2231121--- /dev/null+++ b/backend/plugin/parser/base/lexer.go@@ -0,0 +1,51 @@+package base++import (+ "github.com/antlr4-go/antlr/v4"+)++func GetDefaultChannelTokenType(tokens []antlr.Token, base int, offset int) int {+ current := base+ step := 1+ remaining := offset+ if offset < 0 {+ step = -1+ remaining = -offset+ }+ for remaining != 0 {+ current += step+ if current < 0 || current >= len(tokens) {+ return antlr.TokenEOF+ }++ if tokens[current].GetChannel() == antlr.TokenDefaultChannel {+ remaining--+ }+ }++ return tokens[current].GetTokenType()+}++// FirstDefaultChannelTokenPosition returns the first token position of the default channel.+// Both line and column are ZERO based.+func FirstDefaultChannelTokenPosition(tokens []antlr.Token) (int, int) {+ for _, token := range tokens {+ if token.GetChannel() == antlr.TokenDefaultChannel {+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ return token.GetLine() - 1, token.GetColumn()+ }+ }+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ return tokens[len(tokens)-1].GetLine() - 1, tokens[len(tokens)-1].GetColumn()+}++func IsEmpty(tokens []antlr.Token, semi int) bool {+ for _, token := range tokens {+ if token.GetChannel() == antlr.TokenDefaultChannel && token.GetTokenType() != semi && token.GetTokenType() != antlr.TokenEOF {+ return false+ }+ }+ return true+}diff --git a/backend/plugin/parser/mysql/mysql.go b/backend/plugin/parser/mysql/mysql.goindex 4ef72e8f93..1b19f6379a 100644--- a/backend/plugin/parser/mysql/mysql.go+++ b/backend/plugin/parser/mysql/mysql.go@@ -61,28 +61,6 @@ func DealWithDelimiter(statement string) (string, error) {return statement, nil}-func getDefaultChannelTokenType(tokens []antlr.Token, base int, offset int) int {- current := base- step := 1- remaining := offset- if offset < 0 {- step = -1- remaining = -offset- }- for remaining != 0 {- current += step- if current < 0 || current >= len(tokens) {- return parser.MySQLParserEOF- }-- if tokens[current].GetChannel() == antlr.TokenDefaultChannel {- remaining--- }- }-- return tokens[current].GetTokenType()-}-func parseSingleStatement(statement string) (antlr.Tree, *antlr.CommonTokenStream, error) {input := antlr.NewInputStream(statement)lexer := parser.NewMySQLLexer(input)diff --git a/backend/plugin/parser/mysql/split.go b/backend/plugin/parser/mysql/split.goindex 8aa957f2ca..1dd1202338 100644--- a/backend/plugin/parser/mysql/split.go+++ b/backend/plugin/parser/mysql/split.go@@ -79,68 +79,68 @@ func splitMySQLStatement(stream *antlr.CommonTokenStream) ([]base.SingleSQL, errfor i := 0; i < len(tokens); i++ {switch tokens[i].GetTokenType() {case parser.MySQLParserBEGIN_SYMBOL:- isBeginWork := getDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserWORK_SYMBOL- isBeginWork = isBeginWork || (getDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserSEMICOLON_SYMBOL)- isBeginWork = isBeginWork || (getDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserEOF)+ isBeginWork := base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserWORK_SYMBOL+ isBeginWork = isBeginWork || (base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserSEMICOLON_SYMBOL)+ isBeginWork = isBeginWork || (base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserEOF)if isBeginWork {continue}- isXa := getDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserXA_SYMBOL+ isXa := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserXA_SYMBOLif isXa {continue}stack = append(stack, openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})case parser.MySQLParserCASE_SYMBOL:- isEndCase := getDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ isEndCase := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOLif isEndCase {continue}stack = append(stack, openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})case parser.MySQLParserIF_SYMBOL:- isEndIf := getDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ isEndIf := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOLif isEndIf {continue}- isIfExists := getDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserEXISTS_SYMBOL+ isIfExists := base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserEXISTS_SYMBOLif isIfExists {continue}- isIfNotExists := (getDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserNOT_SYMBOL ||- getDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserNOT2_SYMBOL) &&- getDefaultChannelTokenType(tokens, i, 2) == parser.MySQLParserEXISTS_SYMBOL+ isIfNotExists := (base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserNOT_SYMBOL ||+ base.GetDefaultChannelTokenType(tokens, i, 1) == parser.MySQLParserNOT2_SYMBOL) &&+ base.GetDefaultChannelTokenType(tokens, i, 2) == parser.MySQLParserEXISTS_SYMBOLif isIfNotExists {continue}stack = append(stack, openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})case parser.MySQLParserLOOP_SYMBOL:- isEndLoop := getDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ isEndLoop := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOLif isEndLoop {continue}stack = append(stack, openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})case parser.MySQLParserWHILE_SYMBOL:- isEndWhile := getDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOL+ isEndWhile := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserEND_SYMBOLif isEndWhile {continue}stack = append(stack, openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})case parser.MySQLParserREPEAT_SYMBOL:- isEndRepeat := getDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserUNTIL_SYMBOL+ isEndRepeat := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserUNTIL_SYMBOLif isEndRepeat {continue}stack = append(stack, openParenthesis{tokenType: tokens[i].GetTokenType(), pos: i})case parser.MySQLParserEND_SYMBOL:- isXa := getDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserXA_SYMBOL+ isXa := base.GetDefaultChannelTokenType(tokens, i, -1) == parser.MySQLParserXA_SYMBOLif isXa {continue}@@ -154,7 +154,7 @@ func splitMySQLStatement(stream *antlr.CommonTokenStream) ([]base.SingleSQL, errreturn nil, errors.New("invalid statement: failed to split multiple statements")}- nextDefaultChannelTokenType := getDefaultChannelTokenType(tokens, i, 1)+ nextDefaultChannelTokenType := base.GetDefaultChannelTokenType(tokens, i, 1)isEndIf := nextDefaultChannelTokenType == parser.MySQLParserIF_SYMBOLif isEndIf {@@ -230,7 +230,7 @@ func splitMySQLStatement(stream *antlr.CommonTokenStream) ([]base.SingleSQL, errcontinue}- line, col := firstDefaultChannelTokenPosition(tokens[start : i+1])+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start : i+1])// From antlr4, the line is ONE based, and the column is ZERO based.// So we should minus 1 for the line.result = append(result, base.SingleSQL{@@ -240,7 +240,7 @@ func splitMySQLStatement(stream *antlr.CommonTokenStream) ([]base.SingleSQL, errLastColumn: tokens[i].GetColumn(),FirstStatementLine: line,FirstStatementColumn: col,- Empty: isEmpty(tokens[start : i+1]),+ Empty: base.IsEmpty(tokens[start:i+1], parser.MySQLLexerSEMICOLON_SYMBOL),})start = i + 1case parser.MySQLParserEOF:@@ -252,7 +252,7 @@ func splitMySQLStatement(stream *antlr.CommonTokenStream) ([]base.SingleSQL, err}if start <= i-1 {- line, col := firstDefaultChannelTokenPosition(tokens[start:i])+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start:i])// From antlr4, the line is ONE based, and the column is ZERO based.// So we should minus 1 for the line.result = append(result, base.SingleSQL{@@ -262,34 +262,10 @@ func splitMySQLStatement(stream *antlr.CommonTokenStream) ([]base.SingleSQL, errLastColumn: tokens[i-1].GetColumn(),FirstStatementLine: line,FirstStatementColumn: col,- Empty: isEmpty(tokens[start:i]),+ Empty: base.IsEmpty(tokens[start:i], parser.MySQLLexerSEMICOLON_SYMBOL),})}}}return result, nil}--func isEmpty(tokens []antlr.Token) bool {- for _, token := range tokens {- if token.GetChannel() == antlr.TokenDefaultChannel && token.GetTokenType() != parser.MySQLParserSEMICOLON_SYMBOL && token.GetTokenType() != parser.MySQLParserEOF {- return false- }- }- return true-}--// firstDefaultChannelTokenPosition returns the first token position of the default channel.-// Both line and column are ZERO based.-func firstDefaultChannelTokenPosition(tokens []antlr.Token) (int, int) {- for _, token := range tokens {- if token.GetChannel() == antlr.TokenDefaultChannel {- // From antlr4, the line is ONE based, and the column is ZERO based.- // So we should minus 1 for the line.- return token.GetLine() - 1, token.GetColumn()- }- }- // From antlr4, the line is ONE based, and the column is ZERO based.- // So we should minus 1 for the line.- return tokens[len(tokens)-1].GetLine() - 1, tokens[len(tokens)-1].GetColumn()-}diff --git a/backend/plugin/parser/pg/split.go b/backend/plugin/parser/pg/split.goindex 9bafba2607..5fc0a1f918 100644--- a/backend/plugin/parser/pg/split.go+++ b/backend/plugin/parser/pg/split.go@@ -3,8 +3,12 @@ package pgimport ("io"+ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ parser "github.com/bytebase/postgresql-parser"+"github.com/bytebase/bytebase/backend/plugin/parser/base"- "github.com/bytebase/bytebase/backend/plugin/parser/tokenizer"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -16,15 +20,17 @@ func init() {// SplitMultiSQLStream splits multiSQL to stream.func SplitMultiSQLStream(src io.Reader, f func(string) error) ([]base.SingleSQL, error) {- t := tokenizer.NewStreamTokenizer(src, f)- list, err := t.SplitPostgreSQLMultiSQL()+ text := antlr.NewIoStream(src).String()+ list, err := SplitSQL(text)if err != nil {return nil, err}var results []base.SingleSQLfor _, sql := range list {- if sql.Empty {- continue+ if f != nil && !sql.Empty {+ if err := f(sql.Text); err != nil {+ return nil, err+ }}results = append(results, sql)}@@ -33,17 +39,170 @@ func SplitMultiSQLStream(src io.Reader, f func(string) error) ([]base.SingleSQL,// SplitSQL splits the given SQL statement into multiple SQL statements.func SplitSQL(statement string) ([]base.SingleSQL, error) {- t := tokenizer.NewTokenizer(statement)- list, err := t.SplitPostgreSQLMultiSQL()- if err != nil {- return nil, err+ lexer := parser.NewPostgreSQLLexer(antlr.NewInputStream(statement))+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)+ return splitSQLImpl(stream)+}++func splitSQLImpl(stream *antlr.CommonTokenStream) ([]base.SingleSQL, error) {+ var result []base.SingleSQL+ stream.Fill()+ tokens := stream.GetAllTokens()+ start := 0+ // Splitting multiple statements by semicolon symbol should consider the special case.+ // For create function/procedure statements, the semicolon symbol is used as part of the statement.+ // We should skip the semicolon symbol between the "BEGIN ATOMIC" and "END" keywords.+ // So this is a parenthesis matching problem.+ type openParenthesis struct {+ tokenType int+ pos int}- var results []base.SingleSQL- for _, sql := range list {- if sql.Empty {- continue+ var stack []openParenthesis+ for i := 0; i < len(tokens); i++ {+ switch tokens[i].GetTokenType() {+ case parser.PostgreSQLLexerBEGIN_P:+ if isBeginTransaction(tokens, i) {+ continue+ }++ stack = append(stack, openParenthesis{+ tokenType: tokens[i].GetTokenType(),+ pos: i,+ })+ case parser.PostgreSQLLexerCASE:+ stack = append(stack, openParenthesis{+ tokenType: tokens[i].GetTokenType(),+ pos: i,+ })+ case parser.PostgreSQLLexerEND_P:+ if isEndTransaction(tokens, i) {+ continue+ }++ if len(stack) == 0 {+ return nil, errors.New("invalid statement: failed to split multiple statements")+ }++ nextToken := base.GetDefaultChannelTokenType(tokens, i, 1)+ switch nextToken {+ case parser.PostgreSQLLexerCASE:+ if stack[len(stack)-1].tokenType != parser.PostgreSQLLexerCASE {+ // Backtracking the process.+ i = stack[len(stack)-1].pos+ stack = stack[:len(stack)-1]+ continue+ }+ stack = stack[:len(stack)-1]+ continue+ case parser.PostgreSQLLexerIF_P:+ if stack[len(stack)-1].tokenType != parser.PostgreSQLLexerIF_P {+ // Backtracking the process.+ i = stack[len(stack)-1].pos+ stack = stack[:len(stack)-1]+ continue+ }+ stack = stack[:len(stack)-1]+ continue+ case parser.PostgreSQLLexerLOOP:+ if stack[len(stack)-1].tokenType != parser.PostgreSQLLexerLOOP {+ // Backtracking the process.+ i = stack[len(stack)-1].pos+ stack = stack[:len(stack)-1]+ continue+ }+ stack = stack[:len(stack)-1]+ continue+ default:+ leftTokenType := stack[len(stack)-1].tokenType+ if leftTokenType != parser.PostgreSQLLexerBEGIN_P && leftTokenType != parser.PostgreSQLLexerCASE {+ // Backtracking the process.+ i = stack[len(stack)-1].pos+ stack = stack[:len(stack)-1]+ continue+ }+ stack = stack[:len(stack)-1]+ }+ case parser.PostgreSQLLexerSEMI:+ if len(stack) > 0 {+ continue+ }++ line, col := base.FirstDefaultChannelTokenPosition(tokens[start:i])+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ result = append(result, base.SingleSQL{+ Text: stream.GetTextFromTokens(tokens[start], tokens[i]),+ BaseLine: tokens[start].GetLine() - 1,+ LastLine: tokens[i].GetLine() - 1,+ LastColumn: tokens[i].GetColumn(),+ FirstStatementLine: line,+ FirstStatementColumn: col,+ Empty: base.IsEmpty(tokens[start:i+1], parser.PostgreSQLLexerSEMI),+ })+ start = i + 1+ case antlr.TokenEOF:+ if len(stack) > 0 {+ // Backtracking the process.+ i = stack[len(stack)-1].pos+ stack = stack[:len(stack)-1]+ continue+ }++ if start <= i-1 {+ line, col := base.FirstDefaultChannelTokenPosition(tokens[start:i])+ // From antlr4, the line is ONE based, and the column is ZERO based.+ // So we should minus 1 for the line.+ result = append(result, base.SingleSQL{+ Text: stream.GetTextFromTokens(tokens[start], tokens[i-1]),+ BaseLine: tokens[start].GetLine() - 1,+ LastLine: tokens[i-1].GetLine() - 1,+ LastColumn: tokens[i-1].GetColumn(),+ FirstStatementLine: line,+ FirstStatementColumn: col,+ Empty: base.IsEmpty(tokens[start:i], parser.PostgreSQLLexerSEMI),+ })+ }}- results = append(results, sql)}- return results, nil+ return result, nil+}++func isEndTransaction(tokens []antlr.Token, index int) bool {+ if tokens[index].GetTokenType() != parser.PostgreSQLLexerEND_P {+ return false+ }++ switch base.GetDefaultChannelTokenType(tokens, index, 1) {+ case parser.PostgreSQLParserTRANSACTION,+ parser.PostgreSQLParserWORK,+ parser.PostgreSQLParserSEMI:+ return true+ case parser.PostgreSQLParserAND:+ if base.GetDefaultChannelTokenType(tokens, index, 2) == parser.PostgreSQLParserNO {+ return base.GetDefaultChannelTokenType(tokens, index, 3) == parser.PostgreSQLParserCHAIN+ }+ return base.GetDefaultChannelTokenType(tokens, index, 2) == parser.PostgreSQLParserCHAIN+ default:+ return false+ }+}++func isBeginTransaction(tokens []antlr.Token, index int) bool {+ if tokens[index].GetTokenType() != parser.PostgreSQLLexerBEGIN_P {+ return false+ }++ switch base.GetDefaultChannelTokenType(tokens, index, 1) {+ case parser.PostgreSQLParserTRANSACTION,+ parser.PostgreSQLParserWORK,+ parser.PostgreSQLParserSEMI,+ parser.PostgreSQLParserISOLATION,+ parser.PostgreSQLParserREAD,+ parser.PostgreSQLLexerDEFERRABLE:+ return true+ case parser.PostgreSQLParserNOT:+ return base.GetDefaultChannelTokenType(tokens, index, 2) == parser.PostgreSQLParserDEFERRABLE+ default:+ return false+ }}diff --git a/backend/plugin/parser/pg/split_test.go b/backend/plugin/parser/pg/split_test.goindex 8f773f3750..8f616300c1 100644--- a/backend/plugin/parser/pg/split_test.go+++ b/backend/plugin/parser/pg/split_test.go@@ -39,6 +39,19 @@ func TestPGSplitMultiSQL(t *testing.T) {statement: `-- klsjdfjasldf-- klsjdflkjaskldfj`,+ want: resData{+ res: []base.SingleSQL{+ {+ Text: "-- klsjdfjasldf\n\t\t\t-- klsjdflkjaskldfj\n\t\t\t",+ BaseLine: 0,+ FirstStatementLine: 2,+ FirstStatementColumn: 0,+ LastLine: 2,+ LastColumn: 0,+ Empty: true,+ },+ },+ },},{statement: `select * from t;@@ -46,8 +59,17 @@ func TestPGSplitMultiSQL(t *testing.T) {want: resData{res: []base.SingleSQL{{- Text: `select * from t;`,- LastLine: 1,+ Text: `select * from t;`,+ LastLine: 0,+ LastColumn: 15,+ },+ {+ Text: "\n\t\t\t/* sdfasdf */",+ LastLine: 1,+ LastColumn: 3,+ FirstStatementLine: 1,+ FirstStatementColumn: 3,+ Empty: true,},},},@@ -59,12 +81,25 @@ func TestPGSplitMultiSQL(t *testing.T) {want: resData{res: []base.SingleSQL{{- Text: `select * from t;`,- LastLine: 1,+ Text: `select * from t;`,+ LastLine: 0,+ LastColumn: 15,+ },+ {+ Text: "\n\t\t\t/* sdfasdf */;",+ FirstStatementLine: 1,+ FirstStatementColumn: 3,+ LastLine: 1,+ LastColumn: 16,+ Empty: true,},{- Text: `select * from t;`,- LastLine: 3,+ Text: "\n\t\t\tselect * from t;",+ BaseLine: 1,+ FirstStatementLine: 2,+ FirstStatementColumn: 3,+ LastLine: 2,+ LastColumn: 18,},},},@@ -74,8 +109,9 @@ func TestPGSplitMultiSQL(t *testing.T) {want: resData{res: []base.SingleSQL{{- Text: bigSQL,- LastLine: 1,+ Text: bigSQL,+ LastLine: 0,+ LastColumn: len(bigSQL) - 1,},},},@@ -85,28 +121,35 @@ func TestPGSplitMultiSQL(t *testing.T) {want: resData{res: []base.SingleSQL{{- Text: "CREATE TABLE t(a int);",- LastLine: 1,+ Text: " CREATE TABLE t(a int);",+ FirstStatementColumn: 4,+ LastLine: 0,+ LastColumn: 25,},{- Text: "CREATE TABLE t1(a int)",- LastLine: 1,+ Text: " CREATE TABLE t1(a int)",+ FirstStatementColumn: 27,+ LastColumn: 48,},},},},{statement: `CREATE TABLE "tech_Book"(id int, name varchar(255));- INSERT INTO "tech_Book" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafa\'jdfl;"ka');`,+ INSERT INTO "tech_Book" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafajdfl;"ka');`,want: resData{res: []base.SingleSQL{{- Text: `CREATE TABLE "tech_Book"(id int, name varchar(255));`,- LastLine: 1,+ Text: `CREATE TABLE "tech_Book"(id int, name varchar(255));`,+ LastLine: 0,+ LastColumn: 51,},{- Text: `INSERT INTO "tech_Book" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafa\'jdfl;"ka');`,- LastLine: 2,+ Text: "\n\t\t\t\t\t\tINSERT INTO \"tech_Book\" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafajdfl;\"ka');",+ FirstStatementLine: 1,+ FirstStatementColumn: 6,+ LastLine: 1,+ LastColumn: 81,},},},@@ -116,18 +159,23 @@ func TestPGSplitMultiSQL(t *testing.T) {/* this is the comment. */CREATE /* inline comment */TABLE "tech_Book"(id int, name varchar(255));-- this is the comment.- INSERT INTO "tech_Book" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafa\'jdfl;"ka');`,+ INSERT INTO "tech_Book" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafajdfl;"ka');`,want: resData{res: []base.SingleSQL{{- Text: `/* this is the comment. */- CREATE /* inline comment */TABLE "tech_Book"(id int, name varchar(255));`,- LastLine: 3,+ Text: "\n\t\t\t\t\t\t/* this is the comment. */\n\t\t\t\t\t\tCREATE /* inline comment */TABLE \"tech_Book\"(id int, name varchar(255));",+ FirstStatementLine: 2,+ FirstStatementColumn: 6,+ LastLine: 2,+ LastColumn: 77,},{- Text: `-- this is the comment.- INSERT INTO "tech_Book" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafa\'jdfl;"ka');`,- LastLine: 5,+ Text: "\n\t\t\t\t\t\t-- this is the comment.\n\t\t\t\t\t\tINSERT INTO \"tech_Book\" VALUES (0, 'abce_ksdf'), (1, 'lks''kjsafajdfl;\"ka');",+ BaseLine: 2,+ FirstStatementLine: 4,+ FirstStatementColumn: 6,+ LastLine: 4,+ LastColumn: 81,},},},@@ -137,7 +185,7 @@ func TestPGSplitMultiSQL(t *testing.T) {LANGUAGE SQLAS $$/*this is the comment */- INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lk\\jasdf\'lkasdf"asdklf\\');+ INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lk\\jasdflkasdf"asdklf\\');-- this is the commentINSERT INTO tbl VALUES ('fasf_bkdjlfa');$$;@@ -149,15 +197,20 @@ func TestPGSplitMultiSQL(t *testing.T) {LANGUAGE SQLAS $$/*this is the comment */- INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lk\\jasdf\'lkasdf"asdklf\\');+ INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lk\\jasdflkasdf"asdklf\\');-- this is the commentINSERT INTO tbl VALUES ('fasf_bkdjlfa');$$;`,- LastLine: 8,+ LastLine: 7,+ LastColumn: 8,},{- Text: `CREATE TABLE t(a int);`,- LastLine: 9,+ Text: "\n\t\t\t\t\t\tCREATE TABLE t(a int);",+ BaseLine: 7,+ FirstStatementLine: 8,+ FirstStatementColumn: 6,+ LastLine: 8,+ LastColumn: 27,},},},@@ -167,7 +220,7 @@ func TestPGSplitMultiSQL(t *testing.T) {LANGUAGE SQLAS $tag_name$/*this is the comment */- INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lkjasdf\'lkasdf"asdklf');+ INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lkjasdflkasdf"asdklf');-- this is the commentINSERT INTO tbl VALUES ('fasf_bkdjlfa');$tag_name$;@@ -179,15 +232,20 @@ func TestPGSplitMultiSQL(t *testing.T) {LANGUAGE SQLAS $tag_name$/*this is the comment */- INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lkjasdf\'lkasdf"asdklf');+ INSERT /* inline comment */ INTO tbl VALUES ('lkjafd''lksjadlf;lkjasdflkasdf"asdklf');-- this is the commentINSERT INTO tbl VALUES ('fasf_bkdjlfa');$tag_name$;`,- LastLine: 8,+ LastLine: 7,+ LastColumn: 16,},{- Text: `CREATE TABLE t(a int);`,- LastLine: 9,+ Text: "\n\t\t\t\t\t\tCREATE TABLE t(a int);",+ BaseLine: 7,+ FirstStatementLine: 8,+ FirstStatementColumn: 6,+ LastLine: 8,+ LastColumn: 27,},},},@@ -198,12 +256,16 @@ func TestPGSplitMultiSQL(t *testing.T) {want: resData{res: []base.SingleSQL{{- Text: "CREATE TABLE t\r\n(a int);",- LastLine: 2,+ Text: "CREATE TABLE t\r\n(a int);",+ LastLine: 1,+ LastColumn: 7,},{- Text: "CREATE TABLE t1(b int);",- LastLine: 3,+ Text: "\r\nCREATE TABLE t1(b int);",+ BaseLine: 1,+ FirstStatementLine: 2,+ LastLine: 2,+ LastColumn: 22,},},},@@ -212,17 +274,14 @@ func TestPGSplitMultiSQL(t *testing.T) {statement: `INSERT INTO "public"."table"("id","content")VALUES(12,'table column name () { :xna,sydfn,,kasdfyn;}; /////test string/// 0'),- (133,'knuandfan public table id\';create table t(a int, b int);set @text=\'\\\\kdaminxkljasdfiebkla.unkonwn\'+\'abcdef.xyz\\\'; local xxxyy.abcddd.mysql @text;------- '),- (1444,'table t xyz abc a\'a\\\\\\\\\'b"c>?>xxxxxx%}}%%>c<[[?${12344556778990{%}}cake\\');`,+ (133,'knuandfan public table id'';create table t(a int, b int);set @text=''\\\\kdaminxkljasdfiebkla.unkonwn''+''abcdef.xyz\\''; local xxxyy.abcddd.mysql @text;------- '),+ (1444,'table t xyz abc a''a\\\\\\\\''b"c>?>xxxxxx%}}%%>c<[[?${12344556778990{%}}cake\\');`,want: resData{res: []base.SingleSQL{{- Text: `INSERT INTO "public"."table"("id","content")- VALUES- (12,'table column name () { :xna,sydfn,,kasdfyn;}; /////test string/// 0'),- (133,'knuandfan public table id\';create table t(a int, b int);set @text=\'\\\\kdaminxkljasdfiebkla.unkonwn\'+\'abcdef.xyz\\\'; local xxxyy.abcddd.mysql @text;------- '),- (1444,'table t xyz abc a\'a\\\\\\\\\'b"c>?>xxxxxx%}}%%>c<[[?${12344556778990{%}}cake\\');`,- LastLine: 5,+ Text: "INSERT INTO \"public\".\"table\"(\"id\",\"content\")\n\t\t\tVALUES\n\t\t\t(12,'table column name () { :xna,sydfn,,kasdfyn;}; /////test string/// 0'),\n\t\t\t(133,'knuandfan public table id'';create table t(a int, b int);set @text=''\\\\\\\\kdaminxkljasdfiebkla.unkonwn''+''abcdef.xyz\\\\''; local xxxyy.abcddd.mysql @text;------- '),\n\t\t\t(1444,'table t xyz abc a''a\\\\\\\\\\\\\\\\''b\"c>?>xxxxxx%}}%%>c<[[?${12344556778990{%}}cake\\\\');",+ LastLine: 4,+ LastColumn: 91,},},},@@ -230,25 +289,55 @@ func TestPGSplitMultiSQL(t *testing.T) {{statement: `INSERT INTO t VALUES ('klajfas)`,want: resData{- err: "invalid string: not found delimiter: ', but found EOF",+ res: []base.SingleSQL{+ {+ Text: "INSERT INTO t VALUES ('klajfas)",+ LastLine: 0,+ LastColumn: 22,+ FirstStatementLine: 0,+ FirstStatementColumn: 0,+ Empty: false,+ },+ },},},{statement: `INSERT INTO "t VALUES ('klajfas)`,want: resData{- err: "invalid indentifier: not found delimiter: \", but found EOF",+ res: []base.SingleSQL{+ {+ Text: "INSERT INTO \"t VALUES ('klajfas)",+ LastLine: 0,+ LastColumn: 12,+ },+ },},},{statement: `/*INSERT INTO "t VALUES ('klajfas)`,want: resData{- err: "invalid comment: not found */, but found EOF",+ res: []base.SingleSQL{+ {+ Text: "/*INSERT INTO \"t VALUES ('klajfas)",+ BaseLine: 0,+ FirstStatementLine: 0,+ FirstStatementColumn: 0,+ LastLine: 0,+ LastColumn: 0,+ Empty: false,+ },+ },},},{statement: `$$INSERT INTO "t VALUES ('klajfas)`,want: resData{- err: "scanTo failed: delimiter \"$$\" not found",+ res: []base.SingleSQL{+ {+ Text: "$$INSERT INTO \"t VALUES ('klajfas)",+ LastColumn: 2,+ },+ },},},}diff --git a/backend/tests/test-data/sql_review_pg.yaml b/backend/tests/test-data/sql_review_pg.yamlindex 2cf5197d73..fd8f426344 100644--- a/backend/tests/test-data/sql_review_pg.yaml+++ b/backend/tests/test-data/sql_review_pg.yaml@@ -25,7 +25,6 @@"title": "Syntax error","content": "syntax error at or near \"user\"","sqlReviewReport": {- "line": 1,"code": 201}}diff --git a/go.mod b/go.modindex f3702c374c..70efa7de3d 100644--- a/go.mod+++ b/go.mod@@ -16,7 +16,7 @@ require (github.com/blang/semver/v4 v4.0.0github.com/bytebase/mysql-parser v0.0.0-20231208095055-182de2379272github.com/bytebase/plsql-parser v0.0.0-20231110065312-688a51648c4a- github.com/bytebase/postgresql-parser v0.0.0-20230926094140-aa337757cdd0+ github.com/bytebase/postgresql-parser v0.0.0-20231211065919-9d1484ceb5aegithub.com/bytebase/snowsql-parser v0.0.0-20230706111031-cafd8faa2dc9github.com/cenkalti/backoff/v4 v4.2.1github.com/coreos/go-oidc v2.2.1+incompatiblediff --git a/go.sum b/go.sumindex 1f595e1781..0aebebca45 100644--- a/go.sum+++ b/go.sum@@ -171,8 +171,8 @@ github.com/bytebase/pg_query_go/v4 v4.0.0-20230802100607-2f34e68d96f5 h1:3Ihj6fsgithub.com/bytebase/pg_query_go/v4 v4.0.0-20230802100607-2f34e68d96f5/go.mod h1:aEkDNOXNM5j0YGzaAapwJ7LB3dLNj+bvbWcLv1hOVqA=github.com/bytebase/plsql-parser v0.0.0-20231110065312-688a51648c4a h1:2t4nAguPYBm7HWz8TA+HM6FWCdldfk7nmjTiksP2ZuE=github.com/bytebase/plsql-parser v0.0.0-20231110065312-688a51648c4a/go.mod h1:kL1Tk89SNE7wPnUzkVMJ9v012an5z8as7OUmkapJQGs=-github.com/bytebase/postgresql-parser v0.0.0-20230926094140-aa337757cdd0 h1:AT9yzDiDkWMBgqsV61pZ3Lw18grBoWqDg7vVYlBGG88=-github.com/bytebase/postgresql-parser v0.0.0-20230926094140-aa337757cdd0/go.mod h1:Jft7oabwuwD+t5BYiUfTjcNVaihZ8F5KT8TsROG0EaE=+github.com/bytebase/postgresql-parser v0.0.0-20231211065919-9d1484ceb5ae h1:5nPEH1Uz9x9vGHXmg1JbecuR6QvM64lRDu2ZuKWlF6o=+github.com/bytebase/postgresql-parser v0.0.0-20231211065919-9d1484ceb5ae/go.mod h1:Jft7oabwuwD+t5BYiUfTjcNVaihZ8F5KT8TsROG0EaE=github.com/bytebase/snowsql-parser v0.0.0-20230706111031-cafd8faa2dc9 h1:XLSpYgrzleY2HFnCSDnYMbqOoZ3QrAdwXs7rca39Fjc=github.com/bytebase/snowsql-parser v0.0.0-20230706111031-cafd8faa2dc9/go.mod h1:gJ1aclz1e9xLArQTbCpDjL+A79Jt3Ro9+/QEw8A6vMM=github.com/bytebase/tidb2 v0.0.0-20231129002249-5bbb6bb83940 h1:EgmWx2TWEnHySUhiRrwmihFOcRIMfPGQLUtzmoblaTs=