Skip to content

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

feat: spanner diagnose (#15029)

h3n4l0cf123469b51
diff --git a/backend/api/lsp/fs_handler.go b/backend/api/lsp/fs_handler.go
index 5ca1211044..7126193856 100644
--- a/backend/api/lsp/fs_handler.go
+++ b/backend/api/lsp/fs_handler.go
@@ -84,7 +84,7 @@ func (h *Handler) handleFileSystemRequest(ctx context.Context, conn *jsonrpc2.Co
}
diagnostics, err := base.Diagnose(ctx, base.DiagnoseContext{}, h.getEngineType(ctx), string(content))
if err != nil {
- slog.Warn("dianose error", log.BBError(err))
+ slog.Warn("diagnose error", log.BBError(err))
}
return conn.Notify(ctx, string(LSPMethodPublishDiagnostics), &lsp.PublishDiagnosticsParams{
URI: uri,
diff --git a/backend/plugin/parser/spanner/dignose.go b/backend/plugin/parser/spanner/dignose.go
new file mode 100644
index 0000000000..c1b7f06dca
--- /dev/null
+++ b/backend/plugin/parser/spanner/dignose.go
@@ -0,0 +1,65 @@
+package spanner
+
+import (
+ "context"
+ "strings"
+ "unicode"
+
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/google-sql-parser"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func init() {
+ base.RegisterDiagnoseFunc(store.Engine_BIGQUERY, Diagnose)
+}
+
+func Diagnose(_ context.Context, _ base.DiagnoseContext, statement string) ([]base.Diagnostic, error) {
+ diagnostics := make([]base.Diagnostic, 0)
+ syntaxError := parseGoogleSQLStatement(statement)
+ if syntaxError != nil {
+ diagnostics = append(diagnostics, base.ConvertSyntaxErrorToDiagnostic(syntaxError))
+ }
+
+ return diagnostics, nil
+}
+
+func parseGoogleSQLStatement(statement string) *base.SyntaxError {
+ trimmedStatement := strings.TrimRightFunc(statement, unicode.IsSpace)
+ if len(trimmedStatement) > 0 && !strings.HasSuffix(trimmedStatement, ";") {
+ // Add a semicolon to the end of the statement to allow users to omit the semicolon
+ // for the last statement in the script.
+ statement += ";"
+ }
+ inputStream := antlr.NewInputStream(statement)
+ lexer := parser.NewGoogleSQLLexer(inputStream)
+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
+
+ p := parser.NewGoogleSQLParser(stream)
+ lexerErrorListener := &base.ParseErrorListener{
+ BaseLine: 0,
+ }
+ lexer.RemoveErrorListeners()
+ lexer.AddErrorListener(lexerErrorListener)
+
+ parserErrorListener := &base.ParseErrorListener{
+ BaseLine: 0,
+ }
+ p.RemoveErrorListeners()
+ p.AddErrorListener(parserErrorListener)
+
+ p.BuildParseTrees = false
+
+ _ = p.Root()
+
+ if lexerErrorListener.Err != nil {
+ return lexerErrorListener.Err
+ }
+
+ if parserErrorListener.Err != nil {
+ return parserErrorListener.Err
+ }
+ return nil
+}