Skip to main content

codeint_lang_sql/schema/
rules.rs

1use std::collections::BTreeSet;
2
3use codeint_model::HazardLine;
4use sqlparser::ast::{
5    AssignmentTarget, Delete, Expr, FromTable, GroupByExpr, Insert, Join, JoinConstraint,
6    JoinOperator, Merge, ObjectName, OrderBy, OrderByExpr, OrderByKind, Query, Select, SelectItem,
7    SetExpr, Statement, TableFactor, TableObject, TableWithJoins, Update, UpdateTableFromKind,
8};
9use sqlparser::keywords::Keyword;
10use sqlparser::tokenizer::TokenWithSpan;
11
12use crate::flagged::expr_contains_aggregate;
13use crate::schema::artifact::{
14    ClauseKind, ConstrainedRef, SchemaCheck, ScopeDef, SqlFileArtifact, TableBindingDef,
15    evaluate_artifact_checks,
16};
17use crate::schema::expr::{
18    ExprContext, ExprExtractor, collect_conjunct_refs, extract_expr, extract_filter_expr,
19    push_constrained_ref, resolve_fallback_line,
20};
21use crate::schema::scope::collect_select_aliases;
22use crate::schema::types::{SqlSchema, normalize_ident, object_name_last_ident, split_object_name};
23use crate::{ParsedSqlStatement, SqlDialect};
24
25const SCHEMA_RULES: &[&str] = &[
26    "filter-on-unindexed-column",
27    "join-on-unindexed-column",
28    "order-by-unindexed-column",
29    "text-compared-to-number",
30    "unknown-column",
31];
32
33pub fn schema_hazard_rules() -> impl Iterator<Item = &'static str> {
34    SCHEMA_RULES.iter().copied()
35}
36
37pub fn collect_schema_hazards(
38    statements: &[ParsedSqlStatement],
39    schema: &SqlSchema,
40    dialect: SqlDialect,
41) -> Vec<HazardLine> {
42    if schema.is_empty() {
43        return Vec::new();
44    }
45    let (scopes, checks) = extract_scopes_and_checks(statements, dialect);
46    let artifact = SqlFileArtifact {
47        is_down_migration: false,
48        ddl_ops: Vec::new(),
49        scopes,
50        checks,
51    };
52    evaluate_artifact_checks(&artifact, schema)
53}
54
55pub(crate) fn extract_scopes_and_checks(
56    statements: &[ParsedSqlStatement],
57    dialect: SqlDialect,
58) -> (Vec<ScopeDef>, Vec<SchemaCheck>) {
59    let mut scopes = Vec::new();
60    let mut checks = Vec::new();
61    for parsed in statements {
62        let mut extractor = SchemaCheckExtractor {
63            dialect,
64            tokens: &parsed.tokens,
65            stmt_start_line: parsed.start_line,
66            scopes: &mut scopes,
67            checks: &mut checks,
68        };
69        extractor.visit_statement(&parsed.statement);
70    }
71    (scopes, checks)
72}
73
74struct SchemaCheckExtractor<'a> {
75    dialect: SqlDialect,
76    tokens: &'a [TokenWithSpan],
77    stmt_start_line: u32,
78    scopes: &'a mut Vec<ScopeDef>,
79    checks: &'a mut Vec<SchemaCheck>,
80}
81
82impl ExprExtractor for SchemaCheckExtractor<'_> {
83    fn tokens(&self) -> &[TokenWithSpan] {
84        self.tokens
85    }
86
87    fn stmt_start_line(&self) -> u32 {
88        self.stmt_start_line
89    }
90
91    fn dialect(&self) -> SqlDialect {
92        self.dialect
93    }
94
95    fn push_check(&mut self, check: SchemaCheck) {
96        self.checks.push(check);
97    }
98
99    fn visit_subquery(&mut self, query: &Query, parent_scope: u32, parent_ctes: &BTreeSet<String>) {
100        self.visit_query_in_parent(query, parent_scope, parent_ctes);
101    }
102}
103
104impl SchemaCheckExtractor<'_> {
105    fn alloc_scope(&mut self, parent: Option<u32>, bindings: Vec<TableBindingDef>) -> u32 {
106        let depth = parent
107            .and_then(|idx| self.scopes.get(idx as usize))
108            .map_or(0, |scope| scope.depth + 1);
109        let id = self.scopes.len() as u32;
110        self.scopes.push(ScopeDef {
111            depth,
112            parent,
113            bindings,
114        });
115        id
116    }
117
118    fn visit_statement(&mut self, stmt: &Statement) {
119        match stmt {
120            Statement::Query(query) => self.visit_query(query, BTreeSet::new()),
121            Statement::Explain { statement, .. } => self.visit_statement(statement),
122            Statement::Insert(insert) => self.visit_insert(insert),
123            Statement::Update(update) => self.visit_update(update),
124            Statement::Delete(delete) => self.visit_delete(delete),
125            Statement::Merge(merge) => self.visit_merge(merge),
126            Statement::CreateView(view) => self.visit_query(&view.query, BTreeSet::new()),
127            Statement::CreateTable(table) => {
128                if let Some(query) = &table.query {
129                    self.visit_query(query, BTreeSet::new());
130                }
131            }
132            _ => {}
133        }
134    }
135
136    fn visit_insert(&mut self, insert: &Insert) {
137        if let TableObject::TableName(table_name) = &insert.table
138            && let Some((table_schema, name)) = split_object_name(table_name)
139        {
140            for col_obj in &insert.columns {
141                self.record_target_column(&table_schema, &name, col_obj);
142            }
143        }
144        if let Some(source) = &insert.source {
145            self.visit_query(source, BTreeSet::new());
146        }
147    }
148
149    fn visit_update(&mut self, update: &Update) {
150        let empty = BTreeSet::new();
151        let mut bindings = Vec::new();
152        collect_table_with_joins_bindings(&update.table, &empty, &mut bindings);
153        if let Some(from) = &update.from {
154            let from_tables = match from {
155                UpdateTableFromKind::BeforeSet(tables) | UpdateTableFromKind::AfterSet(tables) => {
156                    tables
157                }
158            };
159            for twj in from_tables {
160                collect_table_with_joins_bindings(twj, &empty, &mut bindings);
161            }
162        }
163        let scope_id = self.alloc_scope(None, bindings);
164        let target_table = extract_single_factor_table(&update.table.relation, &empty);
165        self.visit_table_with_joins_subqueries(&update.table, scope_id, &empty);
166        self.check_table_with_joins_conditions(&update.table, scope_id, &empty);
167
168        for assign in &update.assignments {
169            if let Some((ref table_schema, ref table_name)) = target_table {
170                self.record_assignment_target(table_schema, table_name, &assign.target);
171            }
172            extract_expr(
173                self,
174                &assign.value,
175                ExprContext::new(scope_id, &empty, &empty, ClauseKind::General, &[]),
176            );
177        }
178        self.check_dml_tail(
179            update.selection.as_ref(),
180            update.returning.as_deref(),
181            &update.order_by,
182            scope_id,
183            &empty,
184        );
185    }
186
187    fn visit_delete(&mut self, delete: &Delete) {
188        let empty = BTreeSet::new();
189        let mut bindings = Vec::new();
190        let from_tables = match &delete.from {
191            FromTable::WithFromKeyword(tables) | FromTable::WithoutKeyword(tables) => tables,
192        };
193        for twj in from_tables {
194            collect_table_with_joins_bindings(twj, &empty, &mut bindings);
195        }
196        if let Some(using) = &delete.using {
197            for twj in using {
198                collect_table_with_joins_bindings(twj, &empty, &mut bindings);
199            }
200        }
201        let scope_id = self.alloc_scope(None, bindings);
202        for twj in from_tables {
203            self.visit_table_with_joins_subqueries(twj, scope_id, &empty);
204            self.check_table_with_joins_conditions(twj, scope_id, &empty);
205        }
206        self.check_dml_tail(
207            delete.selection.as_ref(),
208            delete.returning.as_deref(),
209            &delete.order_by,
210            scope_id,
211            &empty,
212        );
213    }
214
215    fn check_dml_tail(
216        &mut self,
217        selection: Option<&Expr>,
218        returning: Option<&[SelectItem]>,
219        order_by: &[OrderByExpr],
220        scope_id: u32,
221        cte_names: &BTreeSet<String>,
222    ) {
223        let empty = BTreeSet::new();
224        let mut order_prefix = Vec::new();
225        if let Some(filter) = selection {
226            extract_filter_expr(
227                self,
228                filter,
229                ExprContext::new(scope_id, cte_names, &empty, ClauseKind::Filter, &[]),
230            );
231            collect_conjunct_refs(filter, &empty, true, &mut order_prefix);
232        }
233        if let Some(items) = returning {
234            self.check_select_items(items, scope_id, cte_names, &empty);
235        }
236        self.check_order_by_exprs(order_by, scope_id, cte_names, &empty, order_prefix, false);
237    }
238
239    fn visit_merge(&mut self, merge: &Merge) {
240        let empty = BTreeSet::new();
241        let mut bindings = Vec::new();
242        collect_table_factor_bindings(&merge.table, &empty, &mut bindings);
243        collect_table_factor_bindings(&merge.source, &empty, &mut bindings);
244        let scope_id = self.alloc_scope(None, bindings);
245        self.visit_table_factor_subqueries(&merge.table, scope_id, &empty);
246        self.visit_table_factor_subqueries(&merge.source, scope_id, &empty);
247        extract_filter_expr(
248            self,
249            &merge.on,
250            ExprContext::new(scope_id, &empty, &empty, ClauseKind::JoinOn, &[]),
251        );
252        for clause in &merge.clauses {
253            if let Some(predicate) = &clause.predicate {
254                extract_filter_expr(
255                    self,
256                    predicate,
257                    ExprContext::new(scope_id, &empty, &empty, ClauseKind::Filter, &[]),
258                );
259            }
260        }
261    }
262
263    fn visit_query(&mut self, query: &Query, outer_ctes: BTreeSet<String>) {
264        let cte_names = self.collect_and_visit_ctes(query, outer_ctes);
265        self.visit_set_expr(&query.body, query.order_by.as_ref(), cte_names, None);
266    }
267
268    fn visit_query_in_parent(
269        &mut self,
270        query: &Query,
271        parent_scope: u32,
272        parent_ctes: &BTreeSet<String>,
273    ) {
274        let cte_names = self.collect_and_visit_ctes(query, parent_ctes.clone());
275        self.visit_set_expr(
276            &query.body,
277            query.order_by.as_ref(),
278            cte_names,
279            Some(parent_scope),
280        );
281    }
282
283    fn collect_and_visit_ctes(
284        &mut self,
285        query: &Query,
286        mut cte_names: BTreeSet<String>,
287    ) -> BTreeSet<String> {
288        if let Some(with) = &query.with {
289            for cte in &with.cte_tables {
290                let name = normalize_ident(&cte.alias.name);
291                let mut visible = cte_names.clone();
292                if with.recursive {
293                    visible.insert(name.clone());
294                }
295                self.visit_query(&cte.query, visible);
296                cte_names.insert(name);
297            }
298        }
299        cte_names
300    }
301
302    fn visit_set_expr(
303        &mut self,
304        set_expr: &SetExpr,
305        order_by: Option<&OrderBy>,
306        cte_names: BTreeSet<String>,
307        parent_scope: Option<u32>,
308    ) {
309        let mut stack = vec![(set_expr, order_by)];
310        while let Some((current, current_order_by)) = stack.pop() {
311            match current {
312                SetExpr::Select(select) => {
313                    self.visit_select(select, current_order_by, &cte_names, parent_scope);
314                }
315                SetExpr::Query(inner) => match parent_scope {
316                    Some(parent) => self.visit_query_in_parent(inner, parent, &cte_names),
317                    None => self.visit_query(inner, cte_names.clone()),
318                },
319                SetExpr::SetOperation { left, right, .. } => {
320                    stack.push((right, None));
321                    stack.push((left, None));
322                }
323                SetExpr::Insert(stmt)
324                | SetExpr::Update(stmt)
325                | SetExpr::Delete(stmt)
326                | SetExpr::Merge(stmt) => self.visit_statement(stmt),
327                _ => {}
328            }
329        }
330    }
331
332    fn visit_select(
333        &mut self,
334        select: &Select,
335        order_by: Option<&OrderBy>,
336        cte_names: &BTreeSet<String>,
337        parent_scope: Option<u32>,
338    ) {
339        let mut bindings = Vec::new();
340        for twj in &select.from {
341            collect_table_with_joins_bindings(twj, cte_names, &mut bindings);
342        }
343        let scope_id = self.alloc_scope(parent_scope, bindings);
344        let empty = BTreeSet::new();
345        let select_aliases = collect_select_aliases(&select.projection);
346
347        for twj in &select.from {
348            self.visit_table_with_joins_subqueries(twj, scope_id, cte_names);
349            self.check_table_with_joins_conditions(twj, scope_id, cte_names);
350        }
351        self.check_select_items(&select.projection, scope_id, cte_names, &empty);
352        if let Some(prewhere) = &select.prewhere {
353            extract_filter_expr(
354                self,
355                prewhere,
356                ExprContext::new(scope_id, cte_names, &empty, ClauseKind::Filter, &[]),
357            );
358        }
359        if let Some(selection) = &select.selection {
360            extract_filter_expr(
361                self,
362                selection,
363                ExprContext::new(scope_id, cte_names, &empty, ClauseKind::Filter, &[]),
364            );
365        }
366        self.check_select_post_clauses(select, order_by, scope_id, cte_names, &select_aliases);
367    }
368
369    fn check_select_post_clauses(
370        &mut self,
371        select: &Select,
372        order_by: Option<&OrderBy>,
373        scope_id: u32,
374        cte_names: &BTreeSet<String>,
375        select_aliases: &BTreeSet<String>,
376    ) {
377        if let GroupByExpr::Expressions(exprs, _) = &select.group_by {
378            let ctx = ExprContext::new(
379                scope_id,
380                cte_names,
381                select_aliases,
382                ClauseKind::General,
383                &[],
384            );
385            for expr in exprs {
386                extract_expr(self, expr, ctx);
387            }
388        }
389        if let Some(having) = &select.having {
390            extract_expr(
391                self,
392                having,
393                ExprContext::new(
394                    scope_id,
395                    cte_names,
396                    select_aliases,
397                    ClauseKind::General,
398                    &[],
399                ),
400            );
401        }
402        if let Some(qualify) = &select.qualify {
403            extract_expr(
404                self,
405                qualify,
406                ExprContext::new(
407                    scope_id,
408                    cte_names,
409                    select_aliases,
410                    ClauseKind::General,
411                    &[],
412                ),
413            );
414        }
415        if let Some(order) = order_by
416            && let OrderByKind::Expressions(exprs) = &order.kind
417        {
418            let order_prefix = collect_select_order_prefix(select);
419            let grouped = select_has_grouping_or_aggregates(select);
420            self.check_order_by_exprs(
421                exprs,
422                scope_id,
423                cte_names,
424                select_aliases,
425                order_prefix,
426                grouped,
427            );
428        }
429    }
430
431    fn check_select_items(
432        &mut self,
433        items: &[SelectItem],
434        scope_id: u32,
435        cte_names: &BTreeSet<String>,
436        excluded: &BTreeSet<String>,
437    ) {
438        let ctx = ExprContext::new(scope_id, cte_names, excluded, ClauseKind::General, &[]);
439        for item in items {
440            match item {
441                SelectItem::UnnamedExpr(expr)
442                | SelectItem::ExprWithAlias { expr, .. }
443                | SelectItem::ExprWithAliases { expr, .. } => {
444                    extract_expr(self, expr, ctx);
445                }
446                SelectItem::QualifiedWildcard(_, _) | SelectItem::Wildcard(_) => {}
447            }
448        }
449    }
450
451    fn check_order_by_exprs(
452        &mut self,
453        exprs: &[OrderByExpr],
454        scope_id: u32,
455        cte_names: &BTreeSet<String>,
456        excluded: &BTreeSet<String>,
457        mut prefix: Vec<ConstrainedRef>,
458        in_grouped_query: bool,
459    ) {
460        for order_expr in exprs {
461            let ctx =
462                ExprContext::order_by(scope_id, cte_names, excluded, &prefix, in_grouped_query);
463            extract_expr(self, &order_expr.expr, ctx);
464            push_constrained_ref(&order_expr.expr, excluded, &mut prefix);
465        }
466    }
467
468    fn visit_table_with_joins_subqueries(
469        &mut self,
470        twj: &TableWithJoins,
471        scope_id: u32,
472        cte_names: &BTreeSet<String>,
473    ) {
474        self.visit_table_factor_subqueries(&twj.relation, scope_id, cte_names);
475        for join in &twj.joins {
476            self.visit_table_factor_subqueries(&join.relation, scope_id, cte_names);
477        }
478    }
479
480    fn visit_table_factor_subqueries(
481        &mut self,
482        factor: &TableFactor,
483        scope_id: u32,
484        cte_names: &BTreeSet<String>,
485    ) {
486        match factor {
487            TableFactor::Derived {
488                lateral, subquery, ..
489            } => {
490                if *lateral {
491                    self.visit_query_in_parent(subquery, scope_id, cte_names);
492                } else {
493                    self.visit_query(subquery, cte_names.clone());
494                }
495            }
496            TableFactor::NestedJoin {
497                table_with_joins, ..
498            } => self.visit_table_with_joins_subqueries(table_with_joins, scope_id, cte_names),
499            _ => {}
500        }
501    }
502
503    fn check_table_with_joins_conditions(
504        &mut self,
505        twj: &TableWithJoins,
506        scope_id: u32,
507        cte_names: &BTreeSet<String>,
508    ) {
509        if let TableFactor::NestedJoin {
510            table_with_joins, ..
511        } = &twj.relation
512        {
513            self.check_table_with_joins_conditions(table_with_joins, scope_id, cte_names);
514        }
515        let mut left_bindings = Vec::new();
516        collect_table_factor_bindings(&twj.relation, cte_names, &mut left_bindings);
517        for join in &twj.joins {
518            if let TableFactor::NestedJoin {
519                table_with_joins, ..
520            } = &join.relation
521            {
522                self.check_table_with_joins_conditions(table_with_joins, scope_id, cte_names);
523            }
524            self.check_join(join, &left_bindings, scope_id, cte_names);
525            collect_table_factor_bindings(&join.relation, cte_names, &mut left_bindings);
526        }
527    }
528
529    fn check_join(
530        &mut self,
531        join: &Join,
532        left_bindings: &[TableBindingDef],
533        full_scope: u32,
534        cte_names: &BTreeSet<String>,
535    ) {
536        let empty = BTreeSet::new();
537        match &join.join_operator {
538            JoinOperator::Join(constraint)
539            | JoinOperator::Inner(constraint)
540            | JoinOperator::Left(constraint)
541            | JoinOperator::LeftOuter(constraint)
542            | JoinOperator::Right(constraint)
543            | JoinOperator::RightOuter(constraint)
544            | JoinOperator::FullOuter(constraint)
545            | JoinOperator::CrossJoin(constraint)
546            | JoinOperator::Semi(constraint)
547            | JoinOperator::LeftSemi(constraint)
548            | JoinOperator::RightSemi(constraint)
549            | JoinOperator::Anti(constraint)
550            | JoinOperator::LeftAnti(constraint)
551            | JoinOperator::RightAnti(constraint) => {
552                self.check_join_constraint(
553                    constraint,
554                    &join.relation,
555                    left_bindings,
556                    full_scope,
557                    cte_names,
558                );
559            }
560            JoinOperator::AsOf {
561                match_condition,
562                constraint,
563            } => {
564                extract_filter_expr(
565                    self,
566                    match_condition,
567                    ExprContext::new(full_scope, cte_names, &empty, ClauseKind::JoinOn, &[]),
568                );
569                self.check_join_constraint(
570                    constraint,
571                    &join.relation,
572                    left_bindings,
573                    full_scope,
574                    cte_names,
575                );
576            }
577            _ => {}
578        }
579    }
580
581    fn check_join_constraint(
582        &mut self,
583        constraint: &JoinConstraint,
584        right_relation: &TableFactor,
585        left_bindings: &[TableBindingDef],
586        full_scope: u32,
587        cte_names: &BTreeSet<String>,
588    ) {
589        let empty = BTreeSet::new();
590        match constraint {
591            JoinConstraint::On(expr) => {
592                extract_filter_expr(
593                    self,
594                    expr,
595                    ExprContext::new(full_scope, cte_names, &empty, ClauseKind::JoinOn, &[]),
596                );
597            }
598            JoinConstraint::Using(columns) | JoinConstraint::UsingAlias(columns, _) => {
599                let left_scope = self.alloc_scope(None, left_bindings.to_vec());
600                let right_table = extract_single_factor_table(right_relation, cte_names);
601                let using_cols: Vec<String> =
602                    columns.iter().filter_map(object_name_last_ident).collect();
603                for col_obj in columns {
604                    let Some(column) = object_name_last_ident(col_obj) else {
605                        continue;
606                    };
607                    let line =
608                        self.resolve_object_name_line(col_obj, &column, Some(Keyword::USING));
609                    self.checks.push(SchemaCheck::UsingColumn {
610                        left_scope,
611                        right_table: right_table.clone(),
612                        column,
613                        using_cols: using_cols.clone(),
614                        line,
615                    });
616                }
617            }
618            JoinConstraint::Natural | JoinConstraint::None => {}
619        }
620    }
621
622    fn record_assignment_target(
623        &mut self,
624        table_schema: &Option<String>,
625        table_name: &str,
626        target: &AssignmentTarget,
627    ) {
628        match target {
629            AssignmentTarget::ColumnName(col_obj) => {
630                self.record_target_column(table_schema, table_name, col_obj);
631            }
632            AssignmentTarget::Tuple(cols) => {
633                for col_obj in cols {
634                    self.record_target_column(table_schema, table_name, col_obj);
635                }
636            }
637        }
638    }
639
640    fn record_target_column(
641        &mut self,
642        table_schema: &Option<String>,
643        table_name: &str,
644        col_obj: &ObjectName,
645    ) {
646        let Some(column) = object_name_last_ident(col_obj) else {
647            return;
648        };
649        let line = self.resolve_object_name_line(col_obj, &column, None);
650        self.checks.push(SchemaCheck::TargetColumn {
651            table_schema: table_schema.clone(),
652            table_name: table_name.to_owned(),
653            column,
654            line,
655        });
656    }
657
658    fn resolve_object_name_line(
659        &self,
660        obj: &ObjectName,
661        ident_hint: &str,
662        keyword_hint: Option<Keyword>,
663    ) -> u32 {
664        let span_line = crate::ast_loc::object_name_start_loc(obj).line as u32;
665        if span_line > 0 {
666            return span_line;
667        }
668        resolve_fallback_line(
669            self.tokens,
670            self.stmt_start_line,
671            Some(ident_hint),
672            keyword_hint,
673        )
674    }
675}
676
677fn collect_table_with_joins_bindings(
678    twj: &TableWithJoins,
679    cte_names: &BTreeSet<String>,
680    out: &mut Vec<TableBindingDef>,
681) {
682    collect_table_factor_bindings(&twj.relation, cte_names, out);
683    for join in &twj.joins {
684        collect_table_factor_bindings(&join.relation, cte_names, out);
685    }
686}
687
688fn collect_table_factor_bindings(
689    factor: &TableFactor,
690    cte_names: &BTreeSet<String>,
691    out: &mut Vec<TableBindingDef>,
692) {
693    match factor {
694        TableFactor::Table {
695            name, alias, args, ..
696        } => {
697            let alias_name = alias.as_ref().map(|a| normalize_ident(&a.name));
698            if args.is_some() {
699                out.push(TableBindingDef {
700                    schema: None,
701                    table_name: None,
702                    alias: alias_name,
703                    resolvable: false,
704                });
705                return;
706            }
707            let Some((table_schema, table_name)) = split_object_name(name) else {
708                out.push(TableBindingDef {
709                    schema: None,
710                    table_name: None,
711                    alias: alias_name,
712                    resolvable: false,
713                });
714                return;
715            };
716            let is_cte = table_schema.is_none() && cte_names.contains(&table_name);
717            out.push(TableBindingDef {
718                schema: table_schema,
719                table_name: Some(table_name),
720                alias: alias_name,
721                resolvable: !is_cte,
722            });
723        }
724        TableFactor::Derived { alias, .. } => {
725            out.push(TableBindingDef {
726                schema: None,
727                table_name: None,
728                alias: alias.as_ref().map(|a| normalize_ident(&a.name)),
729                resolvable: false,
730            });
731        }
732        TableFactor::NestedJoin {
733            table_with_joins, ..
734        } => collect_table_with_joins_bindings(table_with_joins, cte_names, out),
735        _ => {
736            out.push(TableBindingDef {
737                schema: None,
738                table_name: None,
739                alias: None,
740                resolvable: false,
741            });
742        }
743    }
744}
745
746fn extract_single_factor_table(
747    factor: &TableFactor,
748    cte_names: &BTreeSet<String>,
749) -> Option<(Option<String>, String)> {
750    let TableFactor::Table {
751        name, args: None, ..
752    } = factor
753    else {
754        return None;
755    };
756    let (table_schema, table_name) = split_object_name(name)?;
757    if table_schema.is_none() && cte_names.contains(&table_name) {
758        return None;
759    }
760    Some((table_schema, table_name))
761}
762
763fn select_has_grouping_or_aggregates(select: &Select) -> bool {
764    let has_group_by = match &select.group_by {
765        GroupByExpr::All(_) => true,
766        GroupByExpr::Expressions(exprs, _) => !exprs.is_empty(),
767    };
768    if has_group_by {
769        return true;
770    }
771    select.projection.iter().any(|item| match item {
772        SelectItem::UnnamedExpr(expr)
773        | SelectItem::ExprWithAlias { expr, .. }
774        | SelectItem::ExprWithAliases { expr, .. } => expr_contains_aggregate(expr),
775        SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _) => false,
776    })
777}
778
779fn collect_select_order_prefix(select: &Select) -> Vec<ConstrainedRef> {
780    let empty = BTreeSet::new();
781    let mut prefix = Vec::new();
782    if let Some(prewhere) = &select.prewhere {
783        collect_conjunct_refs(prewhere, &empty, true, &mut prefix);
784    }
785    if let Some(selection) = &select.selection {
786        collect_conjunct_refs(selection, &empty, true, &mut prefix);
787    }
788    for twj in &select.from {
789        collect_inner_join_order_prefix(twj, &empty, &mut prefix);
790    }
791    prefix
792}
793
794fn collect_inner_join_order_prefix(
795    twj: &TableWithJoins,
796    excluded: &BTreeSet<String>,
797    prefix: &mut Vec<ConstrainedRef>,
798) {
799    if let TableFactor::NestedJoin {
800        table_with_joins, ..
801    } = &twj.relation
802    {
803        collect_inner_join_order_prefix(table_with_joins, excluded, prefix);
804    }
805    for join in &twj.joins {
806        if let TableFactor::NestedJoin {
807            table_with_joins, ..
808        } = &join.relation
809        {
810            collect_inner_join_order_prefix(table_with_joins, excluded, prefix);
811        }
812        if let JoinOperator::Inner(JoinConstraint::On(expr))
813        | JoinOperator::Join(JoinConstraint::On(expr))
814        | JoinOperator::StraightJoin(JoinConstraint::On(expr)) = &join.join_operator
815        {
816            collect_conjunct_refs(expr, excluded, true, prefix);
817        }
818    }
819}