Skip to content

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

fix(advisor): only flag functions/calculations on indexed columns in WHERE (#19986)

zchpeter771b66d681b0
diff --git a/.gitignore b/.gitignore
index e851c25954..d62ff5b20b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,3 +39,6 @@ scripts/azure-marketplace/.cnab/
scripts/azure-marketplace/*.tgz
scripts/azure-marketplace/*.backup
/main
+
+# playwright-cli local session artifacts
+.playwright-cli/
diff --git a/.sonarcloud.properties b/.sonarcloud.properties
index f6357d3152..514353bf83 100644
--- a/.sonarcloud.properties
+++ b/.sonarcloud.properties
@@ -15,6 +15,7 @@ sonar.exclusions=\
sonar.test.inclusions=\
action/**/*_test.go,\
backend/**/*_test.go,\
+ backend/**/*_for_tests.go,\
backend/**/testdata/**,\
backend/**/test-data/**,\
backend/common/testcontainer/**,\
@@ -31,7 +32,7 @@ sonar.sourceEncoding=UTF-8
# Suppress false-positive security hotspots that travel with the codebase.
# These have been triaged and confirmed safe. Using sonar.issue.ignore so
# any fork or downstream SonarCloud scan also benefits.
-sonar.issue.ignore.multicriteria=fp_sync_sql,fp_route_creds,fp_stats_explain,fp_dump_sql,fp_role_sql,fp_cognitive_ts,fp_cognitive_tsx,fp_cognitive_vue,fp_cognitive_go
+sonar.issue.ignore.multicriteria=fp_sync_sql,fp_route_creds,fp_stats_explain,fp_dump_sql,fp_role_sql
# go:S2077 (SQL Injection) in db plugin sync.go files.
# These files query system catalogs (information_schema, pg_catalog, sys.*) using
@@ -64,20 +65,6 @@ sonar.issue.ignore.multicriteria.fp_dump_sql.resourceKey=backend/plugin/db/*/dum
sonar.issue.ignore.multicriteria.fp_role_sql.ruleKey=go:S2077
sonar.issue.ignore.multicriteria.fp_role_sql.resourceKey=backend/plugin/db/*/role.go
-# Cognitive Complexity (S3776) — disabled for this repository.
-# Bytebase has complex domain logic (CEL parsing, policy evaluation, SQL generation)
-# where high cognitive complexity is inherent and not a code quality issue.
-# NOTE: SonarCloud multicriteria resourceKey does NOT support `**/*` as a
-# catch-all — it must match actual file path patterns. Use per-extension globs.
-sonar.issue.ignore.multicriteria.fp_cognitive_ts.ruleKey=typescript:S3776
-sonar.issue.ignore.multicriteria.fp_cognitive_ts.resourceKey=**/*.ts
-sonar.issue.ignore.multicriteria.fp_cognitive_tsx.ruleKey=typescript:S3776
-sonar.issue.ignore.multicriteria.fp_cognitive_tsx.resourceKey=**/*.tsx
-sonar.issue.ignore.multicriteria.fp_cognitive_vue.ruleKey=typescript:S3776
-sonar.issue.ignore.multicriteria.fp_cognitive_vue.resourceKey=**/*.vue
-sonar.issue.ignore.multicriteria.fp_cognitive_go.ruleKey=go:S3776
-sonar.issue.ignore.multicriteria.fp_cognitive_go.resourceKey=**/*.go
-
# Exclusions for copy-paste detection
sonar.cpd.exclusions=\
action/**/*_test.go,\
@@ -92,3 +79,4 @@ sonar.cpd.exclusions=\
frontend/src/react/mount*.ts,\
frontend/tests/**,\
proto/gen/**
+
diff --git a/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go b/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go
index 3aca27c8c4..b319be7fd7 100644
--- a/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go
+++ b/backend/plugin/advisor/mssql/rule_statement_where_disallow_functions_and_calculations.go
@@ -3,12 +3,15 @@ package mssql
import (
"context"
"fmt"
+ "slices"
+ "strings"
"github.com/bytebase/omni/mssql/ast"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
+ "github.com/bytebase/bytebase/backend/store/model"
)
func init() {
@@ -28,11 +31,16 @@ func (*DisallowFuncAndCalculationsAdvisor) Check(_ context.Context, checkCtx adv
rule := &disallowFuncAndCalcOmniRule{
OmniBaseRule: OmniBaseRule{Level: level, Title: checkCtx.Rule.Type.String()},
}
+ if checkCtx.DBSchema != nil {
+ rule.dbMetadata = model.NewDatabaseMetadata(checkCtx.DBSchema, nil, nil, storepb.Engine_MSSQL, checkCtx.IsObjectCaseSensitive)
+ }
+
return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
type disallowFuncAndCalcOmniRule struct {
OmniBaseRule
+ dbMetadata *model.DatabaseMetadata
}
func (*disallowFuncAndCalcOmniRule) Name() string {
@@ -40,86 +48,693 @@ func (*disallowFuncAndCalcOmniRule) Name() string {
}
func (r *disallowFuncAndCalcOmniRule) OnStatement(node ast.Node) {
- // Find all statements that have a WHERE clause.
- ast.Inspect(node, func(n ast.Node) bool {
- var where ast.ExprNode
- switch stmt := n.(type) {
- case *ast.SelectStmt:
- where = stmt.WhereClause
- case *ast.UpdateStmt:
- where = stmt.WhereClause
- case *ast.DeleteStmt:
- where = stmt.WhereClause
- default:
- return true
+ switch n := node.(type) {
+ case *ast.SelectStmt:
+ r.checkSelect(n)
+ case *ast.InsertStmt:
+ r.onInsert(n)
+ case *ast.CreateTableAsSelectStmt:
+ r.checkSelectNode(n.Query)
+ case *ast.CreateViewStmt:
+ r.checkSelectNode(n.Query)
+ case *ast.CreateMaterializedViewStmt:
+ r.checkSelectNode(n.Query)
+ case *ast.CreateExternalTableAsSelectStmt:
+ r.checkSelectNode(n.Query)
+ case *ast.CreateRemoteTableAsSelectStmt:
+ r.checkSelectNode(n.Query)
+ case *ast.UpdateStmt:
+ r.onUpdate(n)
+ case *ast.DeleteStmt:
+ r.onDelete(n)
+ case *ast.MergeStmt:
+ r.checkCTEs(n.WithClause)
+ r.checkMerge(n)
+ default:
+ }
+}
+
+// checkSelectNode runs checkSelect if node is a *ast.SelectStmt; no-ops otherwise.
+func (r *disallowFuncAndCalcOmniRule) checkSelectNode(node ast.Node) {
+ if sel, ok := node.(*ast.SelectStmt); ok {
+ r.checkSelect(sel)
+ }
+}
+
+// onInsert handles T-SQL INSERT. Source can be a SELECT or a VALUES list; both
+// may embed scalar subqueries with their own WHERE clauses.
+func (r *disallowFuncAndCalcOmniRule) onInsert(n *ast.InsertStmt) {
+ r.checkCTEs(n.WithClause)
+ r.recurseIntoNestedSelectsInNode(n.Source, nil)
+}
+
+// onUpdate handles T-SQL UPDATE. It covers the WHERE, derived tables in
+// Relation/FromClause (each with its own WHERE), and scalar subqueries hidden
+// in SET assignments.
+func (r *disallowFuncAndCalcOmniRule) onUpdate(n *ast.UpdateStmt) {
+ r.checkCTEs(n.WithClause)
+ tables := r.collectUpdateDeleteTables(n.Relation, n.FromClause)
+ r.checkWhere(n.WhereClause, tables)
+ r.recurseDerivedTables(n.Relation, n.FromClause, tables)
+ r.recurseSetClauseValues(n.SetClause, tables)
+}
+
+// onDelete handles T-SQL DELETE, including any JOINed sources in the FROM clause
+// that carry their own WHERE clauses inside derived tables.
+func (r *disallowFuncAndCalcOmniRule) onDelete(n *ast.DeleteStmt) {
+ r.checkCTEs(n.WithClause)
+ tables := r.collectUpdateDeleteTables(n.Relation, n.FromClause)
+ r.checkWhere(n.WhereClause, tables)
+ r.recurseDerivedTables(n.Relation, n.FromClause, tables)
+}
+
+// collectUpdateDeleteTables merges tables referenced by the target Relation
+// with any JOINed tables in the extra FROM clause (T-SQL UPDATE/DELETE shape).
+func (r *disallowFuncAndCalcOmniRule) collectUpdateDeleteTables(relation ast.TableExpr, from *ast.List) tablesByAlias {
+ tables := r.collectTablesFromRelation(relation)
+ for alias, ref := range r.collectTableNamesFromList(from) {
+ tables[alias] = ref
+ }
+ return tables
+}
+
+// recurseDerivedTables walks the relation and every FROM item for nested SELECTs
+// whose own WHERE clause must be checked in its own scope.
+func (r *disallowFuncAndCalcOmniRule) recurseDerivedTables(relation ast.TableExpr, from *ast.List, outer tablesByAlias) {
+ r.recurseIntoNestedSelectsInNode(relation, outer)
+ if from == nil {
+ return
+ }
+ for _, item := range from.Items {
+ r.recurseIntoNestedSelectsInNode(item, outer)
+ }
+}
+
+// recurseSetClauseValues walks each SET assignment's value for scalar subqueries.
+func (r *disallowFuncAndCalcOmniRule) recurseSetClauseValues(setClause *ast.List, outer tablesByAlias) {
+ if setClause == nil {
+ return
+ }
+ for _, item := range setClause.Items {
+ if se, ok := item.(*ast.SetExpr); ok && se.Value != nil {
+ r.recurseIntoNestedSelectsInNode(se.Value, outer)
+ }
+ }
+}
+
+// checkMerge handles T-SQL MERGE statements. The ON condition and each WHEN-clause
+// condition are treated like a WHERE for index-aware checking, scoped to the target
+// plus source tables. Nested SELECTs inside the source or conditions are recursed.
+func (r *disallowFuncAndCalcOmniRule) checkMerge(n *ast.MergeStmt) {
+ tables := make(tablesByAlias)
+ if ref, ok := n.Target.(*ast.TableRef); ok {
+ addTableRef(r, tables, ref)
+ }
+ // Extract source tables (can be TableRef, SubqueryExpr, JoinClause, etc.).
+ if n.Source != nil {
+ if ref, ok := n.Source.(*ast.TableRef); ok {
+ // Bare table source: honor SourceAlias if set, otherwise use the ref's own alias/object.
+ if n.SourceAlias != "" {
+ tables[r.normalizeIdent(n.SourceAlias)] = tableRef{database: ref.Database, schema: ref.Schema, object: ref.Object}
+ } else {
+ addTableRef(r, tables, ref)
+ }
+ } else {
+ // Non-TableRef source (subquery, join, etc.). Recurse into the inner SELECT
+ // in its own scope. When SourceAlias is set, register it as an opaque entry
+ // so qualified refs like `src.col` resolve to no indexed columns (safely
+ // returning false) rather than falling through to cross-table matches.
+ if n.SourceAlias != "" {
+ tables[r.normalizeIdent(n.SourceAlias)] = tableRef{}
+ }
+ ast.Inspect(n.Source, func(m ast.Node) bool {
+ if sub, ok := m.(*ast.SelectStmt); ok {
+ r.checkSelect(sub)
+ return false
+ }
+ if _, ok := m.(*ast.SubqueryExpr); ok {
+ return true
+ }
+ // When there's a SourceAlias, don't leak inner TableRefs into outer scope.
+ if _, ok := m.(*ast.TableRef); ok {
+ if n.SourceAlias == "" {
+ addTableRef(r, tables, m.(*ast.TableRef))
+ }
+ return false
+ }
+ return true
+ })
+ }
+ }
+ r.checkWhere(n.OnCondition, tables)
+ if n.WhenClauses != nil {
+ for _, item := range n.WhenClauses.Items {
+ when, ok := item.(*ast.MergeWhenClause)
+ if !ok {
+ continue
+ }
+ r.checkWhere(when.Condition, tables)
+ // MERGE actions can embed scalar subqueries with their own WHERE clauses,
+ // e.g. WHEN MATCHED THEN UPDATE SET x = (SELECT ... WHERE ABS(col) > 0).
+ switch a := when.Action.(type) {
+ case *ast.MergeUpdateAction:
+ if a != nil {
+ r.recurseSetClauseValues(a.SetClause, tables)
+ }
+ case *ast.MergeInsertAction:
+ if a != nil && a.Values != nil {
+ for _, v := range a.Values.Items {
+ r.recurseIntoNestedSelectsInNode(v, tables)
+ }
+ }
+ default:
+ }
+ }
+ }
+}
+
+func (r *disallowFuncAndCalcOmniRule) checkCTEs(wc *ast.WithClause) {
+ if wc == nil || wc.CTEs == nil {
+ return
+ }
+ for _, item := range wc.CTEs.Items {
+ if cte, ok := item.(*ast.CommonTableExpr); ok {
+ if sel, ok := cte.Query.(*ast.SelectStmt); ok {
+ r.checkSelect(sel)
+ }
}
+ }
+}
+
+func (r *disallowFuncAndCalcOmniRule) checkSelect(sel *ast.SelectStmt) {
+ r.checkSelectInScope(sel, nil)
+}
+
+// checkSelectInScope is like checkSelect but also threads an outer table scope down
+// so that correlated subqueries can resolve references to outer aliases. Local
+// (inner) tables take precedence for unqualified columns per SQL name resolution;
+// outer tables are consulted only for qualified references.
+func (r *disallowFuncAndCalcOmniRule) checkSelectInScope(sel *ast.SelectStmt, outer tablesByAlias) {
+ if sel == nil {
+ return
+ }
+ // CTEs run before the referencing SELECT and aren't correlated — check without outer scope.
+ r.checkCTEs(sel.WithClause)
+ if sel.Op != ast.SetOpNone {
+ r.checkSelectInScope(sel.Larg, outer)
+ r.checkSelectInScope(sel.Rarg, outer)
+ return
+ }
+ local := r.collectTableNamesFromList(sel.FromClause)
+ 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, r.localHasUnresolvedSources(sel.FromClause, local))
+ r.recurseIntoNestedSelects(sel, combined)
+}
- if where == nil {
+// localHasUnresolvedSources reports whether the given FROM list and local alias
+// map contain sources whose columns we cannot enumerate — CTE references,
+// derived tables (subqueries in FROM), or plain tables absent from metadata.
+// When true, isIndexed must not fall back to outer scope on unqualified refs.
+func (r *disallowFuncAndCalcOmniRule) localHasUnresolvedSources(from *ast.List, local tablesByAlias) bool {
+ if from != nil {
+ for _, item := range from.Items {
+ derivedFound := false
+ ast.Inspect(item, func(n ast.Node) bool {
+ switch n.(type) {
+ case *ast.SubqueryExpr, *ast.SelectStmt:
+ derivedFound = true
+ return false
+ }
+ return !derivedFound
+ })
+ if derivedFound {
+ return true
+ }
+ }
+ }
+ for _, ref := range local {
+ if ref == (tableRef{}) {
+ continue
+ }
+ if r.tableMetadata(ref) == nil {
return true
}
+ }
+ return false
+}
- r.checkWhereClause(where)
+// recurseIntoNestedSelectsInNode walks the given AST node and recurses into any
+// nested *ast.SelectStmt, threading the given outer scope.
+func (r *disallowFuncAndCalcOmniRule) recurseIntoNestedSelectsInNode(n ast.Node, outer tablesByAlias) {
+ if n == nil {
+ return
+ }
+ ast.Inspect(n, func(m ast.Node) bool {
+ if sub, ok := m.(*ast.SelectStmt); ok {
+ r.checkSelectInScope(sub, outer)
+ return false
+ }
return true
})
}
-func (r *disallowFuncAndCalcOmniRule) checkWhereClause(where ast.ExprNode) {
- // Only report the first violation per WHERE clause.
- found := false
+// recurseIntoNestedSelects finds nested SelectStmts in the non-WHERE parts of sel
+// (FROM derived tables, SELECT list, HAVING, GROUP BY, ORDER BY) and invokes
+// checkSelectInScope on them with the given outer scope so correlated subqueries resolve.
+func (r *disallowFuncAndCalcOmniRule) recurseIntoNestedSelects(sel *ast.SelectStmt, outer tablesByAlias) {
+ visitor := func(m ast.Node) bool {
+ if sub, ok := m.(*ast.SelectStmt); ok {
+ r.checkSelectInScope(sub, outer)
+ return false
+ }
+ return true
+ }
+ visitList := func(l *ast.List) {
+ if l == nil {
+ return
+ }
+ for _, item := range l.Items {
+ if item != nil {
+ ast.Inspect(item, visitor)
+ }
+ }
+ }
+ // WhereClause is handled by checkWhere; nested selects there are handled by
+ // checkWhere's own ast.Inspect. No need to revisit it here.
+ visitList(sel.FromClause)
+ visitList(sel.TargetList)
+ if sel.HavingClause != nil {
+ ast.Inspect(sel.HavingClause, visitor)
+ }
+ visitList(sel.GroupByClause)
+ visitList(sel.OrderByClause)
+}
+
+// tableRef captures the real database, schema, and object name for an aliased table reference.
+type tableRef struct {
+ database string // empty means current database
+ schema string // empty means default (dbo)
+ object string
+}
+
+// tablesByAlias maps alias (or object name if no alias) to the underlying tableRef.
+type tablesByAlias = map[string]tableRef
+
+// collectTableNamesFromList extracts table refs from a FROM clause List, preserving schema.
+// Descent is stopped at subquery boundaries so that derived tables don't leak their
+// inner TableRefs into the outer scope, but a derived table's own alias (captured
+// via AliasedTableRef wrapping a SubqueryExpr) is recorded as an opaque entry so
+// qualifier-based resolution can tell it apart from an outer alias of the same name.
+func (r *disallowFuncAndCalcOmniRule) collectTableNamesFromList(from *ast.List) tablesByAlias {
+ tables := make(tablesByAlias)
+ if from == nil {
+ return tables
+ }
+ for _, item := range from.Items {
+ ast.Inspect(item, func(n ast.Node) bool {
+ // AliasedTableRef wraps a real TableRef or a SubqueryExpr with an alias.
+ // For subquery sources, record the alias before we stop descent so that
+ // inner qualified refs resolve locally rather than to an outer table.
+ if atr, ok := n.(*ast.AliasedTableRef); ok {
+ if _, isSub := atr.Table.(*ast.SubqueryExpr); isSub && atr.Alias != "" {
+ key := r.normalizeIdent(atr.Alias)
+ if _, exists := tables[key]; !exists {
+ tables[key] = tableRef{}
+ }
+ return false
+ }
+ return true
+ }
+ if _, ok := n.(*ast.SubqueryExpr); ok {
+ return false
+ }
+ if _, ok := n.(*ast.SelectStmt); ok {
+ return false
+ }
+ t, ok := n.(*ast.TableRef)
+ if !ok {
+ return true
+ }
+ addTableRef(r, tables, t)
+ return false
+ })
+ }
+ return tables
+}
+
+// collectTablesFromRelation builds a table map from a single table reference (UPDATE/DELETE).
+func (r *disallowFuncAndCalcOmniRule) collectTablesFromRelation(te ast.TableExpr) tablesByAlias {
+ tables := make(tablesByAlias)
+ if te == nil {
+ return tables
+ }
+ if ref, ok := te.(*ast.TableRef); ok {
+ addTableRef(r, tables, ref)
+ }
+ return tables
+}
+
+// normalizeIdent lowercases identifiers when the DB is configured case-insensitive
+// (respecting IsObjectCaseSensitive). MSSQL default collation is CI, but a CS DB
+// must be honored too.
+func (r *disallowFuncAndCalcOmniRule) normalizeIdent(name string) string {
+ if r.dbMetadata != nil && r.dbMetadata.GetIsObjectCaseSensitive() {
+ return name
+ }
+ return strings.ToLower(name)
+}
+
+func addTableRef(r *disallowFuncAndCalcOmniRule, tables tablesByAlias, t *ast.TableRef) {
+ key := t.Alias
+ if key == "" {
+ key = t.Object
+ }
+ normKey := r.normalizeIdent(key)
+ newRef := tableRef{database: t.Database, schema: t.Schema, object: t.Object}
+ // If an unaliased same-name from a different schema/database already occupies this
+ // key (rare: `FROM dbo.orders, sales.orders` without aliases), mark the entry as
+ // ambiguous so isIndexed returns false rather than silently resolving to the wrong
+ // table. Users should alias these tables to disambiguate.
+ if existing, ok := tables[normKey]; ok && (existing.database != newRef.database || existing.schema != newRef.schema || existing.object != newRef.object) {
+ tables[normKey] = tableRef{}
+ return
+ }
+ tables[normKey] = newRef
+}
+
+// tableMetadata fetches the store-model table for the given ref, applying the
+// cross-DB guard and MSSQL's dbo-first-then-sorted-others schema resolution.
+// Returns nil when not resolvable.
+func (r *disallowFuncAndCalcOmniRule) tableMetadata(ref tableRef) *model.TableMetadata {
+ if r.dbMetadata == nil {
+ return nil
+ }
+ if ref.database != "" && !strings.EqualFold(ref.database, r.dbMetadata.DatabaseName()) {
+ return nil
+ }
+ if ref.schema != "" {
+ if s := r.dbMetadata.GetSchemaMetadata(ref.schema); s != nil {
+ return s.GetTable(ref.object)
+ }
+ return nil
+ }
+ if s := r.dbMetadata.GetSchemaMetadata("dbo"); s != nil {
+ if t := s.GetTable(ref.object); t != nil {
+ return t
+ }
+ }
+ // Sort schemas for deterministic fallback order (ListSchemaNames is map-backed).
+ names := r.dbMetadata.ListSchemaNames()
+ slices.Sort(names)
+ for _, name := range names {
+ if strings.EqualFold(name, "dbo") {
+ continue
+ }
+ if s := r.dbMetadata.GetSchemaMetadata(name); s != nil {
+ if t := s.GetTable(ref.object); t != nil {
+ return t
+ }
+ }
+ }
+ return nil
+}
+
+// indexedColumns returns indexed column names for the table at the given database+schema+object.
+func (r *disallowFuncAndCalcOmniRule) 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[strings.ToLower(expr)] = true
+ }
+ }
+ if len(cols) == 0 {
+ return nil
+ }
+ return cols
+}
+
+// allColumns returns every column name defined for the given table reference.
+func (r *disallowFuncAndCalcOmniRule) 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[strings.ToLower(c.GetName())] = true
+ }
+ if len(cols) == 0 {
+ return nil
+ }
+ return cols
+}
+
+// indexedByAlias maps alias (or object if no alias) to the set of indexed columns on that table.
+type indexedByAlias = map[string]map[string]bool
+
+// scopeIndexed carries per-alias column metadata for the local (inner) and outer scopes.
+// Unqualified refs resolve against local first (any table that declares the column);
+// only when no local table declares the column — and the local scope is fully
+// resolvable — do we fall back to outer. If any local source has unknown columns
+// (CTEs, derived tables, tables without metadata), we stay silent to avoid
+// misattributing an inner column to an outer indexed column of the same name.
+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
+}
+
+// resolveIndexedColumns builds a per-alias map of indexed columns.
+func (r *disallowFuncAndCalcOmniRule) 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
+}
+
+// resolveAllColumns builds a per-alias map of every known column for each table.
+func (r *disallowFuncAndCalcOmniRule) 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
+}
+
+// isIndexed reports whether a column reference is indexed, respecting its table qualifier
+// and SQL name resolution for correlated subqueries.
+// - Qualified (ref.Table set): check local first, then outer.
+// - Unqualified: if any local table declares the column, local wins. Only if no
+// local table declares the column do we fall back to outer indexed columns.
+func (r *disallowFuncAndCalcOmniRule) isIndexed(ref *ast.ColumnRef, s scopeIndexed) bool {
+ if ref == nil || s.empty() {
+ return false
+ }
+ col := strings.ToLower(ref.Column)
+ if ref.Table != "" {
+ alias := r.normalizeIdent(ref.Table)
+ // Local scope takes precedence: if the alias exists locally (even as a
+ // derived table or CTE without index metadata), the ref resolves there.
+ // Otherwise the qualified alias is definitively outer, even when other
+ // local sources have unresolved metadata — collectTableNamesFromList
+ // records every local alias (including derived tables) so this check
+ // is sound.
+ 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
+ }
+ // No local alias declared the column. Only fall back to outer when the local
+ // scope is fully resolvable; otherwise a CTE/derived-table column could be
+ // misattributed to an outer indexed column of the same name.
+ if s.localUnresolved {
+ return false
+ }
+ for _, cols := range s.outer {
+ if cols[col] {
+ return true
+ }
+ }
+ return false
+}
+
+func (r *disallowFuncAndCalcOmniRule) checkWhere(where ast.ExprNode, tables tablesByAlias) {
+ r.checkWhereWithScopes(where, tables, nil, false)
+}
+func (r *disallowFuncAndCalcOmniRule) checkWhereWithScopes(where ast.ExprNode, 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 {
- if found {
+ if sub, ok := n.(*ast.SelectStmt); ok {
+ r.checkSelectInScope(sub, combined)
return false
}
+ if !s.empty() {
+ r.checkWhereNode(n, s)
+ }
+ return true
+ })
+}
- switch expr := n.(type) {
- case *ast.FuncCallExpr:
- found = true
+func (r *disallowFuncAndCalcOmniRule) checkWhereNode(n ast.Node, indexed scopeIndexed) {
+ switch expr := n.(type) {
+ case *ast.FuncCallExpr:
+ if col := r.findIndexedColumnInFuncArgs(expr.Args, indexed); col != "" {
funcName := ""
if expr.Name != nil {
- funcName = tableRefText(expr.Name)
- }
- r.AddAdvice(&storepb.Advice{
- Status: r.Level,
- Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
- Title: r.Title,
- Content: fmt.Sprintf("Calling function '%s' in 'WHERE' clause is not allowed", funcName),
- StartPosition: &storepb.Position{Line: r.LocToLine(expr.Loc)},
- })
- return false
- case *ast.BinaryExpr:
- if isArithmeticOp(expr.Op) {
- found = true
- r.AddAdvice(&storepb.Advice{
- Status: r.Level,
- Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
- Title: r.Title,
- Content: "Performing calculations in 'WHERE' clause is not allowed",
- StartPosition: &storepb.Position{Line: r.LocToLine(expr.Loc)},
- })
- return false
+ funcName = strings.ToUpper(tableRefText(expr.Name))
}
- case *ast.UnaryExpr:
- if expr.Op == ast.UnaryPlus || expr.Op == ast.UnaryMinus || expr.Op == ast.UnaryBitNot {
- found = true
- r.AddAdvice(&storepb.Advice{
- Status: r.Level,
- Code: code.StatementDisallowFunctionsAndCalculations.Int32(),
- Title: r.Title,
- Content: "Performing calculations in 'WHERE' clause is not allowed",
- StartPosition: &storepb.Position{Line: r.LocToLine(expr.Loc)},
- })
- return false
+ r.addFunctionAdvice(funcName, col, expr.Loc)
+ }
+ case *ast.BinaryExpr:
+ if isArithmeticOp(expr.Op) {
+ if col := r.unwrapAndFindIndexedColumn(expr.Left, indexed); col != "" {
+ r.addCalculationAdvice(col, expr.Loc)
+ } else if col := r.unwrapAndFindIndexedColumn(expr.Right, indexed); col != "" {
+ r.addCalculationAdvice(col, expr.Loc)
}
- default:
}
- return true
+ case *ast.UnaryExpr:
+ // UnaryPlus is a no-op and does not prevent index usage; skip it.
+ if expr.Op == ast.UnaryMinus || expr.Op == ast.UnaryBitNot {
+ if col := r.unwrapAndFindIndexedColumn(expr.Operand, indexed); col != "" {
+ r.addCalculationAdvice(col, expr.Loc)
+ }
+ }
+ default:
+ }
+}
+
+func (r *disallowFuncAndCalcOmniRule) addFunctionAdvice(funcName, col string, loc ast.Loc) {
+ r.AddAdvice(&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: r.LocToLine(loc)},
+ })
+}
+
+func (r *disallowFuncAndCalcOmniRule) addCalculationAdvice(col string, loc ast.Loc) {
+ r.AddAdvice(&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: r.LocToLine(loc)},
})
}
+// findIndexedColumnInFuncArgs searches function arguments for an indexed ColumnRef,
+// descending through passthrough wrappers (ParenExpr, CastExpr, ConvertExpr) so that
+// `ABS((c1))` and `ABS(CAST(c1 AS int))` are still flagged.
+// BinaryExpr/UnaryExpr (arithmetic) are NOT crossed — those are handled by the
+// calculation advice path, so `ABS(c1 + 1)` is reported once as a calculation.
+func (r *disallowFuncAndCalcOmniRule) findIndexedColumnInFuncArgs(args *ast.List, indexed scopeIndexed) string {
+ if args == nil {
+ return ""
+ }
+ for _, item := range args.Items {
+ arg, ok := item.(ast.ExprNode)
+ if !ok {
+ continue
+ }
+ if col := r.unwrapAndFindIndexedColumn(arg, indexed); col != "" {
+ return col
+ }
+ }
+ return ""
+}
+
+// unwrapAndFindIndexedColumn peels ParenExpr/CastExpr/ConvertExpr wrappers off expr
+// and returns the column name if the inner expression is an indexed ColumnRef.
+func (r *disallowFuncAndCalcOmniRule) unwrapAndFindIndexedColumn(expr ast.ExprNode, indexed scopeIndexed) string {
+ for expr != nil {
+ switch e := expr.(type) {
+ case *ast.ColumnRef:
+ if r.isIndexed(e, indexed) {
+ return e.Column
+ }
+ return ""
+ case *ast.ParenExpr:
+ expr = e.Expr
+ case *ast.CastExpr:
+ expr = e.Expr
+ case *ast.ConvertExpr:
+ expr = e.Expr
+ default:
+ return ""
+ }
+ }
+ return ""
+}
+
func isArithmeticOp(op ast.BinaryOp) bool {
switch op {
- case ast.BinOpAdd, ast.BinOpSub, ast.BinOpMul, ast.BinOpDiv, ast.BinOpMod:
+ case ast.BinOpAdd, ast.BinOpSub, ast.BinOpMul, ast.BinOpDiv, ast.BinOpMod,
+ ast.BinOpBitAnd, ast.BinOpBitOr, ast.BinOpBitXor:
return true
default:
return false
diff --git a/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml
index 8b30a93441..9d10b29508 100644
--- a/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml
+++ b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml
@@ -1,62 +1,616 @@
+# Test: Function on indexed column should flag
+- statement: SELECT c1 FROM pokes WHERE ABS(c1) > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: Calculation on indexed column should flag
+- statement: SELECT c1 FROM pokes WHERE c1 + 1 > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: Unary operator on indexed column should flag
+- statement: SELECT c1 FROM pokes WHERE ~c1 > 0;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: Function on non-indexed column should NOT flag
+- statement: SELECT bar FROM pokes WHERE ABS(bar) > 0;
+ changeType: 1
+
+# Test: Calculation on non-indexed column should NOT flag
+- statement: SELECT foo FROM pokes WHERE (foo + 1) * 2 > 0;
+ changeType: 1
+
+# Test: Unary operator on non-indexed column should NOT flag
+- statement: SELECT foo FROM pokes WHERE ~foo > 0;
+ changeType: 1
+
+# Test: Function on value side should NOT flag
+- statement: SELECT c1 FROM pokes WHERE c1 = ABS(-5);
+ changeType: 1
+
+# Test: Simple comparison should NOT flag
+- statement: SELECT c1 FROM pokes WHERE c1 > 1;
+ changeType: 1
+
+# Test: Table with no indexes should NOT flag
+- statement: SELECT foo FROM pokes2 WHERE ABS(foo) > 5;
+ changeType: 1
+
+# Test: Multiple indexed-column violations
+- statement: SELECT c1, c10 FROM pokes WHERE ABS(c1) > 5 AND c10 + 1 > 10;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c10\" 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 \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: Bitwise operator on non-indexed column should NOT flag
+- statement: SELECT foo FROM pokes WHERE foo | -foo > 0;
+ changeType: 1
+
+# Test: HAVING clause should NOT flag
- statement: |-
- CREATE TABLE pokes(foo int);
- SELECT foo FROM pokes WHERE (foo + 1) * 2 > 0;
- INSERT INTO pokes VALUES(1);
- SELECT foo FROM pokes WHERE ~foo > 0;
+ SELECT c1, AVG(c2) AS avg_c2
+ FROM pokes
+ GROUP BY c1
+ HAVING AVG(c2) * 3 + 1 > 50000;
+ changeType: 1
+
+# ---- Subquery tests ----
+
+# Test: IN subquery on non-indexed table — inner should not flag
+- statement: SELECT c1 FROM pokes WHERE c1 IN (SELECT foo FROM pokes2 WHERE ABS(foo) > 0);
+ changeType: 1
+
+# Test: Outer on non-indexed table, inner on indexed table — inner should flag
+- statement: SELECT foo FROM pokes2 WHERE foo IN (SELECT c1 FROM pokes WHERE ABS(c1) > 5);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: Three-level nested subquery — violation at innermost level
+- statement: SELECT foo FROM pokes2 WHERE foo IN (SELECT foo FROM pokes2 WHERE foo IN (SELECT c1 FROM pokes WHERE ABS(c1) > 0));
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: EXISTS subquery with calculation on inner indexed column
+- statement: SELECT foo FROM pokes2 WHERE EXISTS (SELECT 1 FROM pokes WHERE c1 + 1 > 5);
changeType: 1
want:
- status: 2
code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Performing calculations in 'WHERE' clause is not allowed
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: Scalar subquery on value side — only flag inner WHERE violation, not SELECT list
+- statement: SELECT foo FROM pokes2 WHERE foo > (SELECT MAX(c1) FROM pokes WHERE ABS(c1) > 0);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: CTE body with function on indexed column should flag
+- statement: WITH filtered AS (SELECT c1, c2 FROM pokes WHERE ABS(c1) > 5) SELECT * FROM filtered WHERE c1 = 1;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: INSERT...SELECT with function on indexed column should flag
+- statement: INSERT INTO pokes2 (foo) SELECT c1 FROM pokes WHERE ABS(c1) > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: Function wrapping expression with indexed column should flag (as calculation)
+- statement: SELECT c1 FROM pokes WHERE ABS(c1 + 1) > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test: CREATE TABLE AS SELECT with function on indexed column should flag
+- statement: CREATE TABLE new_table WITH (DISTRIBUTION = ROUND_ROBIN) AS SELECT c1 FROM pokes WHERE ABS(c1) > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P1): Same column name, indexed in one JOIN table, non-indexed in another —
+# qualified ref to the non-indexed side should NOT flag.
+# pokes.c1 is indexed; pokes2.c1 exists (non-indexed). Query uses p2.c1.
+- statement: SELECT * FROM pokes p JOIN pokes2 p2 ON p.c1 = p2.c1 WHERE ABS(p2.c1) > 0;
+ changeType: 1
+
+# Test (codex P1): Qualified ref to indexed side of a same-named JOIN column should flag.
+- statement: SELECT * FROM pokes p JOIN pokes2 p2 ON p.c1 = p2.c1 WHERE ABS(p.c1) > 0;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): Table in non-default schema with non-indexed column — should NOT flag.
+- statement: SELECT * FROM sales.orders WHERE UPPER(note) = 'x';
+ changeType: 1
+
+# Test (codex P2): Indexed column in non-dbo schema — should flag.
+- statement: SELECT * FROM sales.orders WHERE ABS(customer_id) > 0;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"customer_id\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (reviewer #1): Derived table in FROM with violation in its own WHERE.
+- statement: SELECT * FROM (SELECT c1 FROM pokes WHERE ABS(c1) > 0) s;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (reviewer #3): Scalar subquery in SELECT list with violation.
+- statement: SELECT (SELECT MAX(c1) FROM pokes WHERE ABS(c1) > 0) FROM pokes2;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (reviewer #4): MSSQL UPDATE with FROM ... JOIN — violation on JOINed indexed column.
+- statement: UPDATE pokes2 SET foo = 0 FROM pokes2 p2 JOIN pokes p ON p2.foo = p.c1 WHERE ABS(p.c1) > 0;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex new P2): Cross-database reference should NOT flag (can't resolve).
+- statement: SELECT * FROM otherdb.dbo.orders_unknown WHERE UPPER(col) = 'x';
+ changeType: 1
+
+# Test (codex new P1): Reference to unknown schema — should NOT panic and NOT flag.
+- statement: SELECT * FROM unknown_schema.orders WHERE UPPER(col) = 'x';
+ changeType: 1
+
+# Test (adversarial): Function wrapping a parenthesized indexed column — should flag.
+- statement: SELECT c1 FROM pokes WHERE ABS((c1)) > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): Calculation on parenthesized indexed column — should flag.
+- statement: SELECT c1 FROM pokes WHERE (c1) + 1 > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): Calculation on CAST indexed column — should flag.
+- statement: SELECT c1 FROM pokes WHERE CAST(c1 AS int) + 1 > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (adversarial): MERGE with SourceAlias — alias in WHEN condition should resolve.
+- statement: |-
+ MERGE INTO pokes2 AS tgt
+ USING pokes AS src
+ ON tgt.foo = src.c1
+ WHEN MATCHED AND ABS(src.c1) > 0 THEN UPDATE SET foo = 0;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 4
+ column: 0
+ endposition: null
+
+# Test (adversarial high): Case-insensitive match — ABS(C1) on indexed `c1`.
+- statement: SELECT c1 FROM pokes WHERE ABS(C1) > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"C1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (adversarial high): Mixed-case alias — P.c1 + 1 on aliased indexed pokes.c1.
+- statement: SELECT c1 FROM pokes P WHERE P.c1 + 1 > 5;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (adversarial high): MERGE with subquery source — inner violation in subquery's WHERE should flag.
+- statement: |-
+ MERGE INTO pokes2 AS tgt
+ USING (SELECT c1 FROM pokes WHERE ABS(c1) > 0) AS src
+ ON tgt.foo = src.c1
+ WHEN MATCHED THEN UPDATE SET foo = 0;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
startposition:
line: 2
column: 0
endposition: null
+
+# Test (adversarial high): MERGE with subquery source — src.col in ON/WHEN does NOT flag
+# (we can't trace subquery aliases through; false negatives are safer than false positives).
+- statement: |-
+ MERGE INTO pokes2 AS tgt
+ USING (SELECT c1 FROM pokes2) AS src
+ ON tgt.foo = src.c1
+ WHEN MATCHED AND ABS(src.c1) > 0 THEN UPDATE SET foo = 0;
+ changeType: 1
+
+# Test (codex P2): UPDATE SET with scalar subquery — inner violation must flag.
+- statement: UPDATE pokes2 SET foo = (SELECT TOP 1 c1 FROM pokes WHERE ABS(c1) > 0);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): UPDATE SET with calculation inside subquery — should flag.
+- statement: UPDATE pokes2 SET foo = (SELECT TOP 1 c1 FROM pokes WHERE c1 + 1 > 0);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): UPDATE ... FROM with derived-table subquery — inner WHERE violation should flag.
+- statement: UPDATE pokes2 SET foo = 0 FROM pokes2 p2 JOIN (SELECT c1 FROM pokes WHERE ABS(c1) > 0) s ON p2.foo = s.c1;
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): DELETE ... FROM with derived-table subquery — inner WHERE violation should flag.
+- statement: DELETE p2 FROM pokes2 p2 JOIN (SELECT c1 FROM pokes WHERE c1 + 1 > 0) s ON p2.foo = s.c1;
+ changeType: 1
+ want:
- status: 2
code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Performing calculations in 'WHERE' clause is not allowed
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): MERGE WHEN MATCHED THEN UPDATE SET with scalar subquery — inner violation should flag.
+- statement: |-
+ MERGE INTO pokes2 AS tgt
+ USING pokes AS src
+ ON tgt.foo = src.c1
+ WHEN MATCHED THEN UPDATE SET foo = (SELECT TOP 1 c1 FROM pokes WHERE ABS(c1) > 0);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
startposition:
line: 4
column: 0
endposition: null
+
+# Test (codex P2): MERGE WHEN NOT MATCHED INSERT VALUES with scalar subquery — inner violation should flag.
- statement: |-
- SELECT foo FROM pokes WHERE foo | -foo > 0;
- SELECT bar FROM pokes WHERE bar > AVG(bar);
+ MERGE INTO pokes2 AS tgt
+ USING pokes AS src
+ ON tgt.foo = src.c1
+ WHEN NOT MATCHED THEN INSERT (foo) VALUES ((SELECT TOP 1 c1 FROM pokes WHERE c1 + 1 > 0));
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 4
+ column: 0
+ endposition: null
+
+# Test (codex P2): unqualified table in non-dbo schema (sales.orders) — indexed column should flag.
+- statement: SELECT * FROM orders WHERE ABS(customer_id) > 0;
changeType: 1
want:
- status: 2
code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Performing calculations in 'WHERE' clause is not allowed
+ content: "Function \"ABS\" is applied to indexed column \"customer_id\" in the WHERE clause, which prevents index usage"
startposition:
line: 1
column: 0
endposition: null
+
+# Test (codex P2): INSERT VALUES with scalar subquery — inner violation should flag.
+- statement: INSERT INTO pokes2 (foo) VALUES ((SELECT TOP 1 c1 FROM pokes WHERE ABS(c1) > 0));
+ changeType: 1
+ want:
- status: 2
code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Calling function 'AVG' in 'WHERE' clause is not allowed
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
startposition:
- line: 2
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (adversarial): correlated EXISTS subquery — inner WHERE references outer indexed column.
+- statement: SELECT * FROM pokes t WHERE EXISTS (SELECT 1 FROM pokes2 o WHERE ABS(t.c1) > 0);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
column: 0
endposition: null
-- statement: SELECT bar FROM pokes WHERE bar > 1;
+
+# Test (codex P2): CREATE VIEW with function on indexed column in WHERE — should flag.
+- statement: CREATE VIEW v AS SELECT * FROM pokes WHERE ABS(c1) > 0;
changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): correlated subquery — unqualified `c1` resolves to inner (pokes2.c1 non-indexed), should NOT flag.
+- statement: SELECT * FROM pokes t WHERE EXISTS (SELECT 1 FROM pokes2 o WHERE ABS(c1) > 0);
+ changeType: 1
+
+# Test (codex P2): correlated unqualified outer column — inner (pokes2) has no `c10`, should resolve to outer pokes.c10 and flag.
+- statement: SELECT * FROM pokes p WHERE EXISTS (SELECT 1 FROM pokes2 p2 WHERE ABS(c10) > 0);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c10\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P1): CTE reference in inner FROM — unqualified `c1` owns by inner CTE, should NOT falsely flag outer pokes.c1.
+- statement: |-
+ WITH c AS (SELECT foo AS c1 FROM pokes2)
+ SELECT * FROM pokes p WHERE EXISTS (SELECT 1 FROM c WHERE ABS(c1) > 0);
+ changeType: 1
+
+# Test (codex P1): Derived table in inner FROM — unqualified `c1` owns by inner derived, should NOT falsely flag outer pokes.c1.
+- statement: SELECT * FROM pokes p WHERE EXISTS (SELECT 1 FROM (SELECT foo AS c1 FROM pokes2) d WHERE ABS(c1) > 0);
+ changeType: 1
+
+# Test (design gap): CREATE MATERIALIZED VIEW with function on indexed column — should flag.
- statement: |-
- SELECT Department, AVG(Salary) AS AvgSalary
- FROM Employees
- GROUP BY Department
- HAVING AVG(Salary) * 3 + 1 > 50000;
+ CREATE MATERIALIZED VIEW v
+ WITH (DISTRIBUTION = ROUND_ROBIN)
+ AS SELECT c1 FROM pokes WHERE ABS(c1) > 0;
changeType: 1
-- statement: select * from (select * from t where t.a > 1) t1 where a > AVG(a);
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 3
+ column: 0
+ endposition: null
+
+# Test (truth table R5): qualified ref to unknown alias — should NOT flag.
+- statement: SELECT * FROM pokes WHERE ABS(unknown.c1) > 0;
+ changeType: 1
+
+# Test (truth table R4): qualified correlated ref to outer non-indexed column — should NOT flag.
+- statement: SELECT * FROM pokes p WHERE EXISTS (SELECT 1 FROM pokes2 o WHERE ABS(p.foo) > 0);
+ changeType: 1
+
+# Test (codex P2): inner derived-table alias shadows outer — qualified p.c1 resolves to inner derived, should NOT flag outer pokes.c1.
+- statement: SELECT * FROM pokes p WHERE EXISTS (SELECT 1 FROM (SELECT foo AS c1 FROM pokes2) p WHERE ABS(p.c1) > 0);
+ changeType: 1
+
+# Test (codex P2): inner CTE ref with qualified correlated outer ref — p.c1 is outer, should flag.
+- statement: |-
+ WITH c AS (SELECT foo AS c1 FROM pokes2)
+ SELECT * FROM pokes p WHERE EXISTS (SELECT 1 FROM c WHERE ABS(p.c1) > 0);
+ changeType: 1
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 2
+ column: 0
+ endposition: null
+
+# Test (codex P2): inner derived with qualified correlated outer ref — p.c1 is outer, should flag.
+- statement: SELECT * FROM pokes p WHERE EXISTS (SELECT 1 FROM (SELECT foo FROM pokes2) d WHERE ABS(p.c1) > 0);
changeType: 1
want:
- status: 2
code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Calling function 'AVG' in 'WHERE' clause is not allowed
+ content: "Function \"ABS\" is applied to indexed column \"c1\" in the WHERE clause, which prevents index usage"
startposition:
line: 1
column: 0
diff --git a/backend/plugin/advisor/mysql/rule_statement_where_disallow_using_function.go b/backend/plugin/advisor/mysql/rule_statement_where_disallow_using_function.go
index 36aa7e1a27..8dc2bf5cab 100644
--- a/backend/plugin/advisor/mysql/rule_statement_where_disallow_using_function.go
+++ b/backend/plugin/advisor/mysql/rule_statement_where_disallow_using_function.go
@@ -11,6 +11,7 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
+ "github.com/bytebase/bytebase/backend/store/model"
)
var (
@@ -36,12 +37,16 @@ func (*StatementWhereDisallowUsingFunctionAdvisor) Check(_ context.Context, chec
Title: checkCtx.Rule.Type.String(),
},
}
+ if checkCtx.DBSchema != nil {
+ rule.dbMetadata = model.NewDatabaseMetadata(checkCtx.DBSchema, nil, nil, storepb.Engine_MYSQL, checkCtx.IsObjectCaseSensitive)
+ }
return RunOmniRules(checkCtx.ParsedStatements, []OmniRule{rule}), nil
}
type whereDisallowFuncOmniRule struct {
OmniBaseRule
+ dbMetadata *model.DatabaseMetadata
}
func (*whereDisallowFuncOmniRule) Name() string {
@@ -49,27 +54,555 @@ func (*whereDisallowFuncOmniRule) Name() string {
}
func (r *whereDisallowFuncOmniRule) OnStatement(node ast.Node) {
- text := strings.TrimSpace(r.StmtText)
- // Collect WHERE expressions from all SelectStmt nodes (including UNION branches).
- ast.Inspect(node, func(n ast.Node) bool {
- sel, ok := n.(*ast.SelectStmt)
- if !ok {
+ switch n := node.(type) {
+ case *ast.SelectStmt:
+ r.checkSelect(n)
+ case *ast.InsertStmt:
+ r.onInsert(n)
+ case *ast.CreateTableStmt:
+ r.onCreateTable(n)
+ case *ast.CreateViewStmt:
+ r.onCreateView(n)
+ case *ast.AlterViewStmt:
+ r.onAlterView(n)
+ case *ast.UpdateStmt:
+ r.onUpdate(n)
+ case *ast.DeleteStmt:
+ r.onDelete(n)
+ default:
+ }
+}
+
+// onInsert handles INSERT [... SELECT | ... VALUES (...) | ... SET ... | ... ON DUPLICATE KEY UPDATE].
+// Each of SELECT/VALUES/SET/ON DUPLICATE KEY can embed scalar subqueries with their own WHERE.
+func (r *whereDisallowFuncOmniRule) onInsert(n *ast.InsertStmt) {
+ if n.Select != nil {
+ r.checkSelect(n.Select)
+ }
+ for _, row := range n.Values {
+ for _, v := range row {
+ r.recurseIntoNestedSelectsInNode(v, nil)
+ }
+ }
+ r.recurseAssignmentValues(n.SetList, nil)
+ r.recurseAssignmentValues(n.OnDuplicateKey, nil)
+}
+
+func (r *whereDisallowFuncOmniRule) onCreateTable(n *ast.CreateTableStmt) {
+ if n.Select != nil {
+ r.checkSelect(n.Select)
+ }
+}
+
+func (r *whereDisallowFuncOmniRule) onCreateView(n *ast.CreateViewStmt) {
+ if n.Select != nil {
+ r.checkSelect(n.Select)
+ }
+}
+
+func (r *whereDisallowFuncOmniRule) onAlterView(n *ast.AlterViewStmt) {
+ if n.Select != nil {
+ r.checkSelect(n.Select)
+ }
+}
+
+// onUpdate handles UPDATE WHERE and any scalar subqueries hidden in SET expressions
+// or derived tables in the table list (e.g. JOIN (SELECT ... WHERE ...) s).
+func (r *whereDisallowFuncOmniRule) onUpdate(n *ast.UpdateStmt) {
+ tables := r.collectTableNames(n.Tables)
+ r.checkWhere(n.Where, tables)
+ for _, te := range n.Tables {
+ r.recurseIntoNestedSelectsInNode(te, tables)
+ }
+ r.recurseAssignmentValues(n.SetList, tables)
+}
+
+// onDelete handles DELETE WHERE, including multi-table DELETE ... USING and derived
+// tables that carry their own WHERE clauses.
+func (r *whereDisallowFuncOmniRule) onDelete(n *ast.DeleteStmt) {
+ tables := r.collectTableNames(n.Tables)
+ for alias, ref := range r.collectTableNames(n.Using) {
+ tables[alias] = ref
+ }
+ r.checkWhere(n.Where, tables)
+ for _, te := range n.Tables {
+ r.recurseIntoNestedSelectsInNode(te, tables)
+ }
+ for _, te := range n.Using {
+ r.recurseIntoNestedSelectsInNode(te, tables)
+ }
+}
+
+// recurseAssignmentValues walks the RHS of each assignment (UPDATE SET, INSERT SET,
+// INSERT ... ON DUPLICATE KEY UPDATE) for scalar subqueries.
+func (r *whereDisallowFuncOmniRule) recurseAssignmentValues(assignments []*ast.Assignment, outer tablesByAlias) {
+ for _, a := range assignments {
+ if a != nil && a.Value != nil {
+ r.recurseIntoNestedSelectsInNode(a.Value, outer)
+ }
+ }
+}
+
+func (r *whereDisallowFuncOmniRule) checkSelect(sel *ast.SelectStmt) {
+ r.checkSelectInScope(sel, nil)
+}
+
+// checkSelectInScope is like checkSelect but also threads an outer table scope down
+// so that correlated subqueries can resolve references to outer aliases. Local
+// (inner) tables take precedence for unqualified columns per SQL name resolution;
+// outer tables are consulted only for qualified references (e.g. outer_alias.col).
+func (r *whereDisallowFuncOmniRule) checkSelectInScope(sel *ast.SelectStmt, outer tablesByAlias) {
+ if sel == nil {
+ return
+ }
+ // CTEs are not correlated with their referencing SELECT, so check them without outer scope.
+ for _, cte := range sel.CTEs {
+ if cte.Select != nil {
+ r.checkSelect(cte.Select)
+ }
+ }
+ if sel.SetOp != ast.SetOpNone {
+ r.checkSelectInScope(sel.Left, outer)
+ r.checkSelectInScope(sel.Right, outer)
+ return
+ }
+ local := r.collectTableNames(sel.From)
+ // Build a combined map for downstream recursion into nested subqueries, where
+ // local aliases are "outer" relative to that deeper scope.
+ 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.Where, local, outer, r.localHasUnresolvedSources(sel.From, local))
+ // Recurse into nested SelectStmts elsewhere in this SELECT, passing current combined
+ // scope as outer so correlated references in scalar/derived subqueries resolve.
+ r.recurseIntoNestedSelects(sel, combined)
+}
+
+// localHasUnresolvedSources reports whether the given FROM and local alias map
+// contain sources whose columns we cannot enumerate from metadata — CTE refs,
+// derived tables (subqueries in FROM), and plain tables absent from metadata.
+// When true, we must not fall back to outer scope for unqualified columns,
+// because the inner source likely owns the name.
+func (r *whereDisallowFuncOmniRule) localHasUnresolvedSources(from []ast.TableExpr, local tablesByAlias) bool {
+ for _, te := range from {
+ derivedFound := false
+ ast.Inspect(te, func(n ast.Node) bool {
+ switch n.(type) {
+ case *ast.SubqueryExpr, *ast.SelectStmt:
+ derivedFound = true
+ return false
+ }
+ return !derivedFound
+ })
+ if derivedFound {
+ return true
+ }
+ }
+ for _, ref := range local {
+ if ref == (tableRef{}) {
+ continue
+ }
+ if r.tableMetadata(ref) == nil {
return true
}
- if sel.Where != nil {
- ast.Inspect(sel.Where, func(wn ast.Node) bool {
- if fn, ok := wn.(*ast.FuncCallExpr); ok {
- r.AddAdviceAbsolute(&storepb.Advice{
- Status: r.Level,
- Code: code.DisabledFunction.Int32(),
- Title: r.Title,
- Content: fmt.Sprintf("Function is disallowed in where clause, but \"%s\" uses", text),
- StartPosition: common.ConvertANTLRLineToPosition(r.BaseLine + int(r.LocToLine(fn.Loc))),
- })
+ }
+ return false
+}
+
+// recurseIntoNestedSelectsInNode walks the given AST node and recurses into any
+// nested *ast.SelectStmt, threading the given outer scope.
+func (r *whereDisallowFuncOmniRule) recurseIntoNestedSelectsInNode(n ast.Node, outer tablesByAlias) {
+ if n == nil {
+ return
+ }
+ ast.Inspect(n, func(m ast.Node) bool {
+ if sub, ok := m.(*ast.SelectStmt); ok {
+ r.checkSelectInScope(sub, outer)
+ return false
+ }
+ return true
+ })
+}
+
+// recurseIntoNestedSelects finds nested *ast.SelectStmt nodes in the non-WHERE parts of
+// the given SELECT and recursively invokes checkSelectInScope on them with outer scope.
+func (r *whereDisallowFuncOmniRule) recurseIntoNestedSelects(sel *ast.SelectStmt, outer tablesByAlias) {
+ visit := func(n ast.Node) {
+ if n == nil {
+ return
+ }
+ ast.Inspect(n, func(m ast.Node) bool {
+ if sub, ok := m.(*ast.SelectStmt); ok {
+ r.checkSelectInScope(sub, outer)
+ return false
+ }
+ return true
+ })
+ }
+ for _, from := range sel.From {
+ visit(from)
+ }
+ for _, t := range sel.TargetList {
+ visit(t)
+ }
+ visit(sel.Having)
+ for _, g := range sel.GroupBy {
+ visit(g)
+ }
+ for _, o := range sel.OrderBy {
+ if o != nil {
+ visit(o.Expr)
+ }
+ }
+}
+
+// tableRef captures the real database and table name for an aliased table reference.
+// In MySQL terminology, TableRef.Schema is the database name.
+type tableRef struct {
+ database string // empty means current database
+ name string
+}
+
+// tablesByAlias maps alias (or name if no alias) to the underlying tableRef.
+type tablesByAlias = map[string]tableRef
+
+// collectTableNames extracts table refs (with database qualifier) from FROM/table expressions.
+// Descent is stopped at subquery boundaries so that derived tables don't leak their
+// inner TableRefs into the outer scope, but the derived table's own alias is captured
+// as an opaque tableRef{} entry so qualifier-based resolution can still tell it apart
+// from an outer alias of the same name.
+// Alias keys are normalized per IsObjectCaseSensitive.
+func (r *whereDisallowFuncOmniRule) collectTableNames(tableExprs []ast.TableExpr) tablesByAlias {
+ tables := make(tablesByAlias)
+ for _, from := range tableExprs {
+ ast.Inspect(from, func(n ast.Node) bool {
+ // Stop at subquery boundaries — inner SELECTs are a separate scope — but
+ // record the derived table's alias so qualifier lookups recognize it as local.
+ if sq, ok := n.(*ast.SubqueryExpr); ok {
+ if sq.Alias != "" {
+ if _, exists := tables[r.normalizeIdent(sq.Alias)]; !exists {
+ tables[r.normalizeIdent(sq.Alias)] = tableRef{}
+ }
}
+ return false
+ }
+ if _, ok := n.(*ast.SelectStmt); ok {
+ return false
+ }
+ t, ok := n.(*ast.TableRef)
+ if !ok {
+ return true
+ }
+ key := t.Alias
+ if key == "" {
+ key = t.Name
+ }
+ normKey := r.normalizeIdent(key)
+ newRef := tableRef{database: t.Schema, name: t.Name}
+ // If an unaliased same-name from a different database already occupies this
+ // key (rare: `FROM db1.orders, db2.orders` without aliases), mark as ambiguous
+ // so isIndexed returns false rather than resolving to the wrong table.
+ // Users should alias these tables to disambiguate.
+ if existing, ok := tables[normKey]; ok && (existing.database != newRef.database || existing.name != newRef.name) {
+ tables[normKey] = tableRef{}
+ } else {
+ tables[normKey] = newRef
+ }
+ return false
+ })
+ }
+ return tables
+}
+
+// normalizeIdent lowercases identifiers when the DB is configured case-insensitive.
+func (r *whereDisallowFuncOmniRule) 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, applying the
+// cross-DB guard. Returns nil when not resolvable.
+func (r *whereDisallowFuncOmniRule) tableMetadata(ref tableRef) *model.TableMetadata {
+ if r.dbMetadata == nil {
+ return nil
+ }
+ // Skip cross-database references; we only have metadata for the current DB.
+ if ref.database != "" && !strings.EqualFold(ref.database, r.dbMetadata.DatabaseName()) {
+ return nil
+ }
+ return r.dbMetadata.GetSchemaMetadata("").GetTable(ref.name)
+}
+
+// indexedColumns returns indexed column names for the given table reference.
+func (r *whereDisallowFuncOmniRule) 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[strings.ToLower(expr)] = true
+ }
+ }
+ if len(cols) == 0 {
+ return nil
+ }
+ return cols
+}
+
+// allColumns returns every column name defined for the given table reference.
+func (r *whereDisallowFuncOmniRule) 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[strings.ToLower(c.GetName())] = true
+ }
+ if len(cols) == 0 {
+ return nil
+ }
+ return cols
+}
+
+// indexedByAlias maps alias (or table name if no alias) to the set of indexed columns on that table.
+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. Unqualified refs first
+// resolve against local (any table that declares the column); only when no
+// local table declares the column — and the full local scope is resolvable —
+// do we fall back to outer. If any local source has unknown columns (CTEs,
+// derived tables, tables without metadata), we do NOT fall back: inner scope
+// still owns the name, we just can't prove indexability, so we stay silent
+// rather than misattribute to an outer indexed column.
+type scopeIndexed struct {
+ local indexedByAlias // per-alias indexed columns (local scope)
+ localAll indexedByAlias // per-alias full column sets (local scope)
+ localAliases map[string]bool // every alias present in the local scope (including unresolved/derived)
+ outer indexedByAlias // per-alias indexed columns (outer scope)
+ localUnresolved bool // true when the local scope has sources whose columns we can't enumerate
+}
+
+func (s scopeIndexed) empty() bool {
+ return len(s.local) == 0 && len(s.outer) == 0
+}
+
+// resolveIndexedColumns builds a per-alias map of indexed columns.
+func (r *whereDisallowFuncOmniRule) 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
+}
+
+// resolveAllColumns builds a per-alias map of every known column for each table.
+func (r *whereDisallowFuncOmniRule) 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
+}
+
+// isIndexed reports whether a column reference is indexed, respecting its table qualifier
+// and SQL name resolution for correlated subqueries.
+// - Qualified (ref.Table set): check local first, then outer.
+// - Unqualified: if any local table declares the column, local wins (flag only if
+// that local table has it indexed). If no local table declares the column, fall
+// back to outer indexed columns (supports correlated subqueries).
+func (r *whereDisallowFuncOmniRule) isIndexed(ref *ast.ColumnRef, s scopeIndexed) bool {
+ if ref == nil || s.empty() {
+ return false
+ }
+ col := strings.ToLower(ref.Column)
+ if ref.Table != "" {
+ alias := r.normalizeIdent(ref.Table)
+ // Local scope takes precedence: if the alias exists locally (even as a
+ // derived table or CTE without index metadata), the ref resolves there.
+ // Otherwise the qualified alias is definitively outer, even when other
+ // local sources have unresolved metadata — collectTableNames records
+ // every local alias (including derived tables) so this check is sound.
+ 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
+ }
+ // No local alias declared the column. Only fall back to outer when the local
+ // scope is fully resolvable; otherwise a CTE/derived-table column could be
+ // misattributed to an outer indexed column of the same name.
+ if s.localUnresolved {
+ return false
+ }
+ for _, cols := range s.outer {
+ if cols[col] {
+ return true
+ }
+ }
+ return false
+}
+
+func (r *whereDisallowFuncOmniRule) checkWhere(where ast.ExprNode, tables tablesByAlias) {
+ r.checkWhereWithScopes(where, tables, nil, false)
+}
+
+func (r *whereDisallowFuncOmniRule) checkWhereWithScopes(where ast.ExprNode, 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 table set for recursing into nested subqueries (each is a new scope
+ // where current local+outer both become "outer").
+ 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 {
+ if sub, ok := n.(*ast.SelectStmt); ok {
+ r.checkSelectInScope(sub, combined)
+ return false
+ }
+ if !s.empty() {
+ r.checkWhereNode(n, s)
}
return true
})
}
+
+func (r *whereDisallowFuncOmniRule) checkWhereNode(n ast.Node, indexed scopeIndexed) {
+ switch expr := n.(type) {
+ case *ast.FuncCallExpr:
+ if col := r.findIndexedColumnInArgs(expr.Args, indexed); col != "" {
+ r.addFunctionAdvice(strings.ToUpper(expr.Name), col, expr.Loc)
+ }
+ case *ast.BinaryExpr:
+ if isArithmeticOp(expr.Op) {
+ if col := r.unwrapAndFindIndexedColumn(expr.Left, indexed); col != "" {
+ r.addCalculationAdvice(col, expr.Loc)
+ } else if col := r.unwrapAndFindIndexedColumn(expr.Right, indexed); col != "" {
+ r.addCalculationAdvice(col, expr.Loc)
+ }
+ }
+ case *ast.UnaryExpr:
+ if expr.Op == ast.UnaryMinus || expr.Op == ast.UnaryBitNot {
+ if col := r.unwrapAndFindIndexedColumn(expr.Operand, indexed); col != "" {
+ r.addCalculationAdvice(col, expr.Loc)
+ }
+ }
+ default:
+ }
+}
+
+func (r *whereDisallowFuncOmniRule) addFunctionAdvice(funcName, col string, loc ast.Loc) {
+ r.AddAdviceAbsolute(&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 + int(r.LocToLine(loc))),
+ })
+}
+
+func (r *whereDisallowFuncOmniRule) addCalculationAdvice(col string, loc ast.Loc) {
+ r.AddAdviceAbsolute(&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 + int(r.LocToLine(loc))),
+ })
+}
+
+// findIndexedColumnInArgs searches function arguments for an indexed ColumnRef,
+// descending through passthrough wrappers (ParenExpr, CastExpr) so that
+// `UPPER((name))` and `UPPER(CAST(name AS CHAR))` are still flagged.
+// BinaryExpr/UnaryExpr (arithmetic) are NOT crossed — those are handled by the
+// calculation advice path, so `ABS(id + 1)` is reported once as a calculation.
+func (r *whereDisallowFuncOmniRule) findIndexedColumnInArgs(args []ast.ExprNode, indexed scopeIndexed) string {
+ for _, arg := range args {
+ if col := r.unwrapAndFindIndexedColumn(arg, indexed); col != "" {
+ return col
+ }
+ }
+ return ""
+}
+
+// unwrapAndFindIndexedColumn peels ParenExpr/CastExpr wrappers off expr and, if the
+// inner expression is an indexed ColumnRef, returns its name. Returns "" otherwise.
+func (r *whereDisallowFuncOmniRule) unwrapAndFindIndexedColumn(expr ast.ExprNode, indexed scopeIndexed) string {
+ for expr != nil {
+ switch e := expr.(type) {
+ case *ast.ColumnRef:
+ if r.isIndexed(e, indexed) {
+ return e.Column
+ }
+ return ""
+ case *ast.ParenExpr:
+ expr = e.Expr
+ case *ast.CastExpr:
+ expr = e.Expr
+ default:
+ return ""
+ }
+ }
+ return ""
+}
+
+func isArithmeticOp(op ast.BinaryOp) bool {
+ switch op {
+ case ast.BinOpAdd, ast.BinOpSub, ast.BinOpMul, ast.BinOpDiv, ast.BinOpMod,
+ ast.BinOpDivInt, ast.BinOpBitAnd, ast.BinOpBitOr, ast.BinOpBitXor,
+ ast.BinOpShiftLeft, ast.BinOpShiftRight:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/backend/plugin/advisor/mysql/test/statement_where_disallow_functions_and_calculations.yaml b/backend/plugin/advisor/mysql/test/statement_where_disallow_functions_and_calculations.yaml
index db7269be56..238a3371ba 100644
--- a/backend/plugin/advisor/mysql/test/statement_where_disallow_functions_and_calculations.yaml
+++ b/backend/plugin/advisor/mysql/test/statement_where_disallow_functions_and_calculations.yaml
@@ -1,9 +1,727 @@
-- statement: SELECT * FROM employee WHERE id = RAND();
+# Test: Function on indexed column should flag
+- statement: SELECT * FROM tech_book WHERE UPPER(name) = 'test';
want:
- status: 2
- code: 1702
+ code: 234
title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
- content: Function is disallowed in where clause, but "SELECT * FROM employee WHERE id = RAND();" uses
+ 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: Multiple violations should flag each one
+- 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 value side should NOT flag (index still usable)
+- statement: SELECT * FROM tech_book WHERE id = ABS(-5);
+
+# Test: Function on value side with RAND should NOT flag
+- statement: SELECT * FROM tech_book WHERE id = RAND();
+
+# Test: Simple comparison should NOT flag
+- statement: SELECT * FROM tech_book WHERE id = 1 AND name = 'test';
+
+# 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 tech_book WHERE creator = CONCAT('a', 'b');
+
+# Test: Table not in schema should NOT flag
+- statement: SELECT * FROM unknown_table WHERE UPPER(col) = 'test';
+
+# 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 the indexed one
+- 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
+
+# Test: Function on indexed column inside IN subquery should flag (subquery's own scope)
+- 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: 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: Three-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: Scalar subquery on value side with function on inner indexed column — should flag (inner scope)
+- 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: EXISTS subquery with function on indexed column
+- 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 IN subquery with function on indexed column
+- 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: NOT EXISTS subquery with calculation on indexed column
+- 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: Subquery with calculation (not function) on indexed column
+- statement: SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE amount * 2 > 1000);
+ 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: Correlated subquery with function on inner indexed column
+- 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: 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
+
+# Test: Multiple independent subqueries in same WHERE — flag each violation
+- 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: Subquery referencing same table as outer
+- statement: SELECT * FROM tech_book WHERE id IN (SELECT id 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: Inner subquery on table with no matching index — should NOT flag
+- statement: SELECT * FROM tech_book WHERE id IN (SELECT order_id FROM orders WHERE UPPER(note) = 'x' AND LOWER(note) = 'y');
+
+# 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: Violations at multiple levels of nesting (outer, middle, inner)
+- statement: SELECT * FROM tech_book WHERE UPPER(name) = 'A' AND id IN (SELECT order_id FROM orders WHERE LOWER(customer_name) = 'x' AND amount > (SELECT AVG(amount) 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 \"LOWER\" 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
+
+# Test: UNION where one branch has a subquery with 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: CTE body with function on indexed column should flag
+- 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: INSERT...SELECT with function on indexed column should flag
+- statement: INSERT INTO orders (order_id) 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 wrapping expression with indexed column should flag
+- 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: 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 (codex P1): Same column name, indexed in one JOIN table, non-indexed in another —
+# qualified ref to the 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';
+
+# Test (codex P1): Same column name — qualified ref to the indexed side should flag.
+- 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 (codex P1): Qualified ref to indexed column in JOIN — baseline sanity.
+- 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 (reviewer #1): Derived table in FROM with a violation in its own WHERE.
+- 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 (reviewer #3): Scalar subquery in SELECT list with its own WHERE violation.
+- 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 (reviewer #3): Subquery in HAVING with violation.
+- statement: SELECT name FROM tech_book GROUP BY name HAVING name 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 (adversarial): MySQL cross-database reference should NOT flag (can't resolve).
+- statement: SELECT * FROM otherdb.tech_book WHERE UPPER(name) = 'x';
+
+# Test (adversarial): MySQL multi-table DELETE ... USING — violation on USING-joined indexed col.
+- statement: DELETE FROM tech_book USING tech_book JOIN orders ON tech_book.id = orders.order_id WHERE UPPER(orders.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 (adversarial): Function wrapping a parenthesized indexed column — should flag.
+- statement: 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 (codex P2): Calculation on parenthesized 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 (codex P2): Calculation on CAST indexed column — should flag.
+- statement: SELECT * FROM tech_book WHERE CAST(id AS CHAR) + 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 (adversarial high): Case-insensitive match — UPPER(NAME) on indexed `name`.
+- statement: 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 (adversarial high): Mixed-case alias — T.Name + 1 on indexed tech_book.name.
+- statement: SELECT * FROM tech_book T WHERE T.Name + 1 > 5;
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"Name\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Test (codex P2): UPDATE SET with scalar subquery — inner violation must flag.
+- statement: UPDATE tech_book SET creator = (SELECT customer_name FROM orders WHERE ABS(amount) > 0 LIMIT 1) WHERE id = 1;
+ 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 (codex P2): UPDATE SET with calculation inside subquery — should flag.
+- statement: UPDATE tech_book SET creator = (SELECT customer_name FROM orders WHERE customer_name + 'x' = 'ax' LIMIT 1);
+ want:
+ - status: 2
+ code: 234
+ title: STATEMENT_WHERE_DISALLOW_FUNCTIONS_AND_CALCULATIONS
+ content: "Calculation is applied to indexed column \"customer_name\" in the WHERE clause, which prevents index usage"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+
+# Documented limitation: outer WHERE over a derived-table / CTE alias is NOT flagged
+# because column lineage through projections is not traced. MySQL may still push the
+# predicate back to the base table, but doing so would require significant column-
+# lineage tracking. Prefer false negatives over false positives for this linter.
+- statement: SELECT * FROM (SELECT name FROM tech_book) s WHERE UPPER(s.name) = 'x';
+
+- statement: |-
+ WITH t AS (SELECT name FROM tech_book)
+ SELECT * FROM t WHERE UPPER(name) = 'x';
+
+# Test (codex P2): UPDATE with derived-table subquery — inner WHERE violation should flag.
+- statement: UPDATE tech_book t JOIN (SELECT order_id FROM orders WHERE ABS(amount) > 0) s ON t.id = s.order_id SET t.creator = 'x';
+ 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 (codex P2): DELETE with derived-table subquery — inner WHERE violation should flag.
+- statement: DELETE t FROM tech_book t JOIN (SELECT order_id FROM orders WHERE UPPER(customer_name) = 'X') s ON t.id = s.order_id;
+ 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 (adversarial): correlated EXISTS subquery — inner WHERE references outer indexed column.
+- 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 (adversarial): correlated scalar subquery — inner WHERE references outer indexed column.
+- statement: SELECT (SELECT COUNT(*) FROM orders o WHERE ABS(t.id) > 0) FROM tech_book t;
+ 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 (codex P2): INSERT VALUES with scalar subquery — inner violation should flag.
+- statement: INSERT INTO tech_book (id, name, creator) VALUES ((SELECT id FROM tech_book WHERE ABS(id) > 0 LIMIT 1), 'n', 'c');
+ 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 (codex P2): CREATE VIEW with function on indexed column in WHERE — should flag.
+- statement: CREATE VIEW v AS 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 (codex P2): ALTER VIEW with calculation on indexed column in WHERE — should flag.
+- statement: ALTER 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
+
+# Test (codex P2): correlated subquery — unqualified `name` resolves to inner (orders.name non-indexed), should NOT flag.
+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM orders o WHERE UPPER(name) = 'x');
+
+# Test: INSERT ... SET with scalar subquery — inner violation should flag.
+- statement: INSERT INTO tech_book SET id = (SELECT order_id FROM orders WHERE ABS(amount) > 0 LIMIT 1), name = 'n', creator = 'c';
+ 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 DUPLICATE KEY UPDATE with scalar subquery — inner violation should flag.
+- statement: INSERT INTO tech_book (id, name, creator) VALUES (1, 'n', 'c') ON DUPLICATE KEY UPDATE creator = (SELECT customer_name FROM orders WHERE UPPER(customer_name) = 'X' LIMIT 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
+
+# Test: same-named unaliased tables from different databases — ambiguity marked, should NOT flag.
+- statement: SELECT * FROM otherdb.tech_book, tech_book WHERE UPPER(tech_book.name) = 'x';
+
+# Test (codex P2): correlated unqualified outer column — inner (orders) has no `id`, should resolve to outer t.id and flag.
+- 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 (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);
+
+# Test (truth table R5): qualified ref to unknown alias — should NOT flag.
+- statement: SELECT * FROM tech_book WHERE ABS(unknown.id) > 0;
+
+# Test (truth table R4): qualified correlated ref to outer non-indexed column — should NOT flag.
+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM orders o WHERE ABS(t.creator) > 0);
+
+# Test (codex P2): inner derived-table alias shadows outer — qualified t.id resolves to inner derived, should NOT flag outer tech_book.id.
+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM (SELECT order_id AS id FROM orders) t WHERE ABS(t.id) > 0);
+
+# Test (codex P2): inner CTE ref with qualified correlated outer ref — t.id is outer, should flag.
+- statement: |-
+ WITH c AS (SELECT order_id AS id FROM orders)
+ SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM c WHERE ABS(t.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: 2
+ column: 0
+ endposition: null
+
+# Test (codex P2): inner derived table with qualified correlated outer ref — t.id is outer, should flag.
+- statement: SELECT * FROM tech_book t WHERE EXISTS (SELECT 1 FROM (SELECT order_id FROM orders) d WHERE ABS(t.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
diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.go
index db8170ed90..067a1f2829 100644
--- a/backend/plugin/advisor/utils_for_tests.go
+++ b/backend/plugin/advisor/utils_for_tests.go
@@ -58,6 +58,10 @@ var (
Name: "name",
Type: "varchar(255)",
},
+ {
+ Name: "creator",
+ Type: "varchar(255)",
+ },
},
Indexes: []*storepb.IndexMetadata{
{
@@ -77,6 +81,34 @@ var (
},
},
},
+ {
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "order_id", Type: "int"},
+ {Name: "customer_name", Type: "varchar(255)"},
+ {Name: "amount", Type: "decimal(10,2)"},
+ {Name: "note", Type: "varchar(255)"},
+ // name also exists here (non-indexed) so tests can verify
+ // qualified lookups distinguish tech_book.name (indexed) from orders.name.
+ {Name: "name", Type: "varchar(255)"},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "PRIMARY",
+ Expressions: []string{"order_id"},
+ Unique: true,
+ Primary: true,
+ },
+ {
+ Name: "idx_customer",
+ Expressions: []string{"customer_name"},
+ },
+ {
+ Name: "idx_amount",
+ Expressions: []string{"amount"},
+ },
+ },
+ },
},
},
},
@@ -127,6 +159,15 @@ var (
Tables: []*storepb.TableMetadata{
{
Name: "pokes",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "c1", Type: "int"},
+ {Name: "c2", Type: "int"},
+ {Name: "c3", Type: "int"},
+ {Name: "c10", Type: "int"},
+ {Name: "c20", Type: "int"},
+ {Name: "foo", Type: "int"},
+ {Name: "bar", Type: "int"},
+ },
Indexes: []*storepb.IndexMetadata{
{
Name: "idx_0",
@@ -138,10 +179,44 @@ var (
},
},
},
- {Name: "pokes2"},
+ {
+ Name: "pokes2",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "foo", Type: "int"},
+ {Name: "bar", Type: "int"},
+ // c1 also exists here (non-indexed) so tests can verify
+ // qualified lookups distinguish pokes.c1 (indexed) from pokes2.c1.
+ {Name: "c1", Type: "int"},
+ },
+ },
{Name: "pokes3"},
},
},
+ {
+ Name: "sales",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "order_id", Type: "int"},
+ {Name: "customer_id", Type: "int"},
+ {Name: "note", Type: "varchar"},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "PRIMARY",
+ Expressions: []string{"order_id"},
+ Unique: true,
+ Primary: true,
+ },
+ {
+ Name: "idx_customer",
+ Expressions: []string{"customer_id"},
+ },
+ },
+ },
+ },
+ },
},
}
)