Skip to content

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

refactor(advisor/mssql): migrate all advisor rules from ANTLR to omni AST [BYT-9012] (#19942)

rebelicec5d9b20cf609
diff --git a/backend/plugin/advisor/mssql/advisor.go b/backend/plugin/advisor/mssql/advisor.go
index c60d6c05ea..fc295add4c 100644
--- a/backend/plugin/advisor/mssql/advisor.go
+++ b/backend/plugin/advisor/mssql/advisor.go
@@ -1,11 +1,2 @@
// Package mssql is the advisor for MSSQL database.
package mssql
-
-// currentConstraintAction is the action of current constraint.
-type currentConstraintAction int
-
-const (
- currentConstraintActionNone currentConstraintAction = iota
- currentConstraintActionAdd
- currentConstraintActionDrop
-)
diff --git a/backend/plugin/advisor/mssql/generic_checker.go b/backend/plugin/advisor/mssql/generic_checker.go
deleted file mode 100644
index 0e12abf8e9..0000000000
--- a/backend/plugin/advisor/mssql/generic_checker.go
+++ /dev/null
@@ -1,167 +0,0 @@
-package mssql
-
-import (
- "fmt"
- "reflect"
- "strings"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
-
- storepb "github.com/bytebase/bytebase/backend/generated-go/store"
-)
-
-// Node type constants for consistent node type checking
-const (
- NodeTypeCreateTable = "Create_table"
- NodeTypeAlterTable = "Alter_table"
- NodeTypeDropTable = "Drop_table"
- NodeTypeCreateIndex = "Create_index"
- NodeTypeDropIndex = "Drop_index"
- NodeTypeInsertStatement = "Insert_statement"
- NodeTypeUpdateStatement = "Update_statement"
- NodeTypeDeleteStatement = "Delete_statement"
- NodeTypeSelectStatement = "Select_statement"
- NodeTypeCreateView = "Create_view"
- NodeTypeDropView = "Drop_view"
- NodeTypeCreateProcedure = "Create_procedure"
- NodeTypeDropProcedure = "Drop_procedure"
- NodeTypeCreateFunction = "Create_function"
- NodeTypeDropFunction = "Drop_function"
- NodeTypeCreateDatabase = "Create_database"
- NodeTypeAlterDatabase = "Alter_database"
- NodeTypeDropDatabase = "Drop_database"
- NodeTypeTruncateTable = "Truncate_table"
- NodeTypeColumnDefinition = "Column_definition"
- NodeTypeColumnDefinitionElement = "Column_definition_element"
- NodeTypeTableConstraint = "Table_constraint"
- NodeTypeSearchCondition = "Search_condition"
- NodeTypeSelectListElem = "Select_list_elem"
- NodeTypeTableConstraintElement = "Table_constraint_element"
- NodeTypeDdlStatement = "Ddl_statement"
- NodeTypeDmlStatement = "Dml_statement"
- NodeTypeAnothStatement = "Another_statement"
- NodeTypeCreateOrAlterProcedure = "Create_or_alter_procedure"
- NodeTypeCreateOrAlterFunction = "Create_or_alter_function"
- NodeTypeTableValueConstructor = "Table_value_constructor"
- NodeTypeExpressionElem = "Expression_elem"
- NodeTypeTableNameWithHint = "Table_name_with_hint"
- NodeTypeTableName = "Table_name"
- NodeTypeSimpleID = "Simple_id"
- NodeTypeID = "Id_"
- NodeTypeKeyword = "Keyword"
- NodeTypeFullColumnNameList = "Full_column_name_list"
- NodeTypeColumnElemList = "Column_elem_list"
- NodeTypeCreateType = "Create_type"
- NodeTypePrimaryKeyOptions = "Primary_key_options"
- NodeTypeForeignKeyOptions = "Foreign_key_options"
- NodeTypeTableConstraintPrimaryKey = "Pk"
- NodeTypeTableConstraintForeignKey = "Fk"
- NodeTypeCommonTableExpression = "Common_table_expression"
- NodeTypeWithExpression = "With_expression"
-)
-
-// Rule defines the interface for individual SQL validation rules.
-// Each rule implements specific checking logic without embedding the base listener.
-type Rule interface {
- // OnEnter is called when entering a parse tree node
- OnEnter(ctx antlr.ParserRuleContext, nodeType string) error
-
- // OnExit is called when exiting a parse tree node
- OnExit(ctx antlr.ParserRuleContext, nodeType string) error
-
- // Name returns the rule name for logging/debugging
- Name() string
-
- // GetAdviceList returns the accumulated advice from this rule
- GetAdviceList() []*storepb.Advice
-}
-
-// GenericChecker embeds the base TSQL parser listener and dispatches events to registered rules.
-// This design ensures only one copy of the listener type metadata in the binary.
-type GenericChecker struct {
- *parser.BaseTSqlParserListener
-
- rules []Rule
-}
-
-// NewGenericChecker creates a new instance of GenericChecker with the given rules.
-func NewGenericChecker(rules []Rule) *GenericChecker {
- return &GenericChecker{
- rules: rules,
- }
-}
-
-// EnterEveryRule is called when any rule is entered.
-// It dispatches the event to all registered rules.
-func (g *GenericChecker) EnterEveryRule(ctx antlr.ParserRuleContext) {
- nodeType := g.getNodeType(ctx)
- for _, rule := range g.rules {
- if err := rule.OnEnter(ctx, nodeType); err != nil {
- // Log error if needed
- fmt.Printf("Rule %s error on enter %s: %v\n", rule.Name(), nodeType, err)
- }
- }
-}
-
-// ExitEveryRule is called when any rule is exited.
-// It dispatches the event to all registered rules.
-func (g *GenericChecker) ExitEveryRule(ctx antlr.ParserRuleContext) {
- nodeType := g.getNodeType(ctx)
- for _, rule := range g.rules {
- if err := rule.OnExit(ctx, nodeType); err != nil {
- // Log error if needed
- fmt.Printf("Rule %s error on exit %s: %v\n", rule.Name(), nodeType, err)
- }
- }
-}
-
-// GetAdviceList collects and returns all advice from registered rules.
-func (g *GenericChecker) GetAdviceList() []*storepb.Advice {
- var allAdvice []*storepb.Advice
- for _, rule := range g.rules {
- allAdvice = append(allAdvice, rule.GetAdviceList()...)
- }
- return allAdvice
-}
-
-// getNodeType returns the type name of the parse tree node.
-func (*GenericChecker) getNodeType(ctx antlr.ParserRuleContext) string {
- t := reflect.TypeOf(ctx)
- if t.Kind() == reflect.Ptr {
- t = t.Elem()
- }
- name := t.Name()
- // Remove "Context" suffix if present
- name = strings.TrimSuffix(name, "Context")
- return name
-}
-
-// BaseRule provides common functionality for rules.
-// Other rules can embed this struct to get common behavior.
-type BaseRule struct {
- level storepb.Advice_Status
- title string
- adviceList []*storepb.Advice
- baseLine int
-}
-
-// GetAdviceList returns the accumulated advice.
-func (r *BaseRule) GetAdviceList() []*storepb.Advice {
- return r.adviceList
-}
-
-// AddAdvice adds a new advice to the list.
-// It automatically adjusts the StartPosition by adding the baseLine offset.
-func (r *BaseRule) AddAdvice(advice *storepb.Advice) {
- // Adjust the line number by adding baseLine offset
- if advice.StartPosition != nil && r.baseLine > 0 {
- advice.StartPosition.Line += int32(r.baseLine)
- }
- r.adviceList = append(r.adviceList, advice)
-}
-
-// SetBaseLine sets the base line number for multi-statement SQL.
-func (r *BaseRule) SetBaseLine(baseLine int) {
- r.baseLine = baseLine
-}
diff --git a/backend/plugin/advisor/mssql/generic_checker_omni.go b/backend/plugin/advisor/mssql/generic_checker_omni.go
new file mode 100644
index 0000000000..2e9f8f048f
--- /dev/null
+++ b/backend/plugin/advisor/mssql/generic_checker_omni.go
@@ -0,0 +1,146 @@
+package mssql
+
+import (
+ "strings"
+
+ "github.com/bytebase/omni/mssql/ast"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+)
+
+// OmniRule defines the interface for omni-based SQL validation rules.
+type OmniRule interface {
+ // OnStatement is called for each top-level statement AST node.
+ OnStatement(node ast.Node)
+
+ // Name returns the rule name for logging/debugging.
+ Name() string
+
+ // GetAdviceList returns the accumulated advice from this rule.
+ GetAdviceList() []*storepb.Advice
+}
+
+// OmniBaseRule provides common functionality for omni-based rules.
+type OmniBaseRule struct {
+ Level storepb.Advice_Status
+ Title string
+ Advice []*storepb.Advice
+ BaseLine int
+ StmtText string
+}
+
+// SetStatement sets the statement context for position calculations.
+func (r *OmniBaseRule) SetStatement(baseLine int, stmtText string) {
+ r.BaseLine = baseLine
+ r.StmtText = stmtText
+}
+
+// GetAdviceList returns the accumulated advice.
+func (r *OmniBaseRule) GetAdviceList() []*storepb.Advice {
+ return r.Advice
+}
+
+// AddAdvice adds advice. The BaseLine offset is added automatically to StartPosition.Line.
+func (r *OmniBaseRule) AddAdvice(advice *storepb.Advice) {
+ if advice.StartPosition != nil {
+ advice.StartPosition.Line += int32(r.BaseLine)
+ }
+ r.Advice = append(r.Advice, advice)
+}
+
+// AddAdviceAbsolute adds advice with an already-absolute line number.
+func (r *OmniBaseRule) AddAdviceAbsolute(advice *storepb.Advice) {
+ r.Advice = append(r.Advice, advice)
+}
+
+// LocToLine converts an omni Loc byte offset to a 1-based line number
+// relative to the current statement (suitable for AddAdvice which adds BaseLine).
+func (r *OmniBaseRule) LocToLine(loc ast.Loc) int32 {
+ if loc.Start < 0 || r.StmtText == "" {
+ return r.ContentStartLine()
+ }
+ pos := tsqlparser.ByteOffsetToRunePosition(r.StmtText, loc.Start)
+ return pos.Line
+}
+
+// ContentStartLine returns the 1-based line number of the first non-whitespace
+// character in StmtText. Returns 1 if the text is empty or has no leading newlines.
+func (r *OmniBaseRule) ContentStartLine() int32 {
+ idx := strings.IndexFunc(r.StmtText, func(c rune) bool {
+ return c != ' ' && c != '\t' && c != '\n' && c != '\r'
+ })
+ if idx <= 0 {
+ return 1
+ }
+ pos := tsqlparser.ByteOffsetToRunePosition(r.StmtText, idx)
+ return pos.Line
+}
+
+// ContentEndLine returns the 1-based line number of the last non-whitespace
+// character in StmtText.
+func (r *OmniBaseRule) ContentEndLine() int32 {
+ if r.StmtText == "" {
+ return 1
+ }
+ idx := -1
+ for i := len(r.StmtText) - 1; i >= 0; i-- {
+ c := r.StmtText[i]
+ if c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != ';' {
+ idx = i
+ break
+ }
+ }
+ if idx <= 0 {
+ return 1
+ }
+ pos := tsqlparser.ByteOffsetToRunePosition(r.StmtText, idx)
+ return pos.Line
+}
+
+// TrimmedStmtText returns the statement text with leading/trailing whitespace
+// and trailing semicolons removed.
+func (r *OmniBaseRule) TrimmedStmtText() string {
+ return strings.TrimRight(strings.TrimSpace(r.StmtText), ";")
+}
+
+// FindLineByName searches for an identifier name in the statement text and returns
+// its 1-based line number. Falls back to ContentStartLine() if not found.
+func (r *OmniBaseRule) FindLineByName(name string) int32 {
+ if name == "" || r.StmtText == "" {
+ return r.ContentStartLine()
+ }
+ idx := strings.Index(r.StmtText, name)
+ if idx < 0 {
+ return r.ContentStartLine()
+ }
+ pos := tsqlparser.ByteOffsetToRunePosition(r.StmtText, idx)
+ return pos.Line
+}
+
+// RunOmniRules iterates over parsed statements and dispatches each omni AST node to all rules.
+// Returns combined advice from all rules. Skips statements without omni AST.
+func RunOmniRules(stmts []base.ParsedStatement, rules []OmniRule) []*storepb.Advice {
+ for _, stmt := range stmts {
+ if stmt.AST == nil {
+ continue
+ }
+ node, ok := tsqlparser.GetOmniNode(stmt.AST)
+ if !ok {
+ continue
+ }
+ baseLine := stmt.BaseLine()
+ for _, rule := range rules {
+ if br, ok := rule.(interface{ SetStatement(int, string) }); ok {
+ br.SetStatement(baseLine, stmt.Text)
+ }
+ rule.OnStatement(node)
+ }
+ }
+ var allAdvice []*storepb.Advice
+ for _, rule := range rules {
+ allAdvice = append(allAdvice, rule.GetAdviceList()...)
+ }
+ return allAdvice
+}
diff --git a/backend/plugin/advisor/mssql/rule_builtin_prior_backup_check.go b/backend/plugin/advisor/mssql/rule_builtin_prior_backup_check.go
index cb341f24ad..98219c21f6 100644
--- a/backend/plugin/advisor/mssql/rule_builtin_prior_backup_check.go
+++ b/backend/plugin/advisor/mssql/rule_builtin_prior_backup_check.go
@@ -6,6 +6,7 @@ import (
"log/slog"
"github.com/antlr4-go/antlr/v4"
+ "github.com/bytebase/omni/mssql/ast"
parser "github.com/bytebase/parser/tsql"
"github.com/bytebase/bytebase/backend/common"
@@ -51,7 +52,7 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx context.Context, checkCtx adv
Title: title,
Content: fmt.Sprintf("The size of statements in the sheet exceeds the limit of %d", common.MaxSheetCheckSize),
Code: code.BuiltinPriorBackupCheck.Int32(),
- StartPosition: common.ConvertANTLRLineToPosition(1),
+ StartPosition: &storepb.Position{Line: 1},
})
}
@@ -62,33 +63,24 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx context.Context, checkCtx adv
Title: title,
Content: fmt.Sprintf("Need database %q to do prior backup but it does not exist", databaseName),
Code: code.DatabaseNotExists.Int32(),
- StartPosition: common.ConvertANTLRLineToPosition(1),
+ StartPosition: &storepb.Position{Line: 1},
})
return adviceList, nil
}
- // Use the refactored rule for DDL/DML checking
- rule := NewStatementDisallowMixDMLRule(level, title)
- checker := NewGenericChecker([]Rule{rule})
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ // Use omni rule for DDL detection.
+ ddlRule := &statementDisallowMixDMLOmniRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: title},
}
+ RunOmniRules(checkCtx.ParsedStatements, []OmniRule{ddlRule})
- if rule.hasDDL {
+ if ddlRule.hasDDL {
adviceList = append(adviceList, &storepb.Advice{
Status: level,
Title: title,
Content: "Prior backup cannot deal with mixed DDL and DML statements",
Code: int32(code.BuiltinPriorBackupCheck),
- StartPosition: common.ConvertANTLRLineToPosition(1),
+ StartPosition: &storepb.Position{Line: 1},
})
}
@@ -113,7 +105,7 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx context.Context, checkCtx adv
Title: title,
Content: fmt.Sprintf("The statement type is not the same for all statements on the same table %q", key),
Code: code.BuiltinPriorBackupCheck.Int32(),
- StartPosition: common.ConvertANTLRLineToPosition(1),
+ StartPosition: &storepb.Position{Line: 1},
})
break
}
@@ -123,63 +115,41 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx context.Context, checkCtx adv
return adviceList, nil
}
-// StatementDisallowMixDMLRule is the rule for checking mixed DDL and DML statements.
-type StatementDisallowMixDMLRule struct {
- BaseRule
- updateStatements []*parser.Update_statementContext
- deleteStatements []*parser.Delete_statementContext
- hasDDL bool
+// statementDisallowMixDMLOmniRule uses omni AST to detect DDL statements.
+type statementDisallowMixDMLOmniRule struct {
+ OmniBaseRule
+ hasDDL bool
}
-// NewStatementDisallowMixDMLRule creates a new StatementDisallowMixDMLRule.
-func NewStatementDisallowMixDMLRule(level storepb.Advice_Status, title string) *StatementDisallowMixDMLRule {
- return &StatementDisallowMixDMLRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
+func (*statementDisallowMixDMLOmniRule) Name() string {
+ return "StatementDisallowMixDMLOmniRule"
}
-// Name returns the rule name.
-func (*StatementDisallowMixDMLRule) Name() string {
- return "StatementDisallowMixDMLRule"
-}
-
-// OnEnter is called when entering a parse tree node.
-func (r *StatementDisallowMixDMLRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case "Ddl_clause":
- r.enterDDLClause(ctx.(*parser.Ddl_clauseContext))
- case NodeTypeUpdateStatement:
- r.enterUpdateStatement(ctx.(*parser.Update_statementContext))
- case NodeTypeDeleteStatement:
- r.enterDeleteStatement(ctx.(*parser.Delete_statementContext))
- default:
- // Ignore other node types
+func (r *statementDisallowMixDMLOmniRule) OnStatement(node ast.Node) {
+ if r.hasDDL {
+ return
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*StatementDisallowMixDMLRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *StatementDisallowMixDMLRule) enterDDLClause(_ *parser.Ddl_clauseContext) {
- r.hasDDL = true
-}
-
-func (r *StatementDisallowMixDMLRule) enterUpdateStatement(ctx *parser.Update_statementContext) {
- if tsqlparser.IsTopLevel(ctx.GetParent()) {
- r.updateStatements = append(r.updateStatements, ctx)
- }
-}
-
-func (r *StatementDisallowMixDMLRule) enterDeleteStatement(ctx *parser.Delete_statementContext) {
- if tsqlparser.IsTopLevel(ctx.GetParent()) {
- r.deleteStatements = append(r.deleteStatements, ctx)
+ switch node.(type) {
+ case *ast.CreateTableStmt,
+ *ast.AlterTableStmt,
+ *ast.DropStmt,
+ *ast.TruncateStmt,
+ *ast.CreateIndexStmt,
+ *ast.CreateViewStmt,
+ *ast.CreateFunctionStmt,
+ *ast.CreateProcedureStmt,
+ *ast.CreateSchemaStmt,
+ *ast.CreateDatabaseStmt,
+ *ast.CreateTriggerStmt,
+ *ast.CreateTypeStmt,
+ *ast.CreateSequenceStmt,
+ *ast.AlterIndexStmt,
+ *ast.AlterSchemaStmt,
+ *ast.AlterDatabaseStmt,
+ *ast.AlterSequenceStmt,
+ *ast.RenameStmt:
+ r.hasDDL = true
+ default:
}
}
diff --git a/backend/plugin/advisor/mssql/rule_column_maximum_varchar_length.go b/backend/plugin/advisor/mssql/rule_column_maximum_varchar_length.go
index c0d3b8cdee..894c8bf623 100644
--- a/backend/plugin/advisor/mssql/rule_column_maximum_varchar_length.go
+++ b/backend/plugin/advisor/mssql/rule_column_maximum_varchar_length.go
@@ -3,23 +3,15 @@ package mssql
import (
"context"
"fmt"
- "log/slog"
"math"
- "strconv"
+ "strings"
+ "github.com/bytebase/omni/mssql/ast"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
-
- "github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/common/log"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
var (
@@ -49,103 +41,64 @@ func (*ColumnMaximumVarcharLengthAdvisor) Check(_ context.Context, checkCtx advi
return nil, nil
}
- // Create the rule
- rule := NewColumnMaximumVarcharLengthRule(level, checkCtx.Rule.Type.String(), int(numberPayload.Number))
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &columnMaximumVarcharLengthRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ maximum: int(numberPayload.Number),
+ checkTypeString: map[string]bool{
+ "varchar": true,
+ "nvarchar": true,
+ "char": true,
+ "nchar": true,
+ },
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// ColumnMaximumVarcharLengthRule checks for maximum varchar length.
-type ColumnMaximumVarcharLengthRule struct {
- BaseRule
-
- checkTypeString map[string]any
+type columnMaximumVarcharLengthRule struct {
+ OmniBaseRule
+ checkTypeString map[string]bool
maximum int
}
-// NewColumnMaximumVarcharLengthRule creates a new ColumnMaximumVarcharLengthRule.
-func NewColumnMaximumVarcharLengthRule(level storepb.Advice_Status, title string, maximum int) *ColumnMaximumVarcharLengthRule {
- return &ColumnMaximumVarcharLengthRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- checkTypeString: map[string]any{
- "varchar": nil,
- "nvarchar": nil,
- "char": nil,
- "nchar": nil,
- },
- maximum: maximum,
- }
-}
-
-// Name returns the rule name.
-func (*ColumnMaximumVarcharLengthRule) Name() string {
+func (*columnMaximumVarcharLengthRule) Name() string {
return "ColumnMaximumVarcharLengthRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *ColumnMaximumVarcharLengthRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == "Data_type" {
- r.enterDataType(ctx.(*parser.Data_typeContext))
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*ColumnMaximumVarcharLengthRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
+func (r *columnMaximumVarcharLengthRule) OnStatement(node ast.Node) {
+ seen := make(map[*ast.DataType]bool)
+ ast.Inspect(node, func(n ast.Node) bool {
+ dt, ok := n.(*ast.DataType)
+ if !ok || dt == nil {
+ return true
+ }
+ if seen[dt] {
+ return true
+ }
+ seen[dt] = true
-func (r *ColumnMaximumVarcharLengthRule) enterDataType(ctx *parser.Data_typeContext) {
- currentLength := 0
- line := ctx.GetStart().GetLine()
- if ctx.MAX() != nil && (ctx.VARCHAR() != nil || ctx.NVARCHAR() != nil) {
- // https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-types-transact-sql?view=sql-server-ver16&redirectedfrom=MSDN
- currentLength = math.MaxInt32 // 2 ^ 31 - 1
- line = ctx.MAX().GetSymbol().GetLine()
- } else if ctx.GetExt_type() != nil && ctx.GetScale() != nil && ctx.GetPrec() == nil && ctx.GetInc() == nil {
- _, normalizedTypeString := tsqlparser.NormalizeTSQLIdentifier(ctx.GetExt_type())
- if _, ok := r.checkTypeString[normalizedTypeString]; !ok {
- return
+ normalizedType := strings.ToLower(dt.Name)
+ if !r.checkTypeString[normalizedType] {
+ return true
}
- length, err := strconv.Atoi(ctx.GetScale().GetText())
- if err != nil {
- slog.Error("failed to convert scale to int", log.BBError(err))
+
+ currentLength := 0
+ if dt.MaxLength {
+ currentLength = math.MaxInt32
+ } else if dt.Length != nil {
+ if lit, ok := dt.Length.(*ast.Literal); ok {
+ currentLength = int(lit.Ival)
+ }
}
- currentLength = length
- line = ctx.GetScale().GetLine()
- } else if ctx.GetUnscaled_type() != nil {
- _, normalizedTypeString := tsqlparser.NormalizeTSQLIdentifier(ctx.GetUnscaled_type())
- if _, ok := r.checkTypeString[normalizedTypeString]; !ok {
- return
+
+ if currentLength > r.maximum {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.VarcharLengthExceedsLimit.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("The maximum varchar length is %d.", r.maximum),
+ StartPosition: &storepb.Position{Line: r.LocToLine(dt.Loc)},
+ })
}
- line = ctx.GetUnscaled_type().GetStart().GetLine()
- }
- if currentLength > r.maximum {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.VarcharLengthExceedsLimit.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("The maximum varchar length is %d.", r.maximum),
- StartPosition: common.ConvertANTLRLineToPosition(line),
- })
- }
+ return true
+ })
}
diff --git a/backend/plugin/advisor/mssql/rule_column_no_null.go b/backend/plugin/advisor/mssql/rule_column_no_null.go
index 39ccf34c3c..f230b50305 100644
--- a/backend/plugin/advisor/mssql/rule_column_no_null.go
+++ b/backend/plugin/advisor/mssql/rule_column_no_null.go
@@ -3,16 +3,13 @@ package mssql
import (
"context"
"fmt"
+ "strings"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
)
var (
@@ -34,180 +31,113 @@ func (*ColumnNoNullAdvisor) Check(_ context.Context, checkCtx advisor.Context) (
return nil, err
}
- // Create the rule
- rule := NewColumnNoNullRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &columnNoNullOmniRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
}
-
- return checker.GetAdviceList(), nil
-}
-
-// ColumnNoNullRule checks for column no NULL value.
-type ColumnNoNullRule struct {
- BaseRule
-
- // currentNormalizedTableName is the normalized table name of the current table.
- currentNormalizedTableName string
- // isCurrentTableColumnNullable is the map of column name to whether the column is nullable.
- isCurrentTableColumnNullable map[string]bool
- // currentTableColumnIsNullableLine is the map of column name to the line number of the column definition.
- currentTableColumnIsNullableLine map[string]int
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// NewColumnNoNullRule creates a new ColumnNoNullRule.
-func NewColumnNoNullRule(level storepb.Advice_Status, title string) *ColumnNoNullRule {
- return &ColumnNoNullRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- isCurrentTableColumnNullable: make(map[string]bool),
- currentTableColumnIsNullableLine: make(map[string]int),
- }
+type columnNoNullOmniRule struct {
+ OmniBaseRule
}
-// Name returns the rule name.
-func (*ColumnNoNullRule) Name() string {
- return "ColumnNoNullRule"
+func (*columnNoNullOmniRule) Name() string {
+ return "ColumnNoNullOmniRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *ColumnNoNullRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
- case NodeTypeTableConstraint:
- r.enterTableConstraint(ctx.(*parser.Table_constraintContext))
- case NodeTypeColumnDefinition:
- r.enterColumnDefinition(ctx.(*parser.Column_definitionContext))
- case NodeTypeAlterTable:
- r.enterAlterTable(ctx.(*parser.Alter_tableContext))
+func (r *columnNoNullOmniRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.CreateTableStmt:
+ r.handleCreateTable(n)
+ case *ast.AlterTableStmt:
+ r.handleAlterTable(n)
default:
}
- return nil
}
-// OnExit is called when exiting a parse tree node.
-func (r *ColumnNoNullRule) OnExit(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.exitCreateTable(ctx.(*parser.Create_tableContext))
- case NodeTypeAlterTable:
- r.exitAlterTable(ctx.(*parser.Alter_tableContext))
- default:
+func (r *columnNoNullOmniRule) handleCreateTable(n *ast.CreateTableStmt) {
+ if n.Name == nil {
+ return
}
- return nil
-}
-func (r *ColumnNoNullRule) enterCreateTable(ctx *parser.Create_tableContext) {
- tableName := ctx.Table_name()
- if tableName == nil {
- return
+ // Collect columns that are part of table-level PK constraints.
+ pkColumns := make(map[string]bool)
+ if n.Constraints != nil {
+ for _, item := range n.Constraints.Items {
+ cd, ok := item.(*ast.ConstraintDef)
+ if !ok {
+ continue
+ }
+ if cd.Type == ast.ConstraintPrimaryKey && cd.Columns != nil {
+ for _, colItem := range cd.Columns.Items {
+ if ic, ok := colItem.(*ast.IndexColumn); ok {
+ pkColumns[strings.ToLower(ic.Name)] = true
+ }
+ }
+ }
+ }
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
- r.currentNormalizedTableName = normalizedTableName
-}
-func (r *ColumnNoNullRule) exitCreateTable(_ *parser.Create_tableContext) {
- r.currentNormalizedTableName = ""
- for columnName, isNullable := range r.isCurrentTableColumnNullable {
- if !isNullable {
+ if n.Columns == nil {
+ return
+ }
+ for _, item := range n.Columns.Items {
+ col, ok := item.(*ast.ColumnDef)
+ if !ok {
continue
}
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.ColumnCannotNull.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Column [%s] is nullable, which is not allowed.", columnName),
- StartPosition: common.ConvertANTLRLineToPosition(r.currentTableColumnIsNullableLine[columnName]),
- })
+ r.checkColumnDef(col, pkColumns)
}
-
- r.isCurrentTableColumnNullable = make(map[string]bool)
- r.currentTableColumnIsNullableLine = make(map[string]int)
}
-func (r *ColumnNoNullRule) enterTableConstraint(ctx *parser.Table_constraintContext) {
- parent := ctx.GetParent()
- switch parent.(type) {
- case *parser.Column_def_table_constraintContext:
- default:
+func (r *columnNoNullOmniRule) handleAlterTable(n *ast.AlterTableStmt) {
+ if n.Actions == nil {
return
}
- if ctx.PRIMARY() != nil {
- allColumns := ctx.Column_name_list_with_order().AllColumn_name_with_order()
- for _, column := range allColumns {
- _, columnName := tsqlparser.NormalizeTSQLIdentifier(column.Id_())
- r.isCurrentTableColumnNullable[columnName] = false
+ for _, item := range n.Actions.Items {
+ action, ok := item.(*ast.AlterTableAction)
+ if !ok {
+ continue
+ }
+ if action.Type != ast.ATAddColumn && action.Type != ast.ATAlterColumn {
+ continue
+ }
+ if action.Column != nil {
+ r.checkColumnDef(action.Column, nil)
}
}
}
-func (r *ColumnNoNullRule) enterColumnDefinition(ctx *parser.Column_definitionContext) {
- parent := ctx.GetParent()
- switch parent.(type) {
- case *parser.Alter_tableContext:
- case *parser.Column_def_table_constraintContext:
- default:
+func (r *columnNoNullOmniRule) checkColumnDef(col *ast.ColumnDef, pkColumns map[string]bool) {
+ // If column is in table-level PK, it's implicitly NOT NULL.
+ if pkColumns != nil && pkColumns[strings.ToLower(col.Name)] {
return
}
- _, columnName := tsqlparser.NormalizeTSQLIdentifier(ctx.Id_())
- r.isCurrentTableColumnNullable[columnName] = true
- r.currentTableColumnIsNullableLine[columnName] = ctx.Id_().GetStart().GetLine()
- allColumnDefinitionElements := ctx.AllColumn_definition_element()
- for _, columnDefinitionElement := range allColumnDefinitionElements {
- if v := columnDefinitionElement.Column_constraint(); v != nil {
- if v.PRIMARY() != nil {
- r.isCurrentTableColumnNullable[columnName] = false
- break
+
+ // Check column-level constraints for PK or NOT NULL.
+ if col.Constraints != nil {
+ for _, cItem := range col.Constraints.Items {
+ cd, ok := cItem.(*ast.ConstraintDef)
+ if !ok {
+ continue
}
- if (v.Null_notnull() != nil && v.Null_notnull().NOT() != nil) || v.Null_notnull() == nil {
- r.isCurrentTableColumnNullable[columnName] = false
- break
+ if cd.Type == ast.ConstraintPrimaryKey || cd.Type == ast.ConstraintNotNull {
+ return
}
}
}
-}
-func (r *ColumnNoNullRule) enterAlterTable(ctx *parser.Alter_tableContext) {
- tableName := ctx.Table_name(0)
- if tableName == nil {
+ // Check the Nullable spec.
+ if col.Nullable != nil && col.Nullable.NotNull {
return
}
- if (len(ctx.AllALTER()) == 2 && ctx.COLUMN() != nil) /* ALTER COLUMN */ || (len(ctx.AllALTER()) == 1 && ctx.ADD() != nil && ctx.WITH() == nil) /* ALTER */ {
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
- r.currentNormalizedTableName = normalizedTableName
- }
-}
-
-func (r *ColumnNoNullRule) exitAlterTable(_ *parser.Alter_tableContext) {
- r.currentNormalizedTableName = ""
- for columnName, isNullable := range r.isCurrentTableColumnNullable {
- if !isNullable {
- continue
- }
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.ColumnCannotNull.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Column [%s] is nullable, which is not allowed.", columnName),
- StartPosition: common.ConvertANTLRLineToPosition(r.currentTableColumnIsNullableLine[columnName]),
- })
- }
- r.isCurrentTableColumnNullable = make(map[string]bool)
- r.currentTableColumnIsNullableLine = make(map[string]int)
+ // Column is nullable.
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.ColumnCannotNull.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Column [%s] is nullable, which is not allowed.", strings.ToLower(col.Name)),
+ StartPosition: &storepb.Position{Line: r.LocToLine(col.Loc)},
+ })
}
diff --git a/backend/plugin/advisor/mssql/rule_column_require.go b/backend/plugin/advisor/mssql/rule_column_require.go
index 4313c7d9c5..1c8a3a3015 100644
--- a/backend/plugin/advisor/mssql/rule_column_require.go
+++ b/backend/plugin/advisor/mssql/rule_column_require.go
@@ -4,19 +4,15 @@ import (
"context"
"fmt"
"slices"
+ "strings"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
var (
@@ -43,158 +39,110 @@ func (*ColumnRequireAdvisor) Check(_ context.Context, checkCtx advisor.Context)
return nil, errors.New("string_array_payload is required for column required rule")
}
- // Create the rule
- rule := NewColumnRequireRule(level, checkCtx.Rule.Type.String(), stringArrayPayload.List)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &columnRequireOmniRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ requireColumns: make(map[string]any),
+ }
+ for _, col := range stringArrayPayload.List {
+ rule.requireColumns[col] = true
}
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// ColumnRequireRule checks for column requirement.
-type ColumnRequireRule struct {
- BaseRule
+type columnRequireOmniRule struct {
+ OmniBaseRule
- // requireColumns is the required columns, the key is the normalized column name.
requireColumns map[string]any
-
- // The following variables should be clean up when ENTER some statement.
- //
- // currentMissingColumn is the missing column, the key is the normalized column name.
- currentMissingColumn map[string]any
- // currentOriginalTableName is the original table name, should be reset when QUIT some statement.
- currentOriginalTableName string
}
-// NewColumnRequireRule creates a new ColumnRequireRule.
-func NewColumnRequireRule(level storepb.Advice_Status, title string, columnList []string) *ColumnRequireRule {
- requireColumns := make(map[string]any)
- for _, column := range columnList {
- requireColumns[column] = true
- }
-
- return &ColumnRequireRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- requireColumns: requireColumns,
- }
-}
-
-// Name returns the rule name.
-func (*ColumnRequireRule) Name() string {
- return "ColumnRequireRule"
+func (*columnRequireOmniRule) Name() string {
+ return "ColumnRequireOmniRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *ColumnRequireRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
- case NodeTypeColumnDefinition:
- r.enterColumnDefinition(ctx.(*parser.Column_definitionContext))
- case NodeTypeAlterTable:
- r.enterAlterTable(ctx.(*parser.Alter_tableContext))
+func (r *columnRequireOmniRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.CreateTableStmt:
+ r.handleCreateTable(n)
+ case *ast.AlterTableStmt:
+ r.handleAlterTable(n)
default:
- // Ignore other node types
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (r *ColumnRequireRule) OnExit(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeCreateTable {
- r.exitCreateTable(ctx.(*parser.Create_tableContext))
- }
- return nil
-}
-
-func (r *ColumnRequireRule) enterCreateTable(ctx *parser.Create_tableContext) {
- r.currentOriginalTableName = ctx.Table_name().GetText()
- r.currentMissingColumn = make(map[string]any)
- for column := range r.requireColumns {
- r.currentMissingColumn[column] = true
}
}
-func (r *ColumnRequireRule) enterColumnDefinition(ctx *parser.Column_definitionContext) {
- if r.currentOriginalTableName == "" {
+func (r *columnRequireOmniRule) handleCreateTable(n *ast.CreateTableStmt) {
+ if n.Name == nil {
return
}
- normalizedColumnName := normalizeMSSQLIdentifier(ctx.Id_())
- delete(r.currentMissingColumn, normalizedColumnName)
-}
-
-func (r *ColumnRequireRule) exitCreateTable(ctx *parser.Create_tableContext) {
- defer func() {
- r.currentOriginalTableName = ""
- r.currentMissingColumn = nil
- }()
-
- if r.currentOriginalTableName == "" {
- return
+ // Build set of columns present.
+ present := make(map[string]bool)
+ if n.Columns != nil {
+ for _, item := range n.Columns.Items {
+ col, ok := item.(*ast.ColumnDef)
+ if !ok {
+ continue
+ }
+ present[strings.ToLower(col.Name)] = true
+ }
}
- if len(r.currentMissingColumn) > 0 {
- missingColumns := []string{}
- for column := range r.currentMissingColumn {
- missingColumns = append(missingColumns, column)
- }
- slices.Sort(missingColumns)
-
- // Generate individual advisor messages for each missing column
- for _, column := range missingColumns {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.NoRequiredColumn.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Table %s missing required column \"%s\"", r.currentOriginalTableName, column),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
+ // Find missing required columns.
+ var missing []string
+ for col := range r.requireColumns {
+ if !present[strings.ToLower(col)] {
+ missing = append(missing, col)
}
}
+ slices.Sort(missing)
+
+ tableName := tableRefText(n.Name)
+ for _, col := range missing {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.NoRequiredColumn.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Table %s missing required column \"%s\"", tableName, col),
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
+ }
}
-func (r *ColumnRequireRule) enterAlterTable(ctx *parser.Alter_tableContext) {
- if ctx.DROP() == nil || ctx.COLUMN() == nil {
+func (r *columnRequireOmniRule) handleAlterTable(n *ast.AlterTableStmt) {
+ if n.Name == nil || n.Actions == nil {
return
}
- tableName := ctx.Table_name(0).GetText()
- allColumnNames := ctx.AllId_()
- for _, columnName := range allColumnNames {
- _, normalizedColumnName := tsqlparser.NormalizeTSQLIdentifier(columnName)
- if _, ok := r.requireColumns[normalizedColumnName]; ok {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.NoRequiredColumn.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Table %s missing required column \"%s\"", tableName, normalizedColumnName),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
+ tableName := tableRefText(n.Name)
+ for _, item := range n.Actions.Items {
+ action, ok := item.(*ast.AlterTableAction)
+ if !ok {
+ continue
+ }
+ if action.Type == ast.ATDropColumn {
+ // Collect all dropped column names from both ColName and Names list.
+ var colNames []string
+ if action.ColName != "" {
+ colNames = append(colNames, strings.ToLower(action.ColName))
+ }
+ if action.Names != nil {
+ for _, nameItem := range action.Names.Items {
+ if ref, ok := nameItem.(*ast.TableRef); ok && ref.Object != "" {
+ colNames = append(colNames, strings.ToLower(ref.Object))
+ }
+ }
+ }
+ for _, colName := range colNames {
+ if _, ok := r.requireColumns[colName]; ok {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.NoRequiredColumn.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Table %s missing required column \"%s\"", tableName, colName),
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
+ }
+ }
}
}
}
-
-func normalizeMSSQLIdentifier(idCtx parser.IId_Context) string {
- if idCtx == nil {
- return ""
- }
- _, name := tsqlparser.NormalizeTSQLIdentifier(idCtx)
- return name
-}
diff --git a/backend/plugin/advisor/mssql/rule_column_type_disallow_list.go b/backend/plugin/advisor/mssql/rule_column_type_disallow_list.go
index 29e09ee2b2..22ff7c2316 100644
--- a/backend/plugin/advisor/mssql/rule_column_type_disallow_list.go
+++ b/backend/plugin/advisor/mssql/rule_column_type_disallow_list.go
@@ -5,17 +5,12 @@ import (
"slices"
"strings"
+ "github.com/bytebase/omni/mssql/ast"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
-
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
var (
@@ -40,77 +35,43 @@ func (*ColumnTypeDisallowListAdvisor) Check(_ context.Context, checkCtx advisor.
return nil, errors.New("string_array_payload is required for column type disallow list rule")
}
- disallowTypes := []string{}
+ disallowTypes := make([]string, 0, len(stringArrayPayload.List))
for _, tp := range stringArrayPayload.List {
disallowTypes = append(disallowTypes, strings.ToUpper(tp))
}
- // Create the rule
- rule := NewColumnTypeDisallowListRule(level, checkCtx.Rule.Type.String(), disallowTypes)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &columnTypeDisallowListRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ disallowTypes: disallowTypes,
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// ColumnTypeDisallowListRule is the rule for column disallow types.
-type ColumnTypeDisallowListRule struct {
- BaseRule
+type columnTypeDisallowListRule struct {
+ OmniBaseRule
disallowTypes []string
}
-// NewColumnTypeDisallowListRule creates a new ColumnTypeDisallowListRule.
-func NewColumnTypeDisallowListRule(level storepb.Advice_Status, title string, disallowTypes []string) *ColumnTypeDisallowListRule {
- return &ColumnTypeDisallowListRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- disallowTypes: disallowTypes,
- }
-}
-
-// Name returns the rule name.
-func (*ColumnTypeDisallowListRule) Name() string {
+func (*columnTypeDisallowListRule) Name() string {
return "ColumnTypeDisallowListRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *ColumnTypeDisallowListRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == "Data_type" {
- r.enterDataType(ctx.(*parser.Data_typeContext))
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*ColumnTypeDisallowListRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *ColumnTypeDisallowListRule) enterDataType(ctx *parser.Data_typeContext) {
- formatedDataType := strings.ToUpper(ctx.GetText())
- if slices.Contains(r.disallowTypes, formatedDataType) {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.DisabledColumnType.Int32(),
- Title: r.title,
- Content: "Column type " + formatedDataType + " is disallowed",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
- }
+func (r *columnTypeDisallowListRule) OnStatement(node ast.Node) {
+ ast.Inspect(node, func(n ast.Node) bool {
+ dt, ok := n.(*ast.DataType)
+ if !ok || dt == nil {
+ return true
+ }
+ formattedDataType := strings.ToUpper(dt.Name)
+ if slices.Contains(r.disallowTypes, formattedDataType) {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.DisabledColumnType.Int32(),
+ Title: r.Title,
+ Content: "Column type " + formattedDataType + " is disallowed",
+ StartPosition: &storepb.Position{Line: r.LocToLine(dt.Loc)},
+ })
+ }
+ return true
+ })
}
diff --git a/backend/plugin/advisor/mssql/rule_function_disallow_create_or_alter.go b/backend/plugin/advisor/mssql/rule_function_disallow_create_or_alter.go
index 85d0df92bc..db0f567512 100644
--- a/backend/plugin/advisor/mssql/rule_function_disallow_create_or_alter.go
+++ b/backend/plugin/advisor/mssql/rule_function_disallow_create_or_alter.go
@@ -3,14 +3,11 @@ package mssql
import (
"context"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
)
func init() {
@@ -19,74 +16,31 @@ func init() {
type FunctionDisallowCreateOrAlterAdvisor struct{}
-// Check implements advisor.Advisor.
func (*FunctionDisallowCreateOrAlterAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
if err != nil {
return nil, err
}
-
- // Create the rule
- rule := NewFunctionDisallowCreateOrAlterRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
- }
-
- return checker.GetAdviceList(), nil
-}
-
-// FunctionDisallowCreateOrAlterRule is the rule for disallowing function creation or alteration.
-type FunctionDisallowCreateOrAlterRule struct {
- BaseRule
+ rule := &functionDisallowCreateOrAlterRule{OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()}}
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// NewFunctionDisallowCreateOrAlterRule creates a new FunctionDisallowCreateOrAlterRule.
-func NewFunctionDisallowCreateOrAlterRule(level storepb.Advice_Status, title string) *FunctionDisallowCreateOrAlterRule {
- return &FunctionDisallowCreateOrAlterRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
+type functionDisallowCreateOrAlterRule struct {
+ OmniBaseRule
}
-// Name returns the rule name.
-func (*FunctionDisallowCreateOrAlterRule) Name() string {
+func (*functionDisallowCreateOrAlterRule) Name() string {
return "FunctionDisallowCreateOrAlterRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *FunctionDisallowCreateOrAlterRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeCreateOrAlterFunction {
- r.enterCreateOrAlterFunction(ctx.(*parser.Create_or_alter_functionContext))
+func (r *functionDisallowCreateOrAlterRule) OnStatement(node ast.Node) {
+ if n, ok := node.(*ast.CreateFunctionStmt); ok {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.DisallowCreateFunction.Int32(),
+ Title: r.Title,
+ Content: "Creating or altering functions is prohibited",
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*FunctionDisallowCreateOrAlterRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *FunctionDisallowCreateOrAlterRule) enterCreateOrAlterFunction(ctx *parser.Create_or_alter_functionContext) {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.DisallowCreateFunction.Int32(),
- Title: r.title,
- Content: "Creating or altering functions is prohibited",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
}
diff --git a/backend/plugin/advisor/mssql/rule_index_not_redundant.go b/backend/plugin/advisor/mssql/rule_index_not_redundant.go
index cdeb48adf2..7aa5c83d93 100644
--- a/backend/plugin/advisor/mssql/rule_index_not_redundant.go
+++ b/backend/plugin/advisor/mssql/rule_index_not_redundant.go
@@ -3,18 +3,13 @@ package mssql
import (
"context"
"fmt"
+ "strings"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
-
- "github.com/bytebase/bytebase/backend/common"
- "github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
func init() {
@@ -36,88 +31,46 @@ func (IndexNotRedundantAdvisor) Check(_ context.Context, checkCtx advisor.Contex
return nil, err
}
- // Create the rule
- rule := NewIndexNotRedundantRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, checkCtx.DBSchema)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &indexNotRedundantRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ curDB: checkCtx.CurrentDatabase,
+ indexMap: getIndexMapFromMetadata(checkCtx.DBSchema),
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// IndexNotRedundantRule checks for redundant indexes.
-type IndexNotRedundantRule struct {
- BaseRule
+type indexNotRedundantRule struct {
+ OmniBaseRule
curDB string
indexMap *IndexMap
}
-// NewIndexNotRedundantRule creates a new IndexNotRedundantRule.
-func NewIndexNotRedundantRule(level storepb.Advice_Status, title string, currentDB string, dbMetadata *storepb.DatabaseSchemaMetadata) *IndexNotRedundantRule {
- return &IndexNotRedundantRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- curDB: currentDB,
- indexMap: getIndexMapFromMetadata(dbMetadata),
- }
-}
-
-// Name returns the rule name.
-func (*IndexNotRedundantRule) Name() string {
+func (*indexNotRedundantRule) Name() string {
return "IndexNotRedundantRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *IndexNotRedundantRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeCreateIndex {
- r.enterCreateIndex(ctx.(*parser.Create_indexContext))
+func (r *indexNotRedundantRule) OnStatement(node ast.Node) {
+ ci, ok := node.(*ast.CreateIndexStmt)
+ if !ok {
+ return
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*IndexNotRedundantRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-func (r *IndexNotRedundantRule) enterCreateIndex(ctx *parser.Create_indexContext) {
idxSchemaName := dftMSSQLSchemaName
idxTblName := ""
- // Get full table name.
- if fullTblName := ctx.Table_name(); fullTblName != nil {
+ if ci.Table != nil {
// TODO(zp): we only check indexes in the current database due to the lack of necessary metadata.
- // Case sensitive!
- if database := fullTblName.GetDatabase(); database != nil {
- if oriName, _ := tsqlparser.NormalizeTSQLIdentifier(database); oriName != r.curDB {
- return
- }
+ if ci.Table.Database != "" && !strings.EqualFold(ci.Table.Database, r.curDB) {
+ return
}
- if schema := fullTblName.GetSchema(); schema != nil {
- idxSchemaName, _ = tsqlparser.NormalizeTSQLIdentifier(schema)
+ if ci.Table.Schema != "" {
+ idxSchemaName = ci.Table.Schema
}
- idxTblName, _ = tsqlparser.NormalizeTSQLIdentifier(fullTblName.GetTable())
+ idxTblName = ci.Table.Object
}
- // Get index name from statement.
- statIdxName, _ := tsqlparser.NormalizeTSQLIdentifier(ctx.AllId_()[0])
+ statIdxName := ci.Name
- // Get ordered index list from metadata.
findIdxKey := FindIndexesKey{
schemaName: idxSchemaName,
tblName: idxTblName,
@@ -127,17 +80,30 @@ func (r *IndexNotRedundantRule) enterCreateIndex(ctx *parser.Create_indexContext
return
}
- // Get ordered column list from statement.
- statIdxColList := ctx.Column_name_list_with_order()
- if metaIdxName := containRedundantPrefix(metaIdxList, &statIdxColList); metaIdxName != "" {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Title: r.title,
- Code: code.RedundantIndex.Int32(),
- Content: fmt.Sprintf("Redundant indexes with the same prefix ('%s' and '%s') in '%s.%s' is not allowed",
- metaIdxName, statIdxName, findIdxKey.schemaName, findIdxKey.tblName),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
+ // Get the first column from the statement's index column list.
+ if ci.Columns == nil || ci.Columns.Len() == 0 {
+ return
+ }
+ firstCol := ""
+ if idxCol, ok := ci.Columns.Items[0].(*ast.IndexColumn); ok && idxCol != nil {
+ firstCol = idxCol.Name
+ }
+ if firstCol == "" {
+ return
+ }
+
+ for _, metaIndex := range metaIdxList {
+ if len(metaIndex.Expressions) > 0 && metaIndex.Expressions[0] == firstCol {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Title: r.Title,
+ Code: code.RedundantIndex.Int32(),
+ Content: fmt.Sprintf("Redundant indexes with the same prefix ('%s' and '%s') in '%s.%s' is not allowed",
+ metaIndex.Name, statIdxName, findIdxKey.schemaName, findIdxKey.tblName),
+ StartPosition: &storepb.Position{Line: r.LocToLine(ci.Loc)},
+ })
+ return
+ }
}
}
@@ -149,19 +115,6 @@ type FindIndexesKey struct {
// The value in the map represents the column list of a certain index.
type IndexMap = map[FindIndexesKey][]*storepb.IndexMetadata
-// Return the name of the index if redundant prefixes are found.
-func containRedundantPrefix(metaIdxList []*storepb.IndexMetadata, statColumnList *parser.IColumn_name_list_with_orderContext) string {
- for _, metaIndex := range metaIdxList {
- if statColumnList != nil && len((*statColumnList).AllColumn_name_with_order()) != 0 && len(metaIdxList) != 0 {
- statIdxCol, _ := tsqlparser.NormalizeTSQLIdentifier((*statColumnList).AllColumn_name_with_order()[0].Id_())
- if metaIndex.Expressions[0] == statIdxCol {
- return metaIndex.Name
- }
- }
- }
- return ""
-}
-
func getIndexMapFromMetadata(dbMetadata *storepb.DatabaseSchemaMetadata) *IndexMap {
indexMap := IndexMap{}
if dbMetadata == nil {
diff --git a/backend/plugin/advisor/mssql/rule_migration_compatibility.go b/backend/plugin/advisor/mssql/rule_migration_compatibility.go
index 6d2fdcb341..80457080f8 100644
--- a/backend/plugin/advisor/mssql/rule_migration_compatibility.go
+++ b/backend/plugin/advisor/mssql/rule_migration_compatibility.go
@@ -5,15 +5,11 @@ import (
"fmt"
"strings"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
advisorcode "github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
)
var (
@@ -35,305 +31,306 @@ func (*MigrationCompatibilityAdvisor) Check(_ context.Context, checkCtx advisor.
return nil, err
}
- // Create the rule
- rule := NewMigrationCompatibilityRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &migrationCompatibilityOmniRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ currentDatabase: checkCtx.CurrentDatabase,
+ newTables: make(map[string]any),
+ newSchemas: make(map[string]any),
+ newDatabases: make(map[string]any),
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// MigrationCompatibilityRule is the rule for migration compatibility.
-type MigrationCompatibilityRule struct {
- BaseRule
- // normalizedLastCreateTableNameMap contain the last created table name in normalized format.
- normalizedNewCreateTableNameMap map[string]any
- // normalizedLastCreateSchemaNameMap contain the last created schema name in normalized format.
- normalizedNewCreateSchemaNameMap map[string]any
- // normalizedNewCreateDatabaseNameMap contain the new created database name in normalized format.
- normalizedNewCreateDatabaseNameMap map[string]any
+type migrationCompatibilityOmniRule struct {
+ OmniBaseRule
- // currentDatabase is the current database name.
currentDatabase string
+ newTables map[string]any
+ newSchemas map[string]any
+ newDatabases map[string]any
}
-// NewMigrationCompatibilityRule creates a new MigrationCompatibilityRule.
-func NewMigrationCompatibilityRule(level storepb.Advice_Status, title string, currentDatabase string) *MigrationCompatibilityRule {
- return &MigrationCompatibilityRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- normalizedNewCreateTableNameMap: make(map[string]any),
- normalizedNewCreateSchemaNameMap: make(map[string]any),
- normalizedNewCreateDatabaseNameMap: make(map[string]any),
- currentDatabase: currentDatabase,
- }
-}
-
-// Name returns the rule name.
-func (*MigrationCompatibilityRule) Name() string {
- return "MigrationCompatibilityRule"
+func (*migrationCompatibilityOmniRule) Name() string {
+ return "MigrationCompatibilityOmniRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *MigrationCompatibilityRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
- case "Create_schema":
- r.enterCreateSchema(ctx.(*parser.Create_schemaContext))
- case NodeTypeCreateDatabase:
- r.enterCreateDatabase(ctx.(*parser.Create_databaseContext))
- case NodeTypeDropTable:
- r.enterDropTable(ctx.(*parser.Drop_tableContext))
- case "Drop_schema":
- r.enterDropSchema(ctx.(*parser.Drop_schemaContext))
- case NodeTypeDropDatabase:
- r.enterDropDatabase(ctx.(*parser.Drop_databaseContext))
- case NodeTypeAlterTable:
- r.enterAlterTable(ctx.(*parser.Alter_tableContext))
- case "Execute_body":
- r.enterExecuteBody(ctx.(*parser.Execute_bodyContext))
+func (r *migrationCompatibilityOmniRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.CreateTableStmt:
+ r.handleCreateTable(n)
+ case *ast.CreateSchemaStmt:
+ r.handleCreateSchema(n)
+ case *ast.CreateDatabaseStmt:
+ r.handleCreateDatabase(n)
+ case *ast.DropStmt:
+ r.handleDrop(n)
+ case *ast.AlterTableStmt:
+ r.handleAlterTable(n)
+ case *ast.ExecStmt:
+ r.handleExec(n)
default:
- // Ignore other node types
}
- return nil
}
-// OnExit is called when exiting a parse tree node.
-func (*MigrationCompatibilityRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *MigrationCompatibilityRule) enterCreateTable(ctx *parser.Create_tableContext) {
- tableName := ctx.Table_name()
- if tableName == nil || tableName.GetTable() == nil {
+func (r *migrationCompatibilityOmniRule) handleCreateTable(n *ast.CreateTableStmt) {
+ if n.Name == nil {
return
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, r.currentDatabase, "dbo", false)
- r.normalizedNewCreateTableNameMap[normalizedTableName] = any(nil)
+ norm := normalizeTableRef(n.Name, r.currentDatabase, "dbo")
+ r.newTables[norm] = nil
}
-func (r *MigrationCompatibilityRule) enterCreateSchema(ctx *parser.Create_schemaContext) {
- var schemaName string
- if v := ctx.GetSchema_name(); v != nil {
- _, schemaName = tsqlparser.NormalizeTSQLIdentifier(v)
- } else {
- _, schemaName = tsqlparser.NormalizeTSQLIdentifier(ctx.GetOwner_name())
+func (r *migrationCompatibilityOmniRule) handleCreateSchema(n *ast.CreateSchemaStmt) {
+ schemaName := strings.ToLower(n.Name)
+ if schemaName == "" {
+ schemaName = strings.ToLower(n.Authorization)
}
-
- normalizedDatabaseSchemaName := fmt.Sprintf("%s.%s", r.currentDatabase, schemaName)
- r.normalizedNewCreateSchemaNameMap[normalizedDatabaseSchemaName] = any(nil)
+ norm := fmt.Sprintf("%s.%s", r.currentDatabase, schemaName)
+ r.newSchemas[norm] = nil
}
-func (r *MigrationCompatibilityRule) enterCreateDatabase(ctx *parser.Create_databaseContext) {
- _, databaseName := tsqlparser.NormalizeTSQLIdentifier(ctx.GetDatabase())
- r.normalizedNewCreateDatabaseNameMap[databaseName] = any(nil)
+func (r *migrationCompatibilityOmniRule) handleCreateDatabase(n *ast.CreateDatabaseStmt) {
+ r.newDatabases[strings.ToLower(n.Name)] = nil
}
-func (r *MigrationCompatibilityRule) enterDropTable(ctx *parser.Drop_tableContext) {
- allTableNames := ctx.AllTable_name()
- for _, tableName := range allTableNames {
- if tableName == nil || tableName.GetTable() == nil {
- continue
+func (r *migrationCompatibilityOmniRule) handleDrop(n *ast.DropStmt) {
+ switch n.ObjectType {
+ case ast.DropTable:
+ if n.Names == nil {
+ return
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, r.currentDatabase, "dbo", false)
- if _, ok := r.normalizedNewCreateTableNameMap[normalizedTableName]; !ok {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityDropSchema.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Drop table %s may cause incompatibility with the existing data and code", normalizedTableName),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
+ for _, item := range n.Names.Items {
+ ref, ok := item.(*ast.TableRef)
+ if !ok {
+ continue
+ }
+ norm := normalizeTableRef(ref, r.currentDatabase, "dbo")
+ if _, ok := r.newTables[norm]; !ok {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityDropSchema.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Drop table %s may cause incompatibility with the existing data and code", norm),
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
+ }
+ delete(r.newTables, norm)
}
- delete(r.normalizedNewCreateTableNameMap, normalizedTableName)
- }
-}
-
-func (r *MigrationCompatibilityRule) enterDropSchema(ctx *parser.Drop_schemaContext) {
- schemaName := ctx.GetSchema_name()
- _, normalizedSchemaName := tsqlparser.NormalizeTSQLIdentifier(schemaName)
- normalizedSchemaName = fmt.Sprintf("%s.%s", r.currentDatabase, normalizedSchemaName)
- if _, ok := r.normalizedNewCreateSchemaNameMap[normalizedSchemaName]; !ok {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityDropSchema.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Drop schema %s may cause incompatibility with the existing data and code", normalizedSchemaName),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
+ case ast.DropSchema:
+ if n.Names == nil {
+ return
+ }
+ for _, item := range n.Names.Items {
+ ref, ok := item.(*ast.TableRef)
+ if !ok {
+ continue
+ }
+ schemaName := strings.ToLower(ref.Object)
+ norm := fmt.Sprintf("%s.%s", r.currentDatabase, schemaName)
+ if _, ok := r.newSchemas[norm]; !ok {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityDropSchema.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Drop schema %s may cause incompatibility with the existing data and code", norm),
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
+ }
+ delete(r.newSchemas, norm)
+ }
+ case ast.DropDatabase:
+ if n.Names == nil {
+ return
+ }
+ for _, item := range n.Names.Items {
+ ref, ok := item.(*ast.TableRef)
+ if !ok {
+ continue
+ }
+ dbName := strings.ToLower(ref.Object)
+ if _, ok := r.newDatabases[dbName]; !ok {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityDropSchema.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Drop database %s may cause incompatibility with the existing data and code", dbName),
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
+ }
+ delete(r.newDatabases, dbName)
+ }
+ default:
}
- delete(r.normalizedNewCreateSchemaNameMap, normalizedSchemaName)
}
-func (r *MigrationCompatibilityRule) enterDropDatabase(ctx *parser.Drop_databaseContext) {
- databaseName := ctx.GetDatabase_name_or_database_snapshot_name()
- _, normalizedDatabaseName := tsqlparser.NormalizeTSQLIdentifier(databaseName)
- if _, ok := r.normalizedNewCreateDatabaseNameMap[normalizedDatabaseName]; !ok {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityDropSchema.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Drop database %s may cause incompatibility with the existing data and code", normalizedDatabaseName),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
+func (r *migrationCompatibilityOmniRule) handleAlterTable(n *ast.AlterTableStmt) {
+ if n.Name == nil {
+ return
}
- delete(r.normalizedNewCreateDatabaseNameMap, normalizedDatabaseName)
-}
-
-func (r *MigrationCompatibilityRule) enterAlterTable(ctx *parser.Alter_tableContext) {
- handleTableName := ctx.Table_name(0)
- normalizedHandleTableName := tsqlparser.NormalizeTSQLTableName(handleTableName, r.currentDatabase, "dbo", false)
- if _, ok := r.normalizedNewCreateTableNameMap[normalizedHandleTableName]; ok {
+ norm := normalizeTableRef(n.Name, r.currentDatabase, "dbo")
+ if _, ok := r.newTables[norm]; ok {
return
}
- if ctx.DROP() != nil && ctx.COLUMN() != nil {
- allDropColumns := ctx.AllId_()
- var allNormalizedDropColumnNames []string
- for _, dropColumn := range allDropColumns {
- _, normalizedDropColumnName := tsqlparser.NormalizeTSQLIdentifier(dropColumn)
- allNormalizedDropColumnNames = append(allNormalizedDropColumnNames, normalizedDropColumnName)
- }
- placeholder := strings.Join(allNormalizedDropColumnNames, ", ")
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityDropSchema.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Drop column %s may cause incompatibility with the existing data and code", placeholder),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.COLUMN().GetSymbol().GetLine()),
- })
+ if n.Actions == nil {
return
}
- if len(ctx.AllALTER()) == 2 && ctx.COLUMN() != nil {
- normalizedColumnName := ""
- if ctx.Column_definition() != nil {
- _, normalizedColumnName = tsqlparser.NormalizeTSQLIdentifier(ctx.Column_definition().Id_())
- } else if ctx.Column_modifier() != nil {
- _, normalizedColumnName = tsqlparser.NormalizeTSQLIdentifier(ctx.Column_modifier().Id_())
+ for _, item := range n.Actions.Items {
+ action, ok := item.(*ast.AlterTableAction)
+ if !ok {
+ continue
}
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityAlterColumn.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Alter COLUMN %s may cause incompatibility with the existing data and code", normalizedColumnName),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.COLUMN().GetSymbol().GetLine()),
- })
- return
- }
- if v := ctx.Column_def_table_constraints(); v != nil {
- allColumnDefTableConstraints := v.AllColumn_def_table_constraint()
- for _, columnDefTableConstraint := range allColumnDefTableConstraints {
- code := advisorcode.Ok
- operation := ""
- tableConstraint := columnDefTableConstraint.Table_constraint()
- if tableConstraint == nil {
+ switch action.Type {
+ case ast.ATDropColumn:
+ colName := strings.ToLower(action.ColName)
+ // Also handle multiple column drops via Names list.
+ var colNames []string
+ if colName != "" {
+ colNames = append(colNames, colName)
+ }
+ if action.Names != nil {
+ for _, nameItem := range action.Names.Items {
+ if ref, ok := nameItem.(*ast.TableRef); ok {
+ colNames = append(colNames, strings.ToLower(ref.Object))
+ }
+ }
+ }
+ if len(colNames) > 0 {
+ placeholder := strings.Join(colNames, ", ")
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityDropSchema.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Drop column %s may cause incompatibility with the existing data and code", placeholder),
+ StartPosition: &storepb.Position{Line: r.LocToLine(action.Loc)},
+ })
+ }
+ case ast.ATAlterColumn:
+ colName := ""
+ if action.Column != nil {
+ colName = strings.ToLower(action.Column.Name)
+ } else if action.ColName != "" {
+ colName = strings.ToLower(action.ColName)
+ }
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityAlterColumn.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Alter COLUMN %s may cause incompatibility with the existing data and code", colName),
+ StartPosition: &storepb.Position{Line: r.LocToLine(action.Loc)},
+ })
+ case ast.ATAddConstraint:
+ if action.Constraint == nil {
continue
}
- if tableConstraint.PRIMARY() != nil {
- code = advisorcode.CompatibilityAddPrimaryKey
- operation = "Add PRIMARY KEY"
+ // WITH NOCHECK variant — the omni parser may use ATAddConstraint
+ // with WithCheck="NOCHECK" instead of ATNocheckConstraint.
+ if strings.EqualFold(action.WithCheck, "NOCHECK") {
+ switch action.Constraint.Type {
+ case ast.ConstraintForeignKey:
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityAddForeignKey.Int32(),
+ Title: r.Title,
+ Content: "Add FOREIGN KEY WITH NO CHECK may cause incompatibility with the existing data and code",
+ StartPosition: &storepb.Position{Line: r.LocToLine(action.Loc)},
+ })
+ case ast.ConstraintCheck:
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityAddForeignKey.Int32(),
+ Title: r.Title,
+ Content: "Add CHECK WITH NO CHECK may cause incompatibility with the existing data and code",
+ StartPosition: &storepb.Position{Line: r.LocToLine(action.Loc)},
+ })
+ default:
+ }
+ continue
}
- if tableConstraint.UNIQUE() != nil {
- code = advisorcode.CompatibilityAddUniqueKey
- operation = "Add UNIQUE KEY"
+ // WITH CHECK ADD is safe — skip it.
+ if strings.EqualFold(action.WithCheck, "CHECK") {
+ continue
}
- if tableConstraint.Check_constraint() != nil {
- code = advisorcode.CompatibilityAddCheck
+ c := advisorcode.Ok
+ operation := ""
+ switch action.Constraint.Type {
+ case ast.ConstraintPrimaryKey:
+ c = advisorcode.CompatibilityAddPrimaryKey
+ operation = "Add PRIMARY KEY"
+ case ast.ConstraintUnique:
+ c = advisorcode.CompatibilityAddUniqueKey
+ operation = "Add UNIQUE KEY"
+ case ast.ConstraintCheck:
+ c = advisorcode.CompatibilityAddCheck
operation = "Add CHECK"
+ case ast.ConstraintForeignKey:
+ c = advisorcode.CompatibilityAddForeignKey
+ operation = "Add FOREIGN KEY"
+ default:
+ continue
}
r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.Int32(),
- Title: r.title,
+ Status: r.Level,
+ Code: c.Int32(),
+ Title: r.Title,
Content: fmt.Sprintf("%s may cause incompatibility with the existing data and code", operation),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
})
- }
- return
- }
- if ctx.WITH() != nil && ctx.NOCHECK() != nil {
- if ctx.FOREIGN() != nil {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityAddForeignKey.Int32(),
- Title: r.title,
- Content: "Add FOREIGN KEY WITH NO CHECK may cause incompatibility with the existing data and code",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.FOREIGN().GetSymbol().GetLine()),
- })
- return
- }
- if len(ctx.AllCHECK()) == 1 {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityAddForeignKey.Int32(),
- Title: r.title,
- Content: "Add CHECK WITH NO CHECK may cause incompatibility with the existing data and code",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.CHECK(0).GetSymbol().GetLine()),
- })
- return
+ case ast.ATNocheckConstraint:
+ // Legacy fallback — omni may still use this in some cases.
+ if action.Constraint != nil {
+ switch action.Constraint.Type {
+ case ast.ConstraintForeignKey:
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityAddForeignKey.Int32(),
+ Title: r.Title,
+ Content: "Add FOREIGN KEY WITH NO CHECK may cause incompatibility with the existing data and code",
+ StartPosition: &storepb.Position{Line: r.LocToLine(action.Loc)},
+ })
+ case ast.ConstraintCheck:
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityAddForeignKey.Int32(),
+ Title: r.Title,
+ Content: "Add CHECK WITH NO CHECK may cause incompatibility with the existing data and code",
+ StartPosition: &storepb.Position{Line: r.LocToLine(action.Loc)},
+ })
+ default:
+ }
+ }
+ default:
}
}
}
-// enterExecuteBody is called when production execute_body is entered.
-func (r *MigrationCompatibilityRule) enterExecuteBody(ctx *parser.Execute_bodyContext) {
- if ctx.Func_proc_name_server_database_schema() == nil {
- return
- }
- if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema() == nil {
- return
- }
- if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema() == nil {
+func (r *migrationCompatibilityOmniRule) handleExec(n *ast.ExecStmt) {
+ if n.Name == nil {
return
}
- if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema().GetSchema() != nil {
+ if n.Name.Schema != "" {
return
}
-
- v := ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema().GetProcedure()
- _, normalizedProcedureName := tsqlparser.NormalizeTSQLIdentifier(v)
- if normalizedProcedureName != "sp_rename" {
+ if strings.ToLower(n.Name.Object) != "sp_rename" {
return
}
-
- unnamedArguments := tsqlparser.FlattenExecuteStatementArgExecuteStatementArgUnnamed(ctx.Execute_statement_arg())
-
- firstArgument := unnamedArguments[0]
- if firstArgument == nil {
+ // Check that there is at least one argument.
+ if n.Args == nil || n.Args.Len() == 0 {
return
}
- if firstArgument.Execute_parameter() == nil {
+ firstArg, ok := n.Args.Items[0].(*ast.ExecArg)
+ if !ok {
return
}
- if firstArgument.Execute_parameter().Constant() == nil {
- return
- }
- if firstArgument.Execute_parameter().Constant().STRING() == nil {
- return
+ // Check that the first argument is a string literal.
+ if lit, ok := firstArg.Value.(*ast.Literal); ok && lit.Type == ast.LitString {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: advisorcode.CompatibilityRenameTable.Int32(),
+ Title: r.Title,
+ Content: "sp_rename may cause incompatibility with the existing data and code, and break scripts and stored procedures.",
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
}
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: advisorcode.CompatibilityRenameTable.Int32(),
- Title: r.title,
- Content: "sp_rename may cause incompatibility with the existing data and code, and break scripts and stored procedures.",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
}
diff --git a/backend/plugin/advisor/mssql/rule_naming_identifier_no_keyword.go b/backend/plugin/advisor/mssql/rule_naming_identifier_no_keyword.go
index f1295cd6f7..641ed3dede 100644
--- a/backend/plugin/advisor/mssql/rule_naming_identifier_no_keyword.go
+++ b/backend/plugin/advisor/mssql/rule_naming_identifier_no_keyword.go
@@ -3,16 +3,13 @@ package mssql
import (
"context"
"fmt"
+ "strings"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
)
@@ -35,89 +32,54 @@ func (*NamingIdentifierNoKeywordAdvisor) Check(_ context.Context, checkCtx advis
return nil, err
}
- // Create the rule
- rule := NewNamingIdentifierNoKeywordRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &namingIdentifierNoKeywordRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
}
-
- return checker.GetAdviceList(), nil
-}
-
-// NamingIdentifierNoKeywordRule is the rule for identifier naming convention without keyword.
-type NamingIdentifierNoKeywordRule struct {
- BaseRule
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// NewNamingIdentifierNoKeywordRule creates a new NamingIdentifierNoKeywordRule.
-func NewNamingIdentifierNoKeywordRule(level storepb.Advice_Status, title string) *NamingIdentifierNoKeywordRule {
- return &NamingIdentifierNoKeywordRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
+type namingIdentifierNoKeywordRule struct {
+ OmniBaseRule
}
-// Name returns the rule name.
-func (*NamingIdentifierNoKeywordRule) Name() string {
+func (*namingIdentifierNoKeywordRule) Name() string {
return "NamingIdentifierNoKeywordRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *NamingIdentifierNoKeywordRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeID {
- r.enterID(ctx.(*parser.Id_Context))
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*NamingIdentifierNoKeywordRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *NamingIdentifierNoKeywordRule) enterID(ctx *parser.Id_Context) {
- if ctx == nil {
- return
- }
-
- parent := ctx.GetParent()
- switch parent.(type) {
- case *parser.Column_definitionContext:
- case *parser.Table_constraintContext:
- case *parser.Create_schemaContext:
- case *parser.Create_databaseContext:
- case *parser.Create_indexContext:
- case *parser.Table_nameContext:
- default:
- return
- }
- if ctx.GetText() == "" {
- return
- }
-
- _, normalizedID := tsqlparser.NormalizeTSQLIdentifier(ctx)
- if tsqlparser.IsTSQLReservedKeyword(normalizedID, false) {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.NameIsKeywordIdentifier.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Identifier [%s] is a keyword identifier and should be avoided.", normalizedID),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
- }
+func (r *namingIdentifierNoKeywordRule) OnStatement(node ast.Node) {
+ ast.Inspect(node, func(n ast.Node) bool {
+ var name string
+ switch v := n.(type) {
+ case *ast.ColumnDef:
+ name = v.Name
+ case *ast.ConstraintDef:
+ name = v.Name
+ case *ast.CreateSchemaStmt:
+ name = v.Name
+ case *ast.CreateDatabaseStmt:
+ name = v.Name
+ case *ast.CreateIndexStmt:
+ name = v.Name
+ case *ast.CreateTableStmt:
+ if v.Name != nil {
+ name = v.Name.Object
+ }
+ default:
+ return true
+ }
+ if name == "" {
+ return true
+ }
+ lower := strings.ToLower(name)
+ if tsqlparser.IsTSQLReservedKeyword(lower, false) {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.NameIsKeywordIdentifier.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Identifier [%s] is a keyword identifier and should be avoided.", lower),
+ StartPosition: &storepb.Position{Line: r.FindLineByName(name)},
+ })
+ }
+ return true
+ })
}
diff --git a/backend/plugin/advisor/mssql/rule_naming_table.go b/backend/plugin/advisor/mssql/rule_naming_table.go
index 4169e6afc9..ab790e6da7 100644
--- a/backend/plugin/advisor/mssql/rule_naming_table.go
+++ b/backend/plugin/advisor/mssql/rule_naming_table.go
@@ -6,16 +6,12 @@ import (
"regexp"
"strings"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
)
var (
@@ -51,170 +47,90 @@ func (*NamingTableAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([
maxLength = advisor.DefaultNameLengthLimit
}
- // Create the rule
- rule := NewNamingTableRule(level, checkCtx.Rule.Type.String(), format, maxLength)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &namingTableRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ format: format,
+ maxLength: maxLength,
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// NamingTableRule is the rule for table naming convention.
-type NamingTableRule struct {
- BaseRule
+type namingTableRule struct {
+ OmniBaseRule
format *regexp.Regexp
maxLength int
}
-// NewNamingTableRule creates a new NamingTableRule.
-func NewNamingTableRule(level storepb.Advice_Status, title string, format *regexp.Regexp, maxLength int) *NamingTableRule {
- return &NamingTableRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- format: format,
- maxLength: maxLength,
- }
-}
-
-// Name returns the rule name.
-func (*NamingTableRule) Name() string {
+func (*namingTableRule) Name() string {
return "NamingTableRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *NamingTableRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
- case "Execute_body":
- r.enterExecuteBody(ctx.(*parser.Execute_bodyContext))
+func (r *namingTableRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.CreateTableStmt:
+ if n.Name == nil {
+ return
+ }
+ r.checkTableName(n.Name.Object, n.Loc)
+ case *ast.ExecStmt:
+ r.checkSpRename(n)
default:
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*NamingTableRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
}
-func (r *NamingTableRule) enterCreateTable(ctx *parser.Create_tableContext) {
- tableName := ctx.Table_name().GetTable().GetText()
-
+func (r *namingTableRule) checkTableName(tableName string, loc ast.Loc) {
+ if tableName == "" {
+ return
+ }
if !r.format.MatchString(tableName) {
r.AddAdvice(&storepb.Advice{
- Status: r.level,
+ Status: r.Level,
Code: code.NamingTableConventionMismatch.Int32(),
- Title: r.title,
+ Title: r.Title,
Content: fmt.Sprintf(`%s mismatches table naming convention, naming format should be %q`, tableName, r.format),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
+ StartPosition: &storepb.Position{Line: r.LocToLine(loc)},
})
}
if r.maxLength > 0 && len(tableName) > r.maxLength {
r.AddAdvice(&storepb.Advice{
- Status: r.level,
+ Status: r.Level,
Code: code.NamingTableConventionMismatch.Int32(),
- Title: r.title,
+ Title: r.Title,
Content: fmt.Sprintf(`%s mismatches table naming convention, its length should be within %d characters`, tableName, r.maxLength),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
+ StartPosition: &storepb.Position{Line: r.LocToLine(loc)},
})
}
}
-func (r *NamingTableRule) enterExecuteBody(ctx *parser.Execute_bodyContext) {
- if ctx.Func_proc_name_server_database_schema() == nil {
+func (r *namingTableRule) checkSpRename(execStmt *ast.ExecStmt) {
+ if execStmt.Name == nil {
return
}
- if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema() == nil {
+ // Check if the procedure is sp_rename.
+ if execStmt.Name.Schema != "" {
return
}
- if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema() == nil {
- return
- }
- if ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema().GetSchema() != nil {
+ if !strings.EqualFold(execStmt.Name.Object, "sp_rename") {
return
}
- v := ctx.Func_proc_name_server_database_schema().Func_proc_name_database_schema().Func_proc_name_schema().GetProcedure()
- _, normalizedProcedureName := tsqlparser.NormalizeTSQLIdentifier(v)
- if normalizedProcedureName != "sp_rename" {
- return
- }
-
- firstArgument := ctx.Execute_statement_arg()
- if firstArgument == nil {
- return
- }
- if firstArgument.Execute_statement_arg_unnamed() == nil {
- return
- }
- if firstArgument.Execute_statement_arg_unnamed().Execute_parameter() == nil {
- return
- }
- if firstArgument.Execute_statement_arg_unnamed().Execute_parameter().Constant() == nil {
- return
- }
- if firstArgument.Execute_statement_arg_unnamed().Execute_parameter().Constant().STRING() == nil {
+ if execStmt.Args == nil || execStmt.Args.Len() < 2 {
return
}
- if len(ctx.Execute_statement_arg().AllExecute_statement_arg()) != 1 {
- return
- }
- secondArgument := ctx.Execute_statement_arg().Execute_statement_arg(0)
- if secondArgument == nil {
- return
- }
- if secondArgument.Execute_statement_arg_unnamed() == nil {
- return
- }
- if secondArgument.Execute_statement_arg_unnamed().Execute_parameter() == nil {
+ // Get the second argument (new name).
+ arg1, ok := execStmt.Args.Items[1].(*ast.ExecArg)
+ if !ok || arg1 == nil {
return
}
- if secondArgument.Execute_statement_arg_unnamed().Execute_parameter().Constant() == nil {
+ lit, ok := arg1.Value.(*ast.Literal)
+ if !ok || lit == nil {
return
}
- if secondArgument.Execute_statement_arg_unnamed().Execute_parameter().Constant().STRING() == nil {
- return
- }
-
- newTableName := secondArgument.Execute_statement_arg_unnamed().Execute_parameter().Constant().STRING().GetText()
+ newTableName := lit.Str
if strings.HasPrefix(newTableName, "'") && strings.HasSuffix(newTableName, "'") {
newTableName = newTableName[1 : len(newTableName)-1]
}
- if !r.format.MatchString(newTableName) {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.NamingTableConventionMismatch.Int32(),
- Title: r.title,
- Content: fmt.Sprintf(`%s mismatches table naming convention, naming format should be %q`, newTableName, r.format),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
- }
- if r.maxLength > 0 && len(newTableName) > r.maxLength {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.NamingTableConventionMismatch.Int32(),
- Title: r.title,
- Content: fmt.Sprintf(`%s mismatches table naming convention, its length should be within %d characters`, newTableName, r.maxLength),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
- }
+ r.checkTableName(newTableName, execStmt.Loc)
}
diff --git a/backend/plugin/advisor/mssql/rule_naming_table_no_keyword.go b/backend/plugin/advisor/mssql/rule_naming_table_no_keyword.go
index f6785c2996..21b755527f 100644
--- a/backend/plugin/advisor/mssql/rule_naming_table_no_keyword.go
+++ b/backend/plugin/advisor/mssql/rule_naming_table_no_keyword.go
@@ -4,15 +4,11 @@ import (
"context"
"fmt"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
)
@@ -35,71 +31,36 @@ func (*NamingTableNoKeywordAdvisor) Check(_ context.Context, checkCtx advisor.Co
return nil, err
}
- // Create the rule
- rule := NewNamingTableNoKeywordRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &namingTableNoKeywordRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
}
-
- return checker.GetAdviceList(), nil
-}
-
-// NamingTableNoKeywordRule is the rule for table naming convention without keyword.
-type NamingTableNoKeywordRule struct {
- BaseRule
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// NewNamingTableNoKeywordRule creates a new NamingTableNoKeywordRule.
-func NewNamingTableNoKeywordRule(level storepb.Advice_Status, title string) *NamingTableNoKeywordRule {
- return &NamingTableNoKeywordRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
+type namingTableNoKeywordRule struct {
+ OmniBaseRule
}
-// Name returns the rule name.
-func (*NamingTableNoKeywordRule) Name() string {
+func (*namingTableNoKeywordRule) Name() string {
return "NamingTableNoKeywordRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *NamingTableNoKeywordRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeCreateTable {
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
+func (r *namingTableNoKeywordRule) OnStatement(node ast.Node) {
+ ct, ok := node.(*ast.CreateTableStmt)
+ if !ok || ct.Name == nil {
+ return
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*NamingTableNoKeywordRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *NamingTableNoKeywordRule) enterCreateTable(ctx *parser.Create_tableContext) {
- tableName := ctx.Table_name().GetTable()
- _, normalizedTableName := tsqlparser.NormalizeTSQLIdentifier(tableName)
- if tsqlparser.IsTSQLReservedKeyword(normalizedTableName, false) {
+ tableName := ct.Name.Object
+ if tableName == "" {
+ return
+ }
+ if tsqlparser.IsTSQLReservedKeyword(tableName, false) {
r.AddAdvice(&storepb.Advice{
- Status: r.level,
+ Status: r.Level,
Code: code.NameIsKeywordIdentifier.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Table name [%s] is a reserved keyword and should be avoided.", normalizedTableName),
- StartPosition: common.ConvertANTLRLineToPosition(tableName.GetStart().GetLine()),
+ Title: r.Title,
+ Content: fmt.Sprintf("Table name [%s] is a reserved keyword and should be avoided.", tableName),
+ StartPosition: &storepb.Position{Line: r.LocToLine(ct.Loc)},
})
}
}
diff --git a/backend/plugin/advisor/mssql/rule_procedure_disallow_create_or_alter.go b/backend/plugin/advisor/mssql/rule_procedure_disallow_create_or_alter.go
index ba0dd3a78a..9a810ec680 100644
--- a/backend/plugin/advisor/mssql/rule_procedure_disallow_create_or_alter.go
+++ b/backend/plugin/advisor/mssql/rule_procedure_disallow_create_or_alter.go
@@ -3,14 +3,11 @@ package mssql
import (
"context"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
)
func init() {
@@ -24,68 +21,26 @@ func (*ProcedureDisallowCreateOrAlterAdvisor) Check(_ context.Context, checkCtx
if err != nil {
return nil, err
}
-
- // Create the rule
- rule := NewProcedureDisallowCreateOrAlterRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
- }
-
- return checker.GetAdviceList(), nil
-}
-
-// ProcedureDisallowCreateOrAlterRule is the rule for disallowing procedure creation or alteration.
-type ProcedureDisallowCreateOrAlterRule struct {
- BaseRule
+ rule := &procedureDisallowCreateOrAlterRule{OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()}}
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// NewProcedureDisallowCreateOrAlterRule creates a new ProcedureDisallowCreateOrAlterRule.
-func NewProcedureDisallowCreateOrAlterRule(level storepb.Advice_Status, title string) *ProcedureDisallowCreateOrAlterRule {
- return &ProcedureDisallowCreateOrAlterRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
+type procedureDisallowCreateOrAlterRule struct {
+ OmniBaseRule
}
-// Name returns the rule name.
-func (*ProcedureDisallowCreateOrAlterRule) Name() string {
+func (*procedureDisallowCreateOrAlterRule) Name() string {
return "ProcedureDisallowCreateOrAlterRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *ProcedureDisallowCreateOrAlterRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeCreateOrAlterProcedure {
- r.enterCreateOrAlterProcedure(ctx.(*parser.Create_or_alter_procedureContext))
+func (r *procedureDisallowCreateOrAlterRule) OnStatement(node ast.Node) {
+ if n, ok := node.(*ast.CreateProcedureStmt); ok {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.DisallowCreateProcedure.Int32(),
+ Title: r.Title,
+ Content: "Creating or altering procedures is prohibited",
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*ProcedureDisallowCreateOrAlterRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *ProcedureDisallowCreateOrAlterRule) enterCreateOrAlterProcedure(ctx *parser.Create_or_alter_procedureContext) {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.DisallowCreateProcedure.Int32(),
- Title: r.title,
- Content: "Creating or altering procedures is prohibited",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
}
diff --git a/backend/plugin/advisor/mssql/rule_select_no_select_all.go b/backend/plugin/advisor/mssql/rule_select_no_select_all.go
index b17d54b9e4..b534fab8b4 100644
--- a/backend/plugin/advisor/mssql/rule_select_no_select_all.go
+++ b/backend/plugin/advisor/mssql/rule_select_no_select_all.go
@@ -3,100 +3,67 @@ package mssql
import (
"context"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
-)
-
-var (
- _ advisor.Advisor = (*SelectNoSelectAllAdvisor)(nil)
)
func init() {
advisor.Register(storepb.Engine_MSSQL, storepb.SQLReviewRule_STATEMENT_SELECT_NO_SELECT_ALL, &SelectNoSelectAllAdvisor{})
}
-// SelectNoSelectAllAdvisor is the advisor checking for no select all.
-type SelectNoSelectAllAdvisor struct {
-}
+type SelectNoSelectAllAdvisor struct{}
-// Check checks for no select all.
func (*SelectNoSelectAllAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
if err != nil {
return nil, err
}
-
- // Create the rule
- rule := NewSelectNoSelectAllRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
- }
-
- return checker.GetAdviceList(), nil
+ rule := &selectNoSelectAllRule{OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()}}
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// SelectNoSelectAllRule checks for no select all.
-type SelectNoSelectAllRule struct {
- BaseRule
+type selectNoSelectAllRule struct {
+ OmniBaseRule
}
-// NewSelectNoSelectAllRule creates a new SelectNoSelectAllRule.
-func NewSelectNoSelectAllRule(level storepb.Advice_Status, title string) *SelectNoSelectAllRule {
- return &SelectNoSelectAllRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
-}
-
-// Name returns the rule name.
-func (*SelectNoSelectAllRule) Name() string {
+func (*selectNoSelectAllRule) Name() string {
return "SelectNoSelectAllRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *SelectNoSelectAllRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeSelectListElem {
- r.enterSelectListElem(ctx.(*parser.Select_list_elemContext))
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*SelectNoSelectAllRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *SelectNoSelectAllRule) enterSelectListElem(ctx *parser.Select_list_elemContext) {
- if v := ctx.Asterisk(); v != nil {
- if v.STAR() != nil {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.StatementSelectAll.Int32(),
- Title: r.title,
- Content: "Avoid using SELECT *.",
- StartPosition: common.ConvertANTLRLineToPosition(v.STAR().GetSymbol().GetLine()),
- })
+func (r *selectNoSelectAllRule) OnStatement(node ast.Node) {
+ // Find all SelectStmt nodes, then check their TargetList for StarExpr.
+ // This avoids false positives from COUNT(*) and similar expressions.
+ ast.Inspect(node, func(n ast.Node) bool {
+ sel, ok := n.(*ast.SelectStmt)
+ if !ok || sel.TargetList == nil {
+ return true
}
- }
+ for _, item := range sel.TargetList.Items {
+ switch v := item.(type) {
+ case *ast.StarExpr:
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementSelectAll.Int32(),
+ Title: r.Title,
+ Content: "Avoid using SELECT *.",
+ StartPosition: &storepb.Position{Line: r.LocToLine(v.Loc)},
+ })
+ case *ast.ResTarget:
+ if star, ok := v.Val.(*ast.StarExpr); ok {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementSelectAll.Int32(),
+ Title: r.Title,
+ Content: "Avoid using SELECT *.",
+ StartPosition: &storepb.Position{Line: r.LocToLine(star.Loc)},
+ })
+ }
+ default:
+ }
+ }
+ return true
+ })
}
diff --git a/backend/plugin/advisor/mssql/rule_statement_disallow_cross_db_queries.go b/backend/plugin/advisor/mssql/rule_statement_disallow_cross_db_queries.go
index 395a66f2c9..ba0795a2c6 100644
--- a/backend/plugin/advisor/mssql/rule_statement_disallow_cross_db_queries.go
+++ b/backend/plugin/advisor/mssql/rule_statement_disallow_cross_db_queries.go
@@ -5,15 +5,11 @@ import (
"fmt"
"strings"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
)
func init() {
@@ -28,87 +24,45 @@ func (*DisallowCrossDBQueriesAdvisor) Check(_ context.Context, checkCtx advisor.
return nil, err
}
- // Create the rule
- rule := NewDisallowCrossDBQueriesRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &disallowCrossDBQueriesRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ curDB: checkCtx.CurrentDatabase,
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// DisallowCrossDBQueriesRule is the rule for disallowing cross database queries.
-type DisallowCrossDBQueriesRule struct {
- BaseRule
+type disallowCrossDBQueriesRule struct {
+ OmniBaseRule
curDB string
}
-// NewDisallowCrossDBQueriesRule creates a new DisallowCrossDBQueriesRule.
-func NewDisallowCrossDBQueriesRule(level storepb.Advice_Status, title string, currentDatabase string) *DisallowCrossDBQueriesRule {
- return &DisallowCrossDBQueriesRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- curDB: currentDatabase,
- }
-}
-
-// Name returns the rule name.
-func (*DisallowCrossDBQueriesRule) Name() string {
+func (*disallowCrossDBQueriesRule) Name() string {
return "DisallowCrossDBQueriesRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *DisallowCrossDBQueriesRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case "Table_source_item":
- r.enterTableSourceItem(ctx.(*parser.Table_source_itemContext))
- case "Use_statement":
- r.enterUseStatement(ctx.(*parser.Use_statementContext))
- default:
- // Ignore other node types
+func (r *disallowCrossDBQueriesRule) OnStatement(node ast.Node) {
+ // Check for USE statement to track current database.
+ if useStmt, ok := node.(*ast.UseStmt); ok {
+ if useStmt.Database != "" {
+ r.curDB = strings.ToLower(useStmt.Database)
+ }
+ return
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*DisallowCrossDBQueriesRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-func (r *DisallowCrossDBQueriesRule) enterTableSourceItem(ctx *parser.Table_source_itemContext) {
- if fullTblnameCtx := ctx.Full_table_name(); fullTblnameCtx != nil {
- // Case insensitive.
- if fullTblName, err := tsqlparser.NormalizeFullTableName(fullTblnameCtx); err == nil && fullTblName.Database != "" && !strings.EqualFold(fullTblName.Database, r.curDB) {
+ ast.Inspect(node, func(n ast.Node) bool {
+ ref, ok := n.(*ast.TableRef)
+ if !ok || ref == nil {
+ return true
+ }
+ if ref.Database != "" && !strings.EqualFold(ref.Database, r.curDB) {
r.AddAdvice(&storepb.Advice{
- Status: r.level,
+ Status: r.Level,
Code: code.StatementDisallowCrossDBQueries.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Cross database queries (target databse: '%s', current database: '%s') are prohibited", fullTblName.Database, r.curDB),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
+ Title: r.Title,
+ Content: fmt.Sprintf("Cross database queries (target databse: '%s', current database: '%s') are prohibited", ref.Database, r.curDB),
+ StartPosition: &storepb.Position{Line: r.LocToLine(ref.Loc)},
})
}
- // Ignore internal error...
- }
-}
-
-func (r *DisallowCrossDBQueriesRule) enterUseStatement(ctx *parser.Use_statementContext) {
- if newDB := ctx.GetDatabase(); newDB != nil {
- _, lowercaceDBName := tsqlparser.NormalizeTSQLIdentifier(newDB)
- r.curDB = lowercaceDBName
- }
+ return true
+ })
}
diff --git a/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go b/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go
index 60689a4542..3aca27c8c4 100644
--- a/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go
+++ b/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go
@@ -4,14 +4,11 @@ import (
"context"
"fmt"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
)
func init() {
@@ -28,223 +25,103 @@ func (*DisallowFuncAndCalculationsAdvisor) Check(_ context.Context, checkCtx adv
return nil, err
}
- // Create the rule
- rule := NewDisallowFuncAndCalculationsRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
- }
-
- return checker.GetAdviceList(), nil
-}
-
-// DisallowFuncAndCalculationsRule is the rule for disallowing functions and calculations in WHERE clause.
-type DisallowFuncAndCalculationsRule struct {
- BaseRule
- // We only check the 'WHERE' clause in a 'SELECT' statement.
- // Also, the value of 'whereCnt' represents the depth of entering the 'WHERE' clause. Same below.
- whereCnt int
- selectStatCnt int
- havingCnt int
- // Each statement can only trigger the rule once.
- hasTriggeredRule bool
-}
-
-// NewDisallowFuncAndCalculationsRule creates a new DisallowFuncAndCalculationsRule.
-func NewDisallowFuncAndCalculationsRule(level storepb.Advice_Status, title string) *DisallowFuncAndCalculationsRule {
- return &DisallowFuncAndCalculationsRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- selectStatCnt: 0,
- whereCnt: 0,
- havingCnt: 0,
- hasTriggeredRule: false,
- }
-}
-
-// Name returns the rule name.
-func (*DisallowFuncAndCalculationsRule) Name() string {
- return "DisallowFuncAndCalculationsRule"
-}
-
-// OnEnter is called when entering a parse tree node.
-func (r *DisallowFuncAndCalculationsRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case "Query_specification":
- r.enterQuerySpecification(ctx.(*parser.Query_specificationContext))
- case "Having_clause":
- r.enterHavingClause(ctx.(*parser.Having_clauseContext))
- case NodeTypeSearchCondition:
- r.enterSearchCondition(ctx.(*parser.Search_conditionContext))
- case "BUILT_IN_FUNC":
- r.enterBuiltInFunc(ctx.(*parser.BUILT_IN_FUNCContext))
- case "RANKING_WINDOWED_FUNC":
- r.enterRankingWindowedFunc(ctx.(*parser.RANKING_WINDOWED_FUNCContext))
- case "AGGREGATE_WINDOWED_FUNC":
- r.enterAggregateWindowedFunc(ctx.(*parser.AGGREGATE_WINDOWED_FUNCContext))
- case "ANALYTIC_WINDOWED_FUNC":
- r.enterAnalyticWindowedFunc(ctx.(*parser.ANALYTIC_WINDOWED_FUNCContext))
- case "SCALAR_FUNCTION":
- r.enterScalarFunction(ctx.(*parser.SCALAR_FUNCTIONContext))
- case "FREE_TEXT":
- r.enterFreeText(ctx.(*parser.FREE_TEXTContext))
- case "PARTITION_FUNC":
- r.enterPartitionFunc(ctx.(*parser.PARTITION_FUNCContext))
- case "HIERARCHYID_METHOD":
- r.enterHierarchyIDMethod(ctx.(*parser.HIERARCHYID_METHODContext))
- case "Expression":
- r.enterExpression(ctx.(*parser.ExpressionContext))
- case "Unary_operator_expression":
- r.enterUnaryOperatorExpression(ctx.(*parser.Unary_operator_expressionContext))
- default:
- // Ignore other node types
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (r *DisallowFuncAndCalculationsRule) OnExit(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case "Query_specification":
- r.exitQuerySpecification(ctx.(*parser.Query_specificationContext))
- case "Having_clause":
- r.exitHavingClause(ctx.(*parser.Having_clauseContext))
- case NodeTypeSearchCondition:
- r.exitSearchCondition(ctx.(*parser.Search_conditionContext))
- default:
- // Ignore other node types
- }
- return nil
-}
-
-func (r *DisallowFuncAndCalculationsRule) generateAdviceOnFunctionUsing(ctx antlr.BaseParserRuleContext) *storepb.Advice {
- if r.whereCnt == 0 || r.hasTriggeredRule {
- return nil
- }
- r.hasTriggeredRule = true
- return &storepb.Advice{
- Status: r.level,
- Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Calling function '%s' in 'WHERE' clause is not allowed", ctx.GetText()),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- }
-}
-
-func (r *DisallowFuncAndCalculationsRule) generateAdviceOnPerformingCalculations(ctx antlr.BaseParserRuleContext) *storepb.Advice {
- if r.whereCnt == 0 || r.hasTriggeredRule {
- return nil
- }
- r.hasTriggeredRule = true
- return &storepb.Advice{
- Status: r.level,
- Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
- Title: r.title,
- Content: "Performing calculations in 'WHERE' clause is not allowed",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- }
-}
-
-func (r *DisallowFuncAndCalculationsRule) enterQuerySpecification(_ *parser.Query_specificationContext) {
- r.selectStatCnt++
-}
-
-func (r *DisallowFuncAndCalculationsRule) exitQuerySpecification(_ *parser.Query_specificationContext) {
- r.selectStatCnt--
-}
-
-func (r *DisallowFuncAndCalculationsRule) enterHavingClause(_ *parser.Having_clauseContext) {
- r.havingCnt++
-}
-
-func (r *DisallowFuncAndCalculationsRule) exitHavingClause(_ *parser.Having_clauseContext) {
- r.havingCnt--
-}
-
-func (r *DisallowFuncAndCalculationsRule) enterSearchCondition(_ *parser.Search_conditionContext) {
- if r.selectStatCnt != 0 && r.havingCnt == 0 {
- r.whereCnt++
+ rule := &disallowFuncAndCalcOmniRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
}
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-func (r *DisallowFuncAndCalculationsRule) exitSearchCondition(_ *parser.Search_conditionContext) {
- r.whereCnt--
- r.hasTriggeredRule = false
-}
-
-// Calling functions.
-func (r *DisallowFuncAndCalculationsRule) enterBuiltInFunc(ctx *parser.BUILT_IN_FUNCContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
-}
-
-func (r *DisallowFuncAndCalculationsRule) enterRankingWindowedFunc(ctx *parser.RANKING_WINDOWED_FUNCContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
+type disallowFuncAndCalcOmniRule struct {
+ OmniBaseRule
}
-func (r *DisallowFuncAndCalculationsRule) enterAggregateWindowedFunc(ctx *parser.AGGREGATE_WINDOWED_FUNCContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
+func (*disallowFuncAndCalcOmniRule) Name() string {
+ return "DisallowFuncAndCalcOmniRule"
}
-func (r *DisallowFuncAndCalculationsRule) enterAnalyticWindowedFunc(ctx *parser.ANALYTIC_WINDOWED_FUNCContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
-}
+func (r *disallowFuncAndCalcOmniRule) OnStatement(node ast.Node) {
+ // Find all statements that have a WHERE clause.
+ ast.Inspect(node, func(n ast.Node) bool {
+ var where ast.ExprNode
+ switch stmt := n.(type) {
+ case *ast.SelectStmt:
+ where = stmt.WhereClause
+ case *ast.UpdateStmt:
+ where = stmt.WhereClause
+ case *ast.DeleteStmt:
+ where = stmt.WhereClause
+ default:
+ return true
+ }
-func (r *DisallowFuncAndCalculationsRule) enterScalarFunction(ctx *parser.SCALAR_FUNCTIONContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
-}
+ if where == nil {
+ return true
+ }
-func (r *DisallowFuncAndCalculationsRule) enterFreeText(ctx *parser.FREE_TEXTContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
+ r.checkWhereClause(where)
+ return true
+ })
}
-func (r *DisallowFuncAndCalculationsRule) enterPartitionFunc(ctx *parser.PARTITION_FUNCContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
-}
+func (r *disallowFuncAndCalcOmniRule) checkWhereClause(where ast.ExprNode) {
+ // Only report the first violation per WHERE clause.
+ found := false
-func (r *DisallowFuncAndCalculationsRule) enterHierarchyIDMethod(ctx *parser.HIERARCHYID_METHODContext) {
- if advice := r.generateAdviceOnFunctionUsing(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
- }
-}
+ ast.Inspect(where, func(n ast.Node) bool {
+ if found {
+ return false
+ }
-// Performing calculations.
-func (r *DisallowFuncAndCalculationsRule) enterExpression(ctx *parser.ExpressionContext) {
- if ctx.GetOp() != nil {
- if advice := r.generateAdviceOnPerformingCalculations(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
+ switch expr := n.(type) {
+ case *ast.FuncCallExpr:
+ found = true
+ funcName := ""
+ if expr.Name != nil {
+ funcName = tableRefText(expr.Name)
+ }
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
+ Title: r.Title,
+ Content: fmt.Sprintf("Calling function '%s' in 'WHERE' clause is not allowed", funcName),
+ StartPosition: &storepb.Position{Line: r.LocToLine(expr.Loc)},
+ })
+ return false
+ case *ast.BinaryExpr:
+ if isArithmeticOp(expr.Op) {
+ found = true
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
+ Title: r.Title,
+ Content: "Performing calculations in 'WHERE' clause is not allowed",
+ StartPosition: &storepb.Position{Line: r.LocToLine(expr.Loc)},
+ })
+ return false
+ }
+ case *ast.UnaryExpr:
+ if expr.Op == ast.UnaryPlus || expr.Op == ast.UnaryMinus || expr.Op == ast.UnaryBitNot {
+ found = true
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
+ Title: r.Title,
+ Content: "Performing calculations in 'WHERE' clause is not allowed",
+ StartPosition: &storepb.Position{Line: r.LocToLine(expr.Loc)},
+ })
+ return false
+ }
+ default:
}
- }
+ return true
+ })
}
-func (r *DisallowFuncAndCalculationsRule) enterUnaryOperatorExpression(ctx *parser.Unary_operator_expressionContext) {
- if advice := r.generateAdviceOnPerformingCalculations(ctx.BaseParserRuleContext); advice != nil {
- r.AddAdvice(advice)
+func isArithmeticOp(op ast.BinaryOp) bool {
+ switch op {
+ case ast.BinOpAdd, ast.BinOpSub, ast.BinOpMul, ast.BinOpDiv, ast.BinOpMod:
+ return true
+ default:
+ return false
}
}
diff --git a/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_select.go b/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_select.go
index b0e80510ed..005aa89cd2 100644
--- a/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_select.go
+++ b/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_select.go
@@ -3,99 +3,52 @@ package mssql
import (
"context"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
-)
-
-var (
- _ advisor.Advisor = (*WhereRequirementForSelectAdvisor)(nil)
)
func init() {
advisor.Register(storepb.Engine_MSSQL, storepb.SQLReviewRule_STATEMENT_WHERE_REQUIRE_SELECT, &WhereRequirementForSelectAdvisor{})
}
-// WhereRequirementForSelectAdvisor is the advisor checking for WHERE clause requirement for SELECT statements.
-type WhereRequirementForSelectAdvisor struct {
-}
+type WhereRequirementForSelectAdvisor struct{}
-// Check checks for WHERE clause requirement.
func (*WhereRequirementForSelectAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
if err != nil {
return nil, err
}
-
- // Create the rule
- rule := NewWhereRequirementForSelectRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
- }
-
- return checker.GetAdviceList(), nil
+ rule := &whereRequirementForSelectRule{OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()}}
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// WhereRequirementForSelectRule is the rule for WHERE clause requirement for SELECT statements.
-type WhereRequirementForSelectRule struct {
- BaseRule
+type whereRequirementForSelectRule struct {
+ OmniBaseRule
}
-// NewWhereRequirementForSelectRule creates a new WhereRequirementForSelectRule.
-func NewWhereRequirementForSelectRule(level storepb.Advice_Status, title string) *WhereRequirementForSelectRule {
- return &WhereRequirementForSelectRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
-}
-
-// Name returns the rule name.
-func (*WhereRequirementForSelectRule) Name() string {
+func (*whereRequirementForSelectRule) Name() string {
return "WhereRequirementForSelectRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *WhereRequirementForSelectRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == "Query_specification" {
- r.enterQuerySpecification(ctx.(*parser.Query_specificationContext))
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*WhereRequirementForSelectRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *WhereRequirementForSelectRule) enterQuerySpecification(ctx *parser.Query_specificationContext) {
- // Allow SELECT queries without a FROM clause to proceed, e.g. SELECT 1.
- if ctx.WHERE() == nil && ctx.From_table_sources() != nil {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.StatementNoWhere.Int32(),
- Title: r.title,
- Content: "WHERE clause is required for SELETE statement.",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
- }
+func (r *whereRequirementForSelectRule) OnStatement(node ast.Node) {
+ ast.Inspect(node, func(n ast.Node) bool {
+ sel, ok := n.(*ast.SelectStmt)
+ if !ok {
+ return true
+ }
+ // Allow SELECT queries without a FROM clause, e.g. SELECT 1.
+ if sel.FromClause != nil && sel.WhereClause == nil {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementNoWhere.Int32(),
+ Title: r.Title,
+ Content: "WHERE clause is required for SELETE statement.",
+ StartPosition: &storepb.Position{Line: r.LocToLine(sel.Loc)},
+ })
+ }
+ return true
+ })
}
diff --git a/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_update_delete.go b/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_update_delete.go
index 9464957434..a228a8db1c 100644
--- a/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_update_delete.go
+++ b/backend/plugin/advisor/mssql/rule_statement_where_requirement_for_update_delete.go
@@ -3,115 +3,58 @@ package mssql
import (
"context"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
-)
-
-var (
- _ advisor.Advisor = (*WhereRequirementForUpdateDeleteAdvisor)(nil)
)
func init() {
advisor.Register(storepb.Engine_MSSQL, storepb.SQLReviewRule_STATEMENT_WHERE_REQUIRE_UPDATE_DELETE, &WhereRequirementForUpdateDeleteAdvisor{})
}
-// WhereRequirementForUpdateDeleteAdvisor is the advisor checking for WHERE clause requirement for UPDATE/DELETE statements.
-type WhereRequirementForUpdateDeleteAdvisor struct {
-}
+type WhereRequirementForUpdateDeleteAdvisor struct{}
-// Check checks for WHERE clause requirement.
func (*WhereRequirementForUpdateDeleteAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
if err != nil {
return nil, err
}
-
- // Create the rule
- rule := NewWhereRequirementForUpdateDeleteRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
- }
-
- return checker.GetAdviceList(), nil
+ rule := &whereRequirementForUpdateDeleteRule{OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()}}
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// WhereRequirementForUpdateDeleteRule is the rule for WHERE clause requirement for UPDATE/DELETE statements.
-type WhereRequirementForUpdateDeleteRule struct {
- BaseRule
+type whereRequirementForUpdateDeleteRule struct {
+ OmniBaseRule
}
-// NewWhereRequirementForUpdateDeleteRule creates a new WhereRequirementForUpdateDeleteRule.
-func NewWhereRequirementForUpdateDeleteRule(level storepb.Advice_Status, title string) *WhereRequirementForUpdateDeleteRule {
- return &WhereRequirementForUpdateDeleteRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- }
-}
-
-// Name returns the rule name.
-func (*WhereRequirementForUpdateDeleteRule) Name() string {
+func (*whereRequirementForUpdateDeleteRule) Name() string {
return "WhereRequirementForUpdateDeleteRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *WhereRequirementForUpdateDeleteRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeDeleteStatement:
- r.enterDeleteStatement(ctx.(*parser.Delete_statementContext))
- case NodeTypeUpdateStatement:
- r.enterUpdateStatement(ctx.(*parser.Update_statementContext))
+func (r *whereRequirementForUpdateDeleteRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.DeleteStmt:
+ if n.WhereClause == nil {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementNoWhere.Int32(),
+ Title: r.Title,
+ Content: "WHERE clause is required for DELETE statement.",
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
+ }
+ case *ast.UpdateStmt:
+ if n.WhereClause == nil {
+ r.AddAdvice(&storepb.Advice{
+ Status: r.Level,
+ Code: code.StatementNoWhere.Int32(),
+ Title: r.Title,
+ Content: "WHERE clause is required for UPDATE statement.",
+ StartPosition: &storepb.Position{Line: r.LocToLine(n.Loc)},
+ })
+ }
default:
- // Ignore other node types
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*WhereRequirementForUpdateDeleteRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *WhereRequirementForUpdateDeleteRule) enterDeleteStatement(ctx *parser.Delete_statementContext) {
- if ctx.WHERE() == nil {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.StatementNoWhere.Int32(),
- Title: r.title,
- Content: "WHERE clause is required for DELETE statement.",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
- }
-}
-
-func (r *WhereRequirementForUpdateDeleteRule) enterUpdateStatement(ctx *parser.Update_statementContext) {
- if ctx.WHERE() == nil {
- r.AddAdvice(&storepb.Advice{
- Status: r.level,
- Code: code.StatementNoWhere.Int32(),
- Title: r.title,
- Content: "WHERE clause is required for UPDATE statement.",
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
- })
}
}
diff --git a/backend/plugin/advisor/mssql/rule_table_disallow_ddl.go b/backend/plugin/advisor/mssql/rule_table_disallow_ddl.go
index 80ffac7a5a..10bb740cea 100644
--- a/backend/plugin/advisor/mssql/rule_table_disallow_ddl.go
+++ b/backend/plugin/advisor/mssql/rule_table_disallow_ddl.go
@@ -4,31 +4,19 @@ import (
"context"
"fmt"
+ "github.com/bytebase/omni/mssql/ast"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
-
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
-)
-
-var (
- _ advisor.Advisor = (*TableDisallowDDLAdvisor)(nil)
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
func init() {
advisor.Register(storepb.Engine_MSSQL, storepb.SQLReviewRule_TABLE_DISALLOW_DDL, &TableDisallowDDLAdvisor{})
}
-// TableDisallowDDLAdvisor is the advisor checking for disallow DDL on specific tables.
-type TableDisallowDDLAdvisor struct {
-}
+type TableDisallowDDLAdvisor struct{}
func (*TableDisallowDDLAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
@@ -40,118 +28,60 @@ func (*TableDisallowDDLAdvisor) Check(_ context.Context, checkCtx advisor.Contex
return nil, errors.New("string_array_payload is required for table disallow DDL rule")
}
- // Create the rule
- rule := NewTableDisallowDDLRule(level, checkCtx.Rule.Type.String(), stringArrayPayload.List)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &tableDisallowDDLRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ disallowList: stringArrayPayload.List,
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// TableDisallowDDLRule is the rule checking for disallow DDL on specific tables.
-type TableDisallowDDLRule struct {
- BaseRule
- // disallowList is the list of table names that disallow DDL.
+type tableDisallowDDLRule struct {
+ OmniBaseRule
disallowList []string
}
-// NewTableDisallowDDLRule creates a new TableDisallowDDLRule.
-func NewTableDisallowDDLRule(level storepb.Advice_Status, title string, disallowList []string) *TableDisallowDDLRule {
- return &TableDisallowDDLRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- disallowList: disallowList,
- }
-}
-
-// Name returns the rule name.
-func (*TableDisallowDDLRule) Name() string {
+func (*tableDisallowDDLRule) Name() string {
return "TableDisallowDDLRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *TableDisallowDDLRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
- case NodeTypeAlterTable:
- r.enterAlterTable(ctx.(*parser.Alter_tableContext))
- case NodeTypeDropTable:
- r.enterDropTable(ctx.(*parser.Drop_tableContext))
- case NodeTypeTruncateTable:
- r.enterTruncateTable(ctx.(*parser.Truncate_tableContext))
- default:
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*TableDisallowDDLRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *TableDisallowDDLRule) enterCreateTable(ctx *parser.Create_tableContext) {
- tableName := ctx.Table_name()
- if tableName == nil {
- return
- }
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
- r.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
-}
-
-func (r *TableDisallowDDLRule) enterAlterTable(ctx *parser.Alter_tableContext) {
- tableName := ctx.Table_name(0)
- if tableName == nil {
- return
- }
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
- r.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
-}
-
-func (r *TableDisallowDDLRule) enterDropTable(ctx *parser.Drop_tableContext) {
- for _, tableName := range ctx.AllTable_name() {
- if tableName == nil {
+func (r *tableDisallowDDLRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.CreateTableStmt:
+ if n.Name != nil {
+ r.checkTableName(normalizeTableRef(n.Name, "", ""), r.LocToLine(n.Loc))
+ }
+ case *ast.AlterTableStmt:
+ if n.Name != nil {
+ r.checkTableName(normalizeTableRef(n.Name, "", ""), r.LocToLine(n.Loc))
+ }
+ case *ast.DropStmt:
+ if n.ObjectType != ast.DropTable || n.Names == nil {
return
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
- r.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
- }
-}
-
-func (r *TableDisallowDDLRule) enterTruncateTable(ctx *parser.Truncate_tableContext) {
- tableName := ctx.Table_name()
- if tableName == nil {
- return
+ for _, item := range n.Names.Items {
+ ref, ok := item.(*ast.TableRef)
+ if !ok || ref == nil {
+ continue
+ }
+ r.checkTableName(normalizeTableRef(ref, "", ""), r.LocToLine(n.Loc))
+ }
+ case *ast.TruncateStmt:
+ if n.Table != nil {
+ r.checkTableName(normalizeTableRef(n.Table, "", ""), r.LocToLine(n.Loc))
+ }
+ default:
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
- r.checkTableName(normalizedTableName, ctx.GetStart().GetLine())
}
-func (r *TableDisallowDDLRule) checkTableName(normalizedTableName string, line int) {
+func (r *tableDisallowDDLRule) checkTableName(normalizedTableName string, line int32) {
for _, disallow := range r.disallowList {
if normalizedTableName == disallow {
r.AddAdvice(&storepb.Advice{
- Status: r.level,
+ Status: r.Level,
Code: code.TableDisallowDDL.Int32(),
- Title: r.title,
+ Title: r.Title,
Content: fmt.Sprintf("DDL is disallowed on table %s.", normalizedTableName),
- StartPosition: common.ConvertANTLRLineToPosition(line),
+ StartPosition: &storepb.Position{Line: line},
})
return
}
diff --git a/backend/plugin/advisor/mssql/rule_table_disallow_dml.go b/backend/plugin/advisor/mssql/rule_table_disallow_dml.go
index 43464f010d..f6f31b0a91 100644
--- a/backend/plugin/advisor/mssql/rule_table_disallow_dml.go
+++ b/backend/plugin/advisor/mssql/rule_table_disallow_dml.go
@@ -4,18 +4,12 @@ import (
"context"
"fmt"
+ "github.com/bytebase/omni/mssql/ast"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
-
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
var (
@@ -40,128 +34,68 @@ func (*TableDisallowDMLAdvisor) Check(_ context.Context, checkCtx advisor.Contex
return nil, errors.New("string_array_payload is required for table disallow DML rule")
}
- // Create the rule
- rule := NewTableDisallowDMLRule(level, checkCtx.Rule.Type.String(), stringArrayPayload.List)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &tableDisallowDMLRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ disallowList: stringArrayPayload.List,
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// TableDisallowDMLRule is the rule checking for disallow DML on specific tables.
-type TableDisallowDMLRule struct {
- BaseRule
- // disallowList is the list of table names that disallow DML.
+type tableDisallowDMLRule struct {
+ OmniBaseRule
disallowList []string
}
-// NewTableDisallowDMLRule creates a new TableDisallowDMLRule.
-func NewTableDisallowDMLRule(level storepb.Advice_Status, title string, disallowList []string) *TableDisallowDMLRule {
- return &TableDisallowDMLRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- disallowList: disallowList,
- }
-}
-
-// Name returns the rule name.
-func (*TableDisallowDMLRule) Name() string {
+func (*tableDisallowDMLRule) Name() string {
return "TableDisallowDMLRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *TableDisallowDMLRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case "Merge_statement":
- r.enterMergeStatement(ctx.(*parser.Merge_statementContext))
- case NodeTypeInsertStatement:
- r.enterInsertStatement(ctx.(*parser.Insert_statementContext))
- case NodeTypeDeleteStatement:
- r.enterDeleteStatement(ctx.(*parser.Delete_statementContext))
- case NodeTypeUpdateStatement:
- r.enterUpdateStatement(ctx.(*parser.Update_statementContext))
- case "Select_statement_standalone":
- r.enterSelectStatementStandalone(ctx.(*parser.Select_statement_standaloneContext))
- default:
- // Ignore other node types
- }
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*TableDisallowDMLRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
+func (r *tableDisallowDMLRule) OnStatement(node ast.Node) {
+ var tableName string
+ var loc ast.Loc
-func (r *TableDisallowDMLRule) enterMergeStatement(ctx *parser.Merge_statementContext) {
- if ctx.Ddl_object() == nil {
- return
- }
- tableName := ctx.Ddl_object().GetText()
- r.checkTableName(tableName, ctx.GetStart().GetLine())
-}
-
-func (r *TableDisallowDMLRule) enterInsertStatement(ctx *parser.Insert_statementContext) {
- if ctx.Ddl_object() == nil {
- return
- }
- tableName := ctx.Ddl_object().GetText()
- r.checkTableName(tableName, ctx.GetStart().GetLine())
-}
-
-func (r *TableDisallowDMLRule) enterDeleteStatement(ctx *parser.Delete_statementContext) {
- if ctx.Delete_statement_from() == nil {
- return
- }
- tableName := ctx.Delete_statement_from().GetText()
- r.checkTableName(tableName, ctx.GetStart().GetLine())
-}
-
-func (r *TableDisallowDMLRule) enterUpdateStatement(ctx *parser.Update_statementContext) {
- if ctx.Ddl_object() == nil {
+ switch n := node.(type) {
+ case *ast.InsertStmt:
+ if n.Relation != nil {
+ tableName = normalizeTableRef(n.Relation, "", "")
+ loc = n.Loc
+ }
+ case *ast.UpdateStmt:
+ if n.Relation != nil {
+ tableName = normalizeTableRef(n.Relation, "", "")
+ loc = n.Loc
+ }
+ case *ast.DeleteStmt:
+ if n.Relation != nil {
+ tableName = normalizeTableRef(n.Relation, "", "")
+ loc = n.Loc
+ }
+ case *ast.MergeStmt:
+ if n.Target != nil {
+ tableName = normalizeTableRef(n.Target, "", "")
+ loc = n.Loc
+ }
+ case *ast.SelectStmt:
+ if n.IntoTable != nil {
+ tableName = normalizeTableRef(n.IntoTable, "", "")
+ loc = n.Loc
+ }
+ default:
return
}
- tableName := ctx.Ddl_object().GetText()
- r.checkTableName(tableName, ctx.GetStart().GetLine())
-}
-func (r *TableDisallowDMLRule) enterSelectStatementStandalone(ctx *parser.Select_statement_standaloneContext) {
- querySpec := ctx.Select_statement().Query_expression().Query_specification()
- if querySpec == nil {
- return
- }
- if querySpec.INTO() == nil || querySpec.Table_name() == nil {
+ if tableName == "" {
return
}
- tableName := tsqlparser.NormalizeTSQLTableName(querySpec.Table_name(), "" /* fallbackDatabase */, "" /* fallbackSchema */, false /* caseSensitive */)
- r.checkTableName(tableName, ctx.GetStart().GetLine())
-}
-func (r *TableDisallowDMLRule) checkTableName(normalizedTableName string, line int) {
for _, disallow := range r.disallowList {
- if normalizedTableName == disallow {
+ if tableName == disallow {
r.AddAdvice(&storepb.Advice{
- Status: r.level,
+ Status: r.Level,
Code: code.TableDisallowDML.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("DML is disallowed on table %s.", normalizedTableName),
- StartPosition: common.ConvertANTLRLineToPosition(line),
+ Title: r.Title,
+ Content: fmt.Sprintf("DML is disallowed on table %s.", tableName),
+ StartPosition: &storepb.Position{Line: r.LocToLine(loc)},
})
return
}
diff --git a/backend/plugin/advisor/mssql/rule_table_drop_naming_convention.go b/backend/plugin/advisor/mssql/rule_table_drop_naming_convention.go
index 2a5d562d24..5c06547876 100644
--- a/backend/plugin/advisor/mssql/rule_table_drop_naming_convention.go
+++ b/backend/plugin/advisor/mssql/rule_table_drop_naming_convention.go
@@ -4,32 +4,22 @@ import (
"context"
"fmt"
"regexp"
+ "strings"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
"github.com/pkg/errors"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
-)
-
-var (
- _ advisor.Advisor = (*TableDropNamingConventionAdvisor)(nil)
)
func init() {
advisor.Register(storepb.Engine_MSSQL, storepb.SQLReviewRule_TABLE_DROP_NAMING_CONVENTION, &TableDropNamingConventionAdvisor{})
}
-// TableDropNamingConventionAdvisor is the advisor checking for table drop with naming convention.
-type TableDropNamingConventionAdvisor struct {
-}
+type TableDropNamingConventionAdvisor struct{}
-// Check checks for table drop with naming convention.
func (*TableDropNamingConventionAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
if err != nil {
@@ -46,78 +36,46 @@ func (*TableDropNamingConventionAdvisor) Check(_ context.Context, checkCtx advis
return nil, errors.Wrapf(err, "failed to compile regex format %q", namingPayload.Format)
}
- // Create the rule
- rule := NewTableDropNamingConventionRule(level, checkCtx.Rule.Type.String(), format)
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &tableDropNamingConventionRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ format: format,
}
-
- return checker.GetAdviceList(), nil
+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
-// TableDropNamingConventionRule is the rule for table drop with naming convention.
-type TableDropNamingConventionRule struct {
- BaseRule
+type tableDropNamingConventionRule struct {
+ OmniBaseRule
format *regexp.Regexp
}
-// NewTableDropNamingConventionRule creates a new TableDropNamingConventionRule.
-func NewTableDropNamingConventionRule(level storepb.Advice_Status, title string, format *regexp.Regexp) *TableDropNamingConventionRule {
- return &TableDropNamingConventionRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- format: format,
- }
-}
-
-// Name returns the rule name.
-func (*TableDropNamingConventionRule) Name() string {
+func (*tableDropNamingConventionRule) Name() string {
return "TableDropNamingConventionRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *TableDropNamingConventionRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- if nodeType == NodeTypeDropTable {
- r.enterDropTable(ctx.(*parser.Drop_tableContext))
+func (r *tableDropNamingConventionRule) OnStatement(node ast.Node) {
+ drop, ok := node.(*ast.DropStmt)
+ if !ok || drop.ObjectType != ast.DropTable {
+ return
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (*TableDropNamingConventionRule) OnExit(_ antlr.ParserRuleContext, _ string) error {
- // This rule doesn't need exit processing
- return nil
-}
-
-func (r *TableDropNamingConventionRule) enterDropTable(ctx *parser.Drop_tableContext) {
- allTableNames := ctx.AllTable_name()
- for _, tableName := range allTableNames {
- table := tableName.GetTable()
- if table == nil {
+ if drop.Names == nil {
+ return
+ }
+ for _, item := range drop.Names.Items {
+ ref, ok := item.(*ast.TableRef)
+ if !ok || ref == nil {
+ continue
+ }
+ tableName := strings.ToLower(ref.Object)
+ if tableName == "" {
continue
}
- _, normalizedTableName := tsqlparser.NormalizeTSQLIdentifier(table)
- if !r.format.MatchString(normalizedTableName) {
+ if !r.format.MatchString(tableName) {
r.AddAdvice(&storepb.Advice{
- Status: r.level,
+ Status: r.Level,
Code: code.TableDropNamingConventionMismatch.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("[%s] mismatches drop table naming convention, naming format should be %q", normalizedTableName, r.format),
- StartPosition: common.ConvertANTLRLineToPosition(ctx.GetStart().GetLine()),
+ Title: r.Title,
+ Content: fmt.Sprintf("[%s] mismatches drop table naming convention, naming format should be %q", tableName, r.format),
+ StartPosition: &storepb.Position{Line: r.LocToLine(drop.Loc)},
})
}
}
diff --git a/backend/plugin/advisor/mssql/rule_table_no_foreign_key.go b/backend/plugin/advisor/mssql/rule_table_no_foreign_key.go
index 176943a1ee..800b8b8f51 100644
--- a/backend/plugin/advisor/mssql/rule_table_no_foreign_key.go
+++ b/backend/plugin/advisor/mssql/rule_table_no_foreign_key.go
@@ -4,16 +4,11 @@ import (
"context"
"fmt"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"
)
var (
@@ -35,178 +30,128 @@ func (*TableNoForeignKeyAdvisor) Check(_ context.Context, checkCtx advisor.Conte
return nil, err
}
- // Create the rule
- rule := NewTableNoForeignKeyRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &tableNoForeignKeyOmniRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ tableHasFK: make(map[string]bool),
+ tableOriginal: make(map[string]string),
+ tableLine: make(map[string]int32),
+ tableBaseLine: make(map[string]int),
}
- // Process the final advice after walking
- rule.generateFinalAdvice()
-
- return checker.GetAdviceList(), nil
+ advice := RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})
+ advice = append(advice, rule.generateFinalAdvice()...)
+ return advice, nil
}
-// TableNoForeignKeyRule is the rule for table disallow foreign key.
-type TableNoForeignKeyRule struct {
- BaseRule
-
- // currentNormalizedTableName is the normalized table name of the current table.
- currentNormalizedTableName string
- // currentConstraintAction is the current constraint action.
- currentConstraintAction currentConstraintAction
- // tableHasForeignKey is true if the current table has foreign key.
- tableHasForeignKey map[string]bool
- // tableOriginalName is the original table name of the current table.
- tableOriginalName map[string]string
- // tableLine is the line number of the current table.
- tableLine map[string]int
-}
+type tableNoForeignKeyOmniRule struct {
+ OmniBaseRule
-// NewTableNoForeignKeyRule creates a new TableNoForeignKeyRule.
-func NewTableNoForeignKeyRule(level storepb.Advice_Status, title string) *TableNoForeignKeyRule {
- return &TableNoForeignKeyRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- currentConstraintAction: currentConstraintActionNone,
- tableHasForeignKey: make(map[string]bool),
- tableOriginalName: make(map[string]string),
- tableLine: make(map[string]int),
- }
+ tableHasFK map[string]bool
+ tableOriginal map[string]string
+ tableLine map[string]int32
+ tableBaseLine map[string]int
}
-// Name returns the rule name.
-func (*TableNoForeignKeyRule) Name() string {
- return "TableNoForeignKeyRule"
-}
-
-// OnEnter is called when entering a parse tree node.
-func (r *TableNoForeignKeyRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
- case "Column_def_table_constraints":
- r.enterColumnDefTableConstraints(ctx.(*parser.Column_def_table_constraintsContext))
- case NodeTypeAlterTable:
- r.enterAlterTable(ctx.(*parser.Alter_tableContext))
- default:
- }
- return nil
+func (*tableNoForeignKeyOmniRule) Name() string {
+ return "TableNoForeignKeyOmniRule"
}
-// OnExit is called when exiting a parse tree node.
-func (r *TableNoForeignKeyRule) OnExit(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.exitCreateTable(ctx.(*parser.Create_tableContext))
- case NodeTypeAlterTable:
- r.exitAlterTable(ctx.(*parser.Alter_tableContext))
+func (r *tableNoForeignKeyOmniRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.CreateTableStmt:
+ r.handleCreateTable(n)
+ case *ast.AlterTableStmt:
+ r.handleAlterTable(n)
default:
}
- return nil
}
-func (r *TableNoForeignKeyRule) enterCreateTable(ctx *parser.Create_tableContext) {
- tableName := ctx.Table_name()
- if tableName == nil {
+func (r *tableNoForeignKeyOmniRule) handleCreateTable(n *ast.CreateTableStmt) {
+ if n.Name == nil {
return
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
-
- r.tableHasForeignKey[normalizedTableName] = false
- r.tableOriginalName[normalizedTableName] = tableName.GetText()
- // Store absolute line number (with baseLine offset) so generateFinalAdvice can use it directly
- r.tableLine[normalizedTableName] = tableName.GetStart().GetLine() + r.baseLine
-
- r.currentNormalizedTableName = normalizedTableName
- r.currentConstraintAction = currentConstraintActionAdd
-}
-
-func (r *TableNoForeignKeyRule) exitCreateTable(*parser.Create_tableContext) {
- r.currentNormalizedTableName = ""
- r.currentConstraintAction = currentConstraintActionNone
-}
-
-func (r *TableNoForeignKeyRule) enterColumnDefTableConstraints(ctx *parser.Column_def_table_constraintsContext) {
- if r.currentNormalizedTableName == "" {
- return
- }
-
- allColumnDefTableConstraints := ctx.AllColumn_def_table_constraint()
- for _, columnDefTableConstraint := range allColumnDefTableConstraints {
- if v := columnDefTableConstraint.Column_definition(); v != nil {
- allColumnDefinitionElements := v.AllColumn_definition_element()
- for _, columnDefinitionElement := range allColumnDefinitionElements {
- if v := columnDefinitionElement.Column_constraint(); v != nil {
- if v.Foreign_key_options() != nil {
- if r.currentConstraintAction == currentConstraintActionAdd {
- r.tableHasForeignKey[r.currentNormalizedTableName] = true
- // Store absolute line number (with baseLine offset)
- r.tableLine[r.currentNormalizedTableName] = v.Foreign_key_options().GetStart().GetLine() + r.baseLine
- }
+ norm := normalizeTableRef(n.Name, "", "dbo")
+ original := tableRefText(n.Name)
+
+ r.tableHasFK[norm] = false
+ r.tableOriginal[norm] = original
+ r.tableLine[norm] = r.LocToLine(n.Name.Loc)
+ r.tableBaseLine[norm] = r.BaseLine
+
+ // Check column-level FK constraints.
+ if n.Columns != nil {
+ for _, item := range n.Columns.Items {
+ col, ok := item.(*ast.ColumnDef)
+ if !ok {
+ continue
+ }
+ if col.Constraints != nil {
+ for _, cItem := range col.Constraints.Items {
+ cd, ok := cItem.(*ast.ConstraintDef)
+ if !ok {
+ continue
+ }
+ if cd.Type == ast.ConstraintForeignKey {
+ r.tableHasFK[norm] = true
+ r.tableLine[norm] = r.LocToLine(cd.Loc)
return
}
}
}
- } else if v := columnDefTableConstraint.Table_constraint(); v != nil {
- if v.Foreign_key_options() != nil {
- if r.currentConstraintAction == currentConstraintActionAdd {
- r.tableHasForeignKey[r.currentNormalizedTableName] = true
- // Store absolute line number (with baseLine offset)
- r.tableLine[r.currentNormalizedTableName] = v.Foreign_key_options().GetStart().GetLine() + r.baseLine
- }
+ }
+ }
+
+ // Check table-level constraints.
+ if n.Constraints != nil {
+ for _, item := range n.Constraints.Items {
+ cd, ok := item.(*ast.ConstraintDef)
+ if !ok {
+ continue
+ }
+ if cd.Type == ast.ConstraintForeignKey {
+ r.tableHasFK[norm] = true
+ r.tableLine[norm] = r.LocToLine(cd.Loc)
return
}
}
}
}
-func (r *TableNoForeignKeyRule) enterAlterTable(ctx *parser.Alter_tableContext) {
- tableName := ctx.Table_name(0)
- if tableName == nil {
+func (r *tableNoForeignKeyOmniRule) handleAlterTable(n *ast.AlterTableStmt) {
+ if n.Name == nil || n.Actions == nil {
return
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
- if ctx.ADD() != nil && ctx.Column_def_table_constraints() != nil {
- r.currentNormalizedTableName = normalizedTableName
- r.currentConstraintAction = currentConstraintActionAdd
- } else if ctx.DROP() != nil && ctx.CONSTRAINT() != nil && ctx.GetConstraint() != nil {
- r.currentNormalizedTableName = normalizedTableName
- r.currentConstraintAction = currentConstraintActionDrop
- }
-}
+ norm := normalizeTableRef(n.Name, "", "dbo")
-func (r *TableNoForeignKeyRule) exitAlterTable(*parser.Alter_tableContext) {
- r.currentNormalizedTableName = ""
- r.currentConstraintAction = currentConstraintActionNone
+ for _, item := range n.Actions.Items {
+ action, ok := item.(*ast.AlterTableAction)
+ if !ok {
+ continue
+ }
+ if action.Type == ast.ATAddConstraint && action.Constraint != nil && action.Constraint.Type == ast.ConstraintForeignKey {
+ r.tableHasFK[norm] = true
+ if _, exists := r.tableOriginal[norm]; !exists {
+ r.tableOriginal[norm] = tableRefText(n.Name)
+ }
+ r.tableLine[norm] = r.LocToLine(action.Constraint.Loc)
+ r.tableBaseLine[norm] = r.BaseLine
+ }
+ }
}
-func (r *TableNoForeignKeyRule) generateFinalAdvice() {
- for tableName, hasForeignKey := range r.tableHasForeignKey {
- if hasForeignKey {
- // Directly append to adviceList instead of using AddAdvice,
- // because tableLine already contains the absolute line number
- r.adviceList = append(r.adviceList, &storepb.Advice{
- Status: r.level,
+func (r *tableNoForeignKeyOmniRule) generateFinalAdvice() []*storepb.Advice {
+ var result []*storepb.Advice
+ for norm, hasFK := range r.tableHasFK {
+ if hasFK {
+ line := r.tableLine[norm] + int32(r.tableBaseLine[norm])
+ result = append(result, &storepb.Advice{
+ Status: r.Level,
Code: code.TableHasFK.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("FOREIGN KEY is not allowed in the table %s.", r.tableOriginalName[tableName]),
- StartPosition: common.ConvertANTLRLineToPosition(r.tableLine[tableName]),
+ Title: r.Title,
+ Content: fmt.Sprintf("FOREIGN KEY is not allowed in the table %s.", r.tableOriginal[norm]),
+ StartPosition: &storepb.Position{Line: line},
})
}
}
+ return result
}
diff --git a/backend/plugin/advisor/mssql/rule_table_require_pk.go b/backend/plugin/advisor/mssql/rule_table_require_pk.go
index 2504be47e3..48fe267fb3 100644
--- a/backend/plugin/advisor/mssql/rule_table_require_pk.go
+++ b/backend/plugin/advisor/mssql/rule_table_require_pk.go
@@ -4,15 +4,11 @@ import (
"context"
"fmt"
- "github.com/antlr4-go/antlr/v4"
- parser "github.com/bytebase/parser/tsql"
+ "github.com/bytebase/omni/mssql/ast"
- "github.com/bytebase/bytebase/backend/common"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
- tsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
)
var (
@@ -34,174 +30,155 @@ func (*TableRequirePkAdvisor) Check(_ context.Context, checkCtx advisor.Context)
return nil, err
}
- // Create the rule
- rule := NewTableRequirePkRule(level, checkCtx.Rule.Type.String())
-
- // Create the generic checker with the rule
- checker := NewGenericChecker([]Rule{rule})
-
- for _, stmt := range checkCtx.ParsedStatements {
- if stmt.AST == nil {
- continue
- }
- antlrAST, ok := base.GetANTLRAST(stmt.AST)
- if !ok {
- continue
- }
- rule.SetBaseLine(stmt.BaseLine())
- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)
+ rule := &tableRequirePkOmniRule{
+ OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
+ tableHasPK: make(map[string]bool),
+ tableOriginal: make(map[string]string),
+ tableLine: make(map[string]int32),
+ tableBaseLine: make(map[string]int),
}
- // Process the final advice after walking
- rule.generateFinalAdvice()
-
- return checker.GetAdviceList(), nil
-}
-
-// TableRequirePkRule is the rule for table require primary key.
-type TableRequirePkRule struct {
- BaseRule
-
- currentNormalizedTableName string
- currentConstraintAction currentConstraintAction
-
- // tableHasPrimaryKey is a map from normalized table name to whether the table has primary key.
- tableHasPrimaryKey map[string]bool
- // tableOriginalName is a map from normalized table name to the original table name.
- tableOriginalName map[string]string
- // tableLine is a map from normalized table name to the line number of the table.
- tableLine map[string]int
+ advice := RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})
+ advice = append(advice, rule.generateFinalAdvice()...)
+ return advice, nil
}
-// NewTableRequirePkRule creates a new TableRequirePkRule.
-func NewTableRequirePkRule(level storepb.Advice_Status, title string) *TableRequirePkRule {
- return &TableRequirePkRule{
- BaseRule: BaseRule{
- level: level,
- title: title,
- },
- currentConstraintAction: currentConstraintActionNone,
- tableHasPrimaryKey: make(map[string]bool),
- tableOriginalName: make(map[string]string),
- tableLine: make(map[string]int),
- }
+type tableRequirePkOmniRule struct {
+ OmniBaseRule
+
+ // tableHasPK tracks whether each table has a primary key.
+ tableHasPK map[string]bool
+ // tableOriginal maps normalized name to original text.
+ tableOriginal map[string]string
+ // tableLine maps normalized name to the line within the statement.
+ tableLine map[string]int32
+ // tableBaseLine maps normalized name to the BaseLine of the statement.
+ tableBaseLine map[string]int
}
-// Name returns the rule name.
-func (*TableRequirePkRule) Name() string {
- return "TableRequirePkRule"
+func (*tableRequirePkOmniRule) Name() string {
+ return "TableRequirePkOmniRule"
}
-// OnEnter is called when entering a parse tree node.
-func (r *TableRequirePkRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.enterCreateTable(ctx.(*parser.Create_tableContext))
- case "Column_def_table_constraints":
- r.enterColumnDefTableConstraints(ctx.(*parser.Column_def_table_constraintsContext))
- case NodeTypeAlterTable:
- r.enterAlterTable(ctx.(*parser.Alter_tableContext))
+func (r *tableRequirePkOmniRule) OnStatement(node ast.Node) {
+ switch n := node.(type) {
+ case *ast.CreateTableStmt:
+ r.handleCreateTable(n)
+ case *ast.AlterTableStmt:
+ r.handleAlterTable(n)
default:
- // Ignore other node types
}
- return nil
-}
-
-// OnExit is called when exiting a parse tree node.
-func (r *TableRequirePkRule) OnExit(ctx antlr.ParserRuleContext, nodeType string) error {
- switch nodeType {
- case NodeTypeCreateTable:
- r.exitCreateTable(ctx.(*parser.Create_tableContext))
- case NodeTypeAlterTable:
- r.exitAlterTable(ctx.(*parser.Alter_tableContext))
- default:
- }
- return nil
-}
-
-func (r *TableRequirePkRule) enterCreateTable(ctx *parser.Create_tableContext) {
- tableName := ctx.Table_name()
- if tableName == nil {
- return
- }
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
-
- r.tableHasPrimaryKey[normalizedTableName] = false
- r.tableOriginalName[normalizedTableName] = tableName.GetText()
- // Store absolute line number (with baseLine offset) so generateFinalAdvice can use it directly
- r.tableLine[normalizedTableName] = tableName.GetStart().GetLine() + r.baseLine
-
- r.currentNormalizedTableName = normalizedTableName
- r.currentConstraintAction = currentConstraintActionAdd
-}
-
-func (r *TableRequirePkRule) exitCreateTable(*parser.Create_tableContext) {
- r.currentNormalizedTableName = ""
- r.currentConstraintAction = currentConstraintActionNone
}
-func (r *TableRequirePkRule) enterColumnDefTableConstraints(ctx *parser.Column_def_table_constraintsContext) {
- if r.currentNormalizedTableName == "" {
+func (r *tableRequirePkOmniRule) handleCreateTable(n *ast.CreateTableStmt) {
+ if n.Name == nil {
return
}
-
- allColumnDefTableConstraints := ctx.AllColumn_def_table_constraint()
- for _, columnDefTableConstraint := range allColumnDefTableConstraints {
- if v := columnDefTableConstraint.Column_definition(); v != nil {
- allColumnDefinitionElements := v.AllColumn_definition_element()
- for _, columnDefinitionElement := range allColumnDefinitionElements {
- if v := columnDefinitionElement.Column_constraint(); v != nil {
- if v.PRIMARY() != nil {
- if r.currentConstraintAction == currentConstraintActionAdd {
- r.tableHasPrimaryKey[r.currentNormalizedTableName] = true
- }
+ norm := normalizeTableRef(n.Name, "", "dbo")
+ original := tableRefText(n.Name)
+
+ r.tableHasPK[norm] = false
+ r.tableOriginal[norm] = original
+ r.tableLine[norm] = r.LocToLine(n.Name.Loc)
+ r.tableBaseLine[norm] = r.BaseLine
+
+ // Check column-level PK constraints.
+ if n.Columns != nil {
+ for _, item := range n.Columns.Items {
+ col, ok := item.(*ast.ColumnDef)
+ if !ok {
+ continue
+ }
+ if col.Constraints != nil {
+ for _, cItem := range col.Constraints.Items {
+ cd, ok := cItem.(*ast.ConstraintDef)
+ if !ok {
+ continue
+ }
+ if cd.Type == ast.ConstraintPrimaryKey {
+ r.tableHasPK[norm] = true
return
}
}
}
- } else if v := columnDefTableConstraint.Table_constraint(); v != nil {
- if v.PRIMARY() != nil {
- if r.currentConstraintAction == currentConstraintActionAdd {
- r.tableHasPrimaryKey[r.currentNormalizedTableName] = true
- }
+ }
+ }
+
+ // Check table-level constraints.
+ if n.Constraints != nil {
+ for _, item := range n.Constraints.Items {
+ cd, ok := item.(*ast.ConstraintDef)
+ if !ok {
+ continue
+ }
+ if cd.Type == ast.ConstraintPrimaryKey {
+ r.tableHasPK[norm] = true
return
}
}
}
}
-func (r *TableRequirePkRule) enterAlterTable(ctx *parser.Alter_tableContext) {
- tableName := ctx.Table_name(0)
- if tableName == nil {
+func (r *tableRequirePkOmniRule) handleAlterTable(n *ast.AlterTableStmt) {
+ if n.Name == nil || n.Actions == nil {
return
}
- normalizedTableName := tsqlparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
- if ctx.ADD() != nil && ctx.Column_def_table_constraints() != nil {
- r.currentNormalizedTableName = normalizedTableName
- r.currentConstraintAction = currentConstraintActionAdd
- } else if ctx.DROP() != nil && ctx.CONSTRAINT() != nil && ctx.GetConstraint() != nil {
- r.currentNormalizedTableName = normalizedTableName
- r.currentConstraintAction = currentConstraintActionDrop
- }
-}
+ norm := normalizeTableRef(n.Name, "", "dbo")
-func (r *TableRequirePkRule) exitAlterTable(*parser.Alter_tableContext) {
- r.currentNormalizedTableName = ""
- r.currentConstraintAction = currentConstraintActionNone
+ for _, item := range n.Actions.Items {
+ action, ok := item.(*ast.AlterTableAction)
+ if !ok {
+ continue
+ }
+ switch action.Type {
+ case ast.ATAddColumn:
+ // Check inline PK on added column: ALTER TABLE t ADD id INT PRIMARY KEY.
+ if action.Column != nil && action.Column.Constraints != nil {
+ for _, cItem := range action.Column.Constraints.Items {
+ if cd, ok := cItem.(*ast.ConstraintDef); ok && cd.Type == ast.ConstraintPrimaryKey {
+ r.tableHasPK[norm] = true
+ }
+ }
+ }
+ case ast.ATAddConstraint:
+ if action.Constraint != nil && action.Constraint.Type == ast.ConstraintPrimaryKey {
+ r.tableHasPK[norm] = true
+ }
+ case ast.ATDropConstraint:
+ // Conservatively mark as no PK when a constraint is dropped.
+ default:
+ }
+ }
}
-func (r *TableRequirePkRule) generateFinalAdvice() {
- for tableName, hasPK := range r.tableHasPrimaryKey {
+func (r *tableRequirePkOmniRule) generateFinalAdvice() []*storepb.Advice {
+ var result []*storepb.Advice
+ for norm, hasPK := range r.tableHasPK {
if !hasPK {
- // Directly append to adviceList instead of using AddAdvice,
- // because tableLine already contains the absolute line number
- r.adviceList = append(r.adviceList, &storepb.Advice{
- Status: r.level,
+ line := r.tableLine[norm] + int32(r.tableBaseLine[norm])
+ result = append(result, &storepb.Advice{
+ Status: r.Level,
Code: code.TableNoPK.Int32(),
- Title: r.title,
- Content: fmt.Sprintf("Table %s requires PRIMARY KEY.", r.tableOriginalName[tableName]),
- StartPosition: common.ConvertANTLRLineToPosition(r.tableLine[tableName]),
+ Title: r.Title,
+ Content: fmt.Sprintf("Table %s requires PRIMARY KEY.", r.tableOriginal[norm]),
+ StartPosition: &storepb.Position{Line: line},
})
}
}
+ return result
+}
+
+// tableRefText returns a human-readable string for a TableRef.
+func tableRefText(ref *ast.TableRef) string {
+ if ref == nil {
+ return ""
+ }
+ result := ref.Object
+ if ref.Schema != "" {
+ result = ref.Schema + "." + result
+ }
+ if ref.Database != "" {
+ result = ref.Database + "." + result
+ }
+ return result
}
diff --git a/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yaml b/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yaml
index 3f4b00ad9c..42882603cf 100644
--- a/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yaml
+++ b/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yaml
@@ -27,11 +27,3 @@
line: 2
column: 0
endposition: null
- - status: 2
- code: 308
- title: NAMING_IDENTIFIER_NO_KEYWORD
- content: Identifier [fillfactor] is a keyword identifier and should be avoided.
- startposition:
- line: 2
- column: 0
- endposition: null
diff --git a/backend/plugin/advisor/mssql/test/naming_table.yaml b/backend/plugin/advisor/mssql/test/naming_table.yaml
index fb4f988091..f0969a4083 100644
--- a/backend/plugin/advisor/mssql/test/naming_table.yaml
+++ b/backend/plugin/advisor/mssql/test/naming_table.yaml
@@ -6,7 +6,7 @@
- status: 2
code: 301
title: NAMING_TABLE
- content: '[\\] mismatches table naming convention, naming format should be "^[A-Z]([_A-Za-z])*$"'
+ content: '\\ mismatches table naming convention, naming format should be "^[A-Z]([_A-Za-z])*$"'
startposition:
line: 1
column: 0
diff --git a/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml b/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml
index 02d67cb567..05757114f3 100644
--- a/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml
+++ b/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml
@@ -69,7 +69,15 @@
- status: 2
code: 112
title: SCHEMA_BACKWARD_COMPATIBILITY
- content: Drop column mycolumnone, mycolumntwo may cause incompatibility with the existing data and code
+ content: Drop column mycolumnone may cause incompatibility with the existing data and code
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+ - status: 2
+ code: 112
+ title: SCHEMA_BACKWARD_COMPATIBILITY
+ content: Drop column mycolumntwo may cause incompatibility with the existing data and code
startposition:
line: 1
column: 0
diff --git a/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml
index 63d8cc721f..8b30a93441 100644
--- a/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml
+++ b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml
@@ -37,7 +37,7 @@
- status: 2
code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Calling function 'AVG(bar)' in 'WHERE' clause is not allowed
+ content: Calling function 'AVG' in 'WHERE' clause is not allowed
startposition:
line: 2
column: 0
@@ -56,7 +56,7 @@
- status: 2
code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Calling function 'AVG(a)' in 'WHERE' clause is not allowed
+ content: Calling function 'AVG' in 'WHERE' clause is not allowed
startposition:
line: 1
column: 0
diff --git a/backend/plugin/advisor/mssql/test/statement_where_require_select.yaml b/backend/plugin/advisor/mssql/test/statement_where_require_select.yaml
index 3e5f157282..3e51563e67 100644
--- a/backend/plugin/advisor/mssql/test/statement_where_require_select.yaml
+++ b/backend/plugin/advisor/mssql/test/statement_where_require_select.yaml
@@ -22,7 +22,7 @@
title: STATEMENT_WHERE_REQUIRE_SELECT
content: WHERE clause is required for SELETE statement.
startposition:
- line: 2
+ line: 1
column: 0
endposition: null
- status: 2
@@ -30,7 +30,7 @@
title: STATEMENT_WHERE_REQUIRE_SELECT
content: WHERE clause is required for SELETE statement.
startposition:
- line: 3
+ line: 2
column: 0
endposition: null
- statement: SELECT 1;
diff --git a/backend/plugin/advisor/mssql/utils_omni.go b/backend/plugin/advisor/mssql/utils_omni.go
new file mode 100644
index 0000000000..253008452d
--- /dev/null
+++ b/backend/plugin/advisor/mssql/utils_omni.go
@@ -0,0 +1,33 @@
+package mssql
+
+import (
+ "strings"
+
+ "github.com/bytebase/omni/mssql/ast"
+)
+
+// normalizeTableRef joins non-empty parts of a TableRef into a dot-separated string.
+// Case is preserved to match the original NormalizeTSQLTableName behavior.
+func normalizeTableRef(ref *ast.TableRef, fallbackDB, fallbackSchema string) string {
+ if ref == nil {
+ return ""
+ }
+ db, schema, obj := ref.Database, ref.Schema, ref.Object
+ if db == "" {
+ db = fallbackDB
+ }
+ if schema == "" {
+ schema = fallbackSchema
+ }
+ var parts []string
+ if db != "" {
+ parts = append(parts, db)
+ }
+ if schema != "" {
+ parts = append(parts, schema)
+ }
+ if obj != "" {
+ parts = append(parts, obj)
+ }
+ return strings.Join(parts, ".")
+}
diff --git a/go.mod b/go.mod
index a336b718fd..b1f5a90c63 100644
--- a/go.mod
+++ b/go.mod
@@ -34,7 +34,7 @@ require (
github.com/bmatcuk/doublestar/v4 v4.10.0
github.com/bytebase/gomongo v0.0.0-20260403033636-f6c50d4ab888
github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0
- github.com/bytebase/omni v0.0.0-20260409065645-1b566706b239
+ github.com/bytebase/omni v0.0.0-20260410074538-2f7eebc4b32e
github.com/caarlos0/env/v11 v11.4.0
github.com/cenkalti/backoff/v5 v5.0.3
github.com/cockroachdb/cockroachdb-parser v0.25.2
diff --git a/go.sum b/go.sum
index 74ada55c1f..f1875c6e29 100644
--- a/go.sum
+++ b/go.sum
@@ -253,8 +253,8 @@ github.com/bytebase/gomongo v0.0.0-20260403033636-f6c50d4ab888 h1:E8tz8maxpih/vt
github.com/bytebase/gomongo v0.0.0-20260403033636-f6c50d4ab888/go.mod h1:IgLUOjyiHehdE0G3C92IjGYu9lJQgkPwf2mdNSvPWq8=
github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0 h1:bJ8NSf2K+pccl5m/wuu97fiYjDwpJH6IzURAq/3XA2U=
github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0/go.mod h1:BEWMfiZtqshdmulKJcIsWb45MUaEvDO4CROcgi8dfFg=
-github.com/bytebase/omni v0.0.0-20260409065645-1b566706b239 h1:UK4ooauNQTq8nTJInHLNNEHnnDcy5bGav+gTbNhMEC0=
-github.com/bytebase/omni v0.0.0-20260409065645-1b566706b239/go.mod h1:SBAYEmMjJhA9WujfrIVIq76UFmsvNDOa5CekPhFXIis=
+github.com/bytebase/omni v0.0.0-20260410074538-2f7eebc4b32e h1:FyHUYAu9RU6kdOgqZdslMjCb+FAImKCrJDibrZ6ybhs=
+github.com/bytebase/omni v0.0.0-20260410074538-2f7eebc4b32e/go.mod h1:AT+iLKCu7NyxTaYaOLzETRFBVurjRaqUU3YmFron9pw=
github.com/bytebase/parser v0.0.0-20260324092042-1d52e5412f50 h1:Kq5wlhZ586Rch39y/IQV9MnrEzHob4iiXBG6zrbvSMU=
github.com/bytebase/parser v0.0.0-20260324092042-1d52e5412f50/go.mod h1:jeak/EfutSOAuWKvrFIT2IZunhWprM7oTFBRgZ9RCxo=
github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767 h1:YuR5G3LcxpO5ScSTA+Kdirxg9RW4TRc/v1t7N2Hfmbw=