Skip to content

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

feat(tokenizer): add options to allow keep empty lines between blocks (#10336)

h3n4lb3a940b15ebe
diff --git a/backend/plugin/parser/mysql/mysql.go b/backend/plugin/parser/mysql/mysql.go
index 6bb78f99b6..a4354f2e28 100644
--- a/backend/plugin/parser/mysql/mysql.go
+++ b/backend/plugin/parser/mysql/mysql.go
@@ -23,8 +23,8 @@ type ParseResult struct {
}
// ParseMySQL parses the given SQL statement and returns the AST.
-func ParseMySQL(statement string) ([]*ParseResult, error) {
- statement, err := DealWithDelimiter(statement)
+func ParseMySQL(statement string, options ...tokenizer.Option) ([]*ParseResult, error) {
+ statement, err := DealWithDelimiter(statement, options...)
if err != nil {
return nil, err
}
@@ -37,8 +37,8 @@ func ParseMySQL(statement string) ([]*ParseResult, error) {
}
// DealWithDelimiter converts the delimiter statement to comment, also converts the following statement's delimiter to semicolon(`;`).
-func DealWithDelimiter(statement string) (string, error) {
- has, list, err := hasDelimiter(statement)
+func DealWithDelimiter(statement string, options ...tokenizer.Option) (string, error) {
+ has, list, err := hasDelimiter(statement, options...)
if err != nil {
return "", err
}
@@ -261,9 +261,9 @@ func ExtractDelimiter(stmt string) (string, error) {
return "", errors.Errorf("cannot extract delimiter from %q", stmt)
}
-func hasDelimiter(statement string) (bool, []base.SingleSQL, error) {
+func hasDelimiter(statement string, options ...tokenizer.Option) (bool, []base.SingleSQL, error) {
// use splitTiDBMultiSQL to check if the statement has delimiter
- t := tokenizer.NewTokenizer(statement)
+ t := tokenizer.NewTokenizer(statement, options...)
list, err := t.SplitTiDBMultiSQL()
if err != nil {
return false, nil, errors.Errorf("failed to split multi sql: %v", err)
diff --git a/backend/plugin/parser/tokenizer/testdata/test_split_tidb_multi_sql.yaml b/backend/plugin/parser/tokenizer/testdata/test_split_tidb_multi_sql.yaml
new file mode 100644
index 0000000000..8f88faf2bd
--- /dev/null
+++ b/backend/plugin/parser/tokenizer/testdata/test_split_tidb_multi_sql.yaml
@@ -0,0 +1,66 @@
+- description: empty statement
+ statement: " "
+ expected: []
+- description: multi-newline
+ statement: |-
+ CREATE TABLE `u` (
+ `b` blob NOT NULL,
+ );
+
+
+
+ /*
+
+
+
+ */
+
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `b` blob NOT NULL,
+ );
+ expected:
+ - text: |-
+ CREATE TABLE `u` (
+ `b` blob NOT NULL,
+ );
+ baseline: 0
+ firststatementline: 0
+ firststatementcolumn: 0
+ lastline: 3
+ lastcolumn: 0
+ empty: false
+ - text: |4+
+
+
+ baseline: 3
+ firststatementline: 0
+ firststatementcolumn: 0
+ lastline: 6
+ lastcolumn: 0
+ empty: true
+ - text: |-
+ /*
+
+
+
+ */
+
+
+
+ --
+ -- Table structure for `t`
+ --
+ CREATE TABLE `t` (
+ `b` blob NOT NULL,
+ );
+ baseline: 0
+ firststatementline: 0
+ firststatementcolumn: 0
+ lastline: 20
+ lastcolumn: 0
+ empty: false
diff --git a/backend/plugin/parser/tokenizer/tokenizer.go b/backend/plugin/parser/tokenizer/tokenizer.go
index 9c0a15fc64..38307edc3c 100644
--- a/backend/plugin/parser/tokenizer/tokenizer.go
+++ b/backend/plugin/parser/tokenizer/tokenizer.go
@@ -24,6 +24,41 @@ var (
delimiterRuneList = []rune{'D', 'E', 'L', 'I', 'M', 'I', 'T', 'E', 'R'}
)
+type Option func(*Tokenizer)
+
+// KeepEmptyBlocks is used to keep empty lines between the blocks.
+// Currently, it is only available for SplitTiDBMultiSQL.
+// The following example shows how it affects the result:
+//
+// CREATE TABLE t1 (
+// a int
+// );
+//
+//
+// CREATE TABLE t2 (
+// a int
+// );
+//
+// If we set KeepEmptyBlocks, the result will be:
+// [
+//
+// "CREATE TABLE t1 (
+// a int
+// );",
+// "\n",
+// "CREATE TABLE t2 (
+// a int
+// );"
+//
+// ]
+// Note, the sum of the empty lines in that block will be 1(2-1) instead of 2, the reason is
+// that do not break the current caller.
+func KeepEmptyBlocks() Option {
+ return func(t *Tokenizer) {
+ t.keepEmptyBlocks = true
+ }
+}
+
type Tokenizer struct {
buffer []rune
cursor uint
@@ -35,11 +70,15 @@ type Tokenizer struct {
reader *bufio.Reader
f func(string) error
readErr error
+
+ // Options.
+ // keepEmptyBlocks is used to keep empty lines between the blocks.
+ keepEmptyBlocks bool
}
// NewTokenizer creates a new tokenizer.
// Notice: we append an additional eofRune in the statement. This is a sentinel rune.
-func NewTokenizer(statement string) *Tokenizer {
+func NewTokenizer(statement string, options ...Option) *Tokenizer {
t := &Tokenizer{
buffer: []rune(statement),
cursor: 0,
@@ -48,6 +87,11 @@ func NewTokenizer(statement string) *Tokenizer {
t.len = uint(len(t.buffer))
// append an additional eofRune.
t.buffer = append(t.buffer, eofRune)
+
+ for _, option := range options {
+ option(t)
+ }
+
return t
}
@@ -401,6 +445,25 @@ func (t *Tokenizer) SplitTiDBMultiSQL() ([]base.SingleSQL, error) {
return nil, err
}
}
+
+ if t.keepEmptyBlocks {
+ newRes := make([]base.SingleSQL, 0, len(res))
+ baseline := 0
+ for _, sql := range res {
+ lines := strings.Split(sql.Text, "\n")
+ if lap := sql.LastLine - len(lines) - baseline; lap > 0 {
+ newRes = append(newRes, base.SingleSQL{
+ Text: strings.Repeat("\n", lap-1),
+ BaseLine: baseline,
+ LastLine: baseline + lap,
+ Empty: true,
+ })
+ }
+ newRes = append(newRes, sql)
+ baseline = sql.LastLine
+ }
+ return newRes, t.readErr
+ }
return res, t.readErr
case t.equalWordCaseInsensitive(delimiter):
t.skip(uint(len(delimiter)))
@@ -882,6 +945,7 @@ func (t *Tokenizer) truncate(pos uint) {
t.cursor -= pos
}
+// char returns the rune after the cursor, if out of range, return eofRune.
func (t *Tokenizer) char(after uint) rune {
for t.cursor+after >= t.len && t.reader != nil {
t.scan()
@@ -902,6 +966,7 @@ func (t *Tokenizer) preChar(before uint) rune {
return t.buffer[t.cursor-before]
}
+// skip skips the cursor to the cursor + step, if out of range, skip will be set to len.
func (t *Tokenizer) skip(step uint) {
t.cursor += step
for t.cursor > t.len && t.reader != nil {
@@ -912,9 +977,10 @@ func (t *Tokenizer) skip(step uint) {
}
}
+// skipBlank skips the cursor to the first non-blank rune.
func (t *Tokenizer) skipBlank() {
r := t.char(0)
- for r == ' ' || r == '\n' || r == '\r' || r == '\t' {
+ for unicode.IsSpace(r) {
t.skip(1)
if r == '\n' {
t.line++
@@ -923,9 +989,10 @@ func (t *Tokenizer) skipBlank() {
}
}
+// skipToBlank skips the cursor to the first blank rune.
func (t *Tokenizer) skipToBlank() {
r := t.char(0)
- for r != ' ' && r != '\n' && r != '\r' && r != '\t' && r != eofRune {
+ for r != eofRune && !unicode.IsSpace(r) {
t.skip(1)
r = t.char(0)
}
diff --git a/backend/plugin/parser/tokenizer/tokenizer_test.go b/backend/plugin/parser/tokenizer/tokenizer_test.go
new file mode 100644
index 0000000000..7a78f037f3
--- /dev/null
+++ b/backend/plugin/parser/tokenizer/tokenizer_test.go
@@ -0,0 +1,59 @@
+package tokenizer
+
+import (
+ "io"
+ "os"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+)
+
+func TestSplitTiDBMultiSQL(t *testing.T) {
+ type testCase struct {
+ Description string
+ Statement string
+ Expected []base.SingleSQL
+ }
+
+ const (
+ fp = "testdata/test_split_tidb_multi_sql.yaml"
+ record = false
+ )
+
+ a := require.New(t)
+
+ f, err := os.Open(fp)
+ a.NoError(err)
+ content, err := io.ReadAll(f)
+ a.NoError(err)
+ err = f.Close()
+ a.NoError(err)
+
+ var testCases []testCase
+ err = yaml.Unmarshal(content, &testCases)
+ a.NoError(err)
+
+ for idx, tc := range testCases {
+ tokenizer := NewTokenizer(tc.Statement, KeepEmptyBlocks())
+ list, err := tokenizer.SplitTiDBMultiSQL()
+ a.NoError(err)
+
+ if record {
+ testCases[idx].Expected = list
+ } else {
+ a.Equal(tc.Expected, list, tc.Description)
+ }
+ }
+
+ if record {
+ content, err := yaml.Marshal(testCases)
+ a.NoError(err)
+ f, err := os.OpenFile(fp, os.O_WRONLY|os.O_TRUNC, 0644)
+ a.NoError(err)
+ _, err = f.Write(content)
+ a.NoError(err)
+ }
+}
diff --git a/backend/plugin/schema/mysql/get_design_schema.go b/backend/plugin/schema/mysql/get_design_schema.go
index 084d3def6c..b5b0a82437 100644
--- a/backend/plugin/schema/mysql/get_design_schema.go
+++ b/backend/plugin/schema/mysql/get_design_schema.go
@@ -12,6 +12,7 @@ import (
"github.com/pkg/errors"
mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
+ "github.com/bytebase/bytebase/backend/plugin/parser/tokenizer"
"github.com/bytebase/bytebase/backend/plugin/schema"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -22,7 +23,7 @@ func init() {
func GetDesignSchema(baselineSchema string, to *storepb.DatabaseSchemaMetadata) (string, error) {
toState := convertToDatabaseState(to)
- list, err := mysqlparser.ParseMySQL(baselineSchema)
+ list, err := mysqlparser.ParseMySQL(baselineSchema, tokenizer.KeepEmptyBlocks())
if err != nil {
return "", err
}
diff --git a/backend/plugin/schema/mysql/testdata/get_design_schema.yaml b/backend/plugin/schema/mysql/testdata/get_design_schema.yaml
index bf07300623..919fd2b5fa 100644
--- a/backend/plugin/schema/mysql/testdata/get_design_schema.yaml
+++ b/backend/plugin/schema/mysql/testdata/get_design_schema.yaml
@@ -1,3 +1,106 @@
+- baseline: |-
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `u`
+ --
+ CREATE TABLE `u` (
+ `t` text NOT NULL,
+ `g` geometry NOT NULL,
+ `j` json NOT NULL,
+ `ti` tinyint(1) NOT NULL,
+ `tb` tinyblob
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Function structure for `hello`
+ --
+ SET character_set_client = utf8mb3;
+ SET character_set_results = utf8mb3;
+ SET collation_connection = utf8mb3_general_ci;
+ SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
+ DELIMITER ;;
+ CREATE DEFINER=`root`@`localhost` FUNCTION `hello`(s CHAR(20)) RETURNS char(50) CHARSET utf8mb4
+ DETERMINISTIC
+ RETURN CONCAT ('Hello, ', s, '!') ;;
+ DELIMITER ;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
+ target: |-
+ {
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "u",
+ "engine": "InnoDB",
+ "columns": [
+ {
+ "name": "t",
+ "type": "text",
+ "comment": "123",
+ "position": 1,
+ "userComment": "123"
+ },
+ {
+ "name": "g",
+ "type": "geometry",
+ "position": 2
+ },
+ {
+ "name": "j",
+ "type": "json",
+ "position": 3
+ },
+ {
+ "name": "ti",
+ "type": "tinyint(1)",
+ "position": 4
+ },
+ {
+ "name": "tb",
+ "type": "tinyblob",
+ "nullable": true,
+ "position": 5,
+ "defaultNull": true
+ }
+ ],
+ "collation": "utf8mb4_0900_ai_ci"
+ }
+ ]
+ }
+ ]
+ }
+ result: |
+ SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
+ SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
+ --
+ -- Table structure for `u`
+ --
+ CREATE TABLE `u` (
+ `t` text NOT NULL COMMENT '123',
+ `g` geometry NOT NULL,
+ `j` json NOT NULL,
+ `ti` tinyint(1) NOT NULL,
+ `tb` tinyblob
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+ --
+ -- Function structure for `hello`
+ --
+ SET character_set_client = utf8mb3;
+ SET character_set_results = utf8mb3;
+ SET collation_connection = utf8mb3_general_ci;
+ SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
+ DELIMITER ;;
+ CREATE DEFINER=`root`@`localhost` FUNCTION `hello`(s CHAR(20)) RETURNS char(50) CHARSET utf8mb4
+ DETERMINISTIC
+ RETURN CONCAT ('Hello, ', s, '!') ;;
+ DELIMITER ;
+
+ SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
+ SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
- baseline: |-
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;