Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: introduce diagnose interface (#13683)
h3n4l8233e9744bf2
diff --git a/backend/api/lsp/fs_handler.go b/backend/api/lsp/fs_handler.goindex af15f76d8a..e65a2638e7 100644--- a/backend/api/lsp/fs_handler.go+++ b/backend/api/lsp/fs_handler.go@@ -4,18 +4,16 @@ import ("bytes""context""encoding/json"+ "log/slog""os"- "github.com/antlr4-go/antlr/v4""github.com/pkg/errors""github.com/sourcegraph/go-lsp""github.com/sourcegraph/jsonrpc2"- parser "github.com/bytebase/mysql-parser"-"github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/plugin/parser/base"- "github.com/bytebase/bytebase/proto/generated-go/store")// GetFS returns the file system.@@ -81,14 +79,16 @@ func (h *Handler) handleFileSystemRequest(ctx context.Context, conn *jsonrpc2.Coreturn err}// Beta: Parse and send diagnostics for MySQL.- if h.profile.Mode == common.ReleaseModeDev && h.getEngineType(ctx) == store.Engine_MYSQL {+ if h.profile.Mode == common.ReleaseModeDev {uri := params.TextDocument.URIcontent, found := fs.get(uri)if !found {return &os.PathError{Op: "Open", Path: string(uri), Err: os.ErrNotExist}}- err := parseMySQLStatement(string(content))- diagnostics := collectDiagnostics(err)+ diagnostics, err := base.Diagnose(ctx, base.DiagnoseContext{}, h.getEngineType(ctx), string(content))+ if err != nil {+ slog.Warn("dianose error", log.BBError(err))+ }if err := conn.Notify(ctx, string(LSPMethodPublishDiagnostics), &lsp.PublishDiagnosticsParams{URI: uri,Diagnostics: diagnostics,@@ -118,63 +118,3 @@ func (h *Handler) handleFileSystemRequest(ctx context.Context, conn *jsonrpc2.Coreturn "", false, errors.Errorf("unknown file system request method: %q", req.Method)}}--func parseMySQLStatement(statement string) *base.SyntaxError {- inputStream := antlr.NewInputStream(statement)- lexer := parser.NewMySQLLexer(inputStream)- stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)-- p := parser.NewMySQLParser(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.Script()-- if lexerErrorListener.Err != nil {- return lexerErrorListener.Err- }-- if parserErrorListener.Err != nil {- return parserErrorListener.Err- }- return nil-}--func collectDiagnostics(err *base.SyntaxError) []lsp.Diagnostic {- if err == nil {- return []lsp.Diagnostic{}- }- syntaxDiagnostic := lsp.Diagnostic{- Range: lsp.Range{- Start: lsp.Position{- // Convert to zero-based.- Line: err.Line - 1,- Character: err.Column,- },- End: lsp.Position{- // Convert to zero-based.- Line: err.Line - 1,- // The end position is exclusive.- Character: err.Column + 1,- },- },- Severity: lsp.Error,- Source: "Syntax check",- // Use RawMessage which created by antlr runtime, do not need our fine-tuned message- // because we had indicated the error position in the message.- Message: err.RawMessage,- }-- return []lsp.Diagnostic{syntaxDiagnostic}-}diff --git a/backend/plugin/parser/base/diagnose.go b/backend/plugin/parser/base/diagnose.gonew file mode 100644index 0000000000..5efb75c369--- /dev/null+++ b/backend/plugin/parser/base/diagnose.go@@ -0,0 +1,32 @@+package base++import "github.com/sourcegraph/go-lsp"++// DiagnosticContext is the context for diagnosing SQL statements.+type DiagnoseContext struct {+}++type Diagnostic = lsp.Diagnostic++func ConvertSyntaxErrorToDiagnostic(err *SyntaxError) Diagnostic {+ return Diagnostic{+ Range: lsp.Range{+ Start: lsp.Position{+ // Convert to zero-based.+ Line: err.Line - 1,+ Character: err.Column,+ },+ End: lsp.Position{+ // Convert to zero-based.+ Line: err.Line - 1,+ // The end position is exclusive.+ Character: err.Column + 1,+ },+ },+ Severity: lsp.Error,+ Source: "Syntax check",+ // Use RawMessage which created by antlr runtime, do not need our fine-tuned message+ // because we had indicated the error position in the message.+ Message: err.RawMessage,+ }+}diff --git a/backend/plugin/parser/base/interface.go b/backend/plugin/parser/base/interface.goindex 36666ab173..622a98cba2 100644--- a/backend/plugin/parser/base/interface.go+++ b/backend/plugin/parser/base/interface.go@@ -21,6 +21,7 @@ var (splitters = make(map[storepb.Engine]SplitMultiSQLFunc)schemaDiffers = make(map[storepb.Engine]SchemaDiffFunc)completers = make(map[storepb.Engine]CompletionFunc)+ diagnoseCollectors = make(map[storepb.Engine]DiagnoseFunc)spans = make(map[storepb.Engine]GetQuerySpanFunc)transformDMLToSelect = make(map[storepb.Engine]TransformDMLToSelectFunc)generateRestoreSQL = make(map[storepb.Engine]GenerateRestoreSQLFunc)@@ -32,6 +33,7 @@ type ExtractResourceListFunc func(string, string, string) ([]SchemaResource, errtype SplitMultiSQLFunc func(string) ([]SingleSQL, error)type SchemaDiffFunc func(ctx DiffContext, oldStmt, newStmt string) (string, error)type CompletionFunc func(ctx context.Context, cCtx CompletionContext, statement string, caretLine int, caretOffset int) ([]Candidate, error)+type DiagnoseFunc func(ctx context.Context, dCtx DiagnoseContext, statement string) ([]Diagnostic, error)// GetQuerySpanFunc is the interface of getting the query span for a query.type GetQuerySpanFunc func(ctx context.Context, gCtx GetQuerySpanContext, statement, database, schema string, ignoreCaseSensitive bool) (*QuerySpan, error)@@ -153,6 +155,25 @@ func Completion(ctx context.Context, engine storepb.Engine, cCtx CompletionContereturn f(ctx, cCtx, statement, caretLine, caretOffset)}+// RegisterDiagnoseFunc registers the diagnose function for the engine.+func RegisterDiagnoseFunc(engine storepb.Engine, f DiagnoseFunc) {+ mux.Lock()+ defer mux.Unlock()+ if _, dup := diagnoseCollectors[engine]; dup {+ panic(fmt.Sprintf("Register called twice %s", engine))+ }+ diagnoseCollectors[engine] = f+}++// Diagnose returns the diagnostics for the statement. The diagnostics never be nil, and may not be empty although the error is not nil.+func Diagnose(ctx context.Context, dCtx DiagnoseContext, engine storepb.Engine, statement string) ([]Diagnostic, error) {+ f, ok := diagnoseCollectors[engine]+ if !ok {+ return []Diagnostic{}, nil+ }+ return f(ctx, dCtx, statement)+}+func RegisterGetQuerySpan(engine storepb.Engine, f GetQuerySpanFunc) {mux.Lock()defer mux.Unlock()diff --git a/backend/plugin/parser/mysql/diagnose.go b/backend/plugin/parser/mysql/diagnose.gonew file mode 100644index 0000000000..6c8830f880--- /dev/null+++ b/backend/plugin/parser/mysql/diagnose.go@@ -0,0 +1,63 @@+package mysql++import (+ "context"++ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/mysql-parser"++ "github.com/bytebase/bytebase/backend/plugin/parser/base"+ "github.com/bytebase/bytebase/proto/generated-go/store"+)++func init() {+ base.RegisterDiagnoseFunc(store.Engine_MYSQL, Diagnose)+ base.RegisterDiagnoseFunc(store.Engine_MARIADB, Diagnose)+ base.RegisterDiagnoseFunc(store.Engine_TIDB, Diagnose)+ base.RegisterDiagnoseFunc(store.Engine_OCEANBASE, Diagnose)+ base.RegisterDiagnoseFunc(store.Engine_CLICKHOUSE, Diagnose)+ base.RegisterDiagnoseFunc(store.Engine_STARROCKS, Diagnose)+ base.RegisterDiagnoseFunc(store.Engine_DORIS, Diagnose)+}++func Diagnose(_ context.Context, _ base.DiagnoseContext, statement string) ([]base.Diagnostic, error) {+ diagnostics := make([]base.Diagnostic, 0)+ syntaxError := parseMySQLStatement(statement)+ if syntaxError != nil {+ diagnostics = append(diagnostics, base.ConvertSyntaxErrorToDiagnostic(syntaxError))+ }++ return diagnostics, nil+}++func parseMySQLStatement(statement string) *base.SyntaxError {+ inputStream := antlr.NewInputStream(statement)+ lexer := parser.NewMySQLLexer(inputStream)+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)++ p := parser.NewMySQLParser(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.Script()++ if lexerErrorListener.Err != nil {+ return lexerErrorListener.Err+ }++ if parserErrorListener.Err != nil {+ return parserErrorListener.Err+ }+ return nil+}