Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(advisor): PG & Oracle STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS (#20048)
zchpeter08c5547ba097
diff --git a/backend/plugin/advisor/oracle/generic_checker.go b/backend/plugin/advisor/oracle/generic_checker.goindex ece915ea6b..35eff86b32 100644--- a/backend/plugin/advisor/oracle/generic_checker.go+++ b/backend/plugin/advisor/oracle/generic_checker.go@@ -127,6 +127,10 @@ func (*GenericChecker) getNodeType(ctx antlr.ParserRuleContext) string {return "Drop_table"case *parser.Create_indexContext:return "Create_index"+ case *parser.Create_viewContext:+ return "Create_view"+ case *parser.Create_materialized_viewContext:+ return "Create_materialized_view"case *parser.Drop_indexContext:return "Drop_index"case *parser.Insert_statementContext:diff --git a/backend/plugin/advisor/oracle/oracle_rules_test.go b/backend/plugin/advisor/oracle/oracle_rules_test.goindex 1d48320ae3..79dba1a86a 100644--- a/backend/plugin/advisor/oracle/oracle_rules_test.go+++ b/backend/plugin/advisor/oracle/oracle_rules_test.go@@ -18,6 +18,7 @@ func TestOracleRules(t *testing.T) {{Type: storepb.SQLReviewRule_COLUMN_MAXIMUM_CHARACTER_LENGTH, Level: storepb.SQLReviewRule_WARNING, Payload: &storepb.SQLReviewRule_NumberPayload{NumberPayload: &storepb.SQLReviewRule_NumberRulePayload{Number: 20}}},{Type: storepb.SQLReviewRule_STATEMENT_SELECT_NO_SELECT_ALL, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_WHERE_NO_LEADING_WILDCARD_LIKE, Level: storepb.SQLReviewRule_WARNING},+ {Type: storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_WHERE_REQUIRE_SELECT, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_WHERE_REQUIRE_UPDATE_DELETE, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_INSERT_MUST_SPECIFY_COLUMN, Level: storepb.SQLReviewRule_WARNING},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.gonew file mode 100644index 0000000000..79a9b4be8b--- /dev/null+++ b/backend/plugin/advisor/oracle/rule_statement_where_disallow_functions_and_calculations.go@@ -0,0 +1,1730 @@+// Package oracle is the advisor for oracle database.+package oracle++import (+ "context"+ "fmt"+ "strings"++ "github.com/antlr4-go/antlr/v4"+ 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"+ "github.com/bytebase/bytebase/backend/store/model"+)++var (+ _ advisor.Advisor = (*StatementWhereDisallowFunctionsAndCalculationsAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_ORACLE, storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS, &StatementWhereDisallowFunctionsAndCalculationsAdvisor{})+}++// StatementWhereDisallowFunctionsAndCalculationsAdvisor is the Oracle advisor+// that flags functions or calculations applied to indexed columns in WHERE clauses.+type StatementWhereDisallowFunctionsAndCalculationsAdvisor struct{}++// Check implements advisor.Advisor.+func (*StatementWhereDisallowFunctionsAndCalculationsAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {+ level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)+ if err != nil {+ return nil, err+ }+ // Oracle sync stores ONLY the connected schema's objects under a+ // SchemaMetadata{Name: ""} (see backend/plugin/db/oracle/sync.go:128-135+ // — d.databaseName is used as the DatabaseSchemaMetadata.Name and only+ // that owner's objects are populated). currentSchema must be "" to+ // match the anonymous container; cross-owner qualified refs (e.g.+ // `OTHER_OWNER.TECH_BOOK` where OTHER_OWNER != checkCtx.CurrentDatabase)+ // are NOT in our metadata and must return nil — see tableMetadata.+ rule := NewWhereDisallowFunctionsAndCalculationsRule(+ level,+ checkCtx.Rule.Type.String(),+ "",+ checkCtx.DBSchema,+ checkCtx.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()+}++// ---- Types ---------------------------------------------------------------++type tableRef struct {+ schema string+ name string+}++type tablesByAlias = map[string]tableRef+type indexedByAlias = map[string]map[string]bool++type scopeIndexed struct {+ local indexedByAlias+ localAll indexedByAlias+ localAliases map[string]bool+ outer indexedByAlias+ localUnresolved bool+}++func (s scopeIndexed) empty() bool {+ return len(s.local) == 0 && len(s.outer) == 0+}++// WhereDisallowFunctionsAndCalculationsRule is the rule implementation.+type WhereDisallowFunctionsAndCalculationsRule struct {+ BaseRule+ currentSchema string+ currentDatabase string+ dbMetadata *model.DatabaseMetadata+ isObjectCaseSensitive bool+ depth int+ // cteStack mirrors the PG rule's CTE-shadowing handling. Pushed when+ // entering a Query_block with a Subquery_factoring_clause; popped on+ // exit. A FROM tableview_name matching any stacked entry is recorded+ // as opaque (`tableRef{}`) so it doesn't pick up base-table indexes.+ cteStack []map[string]bool+}++func (r *WhereDisallowFunctionsAndCalculationsRule) pushCTEs(names map[string]bool) {+ r.cteStack = append(r.cteStack, names)+}++func (r *WhereDisallowFunctionsAndCalculationsRule) popCTEs() {+ if n := len(r.cteStack); n > 0 {+ r.cteStack = r.cteStack[:n-1]+ }+}++func (r *WhereDisallowFunctionsAndCalculationsRule) cteVisible(name string) bool {+ for _, frame := range r.cteStack {+ if frame[name] {+ return true+ }+ }+ return false+}++// NewWhereDisallowFunctionsAndCalculationsRule constructs the rule.+func NewWhereDisallowFunctionsAndCalculationsRule(+ level storepb.Advice_Status,+ title string,+ currentSchema string,+ dbSchema *storepb.DatabaseSchemaMetadata,+ isObjectCaseSensitive bool,+) *WhereDisallowFunctionsAndCalculationsRule {+ r := &WhereDisallowFunctionsAndCalculationsRule{+ BaseRule: NewBaseRule(level, title, 0),+ currentSchema: currentSchema,+ isObjectCaseSensitive: isObjectCaseSensitive,+ }+ if dbSchema != nil {+ r.dbMetadata = model.NewDatabaseMetadata(dbSchema, nil, nil, storepb.Engine_ORACLE, isObjectCaseSensitive)+ }+ return r+}++// Name returns the rule name.+func (*WhereDisallowFunctionsAndCalculationsRule) Name() string {+ return "statement.where-disallow-functions-and-calculations"+}++// 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.+//+// Invariant: for every matching context type, OnEnter increments depth and+// OnExit decrements depth — UNCONDITIONALLY, regardless of whether a+// handler was dispatched. This keeps push/pop balanced even when a+// dispatch context nests another (e.g. Insert_statement contains a+// Select_statement source). The handler is called only when this is the+// outermost matching context (depth == 1 after increment).+func (r *WhereDisallowFunctionsAndCalculationsRule) OnEnter(ctx antlr.ParserRuleContext, _ string) error {+ // Defensive reset: at the root of a freshly-walked tree, parent is nil.+ if ctx.GetParent() == nil {+ r.depth = 0+ }+ shouldDispatch := r.depth == 0+ switch c := ctx.(type) {+ case *parser.Select_statementContext:+ r.depth+++ if shouldDispatch {+ r.onSelectStmt(c)+ }+ case *parser.Update_statementContext:+ r.depth+++ if shouldDispatch {+ r.onUpdateStmt(c)+ }+ case *parser.Delete_statementContext:+ r.depth+++ if shouldDispatch {+ r.onDeleteStmt(c)+ }+ case *parser.Insert_statementContext:+ r.depth+++ if shouldDispatch {+ r.onInsertStmt(c)+ }+ case *parser.Merge_statementContext:+ r.depth+++ if shouldDispatch {+ r.onMergeStmt(c)+ }+ case *parser.Create_tableContext:+ r.depth+++ if shouldDispatch {+ r.onCreateTable(c)+ }+ case *parser.Create_viewContext:+ r.depth+++ if shouldDispatch {+ r.onCreateView(c)+ }+ case *parser.Create_materialized_viewContext:+ r.depth+++ if shouldDispatch {+ r.onCreateMaterializedView(c)+ }+ default:+ }+ return nil+}++// OnExit pops depth for the dispatch contexts pushed in OnEnter.+func (r *WhereDisallowFunctionsAndCalculationsRule) OnExit(ctx antlr.ParserRuleContext, _ string) error {+ switch ctx.(type) {+ case *parser.Select_statementContext,+ *parser.Update_statementContext,+ *parser.Delete_statementContext,+ *parser.Insert_statementContext,+ *parser.Merge_statementContext,+ *parser.Create_tableContext,+ *parser.Create_viewContext,+ *parser.Create_materialized_viewContext:+ if r.depth > 0 {+ r.depth--+ }+ default:+ }+ return nil+}++// ---- Identifier / metadata helpers ---------------------------------------++// normalizeIdent returns the canonical lookup key for an identifier, matching+// the case mode of `model.NewDatabaseMetadata`:+//+// - Case-sensitive (production Oracle, store.IsObjectCaseSensitive=true):+// metadata stores names as Oracle's catalog returns them, which is+// UPPER-case for unquoted identifiers and original-case for quoted+// identifiers. The rule must therefore UPPER-case unquoted AST text and+// strip quotes from quoted text without changing case. Lowercasing+// unconditionally (the previous behavior) made every `tech_book` AST ref+// miss against the `TECH_BOOK` metadata key, silently disabling the+// rule in production.+// - Case-insensitive (older test mode): metadata is folded to lower-case+// by `normalizeNameByCaseSensitivity`, so the rule lower-cases too.+func (r *WhereDisallowFunctionsAndCalculationsRule) normalizeIdent(name string) string {+ if name == "" {+ return name+ }+ if strings.HasPrefix(name, "\"") && strings.HasSuffix(name, "\"") && len(name) >= 2 {+ inner := name[1 : len(name)-1]+ if r.isObjectCaseSensitive {+ return inner+ }+ return strings.ToLower(inner)+ }+ if r.isObjectCaseSensitive {+ return strings.ToUpper(name)+ }+ return strings.ToLower(name)+}++// idExprText returns the canonical lookup key for an Id_expression context.+func (r *WhereDisallowFunctionsAndCalculationsRule) idExprText(ctx parser.IId_expressionContext) string {+ if ctx == nil {+ return ""+ }+ if reg := ctx.Regular_id(); reg != nil {+ return r.normalizeIdent(reg.GetText())+ }+ if d := ctx.DELIMITED_ID(); d != nil {+ return r.normalizeIdent(d.GetText())+ }+ return r.normalizeIdent(ctx.GetText())+}++// tableMetadata fetches the store-model table for the given ref.+//+// Oracle sync stores ONLY the connected schema's objects in+// SchemaMetadata{Name: ""} (see backend/plugin/db/oracle/sync.go). So:+// - Bare ref (`TECH_BOOK`) → look up in the anonymous schema (current owner).+// - Same-owner qualified ref (`<currentDatabase>.TECH_BOOK`) → same as bare;+// the qualifier matches the connected schema's owner.+// - Cross-owner qualified ref (`OTHER_OWNER.TECH_BOOK` with+// OTHER_OWNER != currentDatabase) → return nil. We have no metadata for+// other owners; treating it as the current owner's table would attach+// the wrong indexes and emit incorrect advice.+func (r *WhereDisallowFunctionsAndCalculationsRule) tableMetadata(ref tableRef) *model.TableMetadata {+ if r.dbMetadata == nil {+ return nil+ }+ if ref.schema != "" && r.currentDatabase != "" &&+ r.normalizeIdent(ref.schema) != r.normalizeIdent(r.currentDatabase) {+ return nil+ }+ return r.dbMetadata.GetSchemaMetadata(r.currentSchema).GetTable(ref.name)+}++// indexedColumns returns indexed column names for the given table reference.+func (r *WhereDisallowFunctionsAndCalculationsRule) indexedColumns(ref tableRef) map[string]bool {+ table := r.tableMetadata(ref)+ if table == nil {+ return nil+ }+ cols := make(map[string]bool)+ for _, idx := range table.GetProto().GetIndexes() {+ for _, expr := range idx.GetExpressions() {+ cols[r.normalizeIdent(expr)] = true+ }+ }+ if len(cols) == 0 {+ return nil+ }+ return cols+}++// allColumns returns every column name defined for the given table reference.+// Keys use normalizeIdent so case-sensitive schemas distinguish quoted+// mixed-case identifiers; see §5 "Identifier normalization invariant".+func (r *WhereDisallowFunctionsAndCalculationsRule) allColumns(ref tableRef) map[string]bool {+ table := r.tableMetadata(ref)+ if table == nil {+ return nil+ }+ cols := make(map[string]bool)+ for _, c := range table.GetProto().GetColumns() {+ cols[r.normalizeIdent(c.GetName())] = true+ }+ if len(cols) == 0 {+ return nil+ }+ return cols+}++func (r *WhereDisallowFunctionsAndCalculationsRule) resolveIndexedColumns(tables tablesByAlias) indexedByAlias {+ all := make(indexedByAlias)+ for alias, ref := range tables {+ if cols := r.indexedColumns(ref); cols != nil {+ all[alias] = cols+ }+ }+ if len(all) == 0 {+ return nil+ }+ return all+}++func (r *WhereDisallowFunctionsAndCalculationsRule) resolveAllColumns(tables tablesByAlias) indexedByAlias {+ all := make(indexedByAlias)+ for alias, ref := range tables {+ if cols := r.allColumns(ref); cols != nil {+ all[alias] = cols+ }+ }+ if len(all) == 0 {+ return nil+ }+ return all+}++// ---- FROM-clause collection ----------------------------------------------++// collectTableNamesFromFrom walks a From_clause and returns aliases → tableRef.+// Derived tables and CTE references (when they can't be resolved to a real+// table) are recorded as empty tableRef{} placeholders so qualified refs can+// still be routed via alias lookup.+func (r *WhereDisallowFunctionsAndCalculationsRule) collectTableNamesFromFrom(from parser.IFrom_clauseContext) tablesByAlias {+ tables := make(tablesByAlias)+ if from == nil {+ return tables+ }+ list := from.Table_ref_list()+ if list == nil {+ return tables+ }+ for _, tref := range list.AllTable_ref() {+ r.collectTableNamesFromTableRef(tref, tables)+ }+ return tables+}++func (r *WhereDisallowFunctionsAndCalculationsRule) collectTableNamesFromTableRef(tref parser.ITable_refContext, tables tablesByAlias) {+ if tref == nil {+ return+ }+ if aux := tref.Table_ref_aux(); aux != nil {+ r.collectTableNamesFromTableRefAux(aux, tables)+ }+ for _, jc := range tref.AllJoin_clause() {+ if jc == nil {+ continue+ }+ if aux := jc.Table_ref_aux(); aux != nil {+ r.collectTableNamesFromTableRefAux(aux, tables)+ }+ }+}++func (r *WhereDisallowFunctionsAndCalculationsRule) collectTableNamesFromTableRefAux(aux parser.ITable_ref_auxContext, tables tablesByAlias) {+ if aux == nil {+ return+ }+ internal := aux.Table_ref_aux_internal()+ alias := ""+ if ta := aux.Table_alias(); ta != nil {+ alias = r.tableAliasText(ta)+ }+ switch c := internal.(type) {+ case *parser.Table_ref_aux_internal_oneContext:+ // dml_table_expression_clause [pivot/unpivot]+ if dte := c.Dml_table_expression_clause(); dte != nil {+ r.collectTableNamesFromDml(dte, alias, tables)+ }+ case *parser.Table_ref_aux_internal_twoContext:+ // ( table_ref ) [subquery_operation_part]*+ // If the inner table_ref is a single base table (no joins, no+ // subquery), the outer alias points DIRECTLY to that table —+ // `FROM (orders) o` is equivalent to `FROM orders o`. Recording+ // the alias as opaque would erase the indexes and miss real+ // violations on `o.indexed_col`. Otherwise (joins / derived+ // tables / subquery_operation_part), the alias spans multiple+ // or unknown sources and must stay opaque.+ if inner := c.Table_ref(); inner != nil {+ if dte := singleBaseTableInRef(inner); dte != nil {+ r.collectTableNamesFromDml(dte, alias, tables)+ } else {+ if alias != "" {+ key := r.normalizeIdent(alias)+ if _, ok := tables[key]; !ok {+ tables[key] = tableRef{}+ }+ }+ r.collectTableNamesFromTableRef(inner, tables)+ }+ } else if alias != "" {+ key := r.normalizeIdent(alias)+ if _, ok := tables[key]; !ok {+ tables[key] = tableRef{}+ }+ }+ case *parser.Table_ref_aux_internal_threeContext:+ // ONLY ( dml_table_expression_clause )+ if dte := c.Dml_table_expression_clause(); dte != nil {+ r.collectTableNamesFromDml(dte, alias, tables)+ }+ default:+ }+}++// collectTableNamesFromDml records a dml_table_expression_clause (a table or+// a parenthesised SELECT) under the given alias (empty = use table name).+func (r *WhereDisallowFunctionsAndCalculationsRule) collectTableNamesFromDml(+ dte parser.IDml_table_expression_clauseContext,+ alias string,+ tables tablesByAlias,+) {+ dteCtx := dte+ if tvn := dteCtx.Tableview_name(); tvn != nil {+ schema, name := r.splitTableviewName(tvn)+ key := alias+ if key == "" {+ key = name+ }+ normKey := r.normalizeIdent(key)+ // CTE shadowing: an unqualified tableview matching a WITH-factoring+ // name binds to the CTE result, not the physical table.+ if schema == "" && r.cteVisible(name) {+ tables[normKey] = tableRef{}+ return+ }+ ref := tableRef{schema: schema, name: name}+ if existing, ok := tables[normKey]; ok && (existing.schema != ref.schema || existing.name != ref.name) {+ tables[normKey] = tableRef{}+ } else {+ tables[normKey] = ref+ }+ return+ }+ // A nested SELECT inside the dml-table-expression-clause (derived table).+ if dteCtx.Select_statement() != nil {+ key := r.normalizeIdent(alias)+ if key != "" {+ if _, ok := tables[key]; !ok {+ tables[key] = tableRef{}+ }+ }+ }+}++// splitTableviewName returns (schema, name) from a Tableview_name context.+func (r *WhereDisallowFunctionsAndCalculationsRule) splitTableviewName(tvn parser.ITableview_nameContext) (string, string) {+ if tvn == nil {+ return "", ""+ }+ first := ""+ if id := tvn.Identifier(); id != nil {+ first = r.idExprText(id.Id_expression())+ }+ if idExpr := tvn.Id_expression(); idExpr != nil {+ return first, r.idExprText(idExpr)+ }+ return "", first+}++// tableAliasText returns the canonical alias string from a Table_alias.+func (r *WhereDisallowFunctionsAndCalculationsRule) tableAliasText(ta parser.ITable_aliasContext) string {+ if ta == nil {+ return ""+ }+ if id := ta.Identifier(); id != nil {+ return r.idExprText(id.Id_expression())+ }+ if q := ta.Quoted_string(); q != nil {+ text := strings.Trim(q.GetText(), "'\"")+ return r.normalizeIdent(text)+ }+ return ""+}++// localHasUnresolvedSources reports whether any FROM entry hides columns we+// cannot enumerate (derived tables or tables without metadata).+func (r *WhereDisallowFunctionsAndCalculationsRule) localHasUnresolvedSources(from parser.IFrom_clauseContext, local tablesByAlias) bool {+ if from != nil {+ // If the FROM subtree contains a Subquery (derived table), sources are unresolved.+ if containsDerivedTable(from) {+ return true+ }+ }+ for _, ref := range local {+ if ref == (tableRef{}) {+ // Opaque alias (CTE-shadowed tableview, derived source, etc.) —+ // columns can't be enumerated, so the local scope is unresolved.+ return true+ }+ if r.tableMetadata(ref) == nil {+ return true+ }+ }+ return false+}++// singleBaseTableInRef returns the inner Dml_table_expression_clause iff the+// given Table_ref reduces to a single base table — no joins, no subquery+// expansion, no parenthesized join — recursing through nested parentheses+// (e.g. `((orders))`). Returns nil otherwise. Used to propagate the outer+// alias of `FROM (orders) o` directly to the underlying table so indexes+// resolve via `o.indexed_col`.+func singleBaseTableInRef(tr parser.ITable_refContext) parser.IDml_table_expression_clauseContext {+ if tr == nil {+ return nil+ }+ if joins := tr.AllJoin_clause(); len(joins) > 0 {+ return nil+ }+ aux := tr.Table_ref_aux()+ if aux == nil {+ return nil+ }+ switch internal := aux.Table_ref_aux_internal().(type) {+ case *parser.Table_ref_aux_internal_oneContext:+ if dte := internal.Dml_table_expression_clause(); dte != nil && dte.Tableview_name() != nil {+ return dte+ }+ return nil+ case *parser.Table_ref_aux_internal_twoContext:+ // Recurse — `((orders))` is still a single base table.+ return singleBaseTableInRef(internal.Table_ref())+ }+ return nil+}++// containsDerivedTable reports whether any FROM-clause node introduces a+// derived table. Only SOURCE positions are inspected — Join_on_part subtrees+// (JOIN ON predicates) are skipped because their subqueries are value+// expressions, not source producers; treating them as opaque sources sets+// localUnresolved=true on the enclosing query and suppresses the outer-scope+// fallback in isIndexedColumn, masking real correlated-ref violations.+// Mirrors PG's hasOpaqueSource. See spec §3 "Unresolved FROM-item inventory".+func containsDerivedTable(node antlr.Tree) bool {+ if node == nil {+ return false+ }+ if _, ok := node.(*parser.Join_on_partContext); ok {+ return false+ }+ if n, ok := node.(*parser.Table_ref_aux_internal_oneContext); ok {+ if dte, ok := n.Dml_table_expression_clause().(*parser.Dml_table_expression_clauseContext); ok && dte != nil && dte.Select_statement() != nil {+ return true+ }+ }+ for i := 0; i < node.GetChildCount(); i++ {+ if containsDerivedTable(node.GetChild(i)) {+ return true+ }+ }+ return false+}++// elementReferencesName reports whether a factoring element is recursive —+// i.e. its body is a UNION ALL composition AND at least one branch+// references the element's own name as a FROM source.+//+// Why require UNION ALL (not just self-reference):+// - Oracle's recursive subquery factoring REQUIRES a UNION ALL between an+// anchor member and a recursive member; a single-branch self-shadow+// (e.g. `WITH orders AS (SELECT * FROM orders …)`) is NON-recursive and+// resolves the inner FROM to the REAL base table per SQL scope rules.+// - Using UNION ALL as the gate means the function's "recursive" return+// value matches Oracle's runtime binding: recursive members see the+// CTE (opaque); non-recursive bodies see the base table (indexed).+//+// Walk rule for self-reference inside a branch: scan every descendant+// Dml_table_expression_clause; match on Tableview_name iff it has no+// schema qualifier and its normalized name equals `name`. Nested derived+// tables (dte with its own Select_statement) are opaque — their inner+// FROMs belong to a different scope and must not trigger a false match.+func (r *WhereDisallowFunctionsAndCalculationsRule) elementReferencesName(sub parser.ISubqueryContext, name string) bool {+ if sub == nil || name == "" {+ return false+ }+ parts := sub.AllSubquery_operation_part()+ if len(parts) == 0 {+ return false+ }+ hasUnionAll := false+ for _, p := range parts {+ if p == nil {+ continue+ }+ if p.UNION() != nil && p.ALL() != nil {+ hasUnionAll = true+ break+ }+ }+ if !hasUnionAll {+ return false+ }+ return r.treeReferencesName(sub, name)+}++func (r *WhereDisallowFunctionsAndCalculationsRule) treeReferencesName(node antlr.Tree, name string) bool {+ if node == nil {+ return false+ }+ if dte, ok := node.(*parser.Dml_table_expression_clauseContext); ok && dte != nil {+ // Derived table: its inner SELECT is an opaque nested scope — do NOT+ // descend. Its own Tableview_name IS in the element's FROM scope.+ if dte.Select_statement() != nil {+ return false+ }+ if tvn := dte.Tableview_name(); tvn != nil {+ schema, tname := r.splitTableviewName(tvn)+ if schema == "" && r.normalizeIdent(tname) == name {+ return true+ }+ return false+ }+ }+ for i := 0; i < node.GetChildCount(); i++ {+ if r.treeReferencesName(node.GetChild(i), name) {+ return true+ }+ }+ return false+}++// ---- Column reference resolution -----------------------------------------++// extractColumnRefFromGeneralElement returns (qualifier, column) if the+// general_element is a plain column reference (no function arguments on any+// part). Returns ("", "") when the ref is a function call or otherwise not a+// column.+func (r *WhereDisallowFunctionsAndCalculationsRule) extractColumnRefFromGeneralElement(ge parser.IGeneral_elementContext) (string, string) {+ if ge == nil {+ return "", ""+ }+ parts := ge.AllGeneral_element_part()+ if len(parts) == 0 {+ return "", ""+ }+ for _, p := range parts {+ if p.Function_argument() != nil {+ return "", ""+ }+ }+ names := make([]string, 0, len(parts))+ for _, p := range parts {+ names = append(names, r.idExprText(p.Id_expression()))+ }+ if len(names) == 1 {+ return "", names[0]+ }+ // a.b → (a, b). schema.table.col → (table, col).+ return names[len(names)-2], names[len(names)-1]+}++// extractColumnRefFromTableElement handles `table_element outer_join_sign`+// (the bare-column-with-(+) form). Returns (qualifier, column).+func (r *WhereDisallowFunctionsAndCalculationsRule) extractColumnRefFromTableElement(te parser.ITable_elementContext) (string, string) {+ if te == nil {+ return "", ""+ }+ ids := te.AllId_expression()+ if len(ids) == 0 {+ return "", ""+ }+ names := make([]string, 0, len(ids))+ for _, id := range ids {+ names = append(names, r.idExprText(id))+ }+ if len(names) == 1 {+ return "", names[0]+ }+ return names[len(names)-2], names[len(names)-1]+}++// isIndexedColumn reports whether a (qualifier, column) pair refers to an+// indexed column within scope s.+func (r *WhereDisallowFunctionsAndCalculationsRule) isIndexedColumn(qualifier, column string, s scopeIndexed) bool {+ if column == "" || s.empty() {+ return false+ }+ col := r.normalizeIdent(column)+ if qualifier != "" {+ alias := r.normalizeIdent(qualifier)+ if s.localAliases[alias] {+ return s.local[alias][col]+ }+ return s.outer[alias][col]+ }+ localClaims := false+ for _, cols := range s.localAll {+ if cols[col] {+ localClaims = true+ break+ }+ }+ if localClaims {+ for _, cols := range s.local {+ if cols[col] {+ return true+ }+ }+ return false+ }+ if s.localUnresolved {+ return false+ }+ for _, cols := range s.outer {+ if cols[col] {+ return true+ }+ }+ return false+}++// ---- Function-name extraction --------------------------------------------++// functionCallName returns the upper-case function name applied, if the given+// general_element is a function call. Returns ("", false) otherwise.+func (r *WhereDisallowFunctionsAndCalculationsRule) functionCallName(ge parser.IGeneral_elementContext) (string, bool) {+ if ge == nil {+ return "", false+ }+ parts := ge.AllGeneral_element_part()+ if len(parts) == 0 {+ return "", false+ }+ // We treat a general_element as a function call when the LAST part has a+ // function_argument. The function name is the concatenation of all+ // id_expressions (so DBMS_RANDOM.VALUE(...) is "DBMS_RANDOM.VALUE").+ last := parts[len(parts)-1]+ if last.Function_argument() == nil {+ // Check if an earlier part had a function_argument — e.g. `foo(x).bar`+ // — which is "method access on a call". Treat as function form too.+ hasCall := false+ for _, p := range parts {+ if p.Function_argument() != nil {+ hasCall = true+ break+ }+ }+ if !hasCall {+ return "", false+ }+ }+ var names []string+ for _, p := range parts {+ names = append(names, r.idExprText(p.Id_expression()))+ }+ return strings.ToUpper(strings.Join(names, ".")), true+}++// extractStandardFunctionName returns the function keyword for a+// standard_function context (SUBSTR, TO_CHAR, COUNT, CAST, TRIM, etc.).+func (*WhereDisallowFunctionsAndCalculationsRule) extractStandardFunctionName(ctx *parser.Standard_functionContext) string {+ if ctx == nil {+ return ""+ }+ first := ctx.GetStart()+ if first == nil {+ return ""+ }+ return strings.ToUpper(first.GetText())+}++// ---- Core WHERE detection ------------------------------------------------++// checkQueryBlock inspects a Query_block with the given outer scope threaded in.+func (r *WhereDisallowFunctionsAndCalculationsRule) checkQueryBlock(qb parser.IQuery_blockContext, outer tablesByAlias) {+ if qb == nil {+ return+ }+ // CTE visibility matrix — per-factoring-element, matching the PG rule's+ // handleWithClause but at element granularity because Oracle has no+ // RECURSIVE keyword at the factoring-clause level (it is implicit —+ // an element is recursive iff its body is a UNION ALL composition AND+ // at least one branch references its own query_name in a FROM position,+ // which matches Oracle's syntactic requirement for recursive subquery+ // factoring):+ //+ // | Element kind | body sees self | preceding siblings | later siblings |+ // |----------------------|----------------|--------------------|----------------|+ // | Non-recursive | No | Yes | No |+ // | Recursive | Yes | Yes | No |+ //+ // Why per-element (not per-factoring-clause):+ // - Non-recursive body self-shadow (e.g. `WITH orders AS (SELECT * FROM+ // orders …)`, no UNION ALL) — inner `FROM orders` resolves to the+ // REAL base table per SQL scope rules; must push-AFTER so the+ // body-walk sees the base table and can emit `UPPER(indexed_col)`+ // advice. Otherwise false negative.+ // - Recursive body self-ref (e.g. `WITH orders AS (SELECT … FROM dual+ // UNION ALL SELECT … FROM orders WHERE UPPER(customer_name)=…)`) —+ // inner `FROM orders` resolves to the CTE itself; must push-BEFORE+ // so body-walk sees it as opaque and DOESN'T attach the same-named+ // base table's indexes. Otherwise false positive on recursive+ // members.+ //+ // Detection rule (elementReferencesName):+ // 1. body has at least one Subquery_operation_part that is `UNION ALL`,+ // 2. any descendant Dml_table_expression_clause's Tableview_name is a+ // single-component (unqualified) name whose normalized text equals+ // the element's own query_name.+ // Derived-table subquery sources are treated as opaque (not descended).+ //+ // Prior commit 1ee832f7f0 collapsed push-before/push-after into an+ // unconditional push-after, which fixed the non-recursive false negative+ // but re-opened the recursive false positive — addressed by codex+ // #3109425426.+ if sfc := qb.Subquery_factoring_clause(); sfc != nil {+ frame := make(map[string]bool)+ r.pushCTEs(frame)+ defer r.popCTEs()+ for _, fe := range sfc.AllFactoring_element() {+ if fe == nil {+ continue+ }+ name := ""+ if qn := fe.Query_name(); qn != nil {+ if id := qn.Identifier(); id != nil {+ if text := id.GetText(); text != "" {+ name = r.normalizeIdent(text)+ }+ }+ }+ sub := fe.Subquery()+ recursive := name != "" && sub != nil && r.elementReferencesName(sub, name)+ if recursive && name != "" {+ // Push-BEFORE: body's self-reference resolves to the CTE+ // (opaque), not the same-named base table.+ frame[name] = true+ }+ if sub != nil {+ r.checkSubqueryInScope(sub, nil)+ }+ if !recursive && name != "" {+ // Push-AFTER: body's self-reference resolves to the REAL+ // base table per non-recursive SQL scope rules.+ frame[name] = true+ }+ }+ }+ from := qb.From_clause()+ local := r.collectTableNamesFromFrom(from)+ unresolved := r.localHasUnresolvedSources(from, local)+ combined := mergeAliases(outer, local)++ r.checkWhereClause(qb.Where_clause(), local, outer, unresolved)++ // ANSI JOIN ON predicates behave like WHERE predicates in the same scope.+ if from != nil {+ if list := from.Table_ref_list(); list != nil {+ for _, tref := range list.AllTable_ref() {+ if tref == nil {+ continue+ }+ for _, jc := range tref.AllJoin_clause() {+ if jc == nil {+ continue+ }+ for _, jop := range jc.AllJoin_on_part() {+ if jop == nil {+ continue+ }+ if cond := jop.Condition(); cond != nil {+ r.checkExpressionAsWhere(cond, local, outer, unresolved)+ }+ }+ }+ }+ }+ }++ // CONNECT BY / START WITH predicates behave like WHERE predicates.+ if hq := qb.Hierarchical_query_clause(); hq != nil {+ if sp := hq.Start_part(); sp != nil {+ if cond := sp.Condition(); cond != nil {+ r.checkExpressionAsWhere(cond, local, outer, unresolved)+ }+ }+ if cond := hq.Condition(); cond != nil {+ r.checkExpressionAsWhere(cond, local, outer, unresolved)+ }+ }++ // Recurse into subqueries inside SELECT list, FROM (derived tables), HAVING,+ // GROUP BY, ORDER BY — all with combined scope.+ r.recurseIntoNestedSubqueries(qb, combined)+}++func mergeAliases(outer, local tablesByAlias) tablesByAlias {+ combined := make(tablesByAlias, len(outer)+len(local))+ for a, r := range outer {+ combined[a] = r+ }+ for a, r := range local {+ combined[a] = r+ }+ return combined+}++// checkWhereClause is the entry point for the WHERE sub-tree of a query block.+func (r *WhereDisallowFunctionsAndCalculationsRule) checkWhereClause(where parser.IWhere_clauseContext, local, outer tablesByAlias, unresolved bool) {+ if where == nil {+ return+ }+ if expr := where.Expression(); expr != nil {+ r.checkExpressionAsWhere(expr, local, outer, unresolved)+ }+}++// checkExpressionAsWhere runs the function/calculation detector on an arbitrary+// expression tree, recursing into nested subqueries.+func (r *WhereDisallowFunctionsAndCalculationsRule) checkExpressionAsWhere(root antlr.Tree, local, outer tablesByAlias, unresolved bool) {+ localAliases := make(map[string]bool, len(local))+ for a := range local {+ localAliases[a] = true+ }+ s := scopeIndexed{+ local: r.resolveIndexedColumns(local),+ localAll: r.resolveAllColumns(local),+ localAliases: localAliases,+ outer: r.resolveIndexedColumns(outer),+ localUnresolved: unresolved,+ }+ combined := mergeAliases(outer, local)+ r.walkWhere(root, s, combined)+}++// walkWhere traverses the tree looking for nodes to check. Nested subqueries+// are re-entered via checkSubqueryInScope with the combined scope.+func (r *WhereDisallowFunctionsAndCalculationsRule) walkWhere(n antlr.Tree, s scopeIndexed, combined tablesByAlias) {+ if n == nil {+ return+ }+ // Re-enter into nested subqueries without running the detector on them.+ if sub, ok := n.(*parser.SubqueryContext); ok {+ r.checkSubqueryInScope(sub, combined)+ return+ }+ // General_element: may be a column ref (skip — handled via parent) or a+ // function call (detect).+ if ge, ok := n.(*parser.General_elementContext); ok {+ if name, isCall := r.functionCallName(ge); isCall {+ if col := r.findIndexedColumnInFunctionArgs(ge, s); col != "" {+ r.addFunctionAdvice(name, col, ge)+ }+ // Still recurse into the arguments — a nested function/calc on an+ // indexed column should ALSO be flagged (e.g. `ABS(id + 1)`).+ for _, part := range ge.AllGeneral_element_part() {+ if arg := part.Function_argument(); arg != nil {+ r.walkWhere(arg, s, combined)+ }+ }+ return+ }+ // Not a function call — the column ref case is reached via parent+ // nodes (concatenation / unary). Fall through.+ }+ // Standard_function: built-in (SUBSTR / COUNT / CAST / TRIM / …).+ if sf, ok := n.(*parser.Standard_functionContext); ok {+ name := r.extractStandardFunctionName(sf)+ // Special-case CAST: it's a transparent wrapper for the indexed-col+ // check but we still also flag CAST-on-indexed as a function.+ if col := r.findIndexedColumnInStandardFunction(sf, s); col != "" && name != "" {+ r.addFunctionAdvice(name, col, sf)+ }+ for i := 0; i < sf.GetChildCount(); i++ {+ r.walkWhere(sf.GetChild(i), s, combined)+ }+ return+ }+ // Concatenation: arithmetic ASTERISK / SOLIDUS / PLUS_SIGN / MINUS_SIGN.+ if c, ok := n.(*parser.ConcatenationContext); ok {+ if isArithmeticConcat(c) {+ if col := r.unwrapAndFindIndexedColumn(c.Concatenation(0), s); col != "" {+ r.addCalculationAdvice(col, c)+ } else if col := r.unwrapAndFindIndexedColumn(c.Concatenation(1), s); col != "" {+ r.addCalculationAdvice(col, c)+ }+ }+ for i := 0; i < c.GetChildCount(); i++ {+ r.walkWhere(c.GetChild(i), s, combined)+ }+ return+ }+ // Unary minus → calculation (NOT PRIOR, NOT CONNECT_BY_ROOT).+ if u, ok := n.(*parser.Unary_expressionContext); ok {+ if u.MINUS_SIGN() != nil {+ if inner := u.Unary_expression(); inner != nil {+ if col := r.unwrapAndFindIndexedColumn(inner, s); col != "" {+ r.addCalculationAdvice(col, u)+ }+ }+ }+ for i := 0; i < u.GetChildCount(); i++ {+ r.walkWhere(u.GetChild(i), s, combined)+ }+ return+ }++ for i := 0; i < n.GetChildCount(); i++ {+ r.walkWhere(n.GetChild(i), s, combined)+ }+}++// isArithmeticConcat reports whether the concatenation is an arithmetic op.+func isArithmeticConcat(c *parser.ConcatenationContext) bool {+ if c == nil || c.GetOp() == nil {+ return false+ }+ switch c.GetOp().GetTokenType() {+ case parser.PlSqlParserASTERISK,+ parser.PlSqlParserSOLIDUS,+ parser.PlSqlParserPLUS_SIGN,+ parser.PlSqlParserMINUS_SIGN:+ return true+ }+ return false+}++// unwrapAndFindIndexedColumn peels passthrough wrappers (parens, CAST) and,+// if the inner expression is an indexed column reference, returns its+// lower-cased column name. Returns "" otherwise.+func (r *WhereDisallowFunctionsAndCalculationsRule) unwrapAndFindIndexedColumn(n antlr.Tree, s scopeIndexed) string {+ for n != nil {+ switch c := n.(type) {+ case *parser.ConcatenationContext:+ // passthrough: only if not itself an arithmetic op+ if isArithmeticConcat(c) {+ return ""+ }+ if m := c.Model_expression(); m != nil {+ n = m+ continue+ }+ return ""+ case *parser.Model_expressionContext:+ if u := c.Unary_expression(); u != nil {+ n = u+ continue+ }+ return ""+ case *parser.Unary_expressionContext:+ if c.MINUS_SIGN() != nil || c.PRIOR() != nil || c.CONNECT_BY_ROOT() != nil || c.NEW() != nil || c.DISTINCT() != nil || c.ALL() != nil {+ return ""+ }+ if at := c.Atom(); at != nil {+ n = at+ continue+ }+ if sf := c.Standard_function(); sf != nil {+ if sfCtx, ok := sf.(*parser.Standard_functionContext); ok {+ // CAST unwrap: `CAST(col AS TYPE)` — the inside is transparent for column-ref extraction.+ return r.unwrapCastColumn(sfCtx, s)+ }+ return ""+ }+ return ""+ case *parser.AtomContext:+ // LEFT_PAREN expressions RIGHT_PAREN — passthrough if single.+ if ge := c.General_element(); ge != nil {+ qualifier, column := r.extractColumnRefFromGeneralElement(ge)+ if column != "" && r.isIndexedColumn(qualifier, column, s) {+ return r.normalizeIdent(column)+ }+ return ""+ }+ if te := c.Table_element(); te != nil {+ qualifier, column := r.extractColumnRefFromTableElement(te)+ if column != "" && r.isIndexedColumn(qualifier, column, s) {+ return r.normalizeIdent(column)+ }+ return ""+ }+ // (expressions) — unwrap if single expression.+ if exprs := c.Expressions(); exprs != nil {+ all := exprs.AllExpression()+ if len(all) == 1 {+ n = all[0]+ continue+ }+ }+ return ""+ case *parser.ExpressionContext:+ if le := c.Logical_expression(); le != nil {+ n = le+ continue+ }+ return ""+ case *parser.Logical_expressionContext:+ if ul := c.Unary_logical_expression(); ul != nil {+ n = ul+ continue+ }+ return ""+ case *parser.Unary_logical_expressionContext:+ if me := c.Multiset_expression(); me != nil {+ n = me+ continue+ }+ return ""+ case *parser.Multiset_expressionContext:+ if rel := c.Relational_expression(); rel != nil {+ n = rel+ continue+ }+ return ""+ case *parser.Relational_expressionContext:+ rels := c.AllRelational_expression()+ if len(rels) == 1 {+ n = rels[0]+ continue+ }+ if comp := c.Compound_expression(); comp != nil {+ n = comp+ continue+ }+ return ""+ case *parser.Compound_expressionContext:+ cats := c.AllConcatenation()+ if len(cats) >= 1 {+ n = cats[0]+ continue+ }+ return ""+ default:+ return ""+ }+ }+ return ""+}++// unwrapCastColumn returns the indexed-column name inside a `CAST(col AS T)`+// expression, or "" if the inside isn't a bare indexed column.+func (r *WhereDisallowFunctionsAndCalculationsRule) unwrapCastColumn(sf *parser.Standard_functionContext, s scopeIndexed) string {+ if sf == nil {+ return ""+ }+ of := sf.Other_function()+ if of == nil {+ return ""+ }+ ofCtx, ok := of.(*parser.Other_functionContext)+ if !ok {+ return ""+ }+ if ofCtx.CAST() == nil && ofCtx.XMLCAST() == nil {+ return ""+ }+ cats := ofCtx.AllConcatenation()+ if len(cats) == 0 {+ return ""+ }+ return r.unwrapAndFindIndexedColumn(cats[0], s)+}++// findIndexedColumnInFunctionArgs searches a function-call's argument list for+// an indexed column reference (unwrapping CAST / parens). Arithmetic is NOT+// crossed so `ABS(id + 1)` reports as a calculation via the inner walker.+func (r *WhereDisallowFunctionsAndCalculationsRule) findIndexedColumnInFunctionArgs(ge *parser.General_elementContext, s scopeIndexed) string {+ for _, part := range ge.AllGeneral_element_part() {+ arg := part.Function_argument()+ if arg == nil {+ continue+ }+ argCtx, ok := arg.(*parser.Function_argumentContext)+ if !ok {+ continue+ }+ for _, a := range argCtx.AllArgument() {+ if a == nil {+ continue+ }+ aCtx, ok := a.(*parser.ArgumentContext)+ if !ok {+ continue+ }+ if expr := aCtx.Expression(); expr != nil {+ if col := r.unwrapAndFindIndexedColumn(expr, s); col != "" {+ return col+ }+ }+ }+ }+ return ""+}++// findIndexedColumnInStandardFunction searches a built-in function's argument+// subtree for an indexed column reference.+func (r *WhereDisallowFunctionsAndCalculationsRule) findIndexedColumnInStandardFunction(sf *parser.Standard_functionContext, s scopeIndexed) string {+ if sf == nil {+ return ""+ }+ // Walk the function's children (NOT the root node itself — we want to+ // descend into its arguments, stopping only at further function calls /+ // arithmetic).+ for i := 0; i < sf.GetChildCount(); i++ {+ if col := r.findIndexedColumnInChildren(sf.GetChild(i), s); col != "" {+ return col+ }+ }+ return ""+}++// findIndexedColumnInChildren recursively searches for an indexed column+// reference without crossing into arithmetic concatenations (those spawn the+// calculation path) or further function calls.+func (r *WhereDisallowFunctionsAndCalculationsRule) findIndexedColumnInChildren(n antlr.Tree, s scopeIndexed) string {+ if n == nil {+ return ""+ }+ switch c := n.(type) {+ case *parser.ConcatenationContext:+ if isArithmeticConcat(c) {+ return ""+ }+ case *parser.General_elementContext:+ if _, isCall := r.functionCallName(c); isCall {+ return ""+ }+ qualifier, column := r.extractColumnRefFromGeneralElement(c)+ if column != "" && r.isIndexedColumn(qualifier, column, s) {+ return r.normalizeIdent(column)+ }+ return ""+ case *parser.Table_elementContext:+ qualifier, column := r.extractColumnRefFromTableElement(c)+ if column != "" && r.isIndexedColumn(qualifier, column, s) {+ return r.normalizeIdent(column)+ }+ return ""+ case *parser.Standard_functionContext:+ return ""+ default:+ }+ for i := 0; i < n.GetChildCount(); i++ {+ if col := r.findIndexedColumnInChildren(n.GetChild(i), s); col != "" {+ return col+ }+ }+ return ""+}++// ---- Subquery re-entry ---------------------------------------------------++// checkSubqueryInScope re-enters the recursive check on a SubqueryContext,+// threading the given outer scope for correlated refs.+func (r *WhereDisallowFunctionsAndCalculationsRule) checkSubqueryInScope(sub parser.ISubqueryContext, outer tablesByAlias) {+ if sub == nil {+ return+ }+ // Set-op: first element plus each subquery_operation_part.+ if base := sub.Subquery_basic_elements(); base != nil {+ r.checkSubqueryBasicElements(base, outer)+ }+ for _, op := range sub.AllSubquery_operation_part() {+ if op == nil {+ continue+ }+ if base := op.Subquery_basic_elements(); base != nil {+ r.checkSubqueryBasicElements(base, outer)+ }+ }+}++func (r *WhereDisallowFunctionsAndCalculationsRule) checkSubqueryBasicElements(be parser.ISubquery_basic_elementsContext, outer tablesByAlias) {+ if be == nil {+ return+ }+ if qb := be.Query_block(); qb != nil {+ r.checkQueryBlock(qb, outer)+ return+ }+ if inner := be.Subquery(); inner != nil {+ r.checkSubqueryInScope(inner, outer)+ }+}++// recurseIntoNestedSubqueries scans the non-WHERE parts of a query block for+// SubqueryContext nodes and dispatches each with the given outer scope.+func (r *WhereDisallowFunctionsAndCalculationsRule) recurseIntoNestedSubqueries(qb parser.IQuery_blockContext, outer tablesByAlias) {+ if qb == nil {+ return+ }+ // SELECT list+ if sl := qb.Selected_list(); sl != nil {+ r.recurseIntoSubqueriesIn(sl, outer)+ }+ // FROM (derived tables). Subqueries inside JOIN ON predicates are already+ // walked by checkQueryBlock via checkExpressionAsWhere; skip them here to+ // avoid double-flagging.+ if from := qb.From_clause(); from != nil {+ r.recurseIntoFromSubqueries(from, outer)+ }+ // GROUP BY + HAVING (HAVING is never itself flagged; nested subqueries+ // inside are still recursed).+ if gb := qb.Group_by_clause(); gb != nil {+ r.recurseIntoSubqueriesIn(gb, outer)+ }+ if ob := qb.Order_by_clause(); ob != nil {+ r.recurseIntoSubqueriesIn(ob, outer)+ }+}++func (r *WhereDisallowFunctionsAndCalculationsRule) recurseIntoSubqueriesIn(n antlr.Tree, outer tablesByAlias) {+ if n == nil {+ return+ }+ if sub, ok := n.(*parser.SubqueryContext); ok {+ r.checkSubqueryInScope(sub, outer)+ return+ }+ for i := 0; i < n.GetChildCount(); i++ {+ r.recurseIntoSubqueriesIn(n.GetChild(i), outer)+ }+}++// recurseIntoSubqueriesSkipWhere is like recurseIntoSubqueriesIn but skips+// Where_clauseContext subtrees. Callers that already dispatched the WHERE+// through checkWhereClause use this variant to avoid double-walking subqueries+// inside that WHERE (checkWhereClause → walkWhere re-enters SubqueryContext on+// its own).+func (r *WhereDisallowFunctionsAndCalculationsRule) recurseIntoSubqueriesSkipWhere(n antlr.Tree, outer tablesByAlias) {+ if n == nil {+ return+ }+ if _, ok := n.(*parser.Where_clauseContext); ok {+ return+ }+ if sub, ok := n.(*parser.SubqueryContext); ok {+ r.checkSubqueryInScope(sub, outer)+ return+ }+ for i := 0; i < n.GetChildCount(); i++ {+ r.recurseIntoSubqueriesSkipWhere(n.GetChild(i), outer)+ }+}++// recurseIntoFromSubqueries walks a FROM-clause subtree for derived-table+// subqueries but skips Join_on_part subtrees — JOIN ON conditions are+// dispatched separately by checkQueryBlock and would otherwise cause the+// same inner subquery to be checked twice.+func (r *WhereDisallowFunctionsAndCalculationsRule) recurseIntoFromSubqueries(n antlr.Tree, outer tablesByAlias) {+ if n == nil {+ return+ }+ if _, ok := n.(*parser.Join_on_partContext); ok {+ return+ }+ if sub, ok := n.(*parser.SubqueryContext); ok {+ r.checkSubqueryInScope(sub, outer)+ return+ }+ for i := 0; i < n.GetChildCount(); i++ {+ r.recurseIntoFromSubqueries(n.GetChild(i), outer)+ }+}++// ---- Top-level dispatchers -----------------------------------------------++// checkSelectOnly dispatches the top-level subquery of a Select_only_statement.+func (r *WhereDisallowFunctionsAndCalculationsRule) checkSelectOnly(sos parser.ISelect_only_statementContext) {+ if sos == nil {+ return+ }+ if sub := sos.Subquery(); sub != nil {+ r.checkSubqueryInScope(sub, nil)+ }+}++// onSelectStmt handles SELECT (including CTE / UNION / MINUS / INTERSECT).+func (r *WhereDisallowFunctionsAndCalculationsRule) onSelectStmt(ctx *parser.Select_statementContext) {+ if ctx == nil {+ return+ }+ r.checkSelectOnly(ctx.Select_only_statement())+}++// tablesUnresolved reports whether any concrete tableRef lacks metadata.+// Empty (placeholder) refs are skipped; use emptyIsUnresolved=true when an empty+// ref should itself count as unresolved (e.g. MERGE derived source).+func (r *WhereDisallowFunctionsAndCalculationsRule) tablesUnresolved(tables tablesByAlias, emptyIsUnresolved bool) bool {+ for _, ref := range tables {+ if ref == (tableRef{}) {+ if emptyIsUnresolved {+ return true+ }+ continue+ }+ if r.tableMetadata(ref) == nil {+ return true+ }+ }+ return false+}++// onUpdateStmt handles UPDATE ... SET ... WHERE ...+func (r *WhereDisallowFunctionsAndCalculationsRule) onUpdateStmt(ctx *parser.Update_statementContext) {+ if ctx == nil {+ return+ }+ tables := make(tablesByAlias)+ if gtr := ctx.General_table_ref(); gtr != nil {+ r.collectTableNamesFromGeneralTableRef(gtr, tables)+ r.dispatchTargetSubquery(gtr)+ }+ unresolved := r.tablesUnresolved(tables, false)+ if where := ctx.Where_clause(); where != nil {+ r.checkWhereClause(where, tables, nil, unresolved)+ }+ // Recurse into subqueries in SET expressions and WHERE subqueries (latter handled via walkWhere).+ if sc := ctx.Update_set_clause(); sc != nil {+ r.recurseIntoSubqueriesIn(sc, tables)+ }+ if ret := ctx.Static_returning_clause(); ret != nil {+ r.recurseIntoSubqueriesIn(ret, tables)+ }+}++// onDeleteStmt handles DELETE [FROM] … WHERE …+func (r *WhereDisallowFunctionsAndCalculationsRule) onDeleteStmt(ctx *parser.Delete_statementContext) {+ if ctx == nil {+ return+ }+ tables := make(tablesByAlias)+ if gtr := ctx.General_table_ref(); gtr != nil {+ r.collectTableNamesFromGeneralTableRef(gtr, tables)+ r.dispatchTargetSubquery(gtr)+ }+ unresolved := r.tablesUnresolved(tables, false)+ if where := ctx.Where_clause(); where != nil {+ r.checkWhereClause(where, tables, nil, unresolved)+ }+ if ret := ctx.Static_returning_clause(); ret != nil {+ r.recurseIntoSubqueriesIn(ret, tables)+ }+}++// dispatchTargetSubquery dispatches the inner SELECT when the UPDATE / DELETE+// target is a derived table (`UPDATE (SELECT … WHERE …) SET …`). The outer+// collector records only an opaque alias placeholder; the inner WHERE must+// still be checked independently.+func (r *WhereDisallowFunctionsAndCalculationsRule) dispatchTargetSubquery(gtr parser.IGeneral_table_refContext) {+ if gtr == nil {+ return+ }+ dte := gtr.Dml_table_expression_clause()+ if dte == nil {+ return+ }+ sel := dte.Select_statement()+ if sel == nil {+ return+ }+ r.checkSelectOnly(sel.Select_only_statement())+}++// onInsertStmt handles INSERT INTO … SELECT / VALUES …+func (r *WhereDisallowFunctionsAndCalculationsRule) onInsertStmt(ctx *parser.Insert_statementContext) {+ if ctx == nil {+ return+ }+ if sti := ctx.Single_table_insert(); sti != nil {+ if sel := sti.Select_statement(); sel != nil {+ r.checkSelectOnly(sel.Select_only_statement())+ }+ // VALUES (subquery) — walk only the values and returning trees, not+ // the full sti (which would double-walk a sibling SELECT source).+ if v := sti.Values_clause(); v != nil {+ r.recurseIntoSubqueriesIn(v, nil)+ }+ if ret := sti.Static_returning_clause(); ret != nil {+ r.recurseIntoSubqueriesIn(ret, nil)+ }+ }+ if mti := ctx.Multi_table_insert(); mti != nil {+ if sel := mti.Select_statement(); sel != nil {+ r.checkSelectOnly(sel.Select_only_statement())+ }+ // INSERT ALL WHEN <cond> THEN INTO ... — the WHEN predicate is a+ // per-row filter over the driving SELECT's columns. Build a scope from+ // that SELECT's FROM clause so indexed-column refs resolve.+ drivingTables := make(tablesByAlias)+ if sel := mti.Select_statement(); sel != nil {+ if sos := sel.Select_only_statement(); sos != nil {+ if sub := sos.Subquery(); sub != nil {+ if be := sub.Subquery_basic_elements(); be != nil {+ if qb := be.Query_block(); qb != nil {+ drivingTables = r.collectTableNamesFromFrom(qb.From_clause())+ }+ }+ }+ }+ }+ drivingUnresolved := r.tablesUnresolved(drivingTables, false)+ if cic := mti.Conditional_insert_clause(); cic != nil {+ for _, wp := range cic.AllConditional_insert_when_part() {+ if cond := wp.Condition(); cond != nil {+ r.checkExpressionAsWhere(cond, drivingTables, nil, drivingUnresolved)+ }+ // INTO branches may carry VALUES subqueries — recurse into+ // them. The WHEN Condition itself is already handled above+ // via checkExpressionAsWhere (which re-enters subqueries);+ // skip it here to avoid double-walking.+ for _, elt := range wp.AllMulti_table_element() {+ r.recurseIntoSubqueriesIn(elt, nil)+ }+ }+ if ep := cic.Conditional_insert_else_part(); ep != nil {+ r.recurseIntoSubqueriesIn(ep, nil)+ }+ }+ // Walk non-conditional multi-table-element children too (for INSERT+ // ALL without WHEN branches). Skip the driving SELECT (already+ // handled) and the Conditional_insert_clause (handled above, where+ // we split WHEN Condition from INTO branches).+ for i := 0; i < mti.GetChildCount(); i++ {+ child := mti.GetChild(i)+ if _, isSel := child.(parser.ISelect_statementContext); isSel {+ continue+ }+ if _, isCIC := child.(parser.IConditional_insert_clauseContext); isCIC {+ continue+ }+ r.recurseIntoSubqueriesIn(child, nil)+ }+ }+}++// onCreateTable handles CREATE TABLE ... AS subquery (CTAS).+func (r *WhereDisallowFunctionsAndCalculationsRule) onCreateTable(ctx *parser.Create_tableContext) {+ if ctx == nil {+ return+ }+ if sub := findFirstSubquery(ctx); sub != nil {+ r.checkSubqueryInScope(sub, nil)+ }+}++// onCreateView handles CREATE [OR REPLACE] VIEW v AS SELECT …+func (r *WhereDisallowFunctionsAndCalculationsRule) onCreateView(ctx *parser.Create_viewContext) {+ if ctx == nil {+ return+ }+ r.checkSelectOnly(ctx.Select_only_statement())+}++// onCreateMaterializedView handles CREATE MATERIALIZED VIEW mv AS SELECT …+func (r *WhereDisallowFunctionsAndCalculationsRule) onCreateMaterializedView(ctx *parser.Create_materialized_viewContext) {+ if ctx == nil {+ return+ }+ r.checkSelectOnly(ctx.Select_only_statement())+}++// onMergeStmt handles MERGE INTO target USING source ON cond WHEN …+func (r *WhereDisallowFunctionsAndCalculationsRule) onMergeStmt(ctx *parser.Merge_statementContext) {+ if ctx == nil {+ return+ }+ tables := make(tablesByAlias)+ for _, tv := range ctx.AllSelected_tableview() {+ r.collectTableNamesFromSelectedTableview(tv, tables)+ // MERGE source may be a subquery (`USING (SELECT … WHERE …)`). The+ // outer collector records only an opaque alias placeholder; run the+ // rule on the inner SELECT independently so its own WHERE is checked.+ if sel := tv.Select_statement(); sel != nil {+ r.checkSelectOnly(sel.Select_only_statement())+ }+ }+ unresolved := r.tablesUnresolved(tables, true)+ if cond := ctx.Condition(); cond != nil {+ r.checkExpressionAsWhere(cond, tables, nil, unresolved)+ }+ if mu := ctx.Merge_update_clause(); mu != nil {+ if where := mu.Where_clause(); where != nil {+ r.checkWhereClause(where, tables, nil, unresolved)+ }+ if mud := mu.Merge_update_delete_part(); mud != nil {+ if where := mud.Where_clause(); where != nil {+ r.checkWhereClause(where, tables, nil, unresolved)+ }+ }+ // SET col = (subquery) — recurse into any nested subqueries, skipping+ // the Where_clause subtrees already dispatched above.+ r.recurseIntoSubqueriesSkipWhere(mu, tables)+ }+ if mi := ctx.Merge_insert_clause(); mi != nil {+ if where := mi.Where_clause(); where != nil {+ r.checkWhereClause(where, tables, nil, unresolved)+ }+ // INSERT VALUES (subquery) or column-list subqueries — same recursion,+ // skipping the Where_clause subtree already dispatched above.+ r.recurseIntoSubqueriesSkipWhere(mi, tables)+ }+}++// collectTableNamesFromGeneralTableRef records the UPDATE / DELETE target.+func (r *WhereDisallowFunctionsAndCalculationsRule) collectTableNamesFromGeneralTableRef(gtr parser.IGeneral_table_refContext, tables tablesByAlias) {+ if gtr == nil {+ return+ }+ alias := ""+ if ta := gtr.Table_alias(); ta != nil {+ alias = r.tableAliasText(ta)+ }+ if dte := gtr.Dml_table_expression_clause(); dte != nil {+ r.collectTableNamesFromDml(dte, alias, tables)+ }+}++// collectTableNamesFromSelectedTableview records a MERGE target / source.+func (r *WhereDisallowFunctionsAndCalculationsRule) collectTableNamesFromSelectedTableview(tv parser.ISelected_tableviewContext, tables tablesByAlias) {+ if tv == nil {+ return+ }+ alias := ""+ if ta := tv.Table_alias(); ta != nil {+ alias = r.tableAliasText(ta)+ }+ if tvn := tv.Tableview_name(); tvn != nil {+ schema, name := r.splitTableviewName(tvn)+ key := alias+ if key == "" {+ key = name+ }+ normKey := r.normalizeIdent(key)+ // CTE shadowing — see collectTableNamesFromDml.+ if schema == "" && r.cteVisible(name) {+ tables[normKey] = tableRef{}+ return+ }+ ref := tableRef{schema: schema, name: name}+ if existing, ok := tables[normKey]; ok && (existing.schema != ref.schema || existing.name != ref.name) {+ tables[normKey] = tableRef{}+ } else {+ tables[normKey] = ref+ }+ return+ }+ if tv.Select_statement() != nil {+ key := r.normalizeIdent(alias)+ if key != "" {+ if _, ok := tables[key]; !ok {+ tables[key] = tableRef{}+ }+ }+ }+}++// findFirstSubquery does a DFS for the first SubqueryContext child in the tree.+func findFirstSubquery(n antlr.Tree) parser.ISubqueryContext {+ if n == nil {+ return nil+ }+ for i := 0; i < n.GetChildCount(); i++ {+ child := n.GetChild(i)+ if sub, ok := child.(*parser.SubqueryContext); ok {+ return sub+ }+ if sub := findFirstSubquery(child); sub != nil {+ return sub+ }+ }+ return nil+}++// ---- Advice builders ------------------------------------------------------++func (r *WhereDisallowFunctionsAndCalculationsRule) addFunctionAdvice(funcName, col string, ctx antlr.ParserRuleContext) {+ r.adviceList = append(r.adviceList, &storepb.Advice{+ Status: r.level,+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),+ Title: r.title,+ Content: fmt.Sprintf("Function %q is applied to indexed column %q in the WHERE clause, which prevents index usage", funcName, col),+ StartPosition: common.ConvertANTLRLineToPosition(r.baseLine + ctx.GetStart().GetLine()),+ })+}++func (r *WhereDisallowFunctionsAndCalculationsRule) addCalculationAdvice(col string, ctx antlr.ParserRuleContext) {+ r.adviceList = append(r.adviceList, &storepb.Advice{+ Status: r.level,+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),+ Title: r.title,+ Content: fmt.Sprintf("Calculation is applied to indexed column %q in the WHERE clause, which prevents index usage", col),+ StartPosition: common.ConvertANTLRLineToPosition(r.baseLine + ctx.GetStart().GetLine()),+ })+}diff --git a/backend/plugin/advisor/oracle/test/statement_where_disallow_functions_and_calculations.yaml b/backend/plugin/advisor/oracle/test/statement_where_disallow_functions_and_calculations.yamlnew file mode 100644index 0000000000..99d4b77735--- /dev/null+++ b/backend/plugin/advisor/oracle/test/statement_where_disallow_functions_and_calculations.yaml@@ -0,0 +1,1053 @@+# SQL review rule: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+# Cases added incrementally per the TDD plan.++# ---- Basic WARN cases (function on indexed column) ----+- statement: "SELECT * FROM tech_book WHERE UPPER(name) = 'test'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE MOD(id, 2) = 0"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "MOD" is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Basic WARN cases (calculation on indexed column) ----+- statement: "SELECT * FROM tech_book WHERE id + 1 = 2"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE id - 1 = 0"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE id * 2 = 10"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE id / 2 = 5"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE -id > -5"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Basic PASS cases (function/calc on value side, or on non-indexed column/table) ----+- statement: "SELECT * FROM tech_book WHERE id = ABS(-5)"+- statement: "SELECT * FROM tech_book WHERE id = DBMS_RANDOM.VALUE"+- statement: "SELECT * FROM tech_book WHERE UPPER(creator) = 'X'"+- statement: "SELECT * FROM tech_book WHERE id = 1"+- statement: "SELECT * FROM unknown WHERE UPPER(col) = 'X'"+- statement: "SELECT * FROM no_index_table WHERE -col_a > 5"++# ---- UPDATE / DELETE WARN ----+- statement: "UPDATE tech_book SET creator = 'x' WHERE UPPER(name) = 'test'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "UPDATE tech_book SET creator = 'x' WHERE id * 2 = 10"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "DELETE FROM tech_book WHERE UPPER(name) = 'test'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "DELETE FROM tech_book WHERE id + 1 > 10"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- UPDATE / DELETE PASS ----+- statement: "UPDATE tech_book SET creator = 'x' WHERE id = 1"+- statement: "DELETE FROM tech_book WHERE id = 1"+- statement: "UPDATE no_index_table SET col_b = 'x' WHERE UPPER(col_b) = 'Y'"++# ---- JOIN WARN (ANSI) ----+- statement: "SELECT * FROM tech_book t JOIN orders o ON t.id = o.order_id WHERE UPPER(t.name) = 'X'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book t JOIN orders o ON UPPER(o.customer_name) = 'X' WHERE t.id = 1"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- JOIN WARN (implicit via comma) ----+- statement: "SELECT * FROM tech_book t, orders o WHERE t.id = o.order_id AND UPPER(t.name) = 'X'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- JOIN PASS ----+- statement: "SELECT * FROM tech_book t JOIN orders o ON t.id = o.order_id WHERE t.id = 1 AND o.order_id = 1"+- statement: "SELECT * FROM tech_book t JOIN no_index_table n ON t.id = n.col_a WHERE UPPER(n.col_b) = 'Y'"++# ---- INSERT … SELECT / CTAS / VIEW / MATVIEW WARN ----+- statement: "INSERT INTO insert_target (id, name) SELECT id, name FROM tech_book WHERE UPPER(name) = 'test'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "CREATE TABLE new_table AS SELECT * FROM tech_book WHERE UPPER(name) = 'test'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "CREATE OR REPLACE VIEW v AS SELECT * FROM tech_book WHERE id + 1 > 5"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "CREATE MATERIALIZED VIEW mv AS SELECT * FROM orders WHERE ABS(amount) > 10"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "AMOUNT" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- INSERT / CTAS PASS ----+- statement: "INSERT INTO insert_target (id, name) SELECT id, name FROM tech_book WHERE id = 1"+- statement: "CREATE TABLE new_table AS SELECT * FROM no_index_table WHERE UPPER(col_b) = 'X'"++# ---- MERGE ----+- statement: |+ MERGE INTO orders t USING products p+ ON (UPPER(t.customer_name) = p.title)+ WHEN MATCHED THEN UPDATE SET note = 'x'+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++- statement: |+ MERGE INTO orders t USING products p+ ON (t.order_id = p.product_id)+ WHEN MATCHED THEN UPDATE SET note = 'x' WHERE t.amount * 2 > 100+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "AMOUNT" in the WHERE clause, which prevents index usage'+ startposition:+ line: 3+ column: 0+ endposition: null++- statement: |+ MERGE INTO orders t USING products p+ ON (t.order_id = p.product_id)+ WHEN MATCHED THEN UPDATE SET note = 'x'+ DELETE WHERE ABS(t.amount) > 100+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "AMOUNT" in the WHERE clause, which prevents index usage'+ startposition:+ line: 4+ column: 0+ endposition: null++- statement: |+ MERGE INTO orders t USING products p+ ON (t.order_id = p.product_id)+ WHEN MATCHED THEN UPDATE SET note = 'x'++# ---- Subquery WARN: IN / NOT IN / EXISTS / NOT EXISTS / scalar / nested / correlated ----+- statement: "SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'JOHN')"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE id NOT IN (SELECT order_id FROM orders WHERE ABS(amount) > 10)"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "AMOUNT" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE EXISTS (SELECT 1 FROM orders WHERE UPPER(customer_name) = 'X')"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE NOT EXISTS (SELECT 1 FROM orders WHERE amount + 1 > 10)"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "AMOUNT" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT id, (SELECT COUNT(*) FROM orders WHERE UPPER(customer_name) = 'X') FROM tech_book WHERE id = 1"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE amount IN (SELECT price FROM products WHERE UPPER(title) = 'X'))"++- statement: "SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE amount IN (SELECT price FROM products WHERE UPPER(product_id) = 'X'))"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "PRODUCT_ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM orders o WHERE UPPER(t.name) = 'X')"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE UPPER(name) = 'A' AND id IN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'X')"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'A') AND id IN (SELECT product_id FROM products WHERE UPPER(title) = 'B')"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Subquery PASS ----+- statement: "SELECT * FROM tech_book WHERE id IN (SELECT col_a FROM no_index_table WHERE UPPER(col_b) = 'X')"+- statement: "SELECT * FROM tech_book WHERE id IN (SELECT col_a FROM no_index_table WHERE col_a + 1 > 5)"++# ---- UNION / INTERSECT / MINUS ----+- statement: "SELECT * FROM tech_book WHERE UPPER(name) = 'A' UNION SELECT id, name, creator FROM tech_book WHERE id = 2"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE UPPER(name) = 'A' UNION ALL SELECT id, name, creator FROM tech_book WHERE ABS(id) > 5"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT id, name, creator FROM tech_book WHERE id = 1 INTERSECT SELECT id, name, creator FROM tech_book WHERE UPPER(name) = 'A'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT id, name, creator FROM tech_book WHERE id = 1 MINUS SELECT id, name, creator FROM tech_book WHERE UPPER(name) = 'A'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- CTE ----+- statement: |+ WITH filtered AS (SELECT * FROM tech_book WHERE UPPER(name) = 'A')+ SELECT * FROM filtered+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: |+ WITH filtered AS (SELECT * FROM tech_book WHERE id = 1)+ SELECT * FROM filtered f, tech_book t WHERE UPPER(t.name) = 'X'+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++- statement: |+ WITH filtered AS (SELECT * FROM tech_book WHERE id + 1 > 5)+ SELECT * FROM filtered+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: |+ WITH filtered AS (SELECT * FROM tech_book WHERE id = 1)+ SELECT * FROM filtered WHERE id = 2++# ---- Oracle (+) outer join syntax + CONNECT BY hierarchical ----+- statement: "SELECT * FROM tech_book t, orders o WHERE t.id = o.order_id(+) AND UPPER(t.name) = 'X'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: |+ SELECT id, name FROM tech_book+ START WITH id = 1+ CONNECT BY PRIOR id = id AND UPPER(name) = 'X'+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 3+ column: 0+ endposition: null++- statement: |+ SELECT id, name FROM tech_book+ START WITH id = 1+ CONNECT BY PRIOR id = id++- statement: |+ SELECT * FROM tech_book t+ WHERE t.id IN (+ SELECT id FROM tech_book+ CONNECT BY PRIOR id = id AND UPPER(name) = 'X'+ )+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 4+ column: 0+ endposition: null++# ---- HAVING exclusion + wrapper unwrap edge cases ----+- statement: "SELECT name, COUNT(*) FROM tech_book GROUP BY name HAVING COUNT(name) > 5"++- statement: "SELECT * FROM tech_book WHERE ABS(id + 1) > 5"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM tech_book WHERE UPPER(NVL(name, 'x')) = 'TESTX'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "NVL" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++- statement: "SELECT * FROM no_index_table WHERE ABS(col_a + 1) > 5"++# ---- Multi-statement depth-reset regression ----+- statement: |+ SELECT * FROM tech_book WHERE UPPER(name) = 'A';+ UPDATE tech_book SET creator = 'x' WHERE ABS(id) > 5+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# ---- Review fix: MERGE USING (SELECT ... WHERE ...) source subquery ----+- statement: |+ MERGE INTO orders t USING (SELECT * FROM products WHERE ABS(price) > 100) p+ ON (t.order_id = p.product_id)+ WHEN MATCHED THEN UPDATE SET note = 'x'+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "PRICE" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Round 2 fixes ----------------------------------------------------------++# UPDATE against a derived-table target: violation inside source subquery+- statement: |+ UPDATE (SELECT * FROM tech_book WHERE UPPER(name) = 'X') v SET v.creator = 'y'+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# DELETE FROM derived-table target: violation inside source subquery+- statement: |+ DELETE FROM (SELECT * FROM tech_book WHERE ABS(id) > 5) v+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# MERGE WHEN MATCHED SET col = (SELECT … WHERE …) — inner WHERE violation+- statement: |+ MERGE INTO orders t USING products p ON (t.order_id = p.product_id)+ WHEN MATCHED THEN UPDATE SET note = (SELECT MAX(name) FROM tech_book WHERE UPPER(name) = 'X')+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# Adversarial: double-flag regression — correlated EXISTS inside JOIN ON+- statement: |+ SELECT * FROM tech_book t JOIN orders o+ ON EXISTS (SELECT 1 FROM products p JOIN orders o2 ON ABS(t.id) = o2.order_id WHERE p.product_id = o.order_id)+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# Regression: DML inside PL/SQL anonymous block IS checked at top-level DML+- statement: |+ BEGIN+ UPDATE tech_book SET creator = 'x' WHERE UPPER(name) = 'A';+ END;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# ---- Round 3 fixes --------------------------------------------------------++# INSERT ALL with a subquery inside VALUES+- statement: |+ INSERT ALL INTO orders (order_id, note) VALUES (1, (SELECT MAX(name) FROM tech_book WHERE UPPER(name) = 'X'))+ SELECT 1 FROM dual+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# UPDATE ... RETURNING expression with inner subquery violation+- statement: |+ UPDATE orders SET note = 'x' WHERE order_id = 1 RETURNING (SELECT MAX(name) FROM tech_book WHERE UPPER(name) = 'X') INTO :var+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# DELETE ... RETURNING expression with inner subquery violation+- statement: |+ DELETE FROM orders WHERE order_id = 1 RETURNING (SELECT MAX(name) FROM tech_book WHERE UPPER(name) = 'X') INTO :var+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Round 4 fixes --------------------------------------------------------++# INSERT ALL WHEN <cond> — conditional predicate with function on indexed col+- statement: |+ INSERT ALL+ WHEN UPPER(name) = 'X' THEN INTO orders (order_id, customer_name) VALUES (id, name)+ SELECT id, name FROM tech_book+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# MERGE WHEN MATCHED UPDATE ... WHERE EXISTS (SELECT ... WHERE ABS(indexed))+# — previously double-walked, now should emit exactly one advice+- statement: |+ MERGE INTO orders t USING products p ON (t.order_id = p.product_id)+ WHEN MATCHED THEN UPDATE SET note = 'x'+ WHERE EXISTS (SELECT 1 FROM tech_book WHERE ABS(id) > 10)+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 3+ column: 0+ endposition: null++# MERGE WHEN NOT MATCHED INSERT ... WHERE EXISTS (SELECT ... WHERE UPPER(indexed))+# — previously double-walked, now single+- statement: |+ MERGE INTO orders t USING products p ON (t.order_id = p.product_id)+ WHEN NOT MATCHED THEN INSERT (order_id, note) VALUES (p.product_id, 'x')+ WHERE EXISTS (SELECT 1 FROM tech_book b WHERE UPPER(b.name) = 'Y')+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 3+ column: 0+ endposition: null++# ---- Round 5 fix ----------------------------------------------------------++# INSERT ALL WHEN EXISTS (subquery) — subquery inside WHEN must emit exactly 1 advice+- statement: |+ INSERT ALL+ WHEN EXISTS (SELECT 1 FROM tech_book b WHERE UPPER(b.name) = 'X') THEN INTO orders (order_id, note) VALUES (id, name)+ SELECT id, name FROM tech_book+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# ---- Round 6 regression coverage (adversarial hypotheses, all pass) -------++# INSERT FIRST parity with INSERT ALL+- statement: |+ INSERT FIRST+ WHEN UPPER(name) = 'X' THEN INTO orders (order_id, note) VALUES (id, name)+ SELECT id, name FROM tech_book+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# INSERT ALL ELSE branch with violation inside VALUES subquery+- statement: |+ INSERT ALL+ WHEN id = 1 THEN INTO orders (order_id, note) VALUES (id, name)+ ELSE INTO orders (order_id, note) VALUES (id, (SELECT MAX(name) FROM tech_book WHERE UPPER(name) = 'X'))+ SELECT id, name FROM tech_book+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 3+ column: 0+ endposition: null++# WHEN with subquery violation AND INTO-VALUES with separate subquery violation+- statement: |+ INSERT ALL+ WHEN EXISTS (SELECT 1 FROM tech_book b WHERE UPPER(b.name) = 'X') THEN INTO orders (order_id, note) VALUES (id, (SELECT MAX(name) FROM tech_book WHERE ABS(id) > 10))+ SELECT id, name FROM tech_book+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "ABS" is applied to indexed column "ID" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# ---- Codex P1 regression: depth balance across nested contexts -----------++# INSERT ... SELECT source contains a Select_statement nested inside the+# Insert_statement. Previously OnEnter skipped the increment on the nested+# Select_statement while OnExit still decremented, leaving depth at 0 mid-+# statement. The fix makes both events unconditional — depth stays at 1+# throughout, guarding against any potential re-dispatch.+- statement: |+ INSERT INTO insert_target (id, name)+ SELECT id, name FROM tech_book WHERE UPPER(name) = 'X'+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null++# Sibling EXISTS subqueries with matching violations — exactly 2 advice+# regardless of walker re-entry semantics.+- statement: |+ SELECT * FROM tech_book t+ WHERE EXISTS (SELECT 1 FROM orders o1 WHERE UPPER(o1.customer_name) = 'X')+ AND EXISTS (SELECT 1 FROM orders o2 WHERE UPPER(o2.customer_name) = 'Y')+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 2+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 3+ column: 0+ endposition: null++# ---- Codex P1 round-2 regression: Oracle empty-schema resolution ---------++# Oracle prod sync stores SchemaMetadata{Name: ""}. The rule must use "" as+# currentSchema (NOT the database name) to find tables. This test exercises+# both unqualified and database-qualified refs.+- statement: "SELECT * FROM TEST_DB.tech_book WHERE UPPER(name) = 'X'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# Codex round-13 P2 (#3104539932): owner-qualified Oracle refs must+# distinguish current-owner from cross-owner. Bytebase sync only stores+# the connected schema's objects, so `HR.tech_book` (HR != TEST_DB) has+# no metadata and we cannot reason about its indexes — the rule must NOT+# emit advice for cross-owner refs (would otherwise wrongly attach+# current-owner indexes). PASS case (no advice expected):+- statement: "SELECT * FROM HR.tech_book WHERE UPPER(name) = 'X'"++# Codex round-8 P2 (#3104316975): Oracle WITH-factoring name shadows base+# table. The CTE has no indexes, so what looks like an indexed-column+# violation against ORDERS is actually against the CTE result. Previously+# the rule attached real ORDERS indexes to the CTE alias and falsely+# flagged. With CTE shadowing, the CTE alias is opaque (unresolved) and+# the rule no longer falsely flags.+- statement: |+ WITH orders AS (SELECT 1 AS customer_name FROM dual)+ SELECT * FROM orders WHERE UPPER(customer_name) = 'X'++# Codex round-9 P2 (#3104448556): same sibling-CTE-shadowing fix, Oracle.+# C2 body references the prior factoring element ORDERS; it must resolve+# to the CTE (opaque), not the physical ORDERS table.+- statement: |+ WITH orders AS (SELECT 1 AS customer_name FROM dual),+ c2 AS (SELECT * FROM orders WHERE UPPER(customer_name) = 'X')+ SELECT * FROM c2++# Codex round-11 P2 (#3104501040): containsDerivedTable previously walked+# all children of From_clause including Join_on_part subqueries. A derived+# table inside a JOIN ON's nested subquery falsely marked the OUTER+# query's localUnresolved=true, suppressing outer-scope fallback for+# unqualified correlated refs. Now mirrors PG's hasOpaqueSource by+# skipping Join_on_part subtrees.+- statement: |+ SELECT * FROM tech_book t WHERE EXISTS (+ SELECT 1 FROM no_index_table n+ INNER JOIN products p ON p.product_id = (SELECT y.id FROM (SELECT id FROM tech_book) y)+ WHERE UPPER(name) = 'X'+ )+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 4+ column: 0+ endposition: null++# Codex round-12 P2 (#3104516409): parenthesized table_ref alias must+# resolve to the underlying base table (Oracle: `FROM (orders) o` is+# equivalent to `FROM orders o`). Previously the alias was opaque,+# erasing indexes and missing real violations on `o.indexed_col`.+- statement: "SELECT * FROM (orders) o WHERE UPPER(o.customer_name) = 'X'"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# Doubly-parenthesized — same outcome+- statement: "SELECT * FROM ((orders)) o WHERE o.amount + 1 > 5"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "AMOUNT" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# Parenthesized JOIN: alias spans multiple tables → opaque (no advice).+# Verifies we DON'T over-fix; the indexed col `customer_name` belongs+# to the join output (multiple sources), not to a single table via `j`.+- statement: "SELECT * FROM (orders o JOIN products p ON o.order_id = p.product_id) j WHERE UPPER(j.customer_name) = 'X'"++# Codex round-14 P2 (#3104564089): same as PG #3104564086 — Oracle WITH+# non-recursive sibling visibility ordering. Earlier `a` body references+# real ORDERS, NOT the same-named later CTE. Violation must flag.+- statement: |+ WITH a AS (SELECT * FROM orders WHERE UPPER(customer_name) = 'X'),+ orders AS (SELECT 1 AS dummy FROM dual)+ SELECT * FROM a+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# Recursive factoring, no false positive (column-alias variant).+# Oracle detects recursiveness per-element via self-reference in FROM:+# when the body of `orders` contains `FROM orders`, the element is+# recursive and its name is pushed BEFORE walking, so the body's self-ref+# resolves to the (opaque) CTE rather than the same-named base table.+# The recursive arm's `n < 10` therefore references the CTE column alias,+# which yields no advice regardless.+- statement: |+ WITH orders (n, customer_name) AS (+ SELECT 1, customer_name FROM orders WHERE rownum <= 1+ UNION ALL+ SELECT n + 1, customer_name FROM orders WHERE n < 10+ )+ SELECT * FROM orders++# Codex round-17 P2 (#3109425426): recursive subquery factoring body+# must treat self-referring `FROM <same_name>` as opaque, NOT as the+# same-named base table. Prior to this fix (commit 1ee832f7f0 collapsed+# push-before/push-after into unconditional push-after), a recursive+# member applying `UPPER(customer_name)` on what looks like an indexed+# base-table column of ORDERS would falsely flag (code 234 advice).+# With per-element recursiveness detection, `FROM orders` inside the+# body is now opaque → no advice.+- statement: |+ WITH orders AS (+ SELECT order_id, customer_name FROM dual+ UNION ALL+ SELECT order_id + 1, customer_name FROM orders WHERE UPPER(customer_name) = 'X'+ )+ SELECT * FROM orders++# Codex round-16 P2 (#3109237788, Oracle variant): non-recursive WITH+# self-shadow must resolve inner `FROM orders` to the REAL base table.+# Without the fix, push-before-each made inner `orders` opaque → missed+# the UPPER(customer_name) violation. Fixed by push-after-body in the+# non-recursive branch (Oracle's default CTE-visibility mode).+- statement: |+ WITH orders AS (SELECT * FROM orders WHERE UPPER(customer_name) = 'X')+ SELECT * FROM orders+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Function "UPPER" is applied to indexed column "CUSTOMER_NAME" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: null++# Same shape, calculation variant — locks the calculation category too.+- statement: |+ WITH orders AS (SELECT * FROM orders WHERE amount + 1 > 10)+ SELECT * FROM orders+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: 'Calculation is applied to indexed column "AMOUNT" in the WHERE clause, which prevents index usage'+ startposition:+ line: 1+ column: 0+ endposition: nulldiff --git a/backend/plugin/advisor/pg/advisor_statement_where_disallow_functions_and_calculations.go b/backend/plugin/advisor/pg/advisor_statement_where_disallow_functions_and_calculations.gonew file mode 100644index 0000000000..436b46f89a--- /dev/null+++ b/backend/plugin/advisor/pg/advisor_statement_where_disallow_functions_and_calculations.go@@ -0,0 +1,1075 @@+// Package pg is the advisor for postgres database.+package pg++import (+ "context"+ "fmt"+ "strings"++ "github.com/bytebase/omni/pg/ast"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"+ "github.com/bytebase/bytebase/backend/store/model"+)++var (+ _ advisor.Advisor = (*StatementWhereDisallowFunctionsAndCalculationsAdvisor)(nil)+)++func init() {+ advisor.Register(storepb.Engine_POSTGRES, storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS, &StatementWhereDisallowFunctionsAndCalculationsAdvisor{})+}++// StatementWhereDisallowFunctionsAndCalculationsAdvisor is the advisor that flags+// functions or calculations applied to indexed columns in WHERE clauses.+type StatementWhereDisallowFunctionsAndCalculationsAdvisor struct{}++// Check implements advisor.Advisor.+func (*StatementWhereDisallowFunctionsAndCalculationsAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {+ level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)+ if err != nil {+ return nil, err+ }+ rule := &whereDisallowFuncPgRule{+ OmniBaseRule: OmniBaseRule{+ Level: level,+ Title: checkCtx.Rule.Type.String(),+ },+ }+ if checkCtx.DBSchema != nil {+ rule.dbMetadata = model.NewDatabaseMetadata(checkCtx.DBSchema, nil, nil,+ storepb.Engine_POSTGRES, checkCtx.IsObjectCaseSensitive)+ // Resolve $user against checkCtx.SessionUser so deployments using+ // `search_path = "$user", public` correctly include the session+ // user's schema. Plain GetSearchPath() drops $user entries.+ rule.searchPath = rule.dbMetadata.GetSearchPathForCurrentUser(checkCtx.SessionUser)+ }+ if len(rule.searchPath) == 0 {+ // Default PG search_path is `"$user", public`. With no current-user+ // context, fall back to public so the rule still resolves vanilla+ // references when sync hasn't populated search_path.+ rule.searchPath = []string{"public"}+ }+ return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil+}++type whereDisallowFuncPgRule struct {+ OmniBaseRule+ dbMetadata *model.DatabaseMetadata+ // searchPath is the list of schemas to consult for unqualified table refs,+ // in priority order. Mirrors PG's `search_path` GUC. Sync stores the+ // resolved value on DatabaseSchemaMetadata.SearchPath; if absent we fall+ // back to ["public"] to match PG's default.+ searchPath []string+ // cteStack is a stack of CTE-name sets visible at the current nesting+ // level. Pushed on entry to a query that has a WITH clause; popped on+ // exit. A FROM-clause name that matches any stacked entry is treated+ // as opaque (`tableRef{}`) so it never picks up real-table indexes.+ // Inner WITHs shadow outer per normal SQL scoping.+ cteStack []map[string]bool+}++// pushCTEs pushes a new CTE-name set onto the visibility stack.+func (r *whereDisallowFuncPgRule) pushCTEs(names map[string]bool) {+ r.cteStack = append(r.cteStack, names)+}++// popCTEs pops the most-recently pushed CTE-name set.+func (r *whereDisallowFuncPgRule) popCTEs() {+ if n := len(r.cteStack); n > 0 {+ r.cteStack = r.cteStack[:n-1]+ }+}++// cteVisible reports whether `name` (already normalized) is in scope as a CTE.+func (r *whereDisallowFuncPgRule) cteVisible(name string) bool {+ for _, frame := range r.cteStack {+ if frame[name] {+ return true+ }+ }+ return false+}++func (*whereDisallowFuncPgRule) Name() string {+ return string(storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS)+}++// tableRef captures a resolved table reference.+type tableRef struct {+ schema string // empty means resolve via search_path+ name string+}++// tablesByAlias maps alias (or name if no alias) to the underlying tableRef.+type tablesByAlias = map[string]tableRef++// indexedByAlias maps alias to a set of column names for that alias.+type indexedByAlias = map[string]map[string]bool++// scopeIndexed carries per-alias column metadata for the local (inner) scope+// and any outer scope inherited from enclosing queries. See MySQL rule for+// the resolution model documentation.+type scopeIndexed struct {+ local indexedByAlias+ localAll indexedByAlias+ localAliases map[string]bool+ outer indexedByAlias+ localUnresolved bool+}++func (s scopeIndexed) empty() bool {+ return len(s.local) == 0 && len(s.outer) == 0+}++// OnStatement dispatches each top-level AST node to the detector.+func (r *whereDisallowFuncPgRule) OnStatement(node ast.Node) {+ switch n := node.(type) {+ case *ast.SelectStmt:+ r.checkSelectInScope(n, nil)+ case *ast.InsertStmt:+ r.onInsert(n)+ case *ast.UpdateStmt:+ r.onUpdate(n)+ case *ast.DeleteStmt:+ r.onDelete(n)+ case *ast.ViewStmt:+ r.onViewStmt(n)+ case *ast.CreateTableAsStmt:+ r.onCreateTableAs(n)+ case *ast.MergeStmt:+ r.onMerge(n)+ default:+ }+}++// ---- Identifier / metadata helpers ---------------------------------------++// normalizeIdent returns the canonical lookup key for an identifier. PG is+// case-sensitive for unquoted identifiers in our fixtures (all lowercase).+func (r *whereDisallowFuncPgRule) normalizeIdent(name string) string {+ if r.dbMetadata != nil && r.dbMetadata.GetIsObjectCaseSensitive() {+ return name+ }+ return strings.ToLower(name)+}++// tableMetadata fetches the store-model table for the given ref.+//+// PG resolves unqualified table refs through the `search_path` GUC: each+// schema in priority order is consulted until a match is found. Sync stores+// the database's resolved search_path on `DatabaseSchemaMetadata.SearchPath`+// (see backend/plugin/db/pg/sync.go); we honor it here so deployments using+// non-default schemas (tenant/app/etc.) still resolve correctly. Hardcoding+// `public` would silently miss violations on indexed columns under any+// other schema in production.+func (r *whereDisallowFuncPgRule) tableMetadata(ref tableRef) *model.TableMetadata {+ if r.dbMetadata == nil {+ return nil+ }+ if ref.schema != "" {+ return r.dbMetadata.GetSchemaMetadata(ref.schema).GetTable(ref.name)+ }+ for _, schema := range r.searchPath {+ if t := r.dbMetadata.GetSchemaMetadata(schema).GetTable(ref.name); t != nil {+ return t+ }+ }+ return nil+}++// indexedColumns returns indexed column names for the given table reference.+// Keys go through normalizeIdent so case-sensitive schemas distinguish+// quoted mixed-case identifiers; see §5 "Identifier normalization invariant".+func (r *whereDisallowFuncPgRule) indexedColumns(ref tableRef) map[string]bool {+ table := r.tableMetadata(ref)+ if table == nil {+ return nil+ }+ cols := make(map[string]bool)+ for _, idx := range table.GetProto().GetIndexes() {+ for _, expr := range idx.GetExpressions() {+ cols[r.normalizeIdent(expr)] = true+ }+ }+ if len(cols) == 0 {+ return nil+ }+ return cols+}++// allColumns returns every column name defined for the given table reference.+// Keys use normalizeIdent for the same reason as indexedColumns.+func (r *whereDisallowFuncPgRule) allColumns(ref tableRef) map[string]bool {+ table := r.tableMetadata(ref)+ if table == nil {+ return nil+ }+ cols := make(map[string]bool)+ for _, c := range table.GetProto().GetColumns() {+ cols[r.normalizeIdent(c.GetName())] = true+ }+ if len(cols) == 0 {+ return nil+ }+ return cols+}++func (r *whereDisallowFuncPgRule) resolveIndexedColumns(tables tablesByAlias) indexedByAlias {+ all := make(indexedByAlias)+ for alias, ref := range tables {+ if cols := r.indexedColumns(ref); cols != nil {+ all[alias] = cols+ }+ }+ if len(all) == 0 {+ return nil+ }+ return all+}++func (r *whereDisallowFuncPgRule) resolveAllColumns(tables tablesByAlias) indexedByAlias {+ all := make(indexedByAlias)+ for alias, ref := range tables {+ if cols := r.allColumns(ref); cols != nil {+ all[alias] = cols+ }+ }+ if len(all) == 0 {+ return nil+ }+ return all+}++// ---- FROM-clause collection ----------------------------------------------++// collectTableNames walks a FROM-clause list and extracts table aliases/refs.+// Descent stops at subquery boundaries so inner SELECTs do not leak their+// sources into the outer scope; derived-table aliases are recorded as+// opaque tableRef{} entries so qualifier-based resolution can still tell+// them apart from an outer alias of the same name.+func (r *whereDisallowFuncPgRule) collectTableNames(from *ast.List) tablesByAlias {+ tables := make(tablesByAlias)+ if from == nil {+ return tables+ }+ for _, item := range from.Items {+ r.collectTableNamesFromNode(item, tables)+ }+ return tables+}++func (r *whereDisallowFuncPgRule) collectTableNamesFromNode(node ast.Node, tables tablesByAlias) {+ if node == nil {+ return+ }+ switch n := node.(type) {+ case *ast.RangeVar:+ key := ""+ if n.Alias != nil && n.Alias.Aliasname != "" {+ key = n.Alias.Aliasname+ } else {+ key = n.Relname+ }+ normKey := r.normalizeIdent(key)+ // CTE shadowing: if this RangeVar's underlying name (NOT the alias)+ // matches a CTE in scope, the FROM-ref binds to the CTE result, not+ // the physical table. Record opaque so we don't attach base-table+ // indexes to CTE columns. Schema-qualified refs (`s.t`) bypass this+ // since CTEs are unqualified.+ if n.Schemaname == "" && r.cteVisible(r.normalizeIdent(n.Relname)) {+ tables[normKey] = tableRef{}+ return+ }+ newRef := tableRef{schema: n.Schemaname, name: n.Relname}+ if existing, ok := tables[normKey]; ok && (existing.schema != newRef.schema || existing.name != newRef.name) {+ tables[normKey] = tableRef{}+ } else {+ tables[normKey] = newRef+ }+ case *ast.RangeSubselect:+ if n.Alias != nil && n.Alias.Aliasname != "" {+ key := r.normalizeIdent(n.Alias.Aliasname)+ if _, exists := tables[key]; !exists {+ tables[key] = tableRef{}+ }+ }+ case *ast.RangeFunction:+ if n.Alias != nil && n.Alias.Aliasname != "" {+ key := r.normalizeIdent(n.Alias.Aliasname)+ if _, exists := tables[key]; !exists {+ tables[key] = tableRef{}+ }+ }+ case *ast.JoinExpr:+ r.collectTableNamesFromNode(n.Larg, tables)+ r.collectTableNamesFromNode(n.Rarg, tables)+ if n.Alias != nil && n.Alias.Aliasname != "" {+ key := r.normalizeIdent(n.Alias.Aliasname)+ if _, exists := tables[key]; !exists {+ tables[key] = tableRef{}+ }+ }+ default:+ }+}++// localHasUnresolvedSources reports whether any FROM entry hides columns we+// cannot enumerate. This walks SOURCE POSITIONS only — top-level FROM items+// and JoinExpr.Larg/Rarg — looking for opaque producers (derived tables,+// RangeSubselect/SubLink/SelectStmt, RangeFunction). Subqueries appearing+// inside JoinExpr.Quals are VALUE expressions, not source producers, and+// must NOT count toward unresolved: treating them as opaque suppresses the+// outer-scope fallback in isIndexed and produces false negatives for+// correlated refs. See spec §3 "Unresolved FROM-item inventory".+func (r *whereDisallowFuncPgRule) localHasUnresolvedSources(from *ast.List, local tablesByAlias) bool {+ if from != nil {+ for _, item := range from.Items {+ if hasOpaqueSource(item) {+ return true+ }+ }+ }+ for _, ref := range local {+ if ref == (tableRef{}) {+ // Opaque alias (CTE-shadowed RangeVar, JoinExpr, RangeSubselect,+ // or RangeFunction) — by definition we can't enumerate its+ // columns, so the local scope is unresolved.+ return true+ }+ if r.tableMetadata(ref) == nil {+ return true+ }+ }+ return false+}++// hasOpaqueSource reports whether a FROM item (or its JOIN sub-tree) contains+// an opaque source node. Only SOURCE positions are inspected:+// - the item itself+// - for JoinExpr, Larg and Rarg (NOT Quals — those are predicates)+func hasOpaqueSource(n ast.Node) bool {+ if n == nil {+ return false+ }+ switch x := n.(type) {+ case *ast.SubLink, *ast.RangeSubselect, *ast.SelectStmt, *ast.RangeFunction:+ return true+ case *ast.JoinExpr:+ return hasOpaqueSource(x.Larg) || hasOpaqueSource(x.Rarg)+ }+ return false+}++// ---- Column reference resolution -----------------------------------------++// extractColumnRefParts returns (qualifier, column) for a ColumnRef.+// Returns ("", "") when the ref is not a plain column.+func (*whereDisallowFuncPgRule) extractColumnRefParts(ref *ast.ColumnRef) (string, string) {+ if ref == nil || ref.Fields == nil || len(ref.Fields.Items) == 0 {+ return "", ""+ }+ parts := make([]string, 0, len(ref.Fields.Items))+ for _, f := range ref.Fields.Items {+ s, ok := f.(*ast.String)+ if !ok {+ return "", ""+ }+ parts = append(parts, s.Str)+ }+ switch len(parts) {+ case 1:+ return "", parts[0]+ default:+ // a.b -> qualifier=a, column=b. a.b.c -> qualifier=b, column=c+ // (schema 'a' ignored; alias lookup uses the last qualifier).+ return parts[len(parts)-2], parts[len(parts)-1]+ }+}++// isIndexed reports whether a column reference is indexed within scope s.+func (r *whereDisallowFuncPgRule) isIndexed(ref *ast.ColumnRef, s scopeIndexed) bool {+ if ref == nil || s.empty() {+ return false+ }+ qualifier, column := r.extractColumnRefParts(ref)+ if column == "" {+ return false+ }+ col := r.normalizeIdent(column)+ if qualifier != "" {+ alias := r.normalizeIdent(qualifier)+ if s.localAliases[alias] {+ return s.local[alias][col]+ }+ return s.outer[alias][col]+ }+ // Unqualified: does any local table declare this column?+ localClaims := false+ for _, cols := range s.localAll {+ if cols[col] {+ localClaims = true+ break+ }+ }+ if localClaims {+ for _, cols := range s.local {+ if cols[col] {+ return true+ }+ }+ return false+ }+ if s.localUnresolved {+ return false+ }+ for _, cols := range s.outer {+ if cols[col] {+ return true+ }+ }+ return false+}++// ---- Detection ------------------------------------------------------------++// checkSelectInScope is the main recursive entry point for SELECT queries,+// threading an outer scope for correlated subqueries.+func (r *whereDisallowFuncPgRule) checkSelectInScope(sel *ast.SelectStmt, outer tablesByAlias) {+ if sel == nil {+ return+ }+ // CTE visibility per SQL: non-recursive WITH bodies see only earlier+ // siblings; WITH RECURSIVE bodies see all siblings (including self).+ // handleWithClause walks each body in declaration order and pushes+ // names with the right ordering; cleanup pops at our exit.+ popCTEs := r.handleWithClause(sel.WithClause)+ defer popCTEs()+ if sel.Op != ast.SETOP_NONE {+ r.checkSelectInScope(sel.Larg, outer)+ r.checkSelectInScope(sel.Rarg, outer)+ return+ }+ local := r.collectTableNames(sel.FromClause)+ unresolved := r.localHasUnresolvedSources(sel.FromClause, local)+ // Build combined scope so inner subqueries see current local+outer as outer.+ combined := make(tablesByAlias, len(local)+len(outer))+ for alias, ref := range outer {+ combined[alias] = ref+ }+ for alias, ref := range local {+ combined[alias] = ref+ }+ r.checkWhereWithScopes(sel.WhereClause, local, outer, unresolved)+ // JOIN ON predicates are bound to the same local scope as WHERE and must+ // be checked for function/calculation violations on indexed columns.+ r.checkJoinConditions(sel.FromClause, local, outer, unresolved)+ // Recurse into nested subqueries elsewhere (target list, FROM, HAVING,+ // GROUP BY, ORDER BY) passing current combined scope as outer. HAVING+ // predicates are never flagged directly; nested subqueries inside HAVING+ // are still recursed into.+ r.recurseIntoNestedSelects(sel, combined)+}++// checkJoinConditions walks a FROM clause and runs WHERE-detection on each+// JoinExpr.Quals encountered. JOIN ON predicates are semantically WHERE-like+// — a function/calculation on an indexed column still defeats the index.+func (r *whereDisallowFuncPgRule) checkJoinConditions(from *ast.List, local, outer tablesByAlias, unresolved bool) {+ if from == nil {+ return+ }+ for _, item := range from.Items {+ r.checkJoinConditionsInNode(item, local, outer, unresolved)+ }+}++func (r *whereDisallowFuncPgRule) checkJoinConditionsInNode(node ast.Node, local, outer tablesByAlias, unresolved bool) {+ if node == nil {+ return+ }+ j, ok := node.(*ast.JoinExpr)+ if !ok {+ return+ }+ r.checkWhereWithScopes(j.Quals, local, outer, unresolved)+ r.checkJoinConditionsInNode(j.Larg, local, outer, unresolved)+ r.checkJoinConditionsInNode(j.Rarg, local, outer, unresolved)+}++// walkCTEBody dispatches a single CTE body to the appropriate handler.+// The CTE body is checked with fresh scope (CTEs are not correlated with+// their referencing SELECT). Data-modifying CTEs (INSERT/UPDATE/DELETE/+// MERGE) dispatch to their own handlers.+func (r *whereDisallowFuncPgRule) walkCTEBody(query ast.Node) {+ switch q := query.(type) {+ case *ast.SelectStmt:+ r.checkSelectInScope(q, nil)+ case *ast.UpdateStmt:+ r.onUpdate(q)+ case *ast.DeleteStmt:+ r.onDelete(q)+ case *ast.InsertStmt:+ r.onInsert(q)+ case *ast.MergeStmt:+ r.onMerge(q)+ default:+ }+}++// handleWithClause walks the CTE bodies AND maintains the cteStack with+// SQL-correct visibility, returning a cleanup func the caller must defer.+//+// CTE visibility matrix (SQL:2011):+//+// | Mode | body sees self | preceding siblings | later siblings |+// |-----------------------|----------------|--------------------|----------------|+// | Non-recursive WITH | No | Yes | No |+// | WITH RECURSIVE | Yes | Yes | Yes (mutual) |+//+// The distinction matters for this rule because when a CTE name shadows a+// real base table (e.g. `WITH orders AS (SELECT * FROM orders WHERE …) …`):+// - In NON-recursive WITH, inner `FROM orders` resolves to the REAL base+// table (per SQL spec). We MUST resolve indexes against it, otherwise+// we silently miss `UPPER(indexed_col)` violations — a false negative.+// - In WITH RECURSIVE, inner `FROM orders` resolves to the CTE itself+// (self-reference). We MUST treat it as opaque to avoid attaching the+// same-named base table's indexes to the CTE — a false positive.+//+// Strategy: push-timing depends on `with.Recursive`.+// - Recursive: collect all CTE names first, push the whole frame ONCE,+// then walk every body. Every body sees every name (self + others).+// - Non-recursive: push an EMPTY frame, then for each CTE: walk its body+// first (current name invisible), then add its name to the frame so+// subsequent siblings see it.+//+// On exit, the frame contains every CTE name in both modes, so the OUTER+// query (walked by the caller after handleWithClause returns) always sees+// the full set of CTE names — preserving the existing opaque-on-outer+// behavior.+func (r *whereDisallowFuncPgRule) handleWithClause(with *ast.WithClause) func() {+ noop := func() {+ // Intentionally empty: no CTE frame was pushed, so nothing to pop.+ }+ if with == nil || with.Ctes == nil {+ return noop+ }+ frame := make(map[string]bool)+ r.pushCTEs(frame)++ if with.Recursive {+ for _, item := range with.Ctes.Items {+ cte, ok := item.(*ast.CommonTableExpr)+ if !ok || cte.Ctename == "" {+ continue+ }+ frame[r.normalizeIdent(cte.Ctename)] = true+ }+ for _, item := range with.Ctes.Items {+ cte, ok := item.(*ast.CommonTableExpr)+ if !ok || cte.Ctequery == nil {+ continue+ }+ r.walkCTEBody(cte.Ctequery)+ }+ return r.popCTEs+ }++ for _, item := range with.Ctes.Items {+ cte, ok := item.(*ast.CommonTableExpr)+ if !ok || cte.Ctequery == nil {+ continue+ }+ r.walkCTEBody(cte.Ctequery)+ if cte.Ctename != "" {+ frame[r.normalizeIdent(cte.Ctename)] = true+ }+ }+ return r.popCTEs+}++// checkWhereWithScopes builds the scopeIndexed and inspects the WHERE body,+// dispatching to the detector for each non-subquery node. Nested subqueries+// are recursed into with the combined (local+outer) scope as their outer.+func (r *whereDisallowFuncPgRule) checkWhereWithScopes(where ast.Node, local, outer tablesByAlias, localUnresolved bool) {+ if where == nil {+ return+ }+ localAliases := make(map[string]bool, len(local))+ for alias := range local {+ localAliases[alias] = true+ }+ s := scopeIndexed{+ local: r.resolveIndexedColumns(local),+ localAll: r.resolveAllColumns(local),+ localAliases: localAliases,+ outer: r.resolveIndexedColumns(outer),+ localUnresolved: localUnresolved,+ }+ combined := make(tablesByAlias, len(local)+len(outer))+ for alias, ref := range outer {+ combined[alias] = ref+ }+ for alias, ref := range local {+ combined[alias] = ref+ }+ ast.Inspect(where, func(n ast.Node) bool {+ switch x := n.(type) {+ case *ast.SubLink:+ if sub, ok := x.Subselect.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sub, combined)+ }+ // Still visit Testexpr for the outer side of ANY/ALL.+ if x.Testexpr != nil {+ ast.Inspect(x.Testexpr, func(m ast.Node) bool {+ switch y := m.(type) {+ case *ast.SelectStmt:+ r.checkSelectInScope(y, combined)+ return false+ case *ast.SubLink:+ if sub2, ok := y.Subselect.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sub2, combined)+ }+ return false+ case *ast.RangeSubselect:+ if sub2, ok := y.Subquery.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sub2, combined)+ }+ return false+ }+ if !s.empty() {+ r.checkWhereNode(m, s)+ }+ return true+ })+ }+ return false+ case *ast.RangeSubselect:+ if sub, ok := x.Subquery.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sub, combined)+ }+ return false+ case *ast.SelectStmt:+ r.checkSelectInScope(x, combined)+ return false+ }+ if !s.empty() {+ r.checkWhereNode(n, s)+ }+ return true+ })+}++// checkWhereNode runs the detector cells on a single node.+func (r *whereDisallowFuncPgRule) checkWhereNode(n ast.Node, indexed scopeIndexed) {+ switch expr := n.(type) {+ case *ast.FuncCall:+ if col := r.findIndexedColumnInArgs(expr.Args, indexed); col != "" {+ r.addFunctionAdvice(r.funcCallName(expr), col, r.LocToLine(expr.Loc))+ }+ case *ast.A_Expr:+ if expr.Kind != ast.AEXPR_OP {+ return+ }+ op := aExprOpSymbol(expr)+ if op == "" {+ return+ }+ if expr.Lexpr == nil {+ // Unary op.+ if op == "-" || op == "~" {+ if col := r.unwrapAndFindIndexedColumn(expr.Rexpr, indexed); col != "" {+ r.addCalculationAdvice(col, r.LocToLine(expr.Loc))+ }+ }+ return+ }+ if isArithmeticOp(op) {+ if col := r.unwrapAndFindIndexedColumn(expr.Lexpr, indexed); col != "" {+ r.addCalculationAdvice(col, r.LocToLine(expr.Loc))+ return+ }+ if col := r.unwrapAndFindIndexedColumn(expr.Rexpr, indexed); col != "" {+ r.addCalculationAdvice(col, r.LocToLine(expr.Loc))+ }+ }+ default:+ }+}++// funcCallName returns the function's simple name, upper-cased.+func (*whereDisallowFuncPgRule) funcCallName(fc *ast.FuncCall) string {+ if fc == nil || fc.Funcname == nil || len(fc.Funcname.Items) == 0 {+ return ""+ }+ last, ok := fc.Funcname.Items[len(fc.Funcname.Items)-1].(*ast.String)+ if !ok {+ return ""+ }+ return strings.ToUpper(last.Str)+}++// aExprOpSymbol extracts the operator symbol from an A_Expr.Name list.+func aExprOpSymbol(expr *ast.A_Expr) string {+ if expr == nil || expr.Name == nil || len(expr.Name.Items) == 0 {+ return ""+ }+ last, ok := expr.Name.Items[len(expr.Name.Items)-1].(*ast.String)+ if !ok {+ return ""+ }+ return last.Str+}++// isArithmeticOp reports whether a binary operator symbol defeats index use+// on its operand column. The inventory is derived from PostgreSQL's operator+// set (not mirrored from MySQL, whose set differs). Covered:+// - arithmetic: + - * / % ^ (^ is PG exponent, not XOR)+// - bitwise: & | # << >>+func isArithmeticOp(op string) bool {+ switch op {+ case "+", "-", "*", "/", "%", "^", "&", "|", "#", "<<", ">>":+ return true+ }+ return false+}++// findIndexedColumnInArgs searches function arguments for an indexed ColumnRef,+// unwrapping passthrough wrappers (TypeCast) so CAST(name AS TEXT) still flags.+// Arithmetic (A_Expr) is NOT crossed — those are handled by the calculation+// path so `ABS(id + 1)` is reported as a calculation.+func (r *whereDisallowFuncPgRule) findIndexedColumnInArgs(args *ast.List, indexed scopeIndexed) string {+ if args == nil {+ return ""+ }+ for _, arg := range args.Items {+ if col := r.unwrapAndFindIndexedColumn(arg, indexed); col != "" {+ return col+ }+ }+ return ""+}++// unwrapAndFindIndexedColumn peels passthrough wrappers (TypeCast) and, if the+// inner expression is an indexed ColumnRef, returns its lower-cased column+// name. Returns "" otherwise.+func (r *whereDisallowFuncPgRule) unwrapAndFindIndexedColumn(expr ast.Node, indexed scopeIndexed) string {+ for expr != nil {+ switch e := expr.(type) {+ case *ast.ColumnRef:+ if r.isIndexed(e, indexed) {+ _, col := r.extractColumnRefParts(e)+ return r.normalizeIdent(col)+ }+ return ""+ case *ast.TypeCast:+ expr = e.Arg+ default:+ return ""+ }+ }+ return ""+}++// recurseIntoNestedSelects finds nested *SelectStmt / *SubLink / *RangeSubselect+// nodes in the non-WHERE parts of the given SELECT and invokes+// checkSelectInScope on each with the given outer scope. HAVING predicates+// are NEVER flagged themselves, but nested subqueries inside HAVING are still+// recursed into.+func (r *whereDisallowFuncPgRule) recurseIntoNestedSelects(sel *ast.SelectStmt, outer tablesByAlias) {+ if sel.FromClause != nil {+ for _, f := range sel.FromClause.Items {+ r.recurseIntoNestedSelectsInFromItem(f, outer)+ }+ }+ if sel.TargetList != nil {+ for _, t := range sel.TargetList.Items {+ r.recurseIntoNestedSelectsInNode(t, outer)+ }+ }+ // VALUES ((SELECT ... WHERE ...)) — each row is a *List whose Items hold+ // column expressions. ast.Inspect does not descend into *List itself, so+ // iterate the inner items explicitly.+ if sel.ValuesLists != nil {+ for _, row := range sel.ValuesLists.Items {+ if rl, ok := row.(*ast.List); ok {+ for _, item := range rl.Items {+ r.recurseIntoNestedSelectsInNode(item, outer)+ }+ } else {+ r.recurseIntoNestedSelectsInNode(row, outer)+ }+ }+ }+ r.recurseIntoNestedSelectsInNode(sel.HavingClause, outer)+ if sel.GroupClause != nil {+ for _, g := range sel.GroupClause.Items {+ r.recurseIntoNestedSelectsInNode(g, outer)+ }+ }+ if sel.SortClause != nil {+ for _, s := range sel.SortClause.Items {+ if sb, ok := s.(*ast.SortBy); ok {+ r.recurseIntoNestedSelectsInNode(sb.Node, outer)+ } else {+ r.recurseIntoNestedSelectsInNode(s, outer)+ }+ }+ }+}++// recurseIntoNestedSelectsInFromItem walks a FROM-clause item for nested+// subqueries — derived tables (RangeSubselect) and bare SelectStmts.+// JoinExpr.Quals are NOT descended into here, because checkJoinConditions+// already recurses into subqueries inside ON predicates; descending here too+// would double-flag violations inside correlated subqueries.+func (r *whereDisallowFuncPgRule) recurseIntoNestedSelectsInFromItem(n ast.Node, outer tablesByAlias) {+ if n == nil {+ return+ }+ switch x := n.(type) {+ case *ast.JoinExpr:+ r.recurseIntoNestedSelectsInFromItem(x.Larg, outer)+ r.recurseIntoNestedSelectsInFromItem(x.Rarg, outer)+ case *ast.RangeSubselect:+ if sub, ok := x.Subquery.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sub, outer)+ }+ default:+ r.recurseIntoNestedSelectsInNode(n, outer)+ }+}++// recurseIntoNestedSelectsInNode walks an arbitrary expression tree for+// nested subqueries, threading the given outer scope. Does not run the+// WHERE-detector on the expression itself.+func (r *whereDisallowFuncPgRule) recurseIntoNestedSelectsInNode(n ast.Node, outer tablesByAlias) {+ if n == nil {+ return+ }+ ast.Inspect(n, func(m ast.Node) bool {+ switch x := m.(type) {+ case *ast.SelectStmt:+ r.checkSelectInScope(x, outer)+ return false+ case *ast.SubLink:+ if sub, ok := x.Subselect.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sub, outer)+ }+ if x.Testexpr != nil {+ r.recurseIntoNestedSelectsInNode(x.Testexpr, outer)+ }+ return false+ case *ast.RangeSubselect:+ if sub, ok := x.Subquery.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sub, outer)+ }+ return false+ }+ return true+ })+}++// recurseIntoNestedSelectsInList walks each item of a List for nested+// subqueries, passing the given outer scope.+func (r *whereDisallowFuncPgRule) recurseIntoNestedSelectsInList(list *ast.List, outer tablesByAlias) {+ if list == nil {+ return+ }+ for _, item := range list.Items {+ r.recurseIntoNestedSelectsInNode(item, outer)+ }+}++// ---- UPDATE / DELETE / INSERT / MERGE / CTAS / VIEW dispatch -------------++// collectTargetAndExtra collects the target relation plus the items of an+// extra clause (FROM for UPDATE, USING for DELETE).+func (r *whereDisallowFuncPgRule) collectTargetAndExtra(relation ast.Node, extra *ast.List) tablesByAlias {+ tables := make(tablesByAlias)+ if relation != nil {+ r.collectTableNamesFromNode(relation, tables)+ }+ if extra != nil {+ for _, item := range extra.Items {+ r.collectTableNamesFromNode(item, tables)+ }+ }+ return tables+}++// onUpdate handles UPDATE [WITH] … FROM … WHERE …+func (r *whereDisallowFuncPgRule) onUpdate(n *ast.UpdateStmt) {+ if n == nil {+ return+ }+ popCTEs := r.handleWithClause(n.WithClause)+ defer popCTEs()+ tables := r.collectTargetAndExtra(n.Relation, n.FromClause)+ unresolved := r.localHasUnresolvedSources(n.FromClause, tables)+ r.checkWhereWithScopes(n.WhereClause, tables, nil, unresolved)+ r.checkJoinConditions(n.FromClause, tables, nil, unresolved)+ if n.FromClause != nil {+ for _, f := range n.FromClause.Items {+ r.recurseIntoNestedSelectsInFromItem(f, tables)+ }+ }+ r.recurseIntoNestedSelectsInList(n.TargetList, tables)+ r.recurseIntoNestedSelectsInList(n.ReturningList, tables)+}++// onDelete handles DELETE [WITH] … [USING …] WHERE …+func (r *whereDisallowFuncPgRule) onDelete(n *ast.DeleteStmt) {+ if n == nil {+ return+ }+ popCTEs := r.handleWithClause(n.WithClause)+ defer popCTEs()+ tables := r.collectTargetAndExtra(n.Relation, n.UsingClause)+ unresolved := r.localHasUnresolvedSources(n.UsingClause, tables)+ r.checkWhereWithScopes(n.WhereClause, tables, nil, unresolved)+ r.checkJoinConditions(n.UsingClause, tables, nil, unresolved)+ if n.UsingClause != nil {+ for _, u := range n.UsingClause.Items {+ r.recurseIntoNestedSelectsInFromItem(u, tables)+ }+ }+ r.recurseIntoNestedSelectsInList(n.ReturningList, tables)+}++// onInsert handles INSERT [WITH] … SELECT / VALUES … [ON CONFLICT …].+func (r *whereDisallowFuncPgRule) onInsert(n *ast.InsertStmt) {+ if n == nil {+ return+ }+ popCTEs := r.handleWithClause(n.WithClause)+ defer popCTEs()+ if sel, ok := n.SelectStmt.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sel, nil)+ }+ if n.OnConflictClause != nil {+ target := make(tablesByAlias)+ if n.Relation != nil {+ r.collectTableNamesFromNode(n.Relation, target)+ }+ if n.OnConflictClause.WhereClause != nil {+ r.checkWhereWithScopes(n.OnConflictClause.WhereClause, target, nil, false)+ }+ // ON CONFLICT (col) WHERE <pred> — the Infer.WhereClause is the+ // partial-index inference predicate, a filter over the target table.+ if n.OnConflictClause.Infer != nil && n.OnConflictClause.Infer.WhereClause != nil {+ r.checkWhereWithScopes(n.OnConflictClause.Infer.WhereClause, target, nil, false)+ }+ r.recurseIntoNestedSelectsInList(n.OnConflictClause.TargetList, target)+ }+ target := make(tablesByAlias)+ if n.Relation != nil {+ r.collectTableNamesFromNode(n.Relation, target)+ }+ r.recurseIntoNestedSelectsInList(n.ReturningList, target)+}++func (r *whereDisallowFuncPgRule) onViewStmt(n *ast.ViewStmt) {+ if n == nil {+ return+ }+ if sel, ok := n.Query.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sel, nil)+ }+}++func (r *whereDisallowFuncPgRule) onCreateTableAs(n *ast.CreateTableAsStmt) {+ if n == nil {+ return+ }+ if sel, ok := n.Query.(*ast.SelectStmt); ok {+ r.checkSelectInScope(sel, nil)+ }+}++// onMerge handles MERGE … USING … ON … WHEN ….+func (r *whereDisallowFuncPgRule) onMerge(n *ast.MergeStmt) {+ if n == nil {+ return+ }+ popCTEs := r.handleWithClause(n.WithClause)+ defer popCTEs()+ tables := make(tablesByAlias)+ if n.Relation != nil {+ r.collectTableNamesFromNode(n.Relation, tables)+ }+ if n.SourceRelation != nil {+ r.collectTableNamesFromNode(n.SourceRelation, tables)+ }+ unresolved := false+ if n.SourceRelation != nil {+ ast.Inspect(n.SourceRelation, func(m ast.Node) bool {+ switch m.(type) {+ case *ast.SubLink, *ast.RangeSubselect, *ast.SelectStmt:+ unresolved = true+ return false+ }+ return !unresolved+ })+ }+ for _, ref := range tables {+ if ref == (tableRef{}) {+ continue+ }+ if r.tableMetadata(ref) == nil {+ unresolved = true+ break+ }+ }+ r.checkWhereWithScopes(n.JoinCondition, tables, nil, unresolved)+ // Source-side JOIN ON predicates (`USING a JOIN b ON UPPER(a.idx)=…`)+ // are bound to the MERGE's combined target+source scope.+ if n.SourceRelation != nil {+ r.checkJoinConditionsInNode(n.SourceRelation, tables, nil, unresolved)+ }+ // MERGE source may itself be a subquery (`USING (SELECT … WHERE …)`).+ // Use the FromItem walker so JoinExpr.Quals are skipped — those were+ // already handled by checkJoinConditionsInNode above.+ r.recurseIntoNestedSelectsInFromItem(n.SourceRelation, tables)+ if n.MergeWhenClauses != nil {+ for _, item := range n.MergeWhenClauses.Items {+ c, ok := item.(*ast.MergeWhenClause)+ if !ok {+ continue+ }+ r.checkWhereWithScopes(c.Condition, tables, nil, unresolved)+ r.recurseIntoNestedSelectsInList(c.TargetList, tables)+ r.recurseIntoNestedSelectsInList(c.Values, tables)+ }+ }+ r.recurseIntoNestedSelectsInList(n.ReturningList, tables)+}++// ---- Advice builders ------------------------------------------------------++func (r *whereDisallowFuncPgRule) addFunctionAdvice(funcName, col string, line int32) {+ r.Advice = append(r.Advice, &storepb.Advice{+ Status: r.Level,+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),+ Title: r.Title,+ Content: fmt.Sprintf("Function %q is applied to indexed column %q in the WHERE clause, which prevents index usage", funcName, col),+ StartPosition: &storepb.Position{+ Line: int32(r.BaseLine) + line,+ Column: 0,+ },+ })+}++func (r *whereDisallowFuncPgRule) addCalculationAdvice(col string, line int32) {+ r.Advice = append(r.Advice, &storepb.Advice{+ Status: r.Level,+ Code: code.StatementDisallowFunctionsAndCalculations.Int32(),+ Title: r.Title,+ Content: fmt.Sprintf("Calculation is applied to indexed column %q in the WHERE clause, which prevents index usage", col),+ StartPosition: &storepb.Position{+ Line: int32(r.BaseLine) + line,+ Column: 0,+ },+ })+}diff --git a/backend/plugin/advisor/pg/advisor_statement_where_disallow_functions_and_calculations_test.go b/backend/plugin/advisor/pg/advisor_statement_where_disallow_functions_and_calculations_test.gonew file mode 100644index 0000000000..71b3babfff--- /dev/null+++ b/backend/plugin/advisor/pg/advisor_statement_where_disallow_functions_and_calculations_test.go@@ -0,0 +1,118 @@+// Package pg is the advisor for postgres database.+package pg++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/component/sheet"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/store/model"+)++// TestSearchPathResolution proves the rule honors PG's search_path GUC for+// unqualified table refs. Codex P2 (#3104277513): hardcoding `public` makes+// deployments using a different search_path silently miss violations.+func TestSearchPathResolution(t *testing.T) {+ // Custom mock: indexed `tech_book(name)` lives ONLY in `app_schema`.+ // public is empty. SearchPath puts app_schema first.+ dbSchema := &storepb.DatabaseSchemaMetadata{+ Name: "test",+ SearchPath: "app_schema, public",+ Schemas: []*storepb.SchemaMetadata{+ {Name: "public"},+ {+ Name: "app_schema",+ Tables: []*storepb.TableMetadata{+ {+ Name: "tech_book",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer"},+ {Name: "name", Type: "text"},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "tech_book_name_idx", Expressions: []string{"name"}},+ },+ },+ },+ },+ },+ }++ stmt := "SELECT * FROM tech_book WHERE UPPER(name) = 'X';"+ rule := &storepb.SQLReviewRule{+ Type: storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS,+ Level: storepb.SQLReviewRule_WARNING,+ }+ originalMetadata := model.NewDatabaseMetadata(dbSchema, nil, nil, storepb.Engine_POSTGRES, true /* isCaseSensitive */)+ checkCtx := advisor.Context{+ DBType: storepb.Engine_POSTGRES,+ OriginalMetadata: originalMetadata,+ FinalMetadata: originalMetadata,+ CurrentDatabase: "test",+ DBSchema: dbSchema,+ IsObjectCaseSensitive: true,+ NoAppendBuiltin: true,+ }++ sm := sheet.NewManager()+ advice, err := advisor.SQLReviewCheck(context.Background(), sm, stmt, []*storepb.SQLReviewRule{rule}, checkCtx)+ require.NoError(t, err)+ require.Len(t, advice, 1, "expected exactly one advice for UPPER(name) on indexed col in app_schema (search_path)")+ require.Contains(t, advice[0].Content, `Function "UPPER" is applied to indexed column "name"`)+}++// TestSearchPathSessionUserResolution proves the rule resolves the `$user`+// search_path entry against checkCtx.SessionUser. Codex P2 (#3104477258):+// using parameterless GetSearchPath drops `$user`, so deployments with+// `search_path = "$user", public` miss tables in the session-user schema.+func TestSearchPathSessionUserResolution(t *testing.T) {+ dbSchema := &storepb.DatabaseSchemaMetadata{+ Name: "test",+ SearchPath: `"$user", public`,+ Schemas: []*storepb.SchemaMetadata{+ {Name: "public"},+ {+ Name: "alice",+ Tables: []*storepb.TableMetadata{+ {+ Name: "tech_book",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer"},+ {Name: "name", Type: "text"},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "tech_book_name_idx", Expressions: []string{"name"}},+ },+ },+ },+ },+ },+ }++ stmt := "SELECT * FROM tech_book WHERE UPPER(name) = 'X';"+ rule := &storepb.SQLReviewRule{+ Type: storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS,+ Level: storepb.SQLReviewRule_WARNING,+ }+ originalMetadata := model.NewDatabaseMetadata(dbSchema, nil, nil, storepb.Engine_POSTGRES, true)+ checkCtx := advisor.Context{+ DBType: storepb.Engine_POSTGRES,+ OriginalMetadata: originalMetadata,+ FinalMetadata: originalMetadata,+ CurrentDatabase: "test",+ DBSchema: dbSchema,+ IsObjectCaseSensitive: true,+ SessionUser: "alice",+ NoAppendBuiltin: true,+ }++ sm := sheet.NewManager()+ advice, err := advisor.SQLReviewCheck(context.Background(), sm, stmt, []*storepb.SQLReviewRule{rule}, checkCtx)+ require.NoError(t, err)+ require.Len(t, advice, 1, "expected exactly one advice for UPPER(name) in $user-resolved schema (alice)")+ require.Contains(t, advice[0].Content, `Function "UPPER" is applied to indexed column "name"`)+}diff --git a/backend/plugin/advisor/pg/pg_rules_test.go b/backend/plugin/advisor/pg/pg_rules_test.goindex a7729e8dcb..5e8aa3e391 100644--- a/backend/plugin/advisor/pg/pg_rules_test.go+++ b/backend/plugin/advisor/pg/pg_rules_test.go@@ -36,6 +36,7 @@ func TestPostgreSQLRules(t *testing.T) {{Type: storepb.SQLReviewRule_STATEMENT_MAXIMUM_LIMIT_VALUE, Level: storepb.SQLReviewRule_WARNING, Payload: &storepb.SQLReviewRule_NumberPayload{NumberPayload: &storepb.SQLReviewRule_NumberRulePayload{Number: 1000}}},{Type: storepb.SQLReviewRule_STATEMENT_MERGE_ALTER_TABLE, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_WHERE_NO_LEADING_WILDCARD_LIKE, Level: storepb.SQLReviewRule_WARNING},+ {Type: storepb.SQLReviewRule_STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_SELECT_NO_SELECT_ALL, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_OBJECT_OWNER_CHECK, Level: storepb.SQLReviewRule_WARNING},{Type: storepb.SQLReviewRule_STATEMENT_WHERE_REQUIRE_SELECT, Level: storepb.SQLReviewRule_WARNING},diff --git a/backend/plugin/advisor/pg/test/statement_where_disallow_functions_and_calculations.yaml b/backend/plugin/advisor/pg/test/statement_where_disallow_functions_and_calculations.yamlnew file mode 100644index 0000000000..bd5f42e6a2--- /dev/null+++ b/backend/plugin/advisor/pg/test/statement_where_disallow_functions_and_calculations.yaml@@ -0,0 +1,982 @@+# SQL review rule: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS++# Test: Function on indexed column should flag+- statement: SELECT * FROM tech_book WHERE UPPER(name) = 'test';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Calculation on indexed column (+) should flag+- statement: SELECT * FROM tech_book WHERE id + 1 > 5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Multiplication on indexed column should flag+- statement: SELECT * FROM tech_book WHERE id * 2 = 10;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Subtraction on indexed column should flag+- statement: SELECT * FROM tech_book WHERE id - 1 > 5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Division on indexed column should flag+- statement: SELECT * FROM tech_book WHERE id / 2 > 5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Unary minus on indexed column should flag+- statement: SELECT * FROM tech_book WHERE -id > -5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Function on value side should NOT flag+- statement: SELECT * FROM tech_book WHERE id = ABS(-5);++# Test: Function on non-indexed column should NOT flag+- statement: SELECT * FROM tech_book WHERE UPPER(creator) = 'test';++# Test: Calculation on non-indexed column should NOT flag+- statement: SELECT * FROM no_index_table WHERE col_a + 1 > 5;++# Test: Simple comparison should NOT flag+- statement: SELECT * FROM tech_book WHERE id = 1 AND name = 'test';++# Test: Table not in schema should NOT flag+- statement: SELECT * FROM unknown_table WHERE UPPER(col) = 'test';++# Test: Unary minus on non-indexed column should NOT flag+- statement: SELECT * FROM no_index_table WHERE -col_a > 5;++# ---- Medium: UPDATE / DELETE / mixed violations ---------------------------++# Test: Multiple violations in same WHERE — flag each+- statement: SELECT * FROM tech_book WHERE ABS(id) > 5 AND UPPER(name) = 'test';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Function on indexed column in UPDATE WHERE should flag+- statement: UPDATE tech_book SET creator = 'test' WHERE ABS(id) > 5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Function on indexed column in DELETE WHERE should flag+- statement: DELETE FROM tech_book WHERE UPPER(name) = 'test';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Mixed — function on indexed + function on non-indexed — only flag indexed+- statement: SELECT * FROM tech_book WHERE UPPER(name) = 'test' AND LOWER(creator) = 'admin';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- JOIN cases -----------------------------------------------------------++# Test: JOIN with qualified ref to indexed column — should flag+- statement: SELECT * FROM tech_book t JOIN orders o ON t.id = o.order_id WHERE UPPER(o.customer_name) = 'x';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: JOIN, qualified ref to indexed side flags+- statement: SELECT * FROM tech_book t JOIN orders o ON t.id = o.order_id WHERE UPPER(t.name) = 'x';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: JOIN, qualified ref to non-indexed side — should NOT flag+# tech_book.name is indexed; orders.name is non-indexed. Query uses o.name.+- statement: SELECT * FROM tech_book t JOIN orders o ON t.id = o.order_id WHERE UPPER(o.name) = 'x';++# ---- INSERT / CTAS / VIEW -------------------------------------------------++# Test: INSERT...SELECT with function on indexed column should flag+- statement: INSERT INTO insert_target (id, name) SELECT order_id, customer_name FROM orders WHERE UPPER(customer_name) = 'JOHN';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: INSERT...SELECT with plain comparison — PASS+- statement: INSERT INTO insert_target (id, name) SELECT order_id, customer_name FROM orders WHERE order_id = 1;++# Test: CREATE TABLE AS SELECT with function on indexed column should flag+- statement: CREATE TABLE new_table AS SELECT * FROM tech_book WHERE UPPER(name) = 'TEST';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: CREATE TABLE AS SELECT with plain comparison — PASS+- statement: CREATE TABLE new_table2 AS SELECT * FROM tech_book WHERE id = 1;++# Test: CREATE VIEW with function on indexed column should flag+- statement: CREATE VIEW v AS SELECT * FROM tech_book WHERE UPPER(name) = 'test';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: CREATE MATERIALIZED VIEW with calculation on indexed column should flag+- statement: CREATE MATERIALIZED VIEW mv AS SELECT * FROM tech_book WHERE id + 1 > 5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: CREATE VIEW with plain comparison — PASS+- statement: CREATE VIEW v2 AS SELECT * FROM tech_book WHERE id = 1;++# Test: CREATE MATERIALIZED VIEW with plain comparison — PASS+- statement: CREATE MATERIALIZED VIEW mv2 AS SELECT * FROM tech_book WHERE id = 1;++# ---- MERGE ----------------------------------------------------------------++# Test: MERGE ON condition with function on indexed column should flag+- statement: MERGE INTO orders t USING products p ON (UPPER(t.customer_name) = p.title) WHEN MATCHED THEN UPDATE SET note = 'x';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: MERGE WHEN MATCHED AND … with calculation on indexed column should flag+- statement: MERGE INTO orders t USING products p ON (t.order_id = p.product_id) WHEN MATCHED AND t.amount * 2 > 100 THEN UPDATE SET note = 'x';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Clean MERGE — PASS+- statement: MERGE INTO orders t USING products p ON (t.order_id = p.product_id) WHEN MATCHED THEN UPDATE SET note = 'x';++# ---- Subqueries -----------------------------------------------------------++# Test: IN subquery with function on inner indexed column flags+- statement: SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'JOHN');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Function on non-indexed column inside IN subquery should NOT flag+- statement: SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE UPPER(note) = 'X');++# Test: NOT IN subquery with function on indexed column flags+- statement: SELECT * FROM tech_book WHERE id NOT IN (SELECT order_id FROM orders WHERE ABS(amount) > 100);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: EXISTS subquery with function on indexed column flags+- statement: SELECT * FROM tech_book WHERE EXISTS (SELECT 1 FROM orders WHERE UPPER(customer_name) = 'X');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: NOT EXISTS subquery with calculation on indexed column flags+- statement: SELECT * FROM tech_book WHERE NOT EXISTS (SELECT 1 FROM orders WHERE amount + 10 > 100);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Scalar subquery on value side with function on inner indexed column+- statement: SELECT * FROM tech_book WHERE id > (SELECT COUNT(*) FROM orders WHERE ABS(amount) > 0);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Violation in BOTH outer and inner subquery — flag both+- statement: SELECT * FROM tech_book WHERE UPPER(name) = 'A' AND id IN (SELECT order_id FROM orders WHERE ABS(amount) > 0);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: 3-level nested subquery — violation at innermost level+- statement: SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE amount > (SELECT AVG(amount) FROM orders WHERE LOWER(customer_name) = 'john'));+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"LOWER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: 4-level nested subquery — violation at deepest level+- statement: SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE amount IN (SELECT amount FROM orders WHERE order_id IN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'X')));+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Multiple independent subqueries in same WHERE — flag each+- statement: SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE ABS(amount) > 0) AND name IN (SELECT customer_name FROM orders WHERE UPPER(customer_name) = 'A');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Correlated EXISTS — inner refs outer via qualifier, inner violation flags+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM orders o WHERE o.order_id = t.id AND UPPER(o.customer_name) = 'X');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Correlated EXISTS — function on outer indexed column via qualifier+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM orders o WHERE UPPER(t.name) = 'x');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Correlated — unqualified `id` does not exist in inner (orders), resolves to outer tech_book.id and flags+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM orders o WHERE ABS(id) > 0);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: UPDATE with subquery in WHERE — inner violation should flag+- statement: UPDATE tech_book SET creator = 'x' WHERE id IN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'JOHN');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: DELETE with subquery in WHERE — inner violation should flag+- statement: DELETE FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE ABS(amount) > 10);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- CTE / set-ops --------------------------------------------------------++# Test: CTE body with function on indexed column flags+- statement: WITH filtered AS (SELECT * FROM tech_book WHERE UPPER(name) = 'TEST') SELECT * FROM filtered WHERE id = 1;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: CTE body with calculation on indexed column flags+- statement: WITH filtered AS (SELECT * FROM tech_book WHERE id + 1 > 5) SELECT * FROM filtered;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: CTE body with plain comparison — PASS+- statement: WITH filtered AS (SELECT * FROM tech_book WHERE id = 1) SELECT * FROM filtered;++# Test: UNION — violation on one side flags+- statement: SELECT * FROM tech_book WHERE id = 1 UNION SELECT * FROM tech_book WHERE UPPER(name) = 'X';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: UNION with subquery carrying violation+- statement: SELECT * FROM tech_book WHERE id = 1 UNION SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'A');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: INTERSECT — violation flags+- statement: SELECT id FROM tech_book WHERE UPPER(name) = 'A' INTERSECT SELECT order_id FROM orders WHERE note = 'b';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: EXCEPT — violation flags+- statement: SELECT id FROM tech_book WHERE id = 1 EXCEPT SELECT order_id FROM orders WHERE ABS(amount) > 0;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- HAVING exclusion + wrapper unwrap -----------------------------------++# Test: HAVING predicate should NOT be flagged even when wrapping indexed col+- statement: SELECT name, COUNT(*) FROM tech_book GROUP BY name HAVING COUNT(name) > 5;++# Test: HAVING with calculation — PASS+- statement: SELECT id, AVG(id) FROM tech_book GROUP BY id HAVING AVG(id) * 3 + 1 > 100;++# Test: Subquery inside HAVING — inner WHERE violation still flags+- statement: SELECT name FROM tech_book GROUP BY name HAVING name IN (SELECT order_id::text FROM orders WHERE UPPER(customer_name) = 'x');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Function wrapping calculation on indexed column flags (inner calc)+- statement: SELECT * FROM tech_book WHERE ABS(id + 1) > 5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Function with non-indexed column inside calc — PASS+- statement: SELECT * FROM no_index_table WHERE ABS(col_a + 1) > 5;++# Test: CAST wrap on indexed column — function should still flag+- statement: SELECT * FROM tech_book WHERE UPPER(CAST(name AS text)) = 'TEST';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- PG extras: UPDATE FROM / DELETE USING / ON CONFLICT WHERE / dmCTE ---++# Test: UPDATE ... FROM — function on target-side indexed column flags+- statement: UPDATE orders o SET note = 'x' FROM products p WHERE UPPER(o.customer_name) = p.title;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: DELETE ... USING — calculation on target-side indexed column flags+- statement: DELETE FROM orders o USING products p WHERE ABS(o.amount) > 5;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: INSERT ON CONFLICT WHERE — function on target indexed column flags+- statement: INSERT INTO orders (order_id, customer_name) VALUES (1, 'a') ON CONFLICT (order_id) DO UPDATE SET note = 'x' WHERE UPPER(orders.customer_name) = 'A';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: INSERT ON CONFLICT WHERE — function on non-indexed target column — PASS+- statement: INSERT INTO orders (order_id, customer_name) VALUES (1, 'a') ON CONFLICT (order_id) DO UPDATE SET note = 'x' WHERE UPPER(orders.note) = 'A';++# Test: Data-modifying CTE — UPDATE inside WITH flags+- statement: WITH upd AS (UPDATE orders SET note = 'x' WHERE ABS(order_id) > 5 RETURNING *) SELECT * FROM upd;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"order_id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Documented limitation — outer WHERE over derived-table alias is NOT flagged+# (column lineage through projections is not traced).+- statement: SELECT * FROM (SELECT name FROM tech_book) s WHERE UPPER(s.name) = 'x';++# Test: Derived table in FROM with a violation in its own WHERE flags+- statement: SELECT * FROM (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'x') s;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test: Scalar subquery in SELECT list with violation — should flag+- statement: SELECT (SELECT MAX(order_id) FROM orders WHERE UPPER(customer_name) = 'x') FROM tech_book;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Test (truth table R5): qualified ref to unknown alias — should NOT flag.+- statement: SELECT * FROM tech_book WHERE ABS(unknown.id) > 0;++# Test (codex P1): CTE reference in inner FROM — unqualified `id` owns by inner CTE, should NOT falsely flag outer tech_book.id.+- statement: WITH c AS (SELECT order_id AS id FROM orders) SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM c WHERE ABS(id) > 0);++# Test (codex P1): Derived table in inner FROM — unqualified `id` owns by inner derived, should NOT falsely flag outer tech_book.id.+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM (SELECT order_id AS id FROM orders) d WHERE ABS(id) > 0);++# ---- Review fixes ---------------------------------------------------------++# JOIN ON predicate with function on indexed column should flag+- statement: SELECT * FROM tech_book t JOIN orders o ON UPPER(t.name) = 'X' WHERE t.id = o.order_id;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# JOIN ON predicate with calculation on indexed column should flag+- statement: SELECT * FROM tech_book t JOIN orders o ON t.id + 1 = o.order_id;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# MERGE with source subquery WHERE violation should flag+- statement: "MERGE INTO orders t USING (SELECT * FROM products WHERE ABS(price) > 100) p ON (t.order_id = p.product_id) WHEN MATCHED THEN UPDATE SET note = 'x';"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"price\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Round 2 fixes --------------------------------------------------------++# UPDATE ... FROM ... JOIN ON indexed col+- statement: UPDATE orders o SET note = 'x' FROM products p JOIN tech_book t ON UPPER(t.name) = p.title WHERE o.order_id = t.id;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# DELETE ... USING ... JOIN ON indexed col+- statement: DELETE FROM orders o USING products p JOIN tech_book t ON ABS(t.id) = p.product_id WHERE o.order_id = t.id;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# MERGE USING a JOIN b ON indexed col+- statement: "MERGE INTO orders t USING products p JOIN tech_book b ON UPPER(b.name) = p.title ON (t.order_id = p.product_id) WHEN MATCHED THEN UPDATE SET note = 'x';"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Adversarial: correlated EXISTS in JOIN ON — expect exactly ONE advice (not two)+- statement: SELECT * FROM tech_book t JOIN orders o ON EXISTS (SELECT 1 FROM products p JOIN orders o2 ON ABS(t.id) = o2.order_id WHERE p.product_id = o.order_id);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Round 3 fixes --------------------------------------------------------++# CTE body is a MERGE with violation+- statement: "WITH m AS (MERGE INTO orders t USING products p ON (UPPER(t.customer_name) = p.title) WHEN MATCHED THEN UPDATE SET note = 'x' RETURNING t.*) SELECT * FROM m;"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# UPDATE ... RETURNING (subquery with WHERE violation)+- statement: UPDATE orders SET note = 'x' WHERE order_id = 1 RETURNING note, (SELECT COUNT(*) FROM tech_book WHERE UPPER(name) = 'X');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# DELETE ... RETURNING (subquery with WHERE violation)+- statement: DELETE FROM orders WHERE order_id = 1 RETURNING order_id, (SELECT COUNT(*) FROM tech_book WHERE ABS(id) > 10);+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"ABS\" is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# INSERT ... RETURNING (subquery with WHERE violation)+- statement: INSERT INTO insert_target (id, name) VALUES (1, 'a') RETURNING id, (SELECT COUNT(*) FROM tech_book WHERE UPPER(name) = 'X');+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Round 4 fix ----------------------------------------------------------++# INSERT ... VALUES ((SELECT ... WHERE ...)) — inner WHERE violation+- statement: INSERT INTO insert_target (id, name) VALUES (1, (SELECT MAX(name) FROM tech_book WHERE UPPER(name) = 'X'));+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Round 4 fixes --------------------------------------------------------++# PG MERGE ... RETURNING (subquery with WHERE violation)+- statement: "MERGE INTO orders t USING products p ON (t.order_id = p.product_id) WHEN MATCHED THEN UPDATE SET note = 'x' RETURNING (SELECT MAX(name) FROM tech_book WHERE UPPER(name) = 'X');"+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# PG ON CONFLICT (col) WHERE <pred> — Infer WHERE with indexed col+- statement: INSERT INTO orders (order_id, customer_name) VALUES (1, 'a') ON CONFLICT (order_id) WHERE UPPER(customer_name) = 'A' DO UPDATE SET note = 'x';+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# ---- Codex P2 round-3 regression -----------------------------------------++# PG exponent operator `^` on indexed column — must flag as calculation+- statement: SELECT * FROM tech_book WHERE id ^ 2 > 10;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"id\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# RangeFunction (generate_series) aliased in FROM — its presence marks the+# local source unresolved; a bare `n` in WHERE no longer falls through to+# an outer scope and cannot cause a false positive against a same-named+# outer column. Structural regression: must PASS (no advice, no panic).+- statement: SELECT * FROM tech_book t, generate_series(1, 10) AS s(n) WHERE s.n = t.id;++# ---- Codex P2 round-4 regression ------------------------------------------++# Correlated outer ref + inner JOIN with subquery in ON predicate. Previously+# localHasUnresolvedSources set localUnresolved=true because of the ON+# subquery, suppressing the outer-scope fallback in isIndexed for unqualified+# refs. The fix walks only SOURCE positions (Larg/Rarg/top-level FROM items)+# when determining unresolved-ness.+- statement: |+ SELECT * FROM tech_book WHERE id IN (+ SELECT 1 FROM no_index_table n+ JOIN products p ON p.price > (SELECT MIN(price) FROM products)+ WHERE UPPER(name) = 'X'+ );+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 4+ column: 0+ endposition: null++# Codex round-8 P2 (#3104316972): CTE name shadows base table.+# `WITH orders AS (...)` makes the inner FROM `orders` refer to the CTE+# (which has no indexes), NOT the real `orders` table. Previously the+# rule attached real-`orders` indexes to the CTE alias and falsely+# flagged UPPER(customer_name). With CTE shadowing, the local scope is+# unresolved (CTE is opaque) and the rule no longer falsely flags.+- statement: |+ WITH orders AS (SELECT 1 AS customer_name)+ SELECT * FROM orders WHERE UPPER(customer_name) = 'X';++# Codex round-9 P2 (#3104448555): sibling CTE shadowing within same WITH.+# `c2`'s body references `orders` — should resolve as the EARLIER sibling+# CTE (no indexes), NOT the base orders table. Previously the rule walked+# c2's body before pushing CTE names, so `FROM orders` resolved as the+# real table and falsely flagged UPPER(customer_name).+- statement: |+ WITH orders AS (SELECT 1 AS customer_name),+ c2 AS (SELECT * FROM orders WHERE UPPER(customer_name) = 'X')+ SELECT * FROM c2;++# Codex round-14 P2 (#3104564086): non-recursive WITH visibility ordering.+# Earlier CTE `a` references base `orders` (real indexed table).+# Later CTE `orders` is a same-named CTE. Per SQL, `a` cannot see `orders`+# the CTE (it's defined later, non-recursive WITH). So `FROM orders` in+# `a` must resolve to the REAL orders table — and the UPPER(customer_name)+# violation must still flag.+- statement: |+ WITH a AS (SELECT * FROM orders WHERE UPPER(customer_name) = 'X'),+ orders AS (SELECT 1 AS dummy)+ SELECT * FROM a;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Codex round-15 P2 (#3104607277): recursive WITH self-reference must+# resolve to opaque CTE, NOT to a same-named base table. Handled by the+# `with.Recursive` branch — push every CTE name BEFORE walking any body,+# so inner `FROM orders` resolves to the CTE (opaque) and no false+# positive fires against the real `orders` table's indexes.+- statement: |+ WITH RECURSIVE orders AS (+ SELECT order_id, customer_name FROM orders WHERE order_id = 1+ UNION ALL+ SELECT order_id + 1, customer_name FROM orders WHERE order_id < 10+ )+ SELECT * FROM orders;++# Codex round-16 P2 (#3109237788): non-recursive WITH self-shadow must+# resolve inner `FROM orders` to the REAL base table (SQL:2011: a+# non-recursive CTE body cannot see itself). Previously push-before-each+# made inner `orders` opaque and silently dropped the violation — a false+# negative on a valid, common query shape. Fixed by splitting push timing+# by `with.Recursive`: non-recursive pushes the CTE's name AFTER walking+# its body.+- statement: |+ WITH orders AS (SELECT * FROM orders WHERE UPPER(customer_name) = 'X')+ SELECT * FROM orders;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Function \"UPPER\" is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: null++# Same shape, calculation variant (not just function), to lock the whole+# category for non-recursive self-shadow.+- statement: |+ WITH orders AS (SELECT * FROM orders WHERE amount + 1 > 10)+ SELECT * FROM orders;+ want:+ - status: 2+ code: 234+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ content: "Calculation is applied to indexed column \"amount\" in the WHERE clause, which prevents index usage"+ startposition:+ line: 1+ column: 0+ endposition: nulldiff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.goindex 25c330a7c8..b2a45b5030 100644--- a/backend/plugin/advisor/utils_for_tests.go+++ b/backend/plugin/advisor/utils_for_tests.go@@ -126,6 +126,7 @@ var (Columns: []*storepb.ColumnMetadata{{Name: "id", Type: "integer", Position: 1},{Name: "name", Type: "text", Position: 2},+ {Name: "creator", Type: "text", Position: 3},},Indexes: []*storepb.IndexMetadata{{@@ -145,6 +146,47 @@ var (},},},+ {+ Name: "orders",+ Columns: []*storepb.ColumnMetadata{+ {Name: "order_id", Type: "integer", Position: 1},+ {Name: "customer_name", Type: "text", Position: 2},+ {Name: "amount", Type: "numeric", Position: 3},+ {Name: "note", Type: "text", Position: 4},+ {Name: "name", Type: "text", Position: 5},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "orders_pkey", Expressions: []string{"order_id"}, Unique: true, Primary: true},+ {Name: "idx_orders_customer", Expressions: []string{"customer_name"}},+ {Name: "idx_orders_amount", Expressions: []string{"amount"}},+ },+ },+ {+ Name: "products",+ Columns: []*storepb.ColumnMetadata{+ {Name: "product_id", Type: "integer", Position: 1},+ {Name: "title", Type: "text", Position: 2},+ {Name: "price", Type: "numeric", Position: 3},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "products_pkey", Expressions: []string{"product_id"}, Unique: true, Primary: true},+ {Name: "idx_products_price", Expressions: []string{"price"}},+ },+ },+ {+ Name: "no_index_table",+ Columns: []*storepb.ColumnMetadata{+ {Name: "col_a", Type: "integer", Position: 1},+ {Name: "col_b", Type: "text", Position: 2},+ },+ },+ {+ Name: "insert_target",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Position: 1},+ {Name: "name", Type: "text", Position: 2},+ },+ },},},{@@ -220,6 +262,73 @@ var (},},}+ // MockOracleDatabase is the mock Oracle database for test. Oracle sync+ // (`backend/plugin/db/oracle/sync.go`) stores SchemaMetadata{Name: ""}+ // — a single anonymous schema containing every object. The mock mirrors+ // this so advisors resolve tables the same way in tests and production.+ MockOracleDatabase = &storepb.DatabaseSchemaMetadata{+ Name: "TEST_DB",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "",+ Tables: []*storepb.TableMetadata{+ {+ Name: "TECH_BOOK",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER"},+ {Name: "NAME", Type: "VARCHAR2(255)"},+ {Name: "CREATOR", Type: "VARCHAR2(255)"},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "TECH_BOOK_PK", Expressions: []string{"ID", "NAME"}, Unique: true, Primary: true},+ {Name: "IDX_TECH_BOOK_NAME", Expressions: []string{"ID", "NAME"}},+ },+ },+ {+ Name: "ORDERS",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ORDER_ID", Type: "NUMBER"},+ {Name: "CUSTOMER_NAME", Type: "VARCHAR2(255)"},+ {Name: "AMOUNT", Type: "NUMBER"},+ {Name: "NOTE", Type: "VARCHAR2(255)"},+ {Name: "NAME", Type: "VARCHAR2(255)"},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "ORDERS_PK", Expressions: []string{"ORDER_ID"}, Unique: true, Primary: true},+ {Name: "IDX_ORDERS_CUSTOMER", Expressions: []string{"CUSTOMER_NAME"}},+ {Name: "IDX_ORDERS_AMOUNT", Expressions: []string{"AMOUNT"}},+ },+ },+ {+ Name: "PRODUCTS",+ Columns: []*storepb.ColumnMetadata{+ {Name: "PRODUCT_ID", Type: "NUMBER"},+ {Name: "TITLE", Type: "VARCHAR2(255)"},+ {Name: "PRICE", Type: "NUMBER"},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "PRODUCTS_PK", Expressions: []string{"PRODUCT_ID"}, Unique: true, Primary: true},+ {Name: "IDX_PRODUCTS_PRICE", Expressions: []string{"PRICE"}},+ },+ },+ {+ Name: "NO_INDEX_TABLE",+ Columns: []*storepb.ColumnMetadata{+ {Name: "COL_A", Type: "NUMBER"},+ {Name: "COL_B", Type: "VARCHAR2(255)"},+ },+ },+ {+ Name: "INSERT_TARGET",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER"},+ {Name: "NAME", Type: "VARCHAR2(255)"},+ },+ },+ },+ },+ },+ })// TestCase is the data struct for test.@@ -270,6 +379,13 @@ func RunSQLReviewRuleTest(t *testing.T, rule *storepb.SQLReviewRule, dbType storcurDB = "master"case storepb.Engine_MYSQL:schemaMetadata = MockMySQLDatabase+ case storepb.Engine_ORACLE:+ schemaMetadata = MockOracleDatabase+ curDB = "TEST_DB"+ // Match production: store.IsObjectCaseSensitive(Oracle) returns+ // true via the default branch in backend/store/instance.go. Test+ // fixtures use upper-case identifiers like the real Oracle sync.+ isCaseSensitive = truedefault:// Fallback to MySQL for engines without specific mockschemaMetadata = MockMySQLDatabase@@ -291,15 +407,16 @@ func RunSQLReviewRuleTest(t *testing.T, rule *storepb.SQLReviewRule, dbType storruleList := []*storepb.SQLReviewRule{rule}checkCtx := Context{- DBType: dbType,- OriginalMetadata: originalMetadata,- FinalMetadata: finalMetadata,- Driver: nil,- CurrentDatabase: curDB,- DBSchema: schemaMetadata,- EnablePriorBackup: true, // Enable backup for testing- NoAppendBuiltin: true,- TenantMode: true,+ DBType: dbType,+ OriginalMetadata: originalMetadata,+ FinalMetadata: finalMetadata,+ Driver: nil,+ CurrentDatabase: curDB,+ DBSchema: schemaMetadata,+ IsObjectCaseSensitive: isCaseSensitive,+ EnablePriorBackup: true, // Enable backup for testing+ NoAppendBuiltin: true,+ TenantMode: true,}adviceList, err := SQLReviewCheck(t.Context(), sm, tc.Statement, ruleList, checkCtx)diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yamlindex 83e9139abb..8f481325d9 100644--- a/frontend/src/types/sql-review-schema.yaml+++ b/frontend/src/types/sql-review-schema.yaml@@ -558,6 +558,12 @@- type: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONScategory: STATEMENTengine: MSSQL+- type: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ category: STATEMENT+ engine: POSTGRES+- type: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ category: STATEMENT+ engine: ORACLE- type: STATEMENT_QUERY_MINIMUM_PLAN_LEVELcategory: STATEMENTcomponentList:diff --git a/frontend/src/types/sql-review.prod.yaml b/frontend/src/types/sql-review.prod.yamlindex 1be424e681..73a720ee59 100644--- a/frontend/src/types/sql-review.prod.yaml+++ b/frontend/src/types/sql-review.prod.yaml@@ -445,6 +445,12 @@ ruleList:- type: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONSlevel: WARNINGengine: MSSQL+ - type: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ level: WARNING+ engine: POSTGRES+ - type: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS+ level: WARNING+ engine: ORACLE- type: STATEMENT_QUERY_MINIMUM_PLAN_LEVELlevel: WARNINGpayload: