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: statement range for snowflake (#16416)
h3n4l24252b834cbb
diff --git a/backend/plugin/parser/base/interface.go b/backend/plugin/parser/base/interface.goindex 93f6bc2272..a4a8ff38ec 100644--- a/backend/plugin/parser/base/interface.go+++ b/backend/plugin/parser/base/interface.go@@ -170,6 +170,8 @@ func RegisterStatementRangesFunc(engine storepb.Engine, f StatementRangeFunc) {statementRanges[engine] = f}+// GetStatementRanges returns a list of ranges for the statement.+// Start is inclusive and end is exclusive. Character is 0-based UTF-16 code unit offset, Line is 0-based line number.func GetStatementRanges(ctx context.Context, sCtx StatementRangeContext, engine storepb.Engine, statement string) ([]Range, error) {f, ok := statementRanges[engine]if !ok {diff --git a/backend/plugin/parser/snowflake/statement_ranges.go b/backend/plugin/parser/snowflake/statement_ranges.gonew file mode 100644index 0000000000..c1a5a16b66--- /dev/null+++ b/backend/plugin/parser/snowflake/statement_ranges.go@@ -0,0 +1,108 @@+package snowflake++import (+ "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"+)++func init() {+ base.RegisterStatementRangesFunc(storepb.Engine_SNOWFLAKE, GetStatementRanges)+}++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),+ },+ })+ }++ return ranges+}diff --git a/backend/plugin/parser/snowflake/statement_ranges_test.go b/backend/plugin/parser/snowflake/statement_ranges_test.gonew file mode 100644index 0000000000..03bb37f83e--- /dev/null+++ b/backend/plugin/parser/snowflake/statement_ranges_test.go@@ -0,0 +1,63 @@+package snowflake++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/snowflake/test-data/statement-ranges/standard.yaml b/backend/plugin/parser/snowflake/test-data/statement-ranges/standard.yamlnew file mode 100644index 0000000000..ae9b56490d--- /dev/null+++ b/backend/plugin/parser/snowflake/test-data/statement-ranges/standard.yaml@@ -0,0 +1,144 @@+- statement: SELECT * FROM t;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 16+- statement: SELECT * FROM t; SELECT * FROM t;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 16+ - start:+ line: 0+ character: 17+ end:+ line: 0+ character: 33+- statement: |-+ SELECT id, name FROM users WHERE status = 'active'; -- Get active users+ /*+ This is a+ multi-line comment+ with a semicolon; that should be ignored.+ */+ INSERT INTO logs (message) VALUES ('Operation completed successfully.');+ UPDATE products SET price = 100 WHERE category = 'electronics';+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 51+ - start:+ line: 0+ character: 52+ end:+ line: 6+ character: 72+ - start:+ line: 7+ character: 0+ end:+ line: 7+ character: 63+- statement: |-+ SELECT 'User: Smith; ID: 123' AS user_info, "column_with_semicolon;" FROM data_table;+ CREATE OR REPLACE TABLE my_new_table (+ id INT,+ description VARCHAR(255) DEFAULT 'No description provided; please update.'+ );+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 0+ character: 85+ - start:+ line: 1+ character: 0+ end:+ line: 4+ character: 2+- statement: |-+ CREATE OR REPLACE FUNCTION my_udf(x NUMBER)+ RETURNS NUMBER+ LANGUAGE JAVASCRIPT+ AS+ $$+ var result = x * 2;+ // This is a JavaScript comment; it contains a semicolon.+ return result;+ $$;++ SELECT my_udf(10) AS result;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 8+ character: 3+ - start:+ line: 10+ character: 0+ end:+ line: 10+ character: 28+- statement: |-+ -- A complex query+ SELECT+ c.customer_name,+ o.order_id,+ SUM(li.quantity * li.price) AS total_amount,+ 'Order processed; Check details.' AS status_msg -- A string with semicolon+ FROM+ customers c+ JOIN+ orders o ON c.customer_id = o.customer_id+ JOIN+ order_items li ON o.order_id = li.order_id+ GROUP BY+ c.customer_name, o.order_id+ HAVING+ total_amount > 1000; /* End of a query */++ -- Another statement+ GRANT SELECT ON ALL TABLES IN SCHEMA public TO ROLE reporter_role;++ CREATE PROCEDURE my_proc()+ RETURNS VARCHAR+ LANGUAGE SQL+ AS+ $$+ BEGIN+ INSERT INTO audit_log (event_type, event_details) VALUES ('Procedure call', 'my_proc executed;');+ RETURN 'Success; Procedure finished.';+ END;+ $$;+ ranges:+ - start:+ line: 0+ character: 0+ end:+ line: 15+ character: 22+ - start:+ line: 15+ character: 23+ end:+ line: 18+ character: 66+ - start:+ line: 20+ character: 0+ end:+ line: 29+ character: 3