Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test(parser/doris): add statement range tests with YAML cases (#16427)
h3n4lfa339de31026
diff --git a/backend/plugin/parser/base/statement_ranges.go b/backend/plugin/parser/base/statement_ranges.gonew file mode 100644index 0000000000..eff37323ee--- /dev/null+++ b/backend/plugin/parser/base/statement_ranges.go@@ -0,0 +1,119 @@+package base++import (+ "strings"+ "unicode"++ "github.com/antlr4-go/antlr/v4"++ protocol "github.com/bytebase/lsp-protocol"+)++// GetANTLRStatementRangesUTF16Position is a generic function to extract statement ranges from ANTLR token streams.+// It returns the ranges of statements in UTF-16 positions suitable for LSP protocol.+//+// Parameters:+// - tokenStream: The ANTLR token stream to process+// - eofTokenType: The EOF token type (e.g., parser.SnowflakeParserEOF)+// - terminatorTokenType: The statement terminator token type (e.g., parser.SnowflakeParserSEMI)+//+// The function handles:+// - UTF-16 surrogate pairs for characters outside the Basic Multilingual Plane (BMP)+// - Trimming leading whitespace from statements for more accurate ranges+// - Ignoring single terminator statements+// - Handling statements that don't end with a terminator+func GetANTLRStatementRangesUTF16Position(tokenStream *antlr.CommonTokenStream, eofTokenType, terminatorTokenType int) []Range {+ var ranges []Range+ var buf []antlr.Token+ beginLine, beginUTF16CodePointOffset := 0, 0+ endLine, endUTF16CodePointOffset := 0, 0++ for _, token := range tokenStream.GetAllTokens() {+ if token.GetTokenType() == eofTokenType {+ break+ }+ tokenText := token.GetText()+ for _, r := range tokenText {+ if r == '\n' {+ endLine+++ endUTF16CodePointOffset = 0+ } else {+ if r <= 0xFFFF {+ endUTF16CodePointOffset+++ } else {+ // For non-BMP characters, we count as 2 UTF-16 code units.+ endUTF16CodePointOffset += 2+ }+ }+ }++ // Ignore heading spaces to provide more accurate range.+ if len(buf) == 0 && len(strings.TrimSpace(tokenText)) == 0 {+ beginLine = endLine+ beginUTF16CodePointOffset = endUTF16CodePointOffset+ continue+ }++ buf = append(buf, token)++ // Check if this is a statement terminator.+ if token.GetTokenType() != terminatorTokenType {+ continue+ }+ if len(buf) == 1 {+ // Ignore single terminator statement.+ buf = nil+ continue+ }++ ranges = append(ranges, Range{+ Start: protocol.Position{+ Line: uint32(beginLine),+ Character: uint32(beginUTF16CodePointOffset),+ },+ End: protocol.Position{+ Line: uint32(endLine),+ Character: uint32(endUTF16CodePointOffset),+ },+ })+ buf = nil++ // Set the next begin position to the next token after terminator.+ beginLine = endLine+ beginUTF16CodePointOffset = endUTF16CodePointOffset+ }++ // If there are remaining tokens in the buffer, it means the last statement does not end with terminator.+ if len(buf) > 0 {+ ranges = append(ranges, Range{+ Start: protocol.Position{+ Line: uint32(beginLine),+ Character: uint32(beginUTF16CodePointOffset),+ },+ End: protocol.Position{+ Line: uint32(endLine),+ Character: uint32(endUTF16CodePointOffset),+ },+ })+ }++ return ranges+}++// PrepareANTLRTokenStream is a helper function to prepare an ANTLR token stream from a statement.+// It trims trailing whitespace and creates the necessary lexer and token stream.+//+// Parameters:+// - statement: The SQL statement to process+// - createLexer: A function that creates an ANTLR lexer from an input stream+//+// Returns:+// - A filled CommonTokenStream ready for processing+func PrepareANTLRTokenStream(statement string, createLexer func(antlr.CharStream) antlr.Lexer) *antlr.CommonTokenStream {+ trimmedStatement := strings.TrimRightFunc(statement, unicode.IsSpace)+ inputStream := antlr.NewInputStream(trimmedStatement)+ lexer := createLexer(inputStream)+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)+ stream.Fill()+ return stream+}diff --git a/backend/plugin/parser/doris/statement_ranges.go b/backend/plugin/parser/doris/statement_ranges.gonew file mode 100644index 0000000000..68d2d69a81--- /dev/null+++ b/backend/plugin/parser/doris/statement_ranges.go@@ -0,0 +1,27 @@+package doris++import (+ "context"++ "github.com/antlr4-go/antlr/v4"++ "github.com/bytebase/bytebase/backend/plugin/parser/base"++ parser "github.com/bytebase/doris-parser"++ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++func init() {+ base.RegisterStatementRangesFunc(storepb.Engine_DORIS, GetStatementRanges)+ base.RegisterStatementRangesFunc(storepb.Engine_STARROCKS, GetStatementRanges)+}++func GetStatementRanges(_ context.Context, _ base.StatementRangeContext, statement string) ([]base.Range, error) {+ createLexer := func(input antlr.CharStream) antlr.Lexer {+ return parser.NewDorisSQLLexer(input)+ }+ stream := base.PrepareANTLRTokenStream(statement, createLexer)+ ranges := base.GetANTLRStatementRangesUTF16Position(stream, parser.DorisSQLParserEOF, parser.DorisSQLParserSEMICOLON)+ return ranges, nil+}diff --git a/backend/plugin/parser/doris/statement_ranges_test.go b/backend/plugin/parser/doris/statement_ranges_test.gonew file mode 100644index 0000000000..471da1c3f2--- /dev/null+++ b/backend/plugin/parser/doris/statement_ranges_test.go@@ -0,0 +1,63 @@+package doris++import (+ "context"+ "io"+ "os"+ "path"+ "testing"++ "github.com/stretchr/testify/require"+ "gopkg.in/yaml.v3"++ "github.com/bytebase/bytebase/backend/plugin/parser/base"+)++func TestGetStatementRange(t *testing.T) {+ type testCase struct {+ Statement string `yaml:"statement,omitempty"`+ Expected []base.Range `yaml:"ranges,omitempty"`+ }++ const (+ record = false+ testDataDir = "test-data/statement-ranges"+ )+ a := require.New(t)++ // Recursively find all YAML files in the testDataDir+ entries, err := os.ReadDir(testDataDir)+ a.NoError(err)+ for _, entry := range entries {+ if entry.IsDir() {+ continue+ }+ filepath := path.Join(testDataDir, entry.Name())+ yamlFile, err := os.Open(filepath)+ a.NoError(err)+ var testCases []testCase+ byteValue, err := io.ReadAll(yamlFile)+ a.NoError(err)+ a.NoError(yamlFile.Close())+ a.NoError(yaml.Unmarshal(byteValue, &testCases))+ for i, tc := range testCases {+ if tc.Statement == "" {+ continue+ }+ ranges, err := GetStatementRanges(context.TODO(), base.StatementRangeContext{}, tc.Statement)+ a.NoError(err)+ if record {+ testCases[i].Expected = ranges+ } else {+ a.Equal(tc.Expected, ranges, "statement: %s", tc.Statement)+ }+ }++ if record {+ yamlData, err := yaml.Marshal(testCases)+ a.NoError(err)+ err = os.WriteFile(filepath, yamlData, 0644)+ a.NoError(err)+ }+ }+}diff --git a/backend/plugin/parser/doris/test-data/statement-ranges/doris-features.yaml b/backend/plugin/parser/doris/test-data/statement-ranges/doris-features.yamlnew file mode 100644index 0000000000..2ffcc99958--- /dev/null+++ b/backend/plugin/parser/doris/test-data/statement-ranges/doris-features.yaml@@ -0,0 +1,162 @@+- statement: |-+ -- External table creation in Doris+ CREATE EXTERNAL TABLE hdfs_table (+ id INT,+ name STRING,+ age INT+ )+ ENGINE=BROKER+ PROPERTIES (+ "broker.name" = "hdfs_broker",+ "path" = "hdfs://namenode:9000/path/to/data",+ "format" = "parquet"+ );++ -- Query external table+ SELECT * FROM hdfs_table WHERE age > 25;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 11+ character: 2+ - start:+ line: 13+ character: 0+ end:+ line: 14+ character: 40+- statement: |-+ -- Doris ROUTINE LOAD for Kafka streaming+ CREATE ROUTINE LOAD example_db.kafka_load_job ON orders+ COLUMNS TERMINATED BY ","+ PROPERTIES+ (+ "desired_concurrent_number"="3",+ "max_batch_interval" = "20",+ "max_batch_rows" = "300000",+ "max_batch_size" = "209715200",+ "strict_mode" = "false"+ )+ FROM KAFKA+ (+ "kafka_broker_list" = "broker1:9092,broker2:9092",+ "kafka_topic" = "order_topic",+ "property.group.id" = "doris_consumer_group",+ "property.kafka_default_offsets" = "OFFSET_BEGINNING"+ );++ -- Show routine load status+ SHOW ROUTINE LOAD FOR kafka_load_job;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 17+ character: 2+ - start:+ line: 19+ character: 0+ end:+ line: 20+ character: 37+- statement: |-+ -- Doris dynamic partition+ CREATE TABLE dynamic_partition_table (+ event_date DATE,+ event_id BIGINT,+ event_type VARCHAR(50)+ )+ PARTITION BY RANGE(event_date)()+ DISTRIBUTED BY HASH(event_id) BUCKETS 10+ PROPERTIES(+ "dynamic_partition.enable" = "true",+ "dynamic_partition.time_unit" = "DAY",+ "dynamic_partition.start" = "-7",+ "dynamic_partition.end" = "3",+ "dynamic_partition.prefix" = "p",+ "dynamic_partition.buckets" = "10"+ );++ -- Cancel decommission backend+ CANCEL DECOMMISSION BACKEND "host:port";+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 15+ character: 2+ - start:+ line: 17+ character: 0+ end:+ line: 18+ character: 40+- statement: "-- Doris OUTFILE export\nSELECT * FROM orders \nINTO OUTFILE \"s3://bucket/export/\"\nFORMAT AS PARQUET\nPROPERTIES(\n \"s3.endpoint\" = \"s3.amazonaws.com\",\n \"s3.access_key\" = \"key\",\n \"s3.secret_key\" = \"secret\",\n \"s3.region\" = \"us-east-1\"\n);\n\n-- Admin commands\nADMIN SHOW REPLICA DISTRIBUTION FROM tbl;\nADMIN REPAIR TABLE tbl;"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 9+ character: 2+ - start:+ line: 11+ character: 0+ end:+ line: 12+ character: 41+ - start:+ line: 13+ character: 0+ end:+ line: 13+ character: 23+- statement: "-- Doris array and struct operations\nCREATE TABLE complex_types (\n id INT,\n tags ARRAY<STRING>,\n info STRUCT<name:STRING, age:INT>\n) DISTRIBUTED BY HASH(id) BUCKETS 10;\n\nSELECT \n id,\n ARRAY_LENGTH(tags) as tag_count,\n info.name as user_name\nFROM complex_types\nWHERE ARRAY_CONTAINS(tags, 'premium');"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 5+ character: 37+ - start:+ line: 7+ character: 0+ end:+ line: 12+ character: 38+- statement: "-- Backup and restore operations\nBACKUP SNAPSHOT example_db.snapshot_1 \nTO `repository_name`\nON (orders, customers)\nPROPERTIES (\"type\" = \"full\");\n\nRESTORE SNAPSHOT example_db.snapshot_1\nFROM `repository_name`\nON (orders, customers);"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 4+ character: 29+ - start:+ line: 6+ character: 0+ end:+ line: 8+ character: 23+- statement: |-+ -- S3 table function+ SELECT * FROM s3(+ "s3.endpoint" = "s3.amazonaws.com",+ "s3.region" = "us-east-1",+ "s3.access_key" = "key",+ "s3.secret_key" = "secret",+ "uri" = "s3://bucket/path/to/file.parquet",+ "format" = "parquet"+ );+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 8+ character: 2diff --git a/backend/plugin/parser/doris/test-data/statement-ranges/standard.yaml b/backend/plugin/parser/doris/test-data/statement-ranges/standard.yamlnew file mode 100644index 0000000000..ef84fc8605--- /dev/null+++ b/backend/plugin/parser/doris/test-data/statement-ranges/standard.yaml@@ -0,0 +1,214 @@+- statement: SELECT * FROM tbl;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 18+- statement: SELECT * FROM tbl; SELECT count(*) FROM tbl;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 18+ - start:+ line: 0+ character: 19+ end:+ line: 0+ character: 44+- statement: |-+ -- Basic Doris queries+ SELECT id, name FROM users WHERE status = 'active';+ INSERT INTO logs (timestamp, message) VALUES (NOW(), 'User login');+ UPDATE settings SET value = 'true' WHERE key = 'enable_feature';+ DELETE FROM temp_data WHERE created_at < '2024-01-01';+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 1+ character: 51+ - start:+ line: 2+ character: 0+ end:+ line: 2+ character: 67+ - start:+ line: 3+ character: 0+ end:+ line: 3+ character: 64+ - start:+ line: 4+ character: 0+ end:+ line: 4+ character: 54+- statement: |-+ -- Doris specific DDL statements+ CREATE TABLE IF NOT EXISTS orders_partition (+ order_id BIGINT,+ order_date DATE,+ customer_id BIGINT,+ amount DECIMAL(10, 2)+ )+ PARTITION BY RANGE(order_date) (+ PARTITION p202301 VALUES LESS THAN ('2023-02-01'),+ PARTITION p202302 VALUES LESS THAN ('2023-03-01')+ )+ DISTRIBUTED BY HASH(order_id) BUCKETS 32+ PROPERTIES (+ "replication_allocation" = "tag.location.default: 3"+ );++ -- Alter table to add rollup+ ALTER TABLE orders_partition ADD ROLLUP rollup_customer (customer_id, order_date, amount);+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 14+ character: 2+ - start:+ line: 16+ character: 0+ end:+ line: 17+ character: 90+- statement: "-- Doris aggregate materialized view\nCREATE MATERIALIZED VIEW orders_mv AS\nSELECT \n customer_id,\n DATE_FORMAT(order_date, '%Y-%m') as order_month,\n SUM(amount) as total_amount,\n COUNT(*) as order_count\nFROM orders_partition\nGROUP BY customer_id, order_month;\n\n-- Refresh materialized view\nREFRESH MATERIALIZED VIEW orders_mv;"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 8+ character: 34+ - start:+ line: 10+ character: 0+ end:+ line: 11+ character: 36+- statement: "-- Complex query with window functions\nWITH monthly_sales AS (\n SELECT \n customer_id,\n DATE_FORMAT(order_date, '%Y-%m') as month,\n SUM(amount) as monthly_total,\n ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY SUM(amount) DESC) as rn\n FROM orders_partition\n WHERE order_date >= '2023-01-01'\n GROUP BY customer_id, month\n)\nSELECT \n customer_id,\n month,\n monthly_total,\n LAG(monthly_total, 1) OVER (PARTITION BY customer_id ORDER BY month) as prev_month_total\nFROM monthly_sales\nWHERE rn <= 3;\n\n-- Load data using stream load syntax comment\n-- curl --location-trusted -u root: -T data.csv -H \"column_separator:,\" http://localhost:8030/api/db/orders/_stream_load;"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 17+ character: 14+ - start:+ line: 19+ character: 0+ end:+ line: 20+ character: 121+- statement: "-- Doris HLL (HyperLogLog) functions\nCREATE TABLE IF NOT EXISTS user_visits (\n date DATE,\n user_id_hll HLL HLL_UNION\n)\nAGGREGATE KEY(date)\nDISTRIBUTED BY HASH(date) BUCKETS 10;\n\nSELECT \n date,\n HLL_CARDINALITY(user_id_hll) as unique_users\nFROM user_visits\nWHERE date >= '2024-01-01';"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 6+ character: 37+ - start:+ line: 8+ character: 0+ end:+ line: 12+ character: 27+- statement: "-- Bitmap index and operations\nCREATE TABLE page_views (\n user_id INT,\n page_id INT,\n visit_time DATETIME,\n INDEX idx_user_bitmap (user_id) USING BITMAP\n) DISTRIBUTED BY HASH(user_id) BUCKETS 10;\n\nSELECT \n page_id,\n BITMAP_COUNT(BITMAP_UNION(TO_BITMAP(user_id))) as unique_visitors\nFROM page_views\nWHERE visit_time >= '2024-01-01 00:00:00'\nGROUP BY page_id;"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 6+ character: 42+ - start:+ line: 8+ character: 0+ end:+ line: 13+ character: 17+- statement: "-- JSON operations in Doris\nCREATE TABLE json_data (\n id INT,\n properties JSON\n) DISTRIBUTED BY HASH(id) BUCKETS 10;\n\nSELECT \n id,\n JSON_EXTRACT(properties, '$.name') as name,\n JSON_EXTRACT(properties, '$.tags[0]') as first_tag\nFROM json_data\nWHERE JSON_EXTRACT(properties, '$.active') = 'true';"+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 4+ character: 37+ - start:+ line: 6+ character: 0+ end:+ line: 11+ character: 52+- statement: |-+ SHOW TABLES;+ SHOW CREATE TABLE orders_partition;+ DESC orders_partition;+ SHOW PARTITIONS FROM orders_partition;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 12+ - start:+ line: 1+ character: 0+ end:+ line: 1+ character: 35+ - start:+ line: 2+ character: 0+ end:+ line: 2+ character: 22+ - start:+ line: 3+ character: 0+ end:+ line: 3+ character: 38+- statement: SELECT * FROM tbl+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 17+- statement: |-+ /* Multi-line comment with semicolon;+ This should be ignored */+ SELECT * FROM users;+ -- Single line comment with semicolon; ignored+ INSERT INTO logs VALUES (1, 'test');+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 2+ character: 20+ - start:+ line: 3+ character: 0+ end:+ line: 4+ character: 36+- statement: ;+- statement: ;;diff --git a/backend/plugin/parser/snowflake/statement_ranges.go b/backend/plugin/parser/snowflake/statement_ranges.goindex c1a5a16b66..90c2edb6d8 100644--- a/backend/plugin/parser/snowflake/statement_ranges.go+++ b/backend/plugin/parser/snowflake/statement_ranges.go@@ -2,14 +2,11 @@ package snowflakeimport ("context"- "strings"- "unicode""github.com/antlr4-go/antlr/v4""github.com/bytebase/bytebase/backend/plugin/parser/base"- protocol "github.com/bytebase/lsp-protocol"parser "github.com/bytebase/snowsql-parser"storepb "github.com/bytebase/bytebase/proto/generated-go/store"@@ -20,89 +17,10 @@ func init() {}func GetStatementRanges(_ context.Context, _ base.StatementRangeContext, statement string) ([]base.Range, error) {- ranges := getSQLStatementRangesUTF16Position(statement)- return ranges, nil-}--func getSQLStatementRangesUTF16Position(statement string) []base.Range {- trimmedStatement := strings.TrimRightFunc(statement, unicode.IsSpace)- inputStream := antlr.NewInputStream(trimmedStatement)- lexer := parser.NewSnowflakeLexer(inputStream)- stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)- stream.Fill()-- var ranges []base.Range- var buf []antlr.Token- beginLine, beginUTF16CodePointOffset := 0, 0- endLine, endUTF16CodePointOffset := 0, 0- for _, token := range stream.GetAllTokens() {- if token.GetTokenType() == parser.SnowflakeParserEOF {- break- }- tokenText := token.GetText()- for _, r := range tokenText {- if r == '\n' {- endLine++- endUTF16CodePointOffset = 0- } else {- if r <= 0xFFFF {- endUTF16CodePointOffset++- } else {- // For non-BMP characters, we count as 2 UTF-16 code units.- endUTF16CodePointOffset += 2- }- }- }-- // Ignore heading spaces to provide more accurate range.- if len(buf) == 0 && len(strings.TrimSpace(tokenText)) == 0 {- beginLine = endLine- beginUTF16CodePointOffset = endUTF16CodePointOffset- continue- }-- buf = append(buf, token)-- // Snowflake parser only uses SEMI as a statement terminator.- if token.GetTokenType() != parser.SnowflakeParserSEMI {- continue- }- if len(buf) == 1 {- // Ignore single SEMI statement.- buf = nil- continue- }-- ranges = append(ranges, base.Range{- Start: protocol.Position{- Line: uint32(beginLine),- Character: uint32(beginUTF16CodePointOffset),- },- End: protocol.Position{- Line: uint32(endLine),- Character: uint32(endUTF16CodePointOffset),- },- })- buf = nil-- // Set the next begin position to the next token after SEMI.- beginLine = endLine- beginUTF16CodePointOffset = endUTF16CodePointOffset- }-- // If there are remaining token in the buffer, it means the last statement does not end with SEMI.- if len(buf) > 0 {- ranges = append(ranges, base.Range{- Start: protocol.Position{- Line: uint32(beginLine),- Character: uint32(beginUTF16CodePointOffset),- },- End: protocol.Position{- Line: uint32(endLine),- Character: uint32(endUTF16CodePointOffset),- },- })+ createLexer := func(input antlr.CharStream) antlr.Lexer {+ return parser.NewSnowflakeLexer(input)}-- return ranges+ stream := base.PrepareANTLRTokenStream(statement, createLexer)+ ranges := base.GetANTLRStatementRangesUTF16Position(stream, parser.SnowflakeParserEOF, parser.SnowflakeParserSEMI)+ return ranges, nil}