Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: migrate oracle sql review to omni (#20419)
rebelicee835ee6751ab
diff --git a/backend/plugin/advisor/oracle/generic_checker.go b/backend/plugin/advisor/oracle/generic_checker.goindex 704cd296b8..3edf1a3298 100644--- a/backend/plugin/advisor/oracle/generic_checker.go+++ b/backend/plugin/advisor/oracle/generic_checker.go@@ -3,9 +3,11 @@ package oracleimport ("github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql"storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql")// Rule is the interface for Oracle advisor rules.@@ -27,6 +29,7 @@ type BaseRule struct {title stringadviceList []*storepb.AdvicebaseLine int+ stmtText string}// NewBaseRule creates a new BaseRule.@@ -59,6 +62,29 @@ func (r *BaseRule) SetBaseLine(baseLine int) {r.baseLine = baseLine}+// SetStatement sets the current statement context for omni-based rules.+func (r *BaseRule) SetStatement(baseLine int, stmtText string) {+ r.baseLine = baseLine+ r.stmtText = stmtText+}++func (r *BaseRule) locLine(loc ast.Loc) int {+ if loc.Start < 0 || r.stmtText == "" {+ return r.baseLine + 1+ }+ return r.baseLine + int(plsqlparser.ByteOffsetToRunePosition(r.stmtText, loc.Start).Line)+}++func (r *BaseRule) rawText(loc ast.Loc) string {+ if loc.Start < 0 || loc.End < loc.Start || r.stmtText == "" || loc.End > len(r.stmtText) {+ return ""+ }+ return r.stmtText[loc.Start:loc.End]+}++// OnStatement is a no-op default for rules while they are migrated to omni.+func (*BaseRule) OnStatement(_ ast.Node) {}+// GenericChecker is the only type that embeds BasePlSqlParserListener.// It dispatches parse tree events to registered rules.type GenericChecker struct {diff --git a/backend/plugin/advisor/oracle/generic_checker_omni.go b/backend/plugin/advisor/oracle/generic_checker_omni.gonew file mode 100644index 0000000000..0c3594cf30--- /dev/null+++ b/backend/plugin/advisor/oracle/generic_checker_omni.go@@ -0,0 +1,67 @@+package oracle++import (+ "github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/parser/base"+ plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql"+)++// OmniRule defines the Oracle omni SQL review rule interface.+type OmniRule interface {+ OnStatement(node ast.Node)+ Name() string+ GetAdviceList() ([]*storepb.Advice, error)+}++// RunOmniRules dispatches parsed Oracle omni AST nodes to rules.+func RunOmniRules(stmts []base.ParsedStatement, rules []OmniRule) ([]*storepb.Advice, error) {+ for _, stmt := range stmts {+ if stmt.AST == nil {+ continue+ }+ node, ok := plsqlparser.GetOmniNode(stmt.AST)+ if !ok {+ rulesForANTLR := make([]Rule, 0, len(rules))+ for _, rule := range rules {+ if legacyRule, ok := rule.(Rule); ok {+ rulesForANTLR = append(rulesForANTLR, legacyRule)+ }+ }+ if len(rulesForANTLR) == 0 {+ continue+ }+ antlrAST, ok := base.GetANTLRAST(stmt.AST)+ if !ok {+ continue+ }+ checker := NewGenericChecker(rulesForANTLR)+ for _, rule := range rulesForANTLR {+ if br, ok := rule.(interface{ SetStatement(int, string) }); ok {+ br.SetStatement(stmt.BaseLine(), stmt.Text)+ }+ }+ checker.SetBaseLine(stmt.BaseLine())+ antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)+ continue+ }+ for _, rule := range rules {+ if br, ok := rule.(interface{ SetStatement(int, string) }); ok {+ br.SetStatement(stmt.BaseLine(), stmt.Text)+ }+ rule.OnStatement(node)+ }+ }++ var adviceList []*storepb.Advice+ for _, rule := range rules {+ list, err := rule.GetAdviceList()+ if err != nil {+ return nil, err+ }+ adviceList = append(adviceList, list...)+ }+ return adviceList, nil+}diff --git a/backend/plugin/advisor/oracle/oracle_rules_test.go b/backend/plugin/advisor/oracle/oracle_rules_test.goindex 077b254372..55512431de 100644--- a/backend/plugin/advisor/oracle/oracle_rules_test.go+++ b/backend/plugin/advisor/oracle/oracle_rules_test.go@@ -2,10 +2,15 @@package oracleimport (+ "context"+ "reflect""testing"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/parser/plsql")func TestOracleRules(t *testing.T) {@@ -39,3 +44,98 @@ func TestOracleRules(t *testing.T) {advisor.RunSQLReviewRuleTest(t, rule, storepb.Engine_ORACLE, false /* record */)}}++func TestOracleAdvisorUsesOmniWithoutANTLRFallback(t *testing.T) {+ tests := []struct {+ name string+ statement string+ rule *storepb.SQLReviewRule+ advisor advisor.Advisor+ wantCount int+ }{+ {+ name: "select no select all",+ statement: "SELECT * FROM users",+ rule: &storepb.SQLReviewRule{+ Type: storepb.SQLReviewRule_STATEMENT_SELECT_NO_SELECT_ALL,+ Level: storepb.SQLReviewRule_WARNING,+ },+ advisor: &SelectNoSelectAllAdvisor{},+ wantCount: 1,+ },+ {+ name: "update inline view target",+ statement: "UPDATE (SELECT * FROM tech_book WHERE UPPER(name) = 'X') v SET v.creator = 'y'",+ rule: &storepb.SQLReviewRule{+ Type: storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS,+ Level: storepb.SQLReviewRule_WARNING,+ },+ advisor: &StatementWhereDisallowFunctionsAndCalculationsAdvisor{},+ wantCount: 1,+ },+ {+ name: "delete inline view target",+ statement: "DELETE FROM (SELECT * FROM tech_book WHERE ABS(id) > 5) v",+ rule: &storepb.SQLReviewRule{+ Type: storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS,+ Level: storepb.SQLReviewRule_WARNING,+ },+ advisor: &StatementWhereDisallowFunctionsAndCalculationsAdvisor{},+ wantCount: 1,+ },+ {+ name: "json column type",+ statement: "CREATE TABLE t(a int, b JSON)",+ rule: &storepb.SQLReviewRule{+ Type: storepb.SQLReviewRule_COLUMN_TYPE_DISALLOW_LIST,+ Level: storepb.SQLReviewRule_WARNING,+ Payload: &storepb.SQLReviewRule_StringArrayPayload{+ StringArrayPayload: &storepb.SQLReviewRule_StringArrayRulePayload{+ List: []string{"JSON"},+ },+ },+ },+ advisor: &ColumnTypeDisallowListAdvisor{},+ wantCount: 1,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ stmts, err := base.ParseStatements(storepb.Engine_ORACLE, test.statement)+ if err != nil {+ t.Fatal(err)+ }++ adviceList, err := test.advisor.Check(context.Background(), advisor.Context{+ Rule: test.rule,+ DBType: storepb.Engine_ORACLE,+ CurrentDatabase: "TEST_DB",+ DBSchema: advisor.MockOracleDatabase,+ IsObjectCaseSensitive: true,+ ParsedStatements: stmts,+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(adviceList) != test.wantCount {+ t.Fatalf("got %d advices, want %d", len(adviceList), test.wantCount)+ }++ assertOracleStmtsDidNotUseANTLRFallback(t, stmts)+ })+ }+}++func assertOracleStmtsDidNotUseANTLRFallback(t *testing.T, stmts []base.ParsedStatement) {+ t.Helper()+ for _, stmt := range stmts {+ if stmt.AST == nil {+ continue+ }+ antlrParsed := reflect.ValueOf(stmt.AST).Elem().FieldByName("antlrParsed").Bool()+ if antlrParsed {+ t.Fatalf("Oracle advisor used ANTLR fallback for %T", stmt.AST)+ }+ }+}diff --git a/backend/plugin/advisor/oracle/rule_builtin_prior_backup_check.go b/backend/plugin/advisor/oracle/rule_builtin_prior_backup_check.goindex ff12ef38c3..0e2a508c2d 100644--- a/backend/plugin/advisor/oracle/rule_builtin_prior_backup_check.go+++ b/backend/plugin/advisor/oracle/rule_builtin_prior_backup_check.go@@ -5,6 +5,7 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast""github.com/bytebase/parser/plsql"@@ -12,8 +13,6 @@ import (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"- plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql")var (@@ -38,22 +37,8 @@ func (*StatementPriorBackupCheckAdvisor) Check(ctx context.Context, checkCtx adv}rule := NewStatementPriorBackupCheckRule(ctx, level, checkCtx.Rule.Type.String(), checkCtx)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}type StatementType int@@ -75,123 +60,10 @@ type TableReference struct {}type statementInfo struct {- offset intstatement string- tree antlr.ParserRuleContexttable *TableReference}-func prepareTransformation(databaseName string, parsedStatements []base.ParsedStatement) []statementInfo {- extractor := &dmlExtractor{- databaseName: databaseName,- }-- // Walk each parse result tree to extract DML statements- for _, stmt := range parsedStatements {- if stmt.AST == nil {- continue- }- antlrAST, ok := base.GetANTLRAST(stmt.AST)- if !ok {- continue- }- antlr.ParseTreeWalkerDefault.Walk(extractor, antlrAST.Tree)- }-- return extractor.dmls-}--func IsTopLevelStatement(ctx antlr.Tree) bool {- if ctx == nil {- return true- }- switch ctx := ctx.(type) {- case *plsql.Unit_statementContext, *plsql.Sql_scriptContext:- return true- case *plsql.Data_manipulation_language_statementsContext:- return IsTopLevelStatement(ctx.GetParent())- default:- return false- }-}--type dmlExtractor struct {- *plsql.BasePlSqlParserListener-- databaseName string- dmls []statementInfo- offset int-}--func (e *dmlExtractor) ExitUnit_statement(_ *plsql.Unit_statementContext) {- e.offset++-}--func (e *dmlExtractor) ExitSql_plus_command(_ *plsql.Sql_plus_commandContext) {- e.offset++-}--func (e *dmlExtractor) EnterDelete_statement(ctx *plsql.Delete_statementContext) {- if IsTopLevelStatement(ctx.GetParent()) {- extractor := &tableExtractor{- databaseName: e.databaseName,- }- antlr.ParseTreeWalkerDefault.Walk(extractor, ctx)- extractor.table.StatementType = StatementTypeDelete-- e.dmls = append(e.dmls, statementInfo{- offset: e.offset,- statement: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),- tree: ctx,- table: extractor.table,- })- }-}--func (e *dmlExtractor) EnterUpdate_statement(ctx *plsql.Update_statementContext) {- if IsTopLevelStatement(ctx.GetParent()) {- extractor := &tableExtractor{- databaseName: e.databaseName,- }- antlr.ParseTreeWalkerDefault.Walk(extractor, ctx)- extractor.table.StatementType = StatementTypeUpdate-- e.dmls = append(e.dmls, statementInfo{- offset: e.offset,- statement: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),- tree: ctx,- table: extractor.table,- })- }-}--type tableExtractor struct {- *plsql.BasePlSqlParserListener-- databaseName string- table *TableReference-}--func (e *tableExtractor) EnterGeneral_table_ref(ctx *plsql.General_table_refContext) {- dmlTableExpr := ctx.Dml_table_expression_clause()- if dmlTableExpr != nil && dmlTableExpr.Tableview_name() != nil {- _, schemaName, tableName := plsqlparser.NormalizeTableViewName("", dmlTableExpr.Tableview_name())- e.table = &TableReference{- Database: schemaName,- HasSchema: true,- Schema: schemaName,- Table: tableName,- }- if schemaName == "" {- e.table.Schema = e.databaseName- e.table.HasSchema = false- }- if ctx.Table_alias() != nil {- e.table.Alias = plsqlparser.NormalizeTableAlias(ctx.Table_alias())- }- }-}-// StatementPriorBackupCheckRule is the rule implementation for prior backup checks.type StatementPriorBackupCheckRule struct {BaseRule@@ -199,9 +71,10 @@ type StatementPriorBackupCheckRule struct {ctx context.ContextcheckCtx advisor.Context- updateStatements []plsql.IUpdate_statementContext- deleteStatements []plsql.IDelete_statementContext- hasDDL bool+ updateStatements []plsql.IUpdate_statementContext+ deleteStatements []plsql.IDelete_statementContext+ statementInfoList []statementInfo+ hasDDL bool}// NewStatementPriorBackupCheckRule creates a new StatementPriorBackupCheckRule.@@ -218,6 +91,32 @@ func (*StatementPriorBackupCheckRule) Name() string {return "builtin.prior-backup-check"}+// OnStatement collects top-level DML/DDL facts from omni statements.+func (r *StatementPriorBackupCheckRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.UpdateStmt:+ r.statementInfoList = append(r.statementInfoList, statementInfo{+ statement: r.stmtText,+ table: oracleTableReferenceFromObjectName(r.checkCtx.DBSchema.Name, n.Table, StatementTypeUpdate),+ })+ case *ast.DeleteStmt:+ r.statementInfoList = append(r.statementInfoList, statementInfo{+ statement: r.stmtText,+ table: oracleTableReferenceFromObjectName(r.checkCtx.DBSchema.Name, n.Table, StatementTypeDelete),+ })+ default:+ if omniIsOracleDDL(node) {+ r.hasDDL = true+ }+ }+}++// GetAdviceList returns final prior-backup advice after all omni statements are processed.+func (r *StatementPriorBackupCheckRule) GetAdviceList() ([]*storepb.Advice, error) {+ r.handleSQLScriptExit()+ return r.BaseRule.GetAdviceList()+}+// OnEnter is called when the parser enters a rule context.func (r *StatementPriorBackupCheckRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Unit_statement" {@@ -282,10 +181,11 @@ func (r *StatementPriorBackupCheckRule) handleSQLScriptExit() {})}- statementInfoList := prepareTransformation(r.checkCtx.DBSchema.Name, r.checkCtx.ParsedStatements)-groupByTable := make(map[string][]statementInfo)- for _, item := range statementInfoList {+ for _, item := range r.statementInfoList {+ if item.table == nil {+ continue+ }key := fmt.Sprintf("%s.%s", item.table.Schema, item.table.Table)groupByTable[key] = append(groupByTable[key], item)}@@ -312,3 +212,31 @@ func (r *StatementPriorBackupCheckRule) handleSQLScriptExit() {r.adviceList = append(r.adviceList, adviceList...)}++func oracleTableReferenceFromObjectName(databaseName string, name *ast.ObjectName, typ StatementType) *TableReference {+ if name == nil {+ return nil+ }+ schemaName := name.Schema+ hasSchema := schemaName != ""+ if schemaName == "" {+ schemaName = databaseName+ }+ return &TableReference{+ Database: schemaName,+ HasSchema: hasSchema,+ Schema: schemaName,+ Table: name.Name,+ StatementType: typ,+ }+}++func omniIsOracleDDL(node ast.Node) bool {+ switch node.(type) {+ case *ast.CreateTableStmt, *ast.AlterTableStmt, *ast.DropStmt, *ast.CreateIndexStmt,+ *ast.CreateViewStmt, *ast.TruncateStmt, *ast.CommentStmt:+ return true+ default:+ return false+ }+}diff --git a/backend/plugin/advisor/oracle/rule_column_add_not_null_column_require_default.go b/backend/plugin/advisor/oracle/rule_column_add_not_null_column_require_default.goindex 25c449e3de..97c786c7bf 100644--- a/backend/plugin/advisor/oracle/rule_column_add_not_null_column_require_default.go+++ b/backend/plugin/advisor/oracle/rule_column_add_not_null_column_require_default.go@@ -6,13 +6,13 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -35,22 +35,8 @@ func (*ColumnAddNotNullColumnRequireDefaultAdvisor) Check(_ context.Context, che}rule := NewColumnAddNotNullColumnRequireDefaultRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ColumnAddNotNullColumnRequireDefaultRule is the rule implementation for adding not null column requires default.@@ -75,6 +61,32 @@ func (*ColumnAddNotNullColumnRequireDefaultRule) Name() string {return "column.add-not-null-column-require-default"}+// OnStatement checks ADD COLUMN actions for NOT NULL columns without DEFAULT.+func (r *ColumnAddNotNullColumnRequireDefaultRule) OnStatement(node ast.Node) {+ stmt, ok := node.(*ast.AlterTableStmt)+ if !ok {+ return+ }+ for _, cmd := range omniAlterTableCmds(stmt) {+ if cmd.Action != ast.AT_ADD_COLUMN {+ continue+ }+ for _, col := range append(omniColumnDefs(cmd.ColumnDefs), cmd.ColumnDef) {+ if col == nil || col.Default != nil {+ continue+ }+ if col.NotNull || omniColumnHasConstraint(col, ast.CONSTRAINT_NOT_NULL) {+ r.AddAdvice(+ r.level,+ code.NotNullColumnWithNoDefault.Int32(),+ fmt.Sprintf("Adding not null column %q requires default.", col.Name),+ common.ConvertANTLRLineToPosition(r.locLine(col.Loc)),+ )+ }+ }+ }+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnAddNotNullColumnRequireDefaultRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_column_comment_convention.go b/backend/plugin/advisor/oracle/rule_column_comment_convention.goindex 08432d2c66..0a37d15763 100644--- a/backend/plugin/advisor/oracle/rule_column_comment_convention.go+++ b/backend/plugin/advisor/oracle/rule_column_comment_convention.go@@ -6,13 +6,13 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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"plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql")@@ -36,22 +36,8 @@ func (*ColumnCommentConventionAdvisor) Check(_ context.Context, checkCtx advisorcommentPayload := checkCtx.Rule.GetCommentConventionPayload()rule := NewColumnCommentConventionRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, commentPayload)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ColumnCommentConventionRule is the rule implementation for column comment convention.@@ -84,6 +70,41 @@ func (*ColumnCommentConventionRule) Name() string {return "column.comment-convention"}+// OnStatement records column definitions and COMMENT ON COLUMN statements from omni.+func (r *ColumnCommentConventionRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, col := range omniColumnDefs(n.Columns) {+ columnName := fmt.Sprintf("%s.%s", tableName, col.Name)+ r.columnNames = append(r.columnNames, columnName)+ r.columnLine[columnName] = r.locLine(col.Loc)+ }+ case *ast.AlterTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, cmd := range omniAlterTableCmds(n) {+ if cmd.Action != ast.AT_ADD_COLUMN {+ continue+ }+ for _, col := range append(omniColumnDefs(cmd.ColumnDefs), cmd.ColumnDef) {+ if col == nil {+ continue+ }+ columnName := fmt.Sprintf("%s.%s", tableName, col.Name)+ r.columnNames = append(r.columnNames, columnName)+ r.columnLine[columnName] = r.locLine(col.Loc)+ }+ }+ case *ast.CommentStmt:+ if n.ObjectType != ast.OBJECT_TABLE || n.Column == "" {+ return+ }+ columnName := fmt.Sprintf("%s.%s", omniObjectName(n.Object, r.currentDatabase), n.Column)+ r.columnComment[columnName] = n.Comment+ default:+ }+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnCommentConventionRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_column_maximum_character_length.go b/backend/plugin/advisor/oracle/rule_column_maximum_character_length.goindex 76fb400211..80debb4c12 100644--- a/backend/plugin/advisor/oracle/rule_column_maximum_character_length.go+++ b/backend/plugin/advisor/oracle/rule_column_maximum_character_length.go@@ -9,13 +9,13 @@ import ("github.com/pkg/errors""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -46,22 +46,8 @@ func (*ColumnMaximumCharacterLengthAdvisor) Check(_ context.Context, checkCtx ad}rule := NewColumnMaximumCharacterLengthRule(level, checkCtx.Rule.Type.String(), int(numberPayload.Number))- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ColumnMaximumCharacterLengthRule is the rule implementation for maximum character length.@@ -84,6 +70,30 @@ func (*ColumnMaximumCharacterLengthRule) Name() string {return "column.maximum-character-length"}+// OnStatement checks CHAR/CHARACTER type modifiers in the omni AST.+func (r *ColumnMaximumCharacterLengthRule) OnStatement(node ast.Node) {+ omniWalk(node, func(n ast.Node) {+ col, ok := n.(*ast.ColumnDef)+ if !ok || col.TypeName == nil {+ return+ }+ typeName := omniTypeName(col.TypeName)+ if typeName != "CHAR" && typeName != "CHARACTER" {+ return+ }+ length, ok := omniFirstTypeModInt(col.TypeName)+ if !ok || length <= r.maximum {+ return+ }+ r.AddAdvice(+ r.level,+ code.CharLengthExceedsLimit.Int32(),+ fmt.Sprintf("The maximum character length is %d.", r.maximum),+ common.ConvertANTLRLineToPosition(r.locLine(col.TypeName.Loc)),+ )+ })+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnMaximumCharacterLengthRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Datatype" {diff --git a/backend/plugin/advisor/oracle/rule_column_maximum_varchar_length.go b/backend/plugin/advisor/oracle/rule_column_maximum_varchar_length.goindex d13b5ab637..fdabc0774d 100644--- a/backend/plugin/advisor/oracle/rule_column_maximum_varchar_length.go+++ b/backend/plugin/advisor/oracle/rule_column_maximum_varchar_length.go@@ -9,13 +9,13 @@ import ("github.com/pkg/errors""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -46,22 +46,8 @@ func (*ColumnMaximumVarcharLengthAdvisor) Check(_ context.Context, checkCtx advi}rule := NewColumnMaximumVarcharLengthRule(level, checkCtx.Rule.Type.String(), int(numberPayload.Number))- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ColumnMaximumVarcharLengthRule is the rule implementation for maximum varchar length.@@ -84,6 +70,30 @@ func (*ColumnMaximumVarcharLengthRule) Name() string {return "column.maximum-varchar-length"}+// OnStatement checks VARCHAR/VARCHAR2 type modifiers in the omni AST.+func (r *ColumnMaximumVarcharLengthRule) OnStatement(node ast.Node) {+ omniWalk(node, func(n ast.Node) {+ col, ok := n.(*ast.ColumnDef)+ if !ok || col.TypeName == nil {+ return+ }+ typeName := omniTypeName(col.TypeName)+ if typeName != "VARCHAR" && typeName != "VARCHAR2" {+ return+ }+ length, ok := omniFirstTypeModInt(col.TypeName)+ if !ok || length <= r.maximum {+ return+ }+ r.AddAdvice(+ r.level,+ code.VarcharLengthExceedsLimit.Int32(),+ fmt.Sprintf("The maximum varchar length is %d.", r.maximum),+ common.ConvertANTLRLineToPosition(r.locLine(col.TypeName.Loc)),+ )+ })+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnMaximumVarcharLengthRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Datatype" {diff --git a/backend/plugin/advisor/oracle/rule_column_no_null.go b/backend/plugin/advisor/oracle/rule_column_no_null.goindex 408978a3cd..45357ede9b 100644--- a/backend/plugin/advisor/oracle/rule_column_no_null.go+++ b/backend/plugin/advisor/oracle/rule_column_no_null.go@@ -7,13 +7,13 @@ import ("slices""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -38,22 +38,8 @@ func (*ColumnNoNullAdvisor) Check(_ context.Context, checkCtx advisor.Context) (}rule := NewColumnNoNullRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ColumnNoNullRule is the rule implementation for column no NULL value.@@ -80,6 +66,49 @@ func (*ColumnNoNullRule) Name() string {return "column.no-null"}+// OnStatement records nullable columns from omni CREATE/ALTER TABLE nodes.+func (r *ColumnNoNullRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, col := range omniColumnDefs(n.Columns) {+ r.recordNullableColumn(tableName, col)+ }+ for _, c := range omniTableConstraints(n.Constraints) {+ if c.Type == ast.CONSTRAINT_PRIMARY {+ for _, columnName := range omniListStrings(c.Columns) {+ delete(r.nullableColumns, fmt.Sprintf("%s.%s", tableName, columnName))+ }+ }+ }+ case *ast.AlterTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, cmd := range omniAlterTableCmds(n) {+ if cmd.Action != ast.AT_MODIFY_COLUMN && cmd.Action != ast.AT_ADD_COLUMN {+ continue+ }+ for _, col := range append(omniColumnDefs(cmd.ColumnDefs), cmd.ColumnDef) {+ if col != nil {+ r.recordNullableColumn(tableName, col)+ }+ }+ }+ default:+ }+}++func (r *ColumnNoNullRule) recordNullableColumn(tableName string, col *ast.ColumnDef) {+ if col == nil {+ return+ }+ columnID := fmt.Sprintf("%s.%s", tableName, col.Name)+ if col.NotNull || omniColumnHasConstraint(col, ast.CONSTRAINT_NOT_NULL) || omniColumnHasConstraint(col, ast.CONSTRAINT_PRIMARY) {+ delete(r.nullableColumns, columnID)+ return+ }+ r.nullableColumns[columnID] = r.locLine(col.Loc)+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnNoNullRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_column_require.go b/backend/plugin/advisor/oracle/rule_column_require.goindex cd0edc47e4..a4f8b06bdc 100644--- a/backend/plugin/advisor/oracle/rule_column_require.go+++ b/backend/plugin/advisor/oracle/rule_column_require.go@@ -10,13 +10,13 @@ import ("github.com/pkg/errors""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -43,22 +43,8 @@ func (*ColumnRequireAdvisor) Check(_ context.Context, checkCtx advisor.Context)}rule := NewColumnRequireRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, stringArrayPayload.List)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}type columnSet map[string]bool@@ -90,6 +76,57 @@ func (*ColumnRequireRule) Name() string {return "column.require"}+// OnStatement checks required columns in CREATE TABLE and ALTER TABLE.+func (r *ColumnRequireRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ missing := make(columnSet)+ for column := range r.requiredColumns {+ missing[column] = true+ }+ for _, col := range omniColumnDefs(n.Columns) {+ delete(missing, col.Name)+ }+ r.addMissingColumnsAdvice(omniLastObjectName(n.Name), missing, r.locLine(n.Loc))+ case *ast.AlterTableStmt:+ missing := make(columnSet)+ for _, cmd := range omniAlterTableCmds(n) {+ switch cmd.Action {+ case ast.AT_DROP_COLUMN:+ if _, ok := r.requiredColumns[cmd.ColumnName]; ok {+ missing[cmd.ColumnName] = true+ }+ case ast.AT_RENAME_COLUMN:+ if cmd.ColumnName != cmd.NewName {+ if _, ok := r.requiredColumns[cmd.ColumnName]; ok {+ missing[cmd.ColumnName] = true+ }+ }+ default:+ }+ }+ r.addMissingColumnsAdvice(omniLastObjectName(n.Name), missing, r.locLine(n.Loc))+ default:+ }+}++func (r *ColumnRequireRule) addMissingColumnsAdvice(tableName string, missing columnSet, line int) {+ if len(missing) == 0 {+ return+ }+ missingColumns := []string{}+ for column := range missing {+ missingColumns = append(missingColumns, fmt.Sprintf("%q", column))+ }+ slices.Sort(missingColumns)+ r.AddAdvice(+ r.level,+ code.NoRequiredColumn.Int32(),+ fmt.Sprintf("Table %q requires columns: %s", tableName, strings.Join(missingColumns, ", ")),+ common.ConvertANTLRLineToPosition(line),+ )+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnRequireRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_column_require_default.go b/backend/plugin/advisor/oracle/rule_column_require_default.goindex 39601a198c..6635d3fd59 100644--- a/backend/plugin/advisor/oracle/rule_column_require_default.go+++ b/backend/plugin/advisor/oracle/rule_column_require_default.go@@ -7,13 +7,13 @@ import ("slices""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -36,22 +36,8 @@ func (*ColumnRequireDefaultAdvisor) Check(_ context.Context, checkCtx advisor.Co}rule := NewColumnRequireDefaultRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ColumnRequireDefaultRule is the rule implementation for column default requirement.@@ -77,6 +63,45 @@ func (*ColumnRequireDefaultRule) Name() string {return "column.require-default"}+// OnStatement records columns without defaults from omni CREATE/ALTER TABLE nodes.+func (r *ColumnRequireDefaultRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, col := range omniColumnDefs(n.Columns) {+ r.recordNoDefaultColumn(tableName, col)+ }+ case *ast.AlterTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, cmd := range omniAlterTableCmds(n) {+ for _, col := range append(omniColumnDefs(cmd.ColumnDefs), cmd.ColumnDef) {+ if col == nil {+ continue+ }+ columnID := fmt.Sprintf("%s.%s", tableName, col.Name)+ if col.Default != nil {+ delete(r.noDefaultColumns, columnID)+ } else if cmd.Action == ast.AT_ADD_COLUMN {+ r.noDefaultColumns[columnID] = r.locLine(col.Loc)+ }+ }+ }+ default:+ }+}++func (r *ColumnRequireDefaultRule) recordNoDefaultColumn(tableName string, col *ast.ColumnDef) {+ if col == nil {+ return+ }+ columnID := fmt.Sprintf("%s.%s", tableName, col.Name)+ if col.Default == nil {+ r.noDefaultColumns[columnID] = r.locLine(col.Loc)+ } else {+ delete(r.noDefaultColumns, columnID)+ }+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnRequireDefaultRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_column_type_disallow_list.go b/backend/plugin/advisor/oracle/rule_column_type_disallow_list.goindex f18b45ba4b..bfbf8ae1c9 100644--- a/backend/plugin/advisor/oracle/rule_column_type_disallow_list.go+++ b/backend/plugin/advisor/oracle/rule_column_type_disallow_list.go@@ -4,15 +4,16 @@ package oracleimport ("context""fmt"+ "strings""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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"plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql")@@ -38,22 +39,8 @@ func (*ColumnTypeDisallowListAdvisor) Check(_ context.Context, checkCtx advisor.stringArrayPayload := checkCtx.Rule.GetStringArrayPayload()rule := NewColumnTypeDisallowListRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, stringArrayPayload.List)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ColumnTypeDisallowListRule is the rule implementation for column type disallow list.@@ -78,6 +65,28 @@ func (*ColumnTypeDisallowListRule) Name() string {return "column.type-disallow-list"}+// OnStatement checks column data types in the omni AST.+func (r *ColumnTypeDisallowListRule) OnStatement(node ast.Node) {+ omniWalk(node, func(n ast.Node) {+ col, ok := n.(*ast.ColumnDef)+ if !ok || col.TypeName == nil {+ return+ }+ typeName := omniTypeName(col.TypeName)+ for _, disallowType := range r.disallowList {+ if strings.EqualFold(typeName, disallowType) {+ r.AddAdvice(+ r.level,+ code.DisabledColumnType.Int32(),+ fmt.Sprintf("Disallow column type %s but column \"%s\" is", typeName, col.Name),+ common.ConvertANTLRLineToPosition(r.locLine(col.TypeName.Loc)),+ )+ return+ }+ }+ })+}+// OnEnter is called when the parser enters a rule context.func (r *ColumnTypeDisallowListRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_index_key_number_limit.go b/backend/plugin/advisor/oracle/rule_index_key_number_limit.goindex 890e5492ea..bf626e67dd 100644--- a/backend/plugin/advisor/oracle/rule_index_key_number_limit.go+++ b/backend/plugin/advisor/oracle/rule_index_key_number_limit.go@@ -8,13 +8,13 @@ import ("github.com/pkg/errors""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -45,22 +45,8 @@ func (*IndexKeyNumberLimitAdvisor) Check(_ context.Context, checkCtx advisor.Con}rule := NewIndexKeyNumberLimitRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, int(numberPayload.Number))- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// IndexKeyNumberLimitRule is the rule implementation for index key number limit.@@ -85,6 +71,46 @@ func (*IndexKeyNumberLimitRule) Name() string {return "index.key-number-limit"}+// OnStatement checks CREATE INDEX and constraint column counts in the omni AST.+func (r *IndexKeyNumberLimitRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateIndexStmt:+ if n.Columns != nil && len(n.Columns.Items) > r.max {+ r.AddAdvice(+ r.level,+ code.IndexKeyNumberExceedsLimit.Int32(),+ fmt.Sprintf("Index key number should be less than or equal to %d", r.max),+ common.ConvertANTLRLineToPosition(r.locLine(n.Loc)),+ )+ }+ case *ast.CreateTableStmt:+ for _, c := range omniTableConstraints(n.Constraints) {+ r.checkConstraint(c)+ }+ case *ast.AlterTableStmt:+ for _, cmd := range omniAlterTableCmds(n) {+ if cmd.Constraint != nil {+ r.checkConstraint(cmd.Constraint)+ }+ }+ default:+ }+}++func (r *IndexKeyNumberLimitRule) checkConstraint(c *ast.TableConstraint) {+ if c == nil || (c.Type != ast.CONSTRAINT_PRIMARY && c.Type != ast.CONSTRAINT_UNIQUE) {+ return+ }+ if c.Columns != nil && len(c.Columns.Items) > r.max {+ r.AddAdvice(+ r.level,+ code.IndexKeyNumberExceedsLimit.Int32(),+ fmt.Sprintf("Index key number should be less than or equal to %d", r.max),+ common.ConvertANTLRLineToPosition(r.locLine(c.Loc)),+ )+ }+}+// OnEnter is called when the parser enters a rule context.func (r *IndexKeyNumberLimitRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_insert_must_specify_column.go b/backend/plugin/advisor/oracle/rule_insert_must_specify_column.goindex 3cf8dff5a8..3c7cbfd701 100644--- a/backend/plugin/advisor/oracle/rule_insert_must_specify_column.go+++ b/backend/plugin/advisor/oracle/rule_insert_must_specify_column.go@@ -5,13 +5,13 @@ import ("context""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -34,22 +34,8 @@ func (*InsertMustSpecifyColumnAdvisor) Check(_ context.Context, checkCtx advisor}rule := NewInsertMustSpecifyColumnRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// InsertMustSpecifyColumnRule is the rule implementation for enforcing column specification in INSERT.@@ -72,6 +58,33 @@ func (*InsertMustSpecifyColumnRule) Name() string {return "insert.must-specify-column"}+// OnStatement checks INSERT INTO clauses in the omni AST.+func (r *InsertMustSpecifyColumnRule) OnStatement(node ast.Node) {+ n, ok := node.(*ast.InsertStmt)+ if !ok {+ return+ }+ if n.InsertType == ast.INSERT_SINGLE && n.Columns == nil {+ r.AddAdvice(+ r.level,+ code.InsertNotSpecifyColumn.Int32(),+ "INSERT statement should specify column name.",+ common.ConvertANTLRLineToPosition(r.locLine(n.Loc)),+ )+ }+ for _, item := range listItems(n.MultiTable) {+ clause, ok := item.(*ast.InsertIntoClause)+ if ok && clause.Columns == nil {+ r.AddAdvice(+ r.level,+ code.InsertNotSpecifyColumn.Int32(),+ "INSERT statement should specify column name.",+ common.ConvertANTLRLineToPosition(r.locLine(clause.Loc)),+ )+ }+ }+}+// OnEnter is called when the parser enters a rule context.func (r *InsertMustSpecifyColumnRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Insert_into_clause" {diff --git a/backend/plugin/advisor/oracle/rule_naming_identifier_case.go b/backend/plugin/advisor/oracle/rule_naming_identifier_case.goindex 94f0837d70..b73997041f 100644--- a/backend/plugin/advisor/oracle/rule_naming_identifier_case.go+++ b/backend/plugin/advisor/oracle/rule_naming_identifier_case.go@@ -7,13 +7,13 @@ import ("strings""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -37,22 +37,8 @@ func (*NamingIdentifierCaseAdvisor) Check(_ context.Context, checkCtx advisor.ConamingCasePayload := checkCtx.Rule.GetNamingCasePayload()rule := NewNamingIdentifierCaseRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, namingCasePayload.Upper)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// NamingIdentifierCaseRule is the rule implementation for identifier case.@@ -77,6 +63,29 @@ func (*NamingIdentifierCaseRule) Name() string {return "naming.identifier-case"}+// OnStatement checks identifier case from the omni AST.+func (r *NamingIdentifierCaseRule) OnStatement(node ast.Node) {+ for _, ident := range omniIdentifiers(node) {+ if r.upper {+ if ident.name != strings.ToUpper(ident.name) {+ r.AddAdvice(+ r.level,+ code.NamingCaseMismatch.Int32(),+ fmt.Sprintf("Identifier %q should be upper case", ident.name),+ common.ConvertANTLRLineToPosition(r.locLine(ident.loc)),+ )+ }+ } else if ident.name != strings.ToLower(ident.name) {+ r.AddAdvice(+ r.level,+ code.NamingCaseMismatch.Int32(),+ fmt.Sprintf("Identifier %q should be lower case", ident.name),+ common.ConvertANTLRLineToPosition(r.locLine(ident.loc)),+ )+ }+ }+}+// OnEnter is called when the parser enters a rule context.func (r *NamingIdentifierCaseRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Id_expression" {diff --git a/backend/plugin/advisor/oracle/rule_naming_identifier_no_keyword.go b/backend/plugin/advisor/oracle/rule_naming_identifier_no_keyword.goindex 1f45ece743..c733dfa7af 100644--- a/backend/plugin/advisor/oracle/rule_naming_identifier_no_keyword.go+++ b/backend/plugin/advisor/oracle/rule_naming_identifier_no_keyword.go@@ -6,13 +6,13 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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"plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql")@@ -36,22 +36,8 @@ func (*NamingIdentifierNoKeywordAdvisor) Check(_ context.Context, checkCtx advis}rule := NewNamingIdentifierNoKeywordRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// NamingIdentifierNoKeywordRule is the rule implementation for identifier naming convention without keyword.@@ -74,6 +60,20 @@ func (*NamingIdentifierNoKeywordRule) Name() string {return "naming.identifier-no-keyword"}+// OnStatement checks identifiers exposed by the omni AST.+func (r *NamingIdentifierNoKeywordRule) OnStatement(node ast.Node) {+ for _, ident := range omniIdentifiers(node) {+ if plsqlparser.IsOracleKeyword(ident.name) {+ r.AddAdvice(+ r.level,+ code.NameIsKeywordIdentifier.Int32(),+ fmt.Sprintf("Identifier %q is a keyword and should be avoided", ident.name),+ common.ConvertANTLRLineToPosition(r.locLine(ident.loc)),+ )+ }+ }+}+// OnEnter is called when the parser enters a rule context.func (r *NamingIdentifierNoKeywordRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Id_expression" {diff --git a/backend/plugin/advisor/oracle/rule_naming_table.go b/backend/plugin/advisor/oracle/rule_naming_table.goindex 4ee7917b7f..4fa77c6ea8 100644--- a/backend/plugin/advisor/oracle/rule_naming_table.go+++ b/backend/plugin/advisor/oracle/rule_naming_table.go@@ -7,6 +7,7 @@ import ("regexp""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""github.com/pkg/errors"@@ -14,7 +15,6 @@ import (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 (@@ -51,22 +51,8 @@ func (*NamingTableAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([}rule := NewNamingTableRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, format, maxLength)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// NamingTableRule is the rule implementation for table naming convention.@@ -93,6 +79,43 @@ func (*NamingTableRule) Name() string {return "naming.table"}+// OnStatement checks table names in omni DDL statements.+func (r *NamingTableRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ r.checkTableName(omniLastObjectName(n.Name), n.Loc)+ case *ast.AlterTableStmt:+ for _, cmd := range omniAlterTableCmds(n) {+ if cmd.Action == ast.AT_RENAME && cmd.NewName != "" {+ r.checkTableName(cmd.NewName, cmd.Loc)+ }+ }+ default:+ }+}++func (r *NamingTableRule) checkTableName(tableName string, loc ast.Loc) {+ if tableName == "" {+ return+ }+ if !r.format.MatchString(tableName) {+ r.AddAdvice(+ r.level,+ code.NamingTableConventionMismatch.Int32(),+ fmt.Sprintf(`"%s" mismatches table naming convention, naming format should be %q`, tableName, r.format),+ common.ConvertANTLRLineToPosition(r.locLine(loc)),+ )+ }+ if r.maxLength > 0 && len(tableName) > r.maxLength {+ r.AddAdvice(+ r.level,+ code.NamingTableConventionMismatch.Int32(),+ fmt.Sprintf("\"%s\" mismatches table naming convention, its length should be within %d characters", tableName, r.maxLength),+ common.ConvertANTLRLineToPosition(r.locLine(loc)),+ )+ }+}+// OnEnter is called when the parser enters a rule context.func (r *NamingTableRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_naming_table_no_keyword.go b/backend/plugin/advisor/oracle/rule_naming_table_no_keyword.goindex 7ef1f1d54d..9e409f96bc 100644--- a/backend/plugin/advisor/oracle/rule_naming_table_no_keyword.go+++ b/backend/plugin/advisor/oracle/rule_naming_table_no_keyword.go@@ -6,13 +6,13 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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"plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql")@@ -36,22 +36,8 @@ func (*NamingTableNoKeywordAdvisor) Check(_ context.Context, checkCtx advisor.Co}rule := NewNamingTableNoKeywordRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// NamingTableNoKeywordRule is the rule implementation for table naming convention without keyword.@@ -74,6 +60,32 @@ func (*NamingTableNoKeywordRule) Name() string {return "naming.table-no-keyword"}+// OnStatement checks table names in omni DDL statements.+func (r *NamingTableNoKeywordRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ r.checkTableName(omniLastObjectName(n.Name), n.Loc)+ case *ast.AlterTableStmt:+ for _, cmd := range omniAlterTableCmds(n) {+ if cmd.Action == ast.AT_RENAME && cmd.NewName != "" {+ r.checkTableName(cmd.NewName, cmd.Loc)+ }+ }+ default:+ }+}++func (r *NamingTableNoKeywordRule) checkTableName(tableName string, loc ast.Loc) {+ if tableName != "" && plsqlparser.IsOracleKeyword(tableName) {+ r.AddAdvice(+ r.level,+ code.NameIsKeywordIdentifier.Int32(),+ fmt.Sprintf("Table name %q is a keyword identifier and should be avoided.", tableName),+ common.ConvertANTLRLineToPosition(r.locLine(loc)),+ )+ }+}+// OnEnter is called when the parser enters a rule context.func (r *NamingTableNoKeywordRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_select_no_select_all.go b/backend/plugin/advisor/oracle/rule_select_no_select_all.goindex 8a61da381e..cbbdc7baaf 100644--- a/backend/plugin/advisor/oracle/rule_select_no_select_all.go+++ b/backend/plugin/advisor/oracle/rule_select_no_select_all.go@@ -5,13 +5,13 @@ import ("context""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -34,22 +34,8 @@ func (*SelectNoSelectAllAdvisor) Check(_ context.Context, checkCtx advisor.Conte}rule := NewSelectNoSelectAllRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// SelectNoSelectAllRule is the rule implementation for no select all.@@ -72,6 +58,25 @@ func (*SelectNoSelectAllRule) Name() string {return "select.no-select-all"}+// OnStatement checks SELECT targets in the omni AST.+func (r *SelectNoSelectAllRule) OnStatement(node ast.Node) {+ omniWalk(node, func(n ast.Node) {+ target, ok := n.(*ast.ResTarget)+ if !ok {+ return+ }+ if _, ok := target.Expr.(*ast.Star); !ok {+ return+ }+ r.AddAdvice(+ r.level,+ code.StatementSelectAll.Int32(),+ "Avoid using SELECT *.",+ common.ConvertANTLRLineToPosition(r.locLine(target.Loc)),+ )+ })+}+// OnEnter is called when the parser enters a rule context.func (r *SelectNoSelectAllRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Selected_list" {diff --git a/backend/plugin/advisor/oracle/rule_statement_disallow_truncate.go b/backend/plugin/advisor/oracle/rule_statement_disallow_truncate.goindex 590bf1357c..e10e3b8d21 100644--- a/backend/plugin/advisor/oracle/rule_statement_disallow_truncate.go+++ b/backend/plugin/advisor/oracle/rule_statement_disallow_truncate.go@@ -6,13 +6,13 @@ import ("strings""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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")// Oracle grammar snapshot (PlSqlParser.g4 v0.0.0-20260417075056-…):@@ -46,26 +46,73 @@ func (*StatementDisallowTruncateAdvisor) Check(_ context.Context, checkCtx advisreturn nil, err}rule := &StatementDisallowTruncateRule{BaseRule: NewBaseRule(level, checkCtx.Rule.Type.String(), 0)}- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}type StatementDisallowTruncateRule struct{ BaseRule }func (*StatementDisallowTruncateRule) Name() string { return "statement.disallow-truncate" }+// OnStatement checks TRUNCATE statements and ALTER TABLE truncate actions in the omni AST.+func (r *StatementDisallowTruncateRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.TruncateStmt:+ if n.Cluster {+ return+ }+ name := omniLastObjectName(n.Table)+ if n.Table != nil {+ if raw := r.rawText(n.Table.Loc); raw != "" {+ name = raw+ }+ }+ r.AddAdvice(+ r.level,+ code.StatementDisallowTruncate.Int32(),+ fmt.Sprintf(`TRUNCATE TABLE %q is not allowed: it issues an implicit COMMIT and cannot be rolled back. Any prior uncommitted work in the same transaction is also committed. Prior-backup treats this as DDL and does not produce row-level snapshots.`, name),+ common.ConvertANTLRLineToPosition(r.locLine(n.Loc)),+ )+ case *ast.AlterTableStmt:+ table := omniLastObjectName(n.Name)+ if n.Name != nil {+ if raw := r.rawText(n.Name.Loc); raw != "" {+ table = raw+ }+ }+ for _, cmd := range omniAlterTableCmds(n) {+ if cmd.Action != ast.AT_TRUNCATE_PARTITION {+ continue+ }+ keyword := "PARTITION"+ if strings.EqualFold(cmd.Subtype, "SUBPARTITION") {+ keyword = "SUBPARTITION"+ }+ target := cmd.ColumnName+ if target == "" {+ target = cmd.NewName+ }+ if rawAction := r.rawText(cmd.Loc); rawAction != "" {+ upperAction := strings.ToUpper(rawAction)+ if idx := strings.Index(upperAction, keyword); idx >= 0 {+ if rawTarget := strings.TrimSpace(rawAction[idx+len(keyword):]); rawTarget != "" {+ if strings.HasPrefix(strings.ToUpper(rawTarget), "FOR ") {+ rawTarget = "FOR" + strings.TrimSpace(rawTarget[len("FOR "):])+ }+ target = rawTarget+ }+ }+ }+ r.AddAdvice(+ r.level,+ code.StatementDisallowTruncate.Int32(),+ fmt.Sprintf(`ALTER TABLE %q TRUNCATE %s %q is not allowed: partition truncate shares the implicit-commit gap of TRUNCATE TABLE on Oracle. Prior-backup treats this as DDL and does not produce row-level snapshots.`, table, keyword, target),+ common.ConvertANTLRLineToPosition(r.locLine(cmd.Loc)),+ )+ }+ default:+ }+}+func (r *StatementDisallowTruncateRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {case "Truncate_table":diff --git a/backend/plugin/advisor/oracle/rule_statement_dml_dry_run.go b/backend/plugin/advisor/oracle/rule_statement_dml_dry_run.goindex ae10496bd5..5e92e84368 100644--- a/backend/plugin/advisor/oracle/rule_statement_dml_dry_run.go+++ b/backend/plugin/advisor/oracle/rule_statement_dml_dry_run.go@@ -6,6 +6,7 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql"@@ -13,7 +14,6 @@ import (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""github.com/bytebase/bytebase/backend/plugin/parser/plsql")@@ -41,24 +41,12 @@ func (*StatementDmlDryRunAdvisor) Check(ctx context.Context, checkCtx advisor.Co}rule := NewStatementDmlDryRunRule(ctx, level, checkCtx.Rule.Type.String(), checkCtx.Driver)- checker := NewGenericChecker([]Rule{rule})if checkCtx.Driver != nil {- for _, stmt := range checkCtx.ParsedStatements {- if stmt.AST == nil {- continue- }- antlrAST, ok := base.GetANTLRAST(stmt.AST)- if !ok {- continue- }- rule.SetBaseLine(stmt.BaseLine())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}- return checker.GetAdviceList()+ return rule.GetAdviceList()}// StatementDmlDryRunRule is the rule implementation for DML dry run checks.@@ -84,6 +72,15 @@ func (*StatementDmlDryRunRule) Name() string {return "statement.dml-dry-run"}+// OnStatement dry-runs top-level DML statements from the omni AST.+func (r *StatementDmlDryRunRule) OnStatement(node ast.Node) {+ switch node.(type) {+ case *ast.InsertStmt, *ast.UpdateStmt, *ast.DeleteStmt, *ast.MergeStmt:+ r.handleStmt(r.stmtText, r.baseLine+1)+ default:+ }+}+// OnEnter is called when the parser enters a rule context.func (r *StatementDmlDryRunRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_statement_where_disallow_functions_and_calculations.go b/backend/plugin/advisor/oracle/rule_statement_where_disallow_functions_and_calculations.goindex 79a9b4be8b..0d05014942 100644--- a/backend/plugin/advisor/oracle/rule_statement_where_disallow_functions_and_calculations.go+++ b/backend/plugin/advisor/oracle/rule_statement_where_disallow_functions_and_calculations.go@@ -7,13 +7,14 @@ import ("strings""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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"+ plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql""github.com/bytebase/bytebase/backend/store/model")@@ -50,21 +51,7 @@ func (*StatementWhereDisallowFunctionsAndCalculationsAdvisor) Check(_ context.CocheckCtx.IsObjectCaseSensitive,)rule.currentDatabase = checkCtx.CurrentDatabase- 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())- checker.SetBaseLine(stmt.BaseLine())- rule.depth = 0- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// ---- Types ---------------------------------------------------------------@@ -147,6 +134,474 @@ func (*WhereDisallowFunctionsAndCalculationsRule) Name() string {return "statement.where-disallow-functions-and-calculations"}+// OnStatement checks omni query-bearing statements for functions or+// calculations applied to indexed columns in WHERE-like predicates.+func (r *WhereDisallowFunctionsAndCalculationsRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.SelectStmt:+ r.checkOmniSelect(n, nil)+ case *ast.UpdateStmt:+ local := r.collectOmniDMLTargetTables(n.Target)+ r.checkOmniWhere(n.WhereClause, local)+ r.checkOmniNestedSubqueries(n, local)+ case *ast.DeleteStmt:+ local := r.collectOmniDMLTargetTables(n.Target)+ r.checkOmniWhere(n.WhereClause, local)+ r.checkOmniNestedSubqueries(n, local)+ case *ast.InsertStmt:+ if n.Select != nil {+ r.checkOmniSelect(n.Select, nil)+ }+ if subquery, ok := n.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(subquery, nil)+ sourceTables := r.collectOmniTables(subquery.FromClause)+ for _, item := range listItems(n.MultiTable) {+ clause, ok := item.(*ast.InsertIntoClause)+ if !ok {+ continue+ }+ r.checkOmniWhere(clause.When, sourceTables)+ }+ }+ r.checkOmniNestedSubqueries(n, nil)+ case *ast.MergeStmt:+ local := tablesByAlias{}+ if n.Target != nil {+ ref := oracleTableRefFromObjectName(n.Target)+ local[""] = ref+ local[r.normalizeIdent(n.Target.Name)] = ref+ if n.TargetAlias != nil && n.TargetAlias.Name != "" {+ local[r.normalizeIdent(n.TargetAlias.Name)] = ref+ }+ }+ switch source := n.Source.(type) {+ case *ast.TableRef:+ if source.Name == nil {+ break+ }+ ref := oracleTableRefFromObjectName(source.Name)+ local[r.normalizeIdent(ref.name)] = ref+ if source.Alias != nil && source.Alias.Name != "" {+ local[r.normalizeIdent(source.Alias.Name)] = ref+ }+ if n.SourceAlias != nil && n.SourceAlias.Name != "" {+ local[r.normalizeIdent(n.SourceAlias.Name)] = ref+ }+ case *ast.SubqueryRef:+ if selectStmt, ok := source.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, nil)+ }+ if source.Alias != nil && source.Alias.Name != "" {+ local[r.normalizeIdent(source.Alias.Name)] = tableRef{}+ }+ if n.SourceAlias != nil && n.SourceAlias.Name != "" {+ local[r.normalizeIdent(n.SourceAlias.Name)] = tableRef{}+ }+ default:+ }+ r.checkOmniWhere(n.On, local)+ for _, item := range listItems(n.Clauses) {+ clause, ok := item.(*ast.MergeClause)+ if !ok {+ continue+ }+ r.checkOmniWhere(clause.Condition, local)+ r.checkOmniWhere(clause.UpdateWhere, local)+ r.checkOmniWhere(clause.DeleteWhere, local)+ r.checkOmniWhere(clause.InsertWhere, local)+ r.checkOmniNestedSubqueries(clause, local)+ }+ case *ast.CreateTableStmt:+ if selectStmt, ok := n.AsQuery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, nil)+ }+ case *ast.CreateViewStmt:+ if selectStmt, ok := n.Query.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, nil)+ }+ case *ast.PLSQLBlock:+ r.runLegacyCurrentStatement()+ default:+ }+}++func (r *WhereDisallowFunctionsAndCalculationsRule) collectOmniDMLTargetTables(target ast.TableExpr) tablesByAlias {+ switch n := target.(type) {+ case *ast.TableRef:+ ref := oracleTableRefFromObjectName(n.Name)+ tables := tablesByAlias{"": ref}+ if n.Name != nil {+ tables[r.normalizeIdent(n.Name.Name)] = ref+ }+ if n.Alias != nil && n.Alias.Name != "" {+ tables[r.normalizeIdent(n.Alias.Name)] = ref+ }+ return tables+ case *ast.SubqueryRef:+ if selectStmt, ok := n.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, nil)+ }+ if n.Alias != nil && n.Alias.Name != "" {+ return tablesByAlias{r.normalizeIdent(n.Alias.Name): tableRef{}}+ }+ default:+ }+ return nil+}++func (r *WhereDisallowFunctionsAndCalculationsRule) checkOmniNestedSubqueries(node ast.Node, outer tablesByAlias) {+ omniWalk(node, func(n ast.Node) {+ switch subquery := n.(type) {+ case *ast.SubqueryExpr:+ if selectStmt, ok := subquery.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, outer)+ }+ case *ast.ExistsExpr:+ if selectStmt, ok := subquery.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, outer)+ }+ default:+ }+ })+}++func (r *WhereDisallowFunctionsAndCalculationsRule) runLegacyCurrentStatement() {+ if r.stmtText == "" {+ return+ }+ asts, err := plsqlparser.ParsePLSQL(r.stmtText)+ if err != nil {+ return+ }+ checker := NewGenericChecker([]Rule{r})+ checker.SetBaseLine(r.baseLine)+ r.SetBaseLine(r.baseLine)+ for _, antlrAST := range asts {+ antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)+ }+}++func oracleTableRefFromObjectName(name *ast.ObjectName) tableRef {+ if name == nil {+ return tableRef{}+ }+ return tableRef{schema: name.Schema, name: name.Name}+}++func (r *WhereDisallowFunctionsAndCalculationsRule) checkOmniSelect(stmt *ast.SelectStmt, outer tablesByAlias) {+ if stmt == nil {+ return+ }+ if stmt.WithClause != nil {+ names := make(map[string]bool)+ r.pushCTEs(names)+ defer r.popCTEs()+ for _, item := range listItems(stmt.WithClause.CTEs) {+ cte, ok := item.(*ast.CTE)+ if !ok {+ continue+ }+ cteName := r.normalizeIdent(cte.Name)+ if r.omniQueryIsRecursiveCTE(cte.Query, cteName) {+ names[cteName] = true+ }+ if query, ok := cte.Query.(*ast.SelectStmt); ok {+ r.checkOmniSelect(query, outer)+ }+ names[cteName] = true+ }+ }+ if stmt.Larg != nil {+ r.checkOmniSelect(stmt.Larg, outer)+ }+ if stmt.Rarg != nil {+ r.checkOmniSelect(stmt.Rarg, outer)+ }+ local := r.collectOmniTables(stmt.FromClause)+ tables := mergeTableAliases(outer, local)+ r.checkOmniWhere(stmt.WhereClause, tables)+ if stmt.Hierarchical != nil {+ r.checkOmniWhere(stmt.Hierarchical.StartWith, tables)+ r.checkOmniWhere(stmt.Hierarchical.ConnectBy, tables)+ }+ for _, item := range listItems(stmt.FromClause) {+ r.checkOmniJoinPredicates(item, tables)+ }+ omniWalk(stmt, func(n ast.Node) {+ subquery, ok := n.(*ast.SubqueryExpr)+ if ok {+ if nested, ok := subquery.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(nested, mergeTableAliases(outer, local))+ }+ }+ })+}++func (r *WhereDisallowFunctionsAndCalculationsRule) omniQueryIsRecursiveCTE(node ast.Node, tableName string) bool {+ selectStmt, ok := node.(*ast.SelectStmt)+ if !ok || (selectStmt.Larg == nil && selectStmt.Rarg == nil) {+ return false+ }+ found := false+ omniWalk(node, func(n ast.Node) {+ if found {+ return+ }+ table, ok := n.(*ast.TableRef)+ if !ok || table.Name == nil {+ return+ }+ found = r.normalizeIdent(table.Name.Name) == tableName+ })+ return found+}++func (r *WhereDisallowFunctionsAndCalculationsRule) checkOmniJoinPredicates(node ast.Node, tables tablesByAlias) {+ join, ok := node.(*ast.JoinClause)+ if !ok {+ return+ }+ r.checkOmniWhere(join.On, tables)+ if left, ok := join.Left.(ast.Node); ok {+ r.checkOmniJoinPredicates(left, tables)+ }+ if right, ok := join.Right.(ast.Node); ok {+ r.checkOmniJoinPredicates(right, tables)+ }+}++func (r *WhereDisallowFunctionsAndCalculationsRule) collectOmniTables(from *ast.List) tablesByAlias {+ tables := make(tablesByAlias)+ for _, item := range listItems(from) {+ switch n := item.(type) {+ case *ast.TableRef:+ ref := oracleTableRefFromObjectName(n.Name)+ if r.cteVisible(r.normalizeIdent(ref.name)) {+ tables[r.normalizeIdent(ref.name)] = tableRef{}+ if n.Alias != nil && n.Alias.Name != "" {+ tables[r.normalizeIdent(n.Alias.Name)] = tableRef{}+ }+ continue+ }+ if ref.name == "" {+ continue+ }+ tables[r.normalizeIdent(ref.name)] = ref+ if n.Alias != nil && n.Alias.Name != "" {+ tables[r.normalizeIdent(n.Alias.Name)] = ref+ }+ if len(tables) == 1 {+ tables[""] = ref+ }+ case *ast.JoinClause:+ for alias, ref := range r.collectOmniJoinTables(n) {+ tables[alias] = ref+ }+ default:+ }+ }+ return tables+}++func (r *WhereDisallowFunctionsAndCalculationsRule) collectOmniJoinTables(join *ast.JoinClause) tablesByAlias {+ tables := make(tablesByAlias)+ for _, item := range []ast.TableExpr{join.Left, join.Right} {+ switch n := item.(type) {+ case *ast.TableRef:+ ref := oracleTableRefFromObjectName(n.Name)+ if r.cteVisible(r.normalizeIdent(ref.name)) {+ tables[r.normalizeIdent(ref.name)] = tableRef{}+ if n.Alias != nil && n.Alias.Name != "" {+ tables[r.normalizeIdent(n.Alias.Name)] = tableRef{}+ }+ continue+ }+ tables[r.normalizeIdent(ref.name)] = ref+ if n.Alias != nil && n.Alias.Name != "" {+ tables[r.normalizeIdent(n.Alias.Name)] = ref+ }+ case *ast.JoinClause:+ for alias, ref := range r.collectOmniJoinTables(n) {+ tables[alias] = ref+ }+ default:+ }+ }+ return tables+}++func mergeTableAliases(a, b tablesByAlias) tablesByAlias {+ merged := make(tablesByAlias)+ for k, v := range a {+ merged[k] = v+ }+ for k, v := range b {+ merged[k] = v+ }+ return merged+}++func (r *WhereDisallowFunctionsAndCalculationsRule) checkOmniWhere(expr ast.ExprNode, tables tablesByAlias) {+ if expr == nil || len(tables) == 0 {+ return+ }+ indexed := r.resolveIndexedColumns(tables)+ allCols := r.resolveAllColumns(tables)+ if len(indexed) == 0 {+ return+ }+ r.walkOmniWhere(expr, scopeIndexed{local: indexed, localAll: allCols, localAliases: map[string]bool{}}, tables)+}++func (r *WhereDisallowFunctionsAndCalculationsRule) walkOmniWhere(expr ast.ExprNode, scope scopeIndexed, tables tablesByAlias) {+ switch n := expr.(type) {+ case *ast.FuncCallExpr:+ if col := r.findIndexedColumnInOmniExprList(n.Args, scope); col != "" {+ r.addOmniFunctionAdvice(n.FuncName.Name, col, n.Loc)+ }+ case *ast.BinaryExpr:+ if n.Op != "=" && n.Op != "<>" && n.Op != "!=" && n.Op != "<" && n.Op != ">" && n.Op != "<=" && n.Op != ">=" {+ if col := r.findIndexedColumnInOmniExpr(n, scope); col != "" {+ r.addOmniCalculationAdvice(col, n.Loc)+ }+ }+ case *ast.UnaryExpr:+ if n.Op == "-" || n.Op == "+" {+ if col := r.findIndexedColumnInOmniExpr(n, scope); col != "" {+ r.addOmniCalculationAdvice(col, n.Loc)+ }+ }+ case *ast.SubqueryExpr:+ if selectStmt, ok := n.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, tables)+ }+ case *ast.ExistsExpr:+ if selectStmt, ok := n.Subquery.(*ast.SelectStmt); ok {+ r.checkOmniSelect(selectStmt, tables)+ }+ default:+ }+ omniWalk(expr, func(child ast.Node) {+ if child == expr {+ return+ }+ if e, ok := child.(ast.ExprNode); ok {+ switch e.(type) {+ case *ast.FuncCallExpr, *ast.BinaryExpr, *ast.UnaryExpr, *ast.SubqueryExpr, *ast.ExistsExpr:+ r.walkOmniWhere(e, scope, tables)+ default:+ }+ }+ })+}++func (r *WhereDisallowFunctionsAndCalculationsRule) findIndexedColumnInOmniExprList(list *ast.List, scope scopeIndexed) string {+ for _, item := range listItems(list) {+ switch expr := item.(type) {+ case *ast.ColumnRef:+ qualifier := r.normalizeIdent(expr.Table)+ column := r.normalizeIdent(expr.Column)+ if r.isOmniIndexedColumn(qualifier, column, scope) {+ return column+ }+ case *ast.UnaryExpr:+ if expr.Op == "PRIOR" {+ if col := r.findDirectIndexedColumnInOmniExpr(expr.Operand, scope); col != "" {+ return col+ }+ }+ default:+ }+ }+ return ""+}++func (r *WhereDisallowFunctionsAndCalculationsRule) findDirectIndexedColumnInOmniExpr(expr ast.ExprNode, scope scopeIndexed) string {+ col, ok := expr.(*ast.ColumnRef)+ if !ok {+ return ""+ }+ qualifier := r.normalizeIdent(col.Table)+ column := r.normalizeIdent(col.Column)+ if r.isOmniIndexedColumn(qualifier, column, scope) {+ return column+ }+ return ""+}++func (r *WhereDisallowFunctionsAndCalculationsRule) findIndexedColumnInOmniExpr(expr ast.ExprNode, scope scopeIndexed) string {+ var found string+ omniWalk(expr, func(n ast.Node) {+ if found != "" {+ return+ }+ col, ok := n.(*ast.ColumnRef)+ if !ok {+ return+ }+ qualifier := r.normalizeIdent(col.Table)+ column := r.normalizeIdent(col.Column)+ if r.isOmniIndexedColumn(qualifier, column, scope) {+ found = column+ }+ })+ return found+}++func (*WhereDisallowFunctionsAndCalculationsRule) isOmniIndexedColumn(qualifier, column string, scope scopeIndexed) bool {+ if qualifier != "" {+ return scope.local[qualifier][column]+ }+ for alias, cols := range scope.local {+ if alias == "" {+ continue+ }+ if cols[column] {+ return true+ }+ }+ return scope.local[""][column]+}++func (r *WhereDisallowFunctionsAndCalculationsRule) addOmniFunctionAdvice(funcName, col string, loc ast.Loc) {+ content := fmt.Sprintf("Function %q is applied to indexed column %q in the WHERE clause, which prevents index usage", funcName, col)+ line := r.locLine(loc)+ if r.hasOmniAdvice(content, line) {+ return+ }+ r.adviceList = append(r.adviceList, &storepb.Advice{+ Status: r.level,+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),+ Title: r.title,+ Content: content,+ StartPosition: common.ConvertANTLRLineToPosition(line),+ })+}++func (r *WhereDisallowFunctionsAndCalculationsRule) addOmniCalculationAdvice(col string, loc ast.Loc) {+ content := fmt.Sprintf("Calculation is applied to indexed column %q in the WHERE clause, which prevents index usage", col)+ line := r.locLine(loc)+ if r.hasOmniAdvice(content, line) {+ return+ }+ r.adviceList = append(r.adviceList, &storepb.Advice{+ Status: r.level,+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),+ Title: r.title,+ Content: content,+ StartPosition: common.ConvertANTLRLineToPosition(line),+ })+}++func (r *WhereDisallowFunctionsAndCalculationsRule) hasOmniAdvice(content string, line int) bool {+ for _, advice := range r.adviceList {+ if advice.Content == content && advice.GetStartPosition().GetLine() == int32(line) {+ return true+ }+ }+ return false+}+// OnEnter dispatches on top-level DML / DDL-with-query contexts. Inner work// is done via manual recursion; the depth guard suppresses the walker's// automatic re-entry into nested DML/SELECT contexts.diff --git a/backend/plugin/advisor/oracle/rule_table_comment_convention.go b/backend/plugin/advisor/oracle/rule_table_comment_convention.goindex 65a4875df1..fc1ed2fbb2 100644--- a/backend/plugin/advisor/oracle/rule_table_comment_convention.go+++ b/backend/plugin/advisor/oracle/rule_table_comment_convention.go@@ -6,13 +6,13 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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"plsqlparser "github.com/bytebase/bytebase/backend/plugin/parser/plsql")@@ -36,22 +36,8 @@ func (*TableCommentConventionAdvisor) Check(_ context.Context, checkCtx advisor.commentPayload := checkCtx.Rule.GetCommentConventionPayload()rule := NewTableCommentConventionRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase, commentPayload)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// TableCommentConventionRule is the rule implementation for table comment convention.@@ -83,6 +69,22 @@ func (*TableCommentConventionRule) Name() string {return "table.comment-convention"}+// OnStatement records table creation and COMMENT ON TABLE statements from omni.+func (r *TableCommentConventionRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ r.tableNames = append(r.tableNames, tableName)+ r.tableLine[tableName] = r.locLine(n.Loc)+ case *ast.CommentStmt:+ if n.ObjectType != ast.OBJECT_TABLE {+ return+ }+ r.tableComment[omniObjectName(n.Object, r.currentDatabase)] = n.Comment+ default:+ }+}+// OnEnter is called when the parser enters a rule context.func (r *TableCommentConventionRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_table_no_foreign_key.go b/backend/plugin/advisor/oracle/rule_table_no_foreign_key.goindex 440d8c671f..8fd556ef6e 100644--- a/backend/plugin/advisor/oracle/rule_table_no_foreign_key.go+++ b/backend/plugin/advisor/oracle/rule_table_no_foreign_key.go@@ -6,13 +6,13 @@ import ("fmt""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -35,22 +35,8 @@ func (*TableNoForeignKeyAdvisor) Check(_ context.Context, checkCtx advisor.Conte}rule := NewTableNoForeignKeyRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// TableNoForeignKeyRule is the rule implementation for table disallow foreign key.@@ -78,6 +64,41 @@ func (*TableNoForeignKeyRule) Name() string {return "table.no-foreign-key"}+// OnStatement checks foreign keys from omni CREATE/ALTER TABLE nodes.+func (r *TableNoForeignKeyRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ if r.createTableHasFK(n) {+ r.tableWithFK[tableName] = true+ r.tableLine[tableName] = r.locLine(n.Loc)+ }+ case *ast.AlterTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, cmd := range omniAlterTableCmds(n) {+ if cmd.Constraint != nil && cmd.Constraint.Type == ast.CONSTRAINT_FOREIGN {+ r.tableWithFK[tableName] = true+ r.tableLine[tableName] = r.locLine(cmd.Constraint.Loc)+ }+ }+ default:+ }+}++func (*TableNoForeignKeyRule) createTableHasFK(stmt *ast.CreateTableStmt) bool {+ for _, col := range omniColumnDefs(stmt.Columns) {+ if omniColumnHasConstraint(col, ast.CONSTRAINT_FOREIGN) {+ return true+ }+ }+ for _, c := range omniTableConstraints(stmt.Constraints) {+ if c.Type == ast.CONSTRAINT_FOREIGN {+ return true+ }+ }+ return false+}+// OnEnter is called when the parser enters a rule context.func (r *TableNoForeignKeyRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_table_require_pk.go b/backend/plugin/advisor/oracle/rule_table_require_pk.goindex cd33fdf53a..946701543a 100644--- a/backend/plugin/advisor/oracle/rule_table_require_pk.go+++ b/backend/plugin/advisor/oracle/rule_table_require_pk.go@@ -4,15 +4,16 @@ package oracleimport ("context""fmt"+ "strings""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -35,22 +36,8 @@ func (*TableRequirePKAdvisor) Check(_ context.Context, checkCtx advisor.Context)}rule := NewTableRequirePKRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// TableRequirePKRule is the rule implementation for table requires PK.@@ -78,6 +65,54 @@ func (*TableRequirePKRule) Name() string {return "table.require-pk"}+// OnStatement checks primary-key state from omni DDL nodes.+func (r *TableRequirePKRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.CreateTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ r.tableWitPK[tableName] = r.createTableHasPK(n)+ r.tableLine[tableName] = r.locLine(n.Loc)+ case *ast.AlterTableStmt:+ tableName := omniObjectName(n.Name, r.currentDatabase)+ for _, cmd := range omniAlterTableCmds(n) {+ switch cmd.Action {+ case ast.AT_ADD_CONSTRAINT:+ if cmd.Constraint != nil && cmd.Constraint.Type == ast.CONSTRAINT_PRIMARY {+ r.tableWitPK[tableName] = true+ }+ case ast.AT_DROP_CONSTRAINT:+ if strings.Contains(strings.ToUpper(cmd.Subtype), "PRIMARY") || strings.EqualFold(cmd.ColumnName, "PRIMARY") {+ r.tableWitPK[tableName] = false+ r.tableLine[tableName] = r.locLine(cmd.Loc)+ }+ default:+ }+ }+ case *ast.DropStmt:+ for _, item := range listItems(n.Names) {+ name, ok := item.(*ast.ObjectName)+ if ok {+ delete(r.tableWitPK, omniObjectName(name, r.currentDatabase))+ }+ }+ default:+ }+}++func (*TableRequirePKRule) createTableHasPK(stmt *ast.CreateTableStmt) bool {+ for _, col := range omniColumnDefs(stmt.Columns) {+ if omniColumnHasConstraint(col, ast.CONSTRAINT_PRIMARY) {+ return true+ }+ }+ for _, c := range omniTableConstraints(stmt.Constraints) {+ if c.Type == ast.CONSTRAINT_PRIMARY {+ return true+ }+ }+ return false+}+// OnEnter is called when the parser enters a rule context.func (r *TableRequirePKRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/rule_where_no_leading_wildcard_like.go b/backend/plugin/advisor/oracle/rule_where_no_leading_wildcard_like.goindex 9e329c8b08..021d722b78 100644--- a/backend/plugin/advisor/oracle/rule_where_no_leading_wildcard_like.go+++ b/backend/plugin/advisor/oracle/rule_where_no_leading_wildcard_like.go@@ -6,13 +6,13 @@ import ("strings""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -35,22 +35,8 @@ func (*WhereNoLeadingWildcardLikeAdvisor) Check(_ context.Context, checkCtx advi}rule := NewWhereNoLeadingWildcardLikeRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// WhereNoLeadingWildcardLikeRule is the rule implementation for no leading wildcard LIKE.@@ -73,6 +59,26 @@ func (*WhereNoLeadingWildcardLikeRule) Name() string {return "where.no-leading-wildcard-like"}+// OnStatement checks LIKE predicates in the omni AST.+func (r *WhereNoLeadingWildcardLikeRule) OnStatement(node ast.Node) {+ omniWalk(node, func(n ast.Node) {+ like, ok := n.(*ast.LikeExpr)+ if !ok {+ return+ }+ pattern, ok := like.Pattern.(*ast.StringLiteral)+ if !ok || !strings.HasPrefix(pattern.Val, "%") {+ return+ }+ r.AddAdvice(+ r.level,+ code.StatementLeadingWildcardLike.Int32(),+ "Avoid using leading wildcard LIKE.",+ common.ConvertANTLRLineToPosition(r.locLine(like.Loc)),+ )+ })+}+// OnEnter is called when the parser enters a rule context.func (r *WhereNoLeadingWildcardLikeRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Compound_expression" {diff --git a/backend/plugin/advisor/oracle/rule_where_require_for_select.go b/backend/plugin/advisor/oracle/rule_where_require_for_select.goindex c83334bb76..abe692ae91 100644--- a/backend/plugin/advisor/oracle/rule_where_require_for_select.go+++ b/backend/plugin/advisor/oracle/rule_where_require_for_select.go@@ -6,13 +6,13 @@ import ("strings""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -35,22 +35,8 @@ func (*WhereRequireForSelectAdvisor) Check(_ context.Context, checkCtx advisor.C}rule := NewWhereRequireForSelectRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// WhereRequireForSelectRule is the rule implementation for WHERE clause requirement in SELECT.@@ -73,6 +59,32 @@ func (*WhereRequireForSelectRule) Name() string {return "where.require-for-select"}+// OnStatement checks SELECT statements with FROM clauses in the omni AST.+func (r *WhereRequireForSelectRule) OnStatement(node ast.Node) {+ omniWalk(node, func(n ast.Node) {+ selectStmt, ok := n.(*ast.SelectStmt)+ if !ok {+ return+ }+ if selectStmt.FromClause == nil || len(selectStmt.FromClause.Items) == 0 {+ return+ }+ if len(selectStmt.FromClause.Items) == 1 {+ if table, ok := selectStmt.FromClause.Items[0].(*ast.TableRef); ok && table.Name != nil && strings.EqualFold(table.Name.Name, "DUAL") {+ return+ }+ }+ if selectStmt.WhereClause == nil {+ r.AddAdvice(+ r.level,+ code.StatementNoWhere.Int32(),+ "WHERE clause is required for SELECT statement.",+ common.ConvertANTLRLineToPosition(r.locLine(selectStmt.Loc)),+ )+ }+ })+}+// OnEnter is called when the parser enters a rule context.func (r *WhereRequireForSelectRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {if nodeType == "Query_block" {diff --git a/backend/plugin/advisor/oracle/rule_where_require_for_update_delete.go b/backend/plugin/advisor/oracle/rule_where_require_for_update_delete.goindex 0e23b7a1da..226fb14ed9 100644--- a/backend/plugin/advisor/oracle/rule_where_require_for_update_delete.go+++ b/backend/plugin/advisor/oracle/rule_where_require_for_update_delete.go@@ -5,13 +5,13 @@ import ("context""github.com/antlr4-go/antlr/v4"+ "github.com/bytebase/omni/oracle/ast"parser "github.com/bytebase/parser/plsql""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 (@@ -34,22 +34,8 @@ func (*WhereRequireForUpdateDeleteAdvisor) Check(_ context.Context, checkCtx adv}rule := NewWhereRequireForUpdateDeleteRule(level, checkCtx.Rule.Type.String(), checkCtx.CurrentDatabase)- 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())- checker.SetBaseLine(stmt.BaseLine())- antlr.ParseTreeWalkerDefault.Walk(checker, antlrAST.Tree)- }-- return checker.GetAdviceList()+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule})}// WhereRequireForUpdateDeleteRule is the rule implementation for WHERE clause requirement in UPDATE/DELETE.@@ -72,6 +58,31 @@ func (*WhereRequireForUpdateDeleteRule) Name() string {return "where.require-for-update-delete"}+// OnStatement checks top-level UPDATE and DELETE statements in the omni AST.+func (r *WhereRequireForUpdateDeleteRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.UpdateStmt:+ if n.WhereClause == nil {+ r.AddAdvice(+ r.level,+ code.StatementNoWhere.Int32(),+ "WHERE clause is required for UPDATE statement.",+ common.ConvertANTLRLineToPosition(r.locLine(n.Loc)),+ )+ }+ case *ast.DeleteStmt:+ if n.WhereClause == nil {+ r.AddAdvice(+ r.level,+ code.StatementNoWhere.Int32(),+ "WHERE clause is required for DELETE statement.",+ common.ConvertANTLRLineToPosition(r.locLine(n.Loc)),+ )+ }+ default:+ }+}+// OnEnter is called when the parser enters a rule context.func (r *WhereRequireForUpdateDeleteRule) OnEnter(ctx antlr.ParserRuleContext, nodeType string) error {switch nodeType {diff --git a/backend/plugin/advisor/oracle/utils_omni.go b/backend/plugin/advisor/oracle/utils_omni.gonew file mode 100644index 0000000000..9152b4c2b3--- /dev/null+++ b/backend/plugin/advisor/oracle/utils_omni.go@@ -0,0 +1,197 @@+package oracle++import (+ "fmt"+ "strconv"+ "strings"++ "github.com/bytebase/omni/oracle/ast"+)++type omniIdentifier struct {+ name string+ loc ast.Loc+}++func omniObjectName(name *ast.ObjectName, currentSchema string) string {+ if name == nil {+ return ""+ }+ schema := name.Schema+ if schema == "" {+ schema = currentSchema+ }+ if schema == "" {+ return name.Name+ }+ return fmt.Sprintf("%s.%s", schema, name.Name)+}++func omniLastObjectName(name *ast.ObjectName) string {+ if name == nil {+ return ""+ }+ return name.Name+}++func omniListStrings(list *ast.List) []string {+ if list == nil {+ return nil+ }+ result := make([]string, 0, len(list.Items))+ for _, item := range list.Items {+ switch n := item.(type) {+ case *ast.String:+ result = append(result, n.Str)+ case *ast.ColumnRef:+ result = append(result, n.Column)+ default:+ }+ }+ return result+}++func listItems(list *ast.List) []ast.Node {+ if list == nil {+ return nil+ }+ return list.Items+}++func omniColumnDefs(list *ast.List) []*ast.ColumnDef {+ if list == nil {+ return nil+ }+ result := make([]*ast.ColumnDef, 0, len(list.Items))+ for _, item := range list.Items {+ if col, ok := item.(*ast.ColumnDef); ok {+ result = append(result, col)+ }+ }+ return result+}++func omniTableConstraints(list *ast.List) []*ast.TableConstraint {+ if list == nil {+ return nil+ }+ result := make([]*ast.TableConstraint, 0, len(list.Items))+ for _, item := range list.Items {+ if c, ok := item.(*ast.TableConstraint); ok {+ result = append(result, c)+ }+ }+ return result+}++func omniAlterTableCmds(stmt *ast.AlterTableStmt) []*ast.AlterTableCmd {+ if stmt == nil || stmt.Actions == nil {+ return nil+ }+ result := make([]*ast.AlterTableCmd, 0, len(stmt.Actions.Items))+ for _, item := range stmt.Actions.Items {+ if cmd, ok := item.(*ast.AlterTableCmd); ok {+ result = append(result, cmd)+ }+ }+ return result+}++func omniColumnConstraints(col *ast.ColumnDef) []*ast.ColumnConstraint {+ if col == nil || col.Constraints == nil {+ return nil+ }+ result := make([]*ast.ColumnConstraint, 0, len(col.Constraints.Items))+ for _, item := range col.Constraints.Items {+ if c, ok := item.(*ast.ColumnConstraint); ok {+ result = append(result, c)+ }+ }+ return result+}++func omniTypeName(tn *ast.TypeName) string {+ parts := omniListStrings(tnNames(tn))+ return strings.ToUpper(strings.Join(parts, "."))+}++func tnNames(tn *ast.TypeName) *ast.List {+ if tn == nil {+ return nil+ }+ return tn.Names+}++func omniFirstTypeModInt(tn *ast.TypeName) (int, bool) {+ if tn == nil || tn.TypeMods == nil || len(tn.TypeMods.Items) == 0 {+ return 0, false+ }+ switch n := tn.TypeMods.Items[0].(type) {+ case *ast.Integer:+ return int(n.Ival), true+ case *ast.Float:+ v, err := strconv.Atoi(n.Fval)+ return v, err == nil+ }+ return 0, false+}++func omniColumnHasConstraint(col *ast.ColumnDef, typ ast.ConstraintType) bool {+ for _, c := range omniColumnConstraints(col) {+ if c.Type == typ {+ return true+ }+ }+ return false+}++func omniIdentifiers(node ast.Node) []omniIdentifier {+ var result []omniIdentifier+ seen := make(map[string]bool)+ add := func(name string, loc ast.Loc) {+ if name == "" {+ return+ }+ key := fmt.Sprintf("%s:%d", name, loc.Start)+ if seen[key] {+ return+ }+ seen[key] = true+ result = append(result, omniIdentifier{name: name, loc: loc})+ }+ omniWalk(node, func(n ast.Node) {+ switch x := n.(type) {+ case *ast.ObjectName:+ add(x.Schema, x.Loc)+ add(x.Name, x.Loc)+ case *ast.ColumnDef:+ add(x.Name, x.Loc)+ case *ast.ColumnRef:+ add(x.Schema, x.Loc)+ add(x.Table, x.Loc)+ add(x.Column, x.Loc)+ case *ast.Alias:+ add(x.Name, x.Loc)+ case *ast.ColumnConstraint:+ add(x.Name, x.Loc)+ case *ast.TableConstraint:+ add(x.Name, x.Loc)+ for _, name := range omniListStrings(x.Columns) {+ add(name, x.Loc)+ }+ case *ast.CTE:+ add(x.Name, x.Loc)+ case *ast.CommentStmt:+ add(x.Column, x.Loc)+ default:+ }+ })+ return result+}++func omniWalk(node ast.Node, visit func(ast.Node)) {+ ast.Inspect(node, func(n ast.Node) bool {+ visit(n)+ return true+ })+}diff --git a/go.mod b/go.modindex a2de5c8d02..99164c8f45 100644--- a/go.mod+++ b/go.mod@@ -34,7 +34,7 @@ require (github.com/bmatcuk/doublestar/v4 v4.10.0github.com/bytebase/gomongo v0.0.0-20260510192859-8526a440b352github.com/bytebase/lsp-protocol v0.0.0-20250324071136-1586d0c10ff0- github.com/bytebase/omni v0.0.0-20260526091314-3332e95cbcc5+ github.com/bytebase/omni v0.0.0-20260527100738-02b1a9f3a954github.com/caarlos0/env/v11 v11.4.1github.com/cenkalti/backoff/v5 v5.0.3github.com/cockroachdb/cockroachdb-parser v0.25.2diff --git a/go.sum b/go.sumindex f46eb95501..322442fd56 100644--- a/go.sum+++ b/go.sum@@ -250,8 +250,8 @@ github.com/bytebase/gomongo v0.0.0-20260510192859-8526a440b352 h1:3sC5pdvJ7bNAhRgithub.com/bytebase/gomongo v0.0.0-20260510192859-8526a440b352/go.mod h1:eyWrxE51HCbjGIChvty/mYaNcAroXshnIiR6SIqlxfY=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-20260526091314-3332e95cbcc5 h1:nwOlLs/5GLVxqjmWRZt0TMO9SIUGoYyo8/sUWsPLuMc=-github.com/bytebase/omni v0.0.0-20260526091314-3332e95cbcc5/go.mod h1:EVG8nQbNPUnUBGKn6J0niSGOs3jgfKo3TciY22R4bfo=+github.com/bytebase/omni v0.0.0-20260527100738-02b1a9f3a954 h1:ADmVnC+pOrjcqzI7m8UAafCUYQwGsXgawz/nsuJYQDY=+github.com/bytebase/omni v0.0.0-20260527100738-02b1a9f3a954/go.mod h1:EVG8nQbNPUnUBGKn6J0niSGOs3jgfKo3TciY22R4bfo=github.com/bytebase/parser v0.0.0-20260417075056-57b6ef7a2640 h1:g4Jed1/Jv/DHBiQmEgN5ILOQDDBjFlG4N4Lp+3B4aYE=github.com/bytebase/parser v0.0.0-20260417075056-57b6ef7a2640/go.mod h1:jeak/EfutSOAuWKvrFIT2IZunhWprM7oTFBRgZ9RCxo=github.com/bytebase/pgx/v5 v5.0.0-20250212161523-96ff8aed8767 h1:YuR5G3LcxpO5ScSTA+Kdirxg9RW4TRc/v1t7N2Hfmbw=