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::{projection_contains_aggregate, select_has_group_by};
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, self.dialect)
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, self.dialect, &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, self.dialect, &mut bindings);
161 }
162 }
163 let scope_id = self.alloc_scope(None, bindings);
164 let target_table =
165 extract_single_factor_table(&update.table.relation, &empty, self.dialect);
166 self.visit_table_with_joins_subqueries(&update.table, scope_id, &empty);
167 self.check_table_with_joins_conditions(&update.table, scope_id, &empty);
168
169 for assign in &update.assignments {
170 if let Some((ref table_schema, ref table_name)) = target_table {
171 self.record_assignment_target(table_schema, table_name, &assign.target);
172 }
173 extract_expr(
174 self,
175 &assign.value,
176 ExprContext::new(scope_id, &empty, &empty, ClauseKind::General, &[]),
177 );
178 }
179 self.check_dml_tail(
180 update.selection.as_ref(),
181 update.returning.as_deref(),
182 &update.order_by,
183 scope_id,
184 &empty,
185 );
186 }
187
188 fn visit_delete(&mut self, delete: &Delete) {
189 let empty = BTreeSet::new();
190 let mut bindings = Vec::new();
191 let from_tables = match &delete.from {
192 FromTable::WithFromKeyword(tables) | FromTable::WithoutKeyword(tables) => tables,
193 };
194 for twj in from_tables {
195 collect_table_with_joins_bindings(twj, &empty, self.dialect, &mut bindings);
196 }
197 if let Some(using) = &delete.using {
198 for twj in using {
199 collect_table_with_joins_bindings(twj, &empty, self.dialect, &mut bindings);
200 }
201 }
202 let scope_id = self.alloc_scope(None, bindings);
203 for twj in from_tables {
204 self.visit_table_with_joins_subqueries(twj, scope_id, &empty);
205 self.check_table_with_joins_conditions(twj, scope_id, &empty);
206 }
207 self.check_dml_tail(
208 delete.selection.as_ref(),
209 delete.returning.as_deref(),
210 &delete.order_by,
211 scope_id,
212 &empty,
213 );
214 }
215
216 fn check_dml_tail(
217 &mut self,
218 selection: Option<&Expr>,
219 returning: Option<&[SelectItem]>,
220 order_by: &[OrderByExpr],
221 scope_id: u32,
222 cte_names: &BTreeSet<String>,
223 ) {
224 let empty = BTreeSet::new();
225 let mut order_prefix = Vec::new();
226 if let Some(filter) = selection {
227 extract_filter_expr(
228 self,
229 filter,
230 ExprContext::new(scope_id, cte_names, &empty, ClauseKind::Filter, &[]),
231 );
232 collect_conjunct_refs(filter, &empty, true, self.dialect, &mut order_prefix);
233 }
234 if let Some(items) = returning {
235 self.check_select_items(items, scope_id, cte_names, &empty);
236 }
237 self.check_order_by_exprs(order_by, scope_id, cte_names, &empty, order_prefix, false);
238 }
239
240 fn visit_merge(&mut self, merge: &Merge) {
241 let empty = BTreeSet::new();
242 let mut bindings = Vec::new();
243 collect_table_factor_bindings(&merge.table, &empty, self.dialect, &mut bindings);
244 collect_table_factor_bindings(&merge.source, &empty, self.dialect, &mut bindings);
245 let scope_id = self.alloc_scope(None, bindings);
246 self.visit_table_factor_subqueries(&merge.table, scope_id, &empty);
247 self.visit_table_factor_subqueries(&merge.source, scope_id, &empty);
248 extract_filter_expr(
249 self,
250 &merge.on,
251 ExprContext::new(scope_id, &empty, &empty, ClauseKind::JoinOn, &[]),
252 );
253 for clause in &merge.clauses {
254 if let Some(predicate) = &clause.predicate {
255 extract_filter_expr(
256 self,
257 predicate,
258 ExprContext::new(scope_id, &empty, &empty, ClauseKind::Filter, &[]),
259 );
260 }
261 }
262 }
263
264 fn visit_query(&mut self, query: &Query, outer_ctes: BTreeSet<String>) {
265 let cte_names = self.collect_and_visit_ctes(query, outer_ctes);
266 self.visit_set_expr(&query.body, query.order_by.as_ref(), cte_names, None);
267 }
268
269 fn visit_query_in_parent(
270 &mut self,
271 query: &Query,
272 parent_scope: u32,
273 parent_ctes: &BTreeSet<String>,
274 ) {
275 let cte_names = self.collect_and_visit_ctes(query, parent_ctes.clone());
276 self.visit_set_expr(
277 &query.body,
278 query.order_by.as_ref(),
279 cte_names,
280 Some(parent_scope),
281 );
282 }
283
284 fn collect_and_visit_ctes(
285 &mut self,
286 query: &Query,
287 mut cte_names: BTreeSet<String>,
288 ) -> BTreeSet<String> {
289 if let Some(with) = &query.with {
290 for cte in &with.cte_tables {
291 let name = normalize_ident(&cte.alias.name, self.dialect);
292 let mut visible = cte_names.clone();
293 if with.recursive {
294 visible.insert(name.clone());
295 }
296 self.visit_query(&cte.query, visible);
297 cte_names.insert(name);
298 }
299 }
300 cte_names
301 }
302
303 fn visit_set_expr(
304 &mut self,
305 set_expr: &SetExpr,
306 order_by: Option<&OrderBy>,
307 cte_names: BTreeSet<String>,
308 parent_scope: Option<u32>,
309 ) {
310 let mut stack = vec![(set_expr, order_by)];
311 while let Some((current, current_order_by)) = stack.pop() {
312 match current {
313 SetExpr::Select(select) => {
314 self.visit_select(select, current_order_by, &cte_names, parent_scope);
315 }
316 SetExpr::Query(inner) => match parent_scope {
317 Some(parent) => self.visit_query_in_parent(inner, parent, &cte_names),
318 None => self.visit_query(inner, cte_names.clone()),
319 },
320 SetExpr::SetOperation { left, right, .. } => {
321 stack.push((right, None));
322 stack.push((left, None));
323 }
324 SetExpr::Insert(stmt)
325 | SetExpr::Update(stmt)
326 | SetExpr::Delete(stmt)
327 | SetExpr::Merge(stmt) => self.visit_statement(stmt),
328 _ => {}
329 }
330 }
331 }
332
333 fn visit_select(
334 &mut self,
335 select: &Select,
336 order_by: Option<&OrderBy>,
337 cte_names: &BTreeSet<String>,
338 parent_scope: Option<u32>,
339 ) {
340 let mut bindings = Vec::new();
341 for twj in &select.from {
342 collect_table_with_joins_bindings(twj, cte_names, self.dialect, &mut bindings);
343 }
344 let scope_id = self.alloc_scope(parent_scope, bindings);
345 let empty = BTreeSet::new();
346 let select_aliases = collect_select_aliases(&select.projection, self.dialect);
347
348 for twj in &select.from {
349 self.visit_table_with_joins_subqueries(twj, scope_id, cte_names);
350 self.check_table_with_joins_conditions(twj, scope_id, cte_names);
351 }
352 self.check_select_items(&select.projection, scope_id, cte_names, &empty);
353 if let Some(prewhere) = &select.prewhere {
354 extract_filter_expr(
355 self,
356 prewhere,
357 ExprContext::new(scope_id, cte_names, &empty, ClauseKind::Filter, &[]),
358 );
359 }
360 if let Some(selection) = &select.selection {
361 extract_filter_expr(
362 self,
363 selection,
364 ExprContext::new(scope_id, cte_names, &empty, ClauseKind::Filter, &[]),
365 );
366 }
367 self.check_select_post_clauses(select, order_by, scope_id, cte_names, &select_aliases);
368 }
369
370 fn check_select_post_clauses(
371 &mut self,
372 select: &Select,
373 order_by: Option<&OrderBy>,
374 scope_id: u32,
375 cte_names: &BTreeSet<String>,
376 select_aliases: &BTreeSet<String>,
377 ) {
378 if let GroupByExpr::Expressions(exprs, _) = &select.group_by {
379 let ctx = ExprContext::new(
380 scope_id,
381 cte_names,
382 select_aliases,
383 ClauseKind::General,
384 &[],
385 );
386 for expr in exprs {
387 extract_expr(self, expr, ctx);
388 }
389 }
390 if let Some(having) = &select.having {
391 extract_expr(
392 self,
393 having,
394 ExprContext::new(
395 scope_id,
396 cte_names,
397 select_aliases,
398 ClauseKind::General,
399 &[],
400 ),
401 );
402 }
403 if let Some(qualify) = &select.qualify {
404 extract_expr(
405 self,
406 qualify,
407 ExprContext::new(
408 scope_id,
409 cte_names,
410 select_aliases,
411 ClauseKind::General,
412 &[],
413 ),
414 );
415 }
416 if let Some(order) = order_by
417 && let OrderByKind::Expressions(exprs) = &order.kind
418 {
419 let order_prefix = collect_select_order_prefix(select, self.dialect);
420 let grouped = select_has_grouping_or_aggregates(select);
421 self.check_order_by_exprs(
422 exprs,
423 scope_id,
424 cte_names,
425 select_aliases,
426 order_prefix,
427 grouped,
428 );
429 }
430 }
431
432 fn check_select_items(
433 &mut self,
434 items: &[SelectItem],
435 scope_id: u32,
436 cte_names: &BTreeSet<String>,
437 excluded: &BTreeSet<String>,
438 ) {
439 let ctx = ExprContext::new(scope_id, cte_names, excluded, ClauseKind::General, &[]);
440 for item in items {
441 match item {
442 SelectItem::UnnamedExpr(expr)
443 | SelectItem::ExprWithAlias { expr, .. }
444 | SelectItem::ExprWithAliases { expr, .. } => {
445 extract_expr(self, expr, ctx);
446 }
447 SelectItem::QualifiedWildcard(_, _) | SelectItem::Wildcard(_) => {}
448 }
449 }
450 }
451
452 fn check_order_by_exprs(
453 &mut self,
454 exprs: &[OrderByExpr],
455 scope_id: u32,
456 cte_names: &BTreeSet<String>,
457 excluded: &BTreeSet<String>,
458 mut prefix: Vec<ConstrainedRef>,
459 in_grouped_query: bool,
460 ) {
461 for order_expr in exprs {
462 let ctx =
463 ExprContext::order_by(scope_id, cte_names, excluded, &prefix, in_grouped_query);
464 extract_expr(self, &order_expr.expr, ctx);
465 push_constrained_ref(&order_expr.expr, excluded, self.dialect, &mut prefix);
466 }
467 }
468
469 fn visit_table_with_joins_subqueries(
470 &mut self,
471 twj: &TableWithJoins,
472 scope_id: u32,
473 cte_names: &BTreeSet<String>,
474 ) {
475 self.visit_table_factor_subqueries(&twj.relation, scope_id, cte_names);
476 for join in &twj.joins {
477 self.visit_table_factor_subqueries(&join.relation, scope_id, cte_names);
478 }
479 }
480
481 fn visit_table_factor_subqueries(
482 &mut self,
483 factor: &TableFactor,
484 scope_id: u32,
485 cte_names: &BTreeSet<String>,
486 ) {
487 match factor {
488 TableFactor::Derived {
489 lateral, subquery, ..
490 } => {
491 if *lateral {
492 self.visit_query_in_parent(subquery, scope_id, cte_names);
493 } else {
494 self.visit_query(subquery, cte_names.clone());
495 }
496 }
497 TableFactor::NestedJoin {
498 table_with_joins, ..
499 } => self.visit_table_with_joins_subqueries(table_with_joins, scope_id, cte_names),
500 _ => {}
501 }
502 }
503
504 fn check_table_with_joins_conditions(
505 &mut self,
506 twj: &TableWithJoins,
507 scope_id: u32,
508 cte_names: &BTreeSet<String>,
509 ) {
510 if let TableFactor::NestedJoin {
511 table_with_joins, ..
512 } = &twj.relation
513 {
514 self.check_table_with_joins_conditions(table_with_joins, scope_id, cte_names);
515 }
516 let mut left_bindings = Vec::new();
517 collect_table_factor_bindings(&twj.relation, cte_names, self.dialect, &mut left_bindings);
518 for join in &twj.joins {
519 if let TableFactor::NestedJoin {
520 table_with_joins, ..
521 } = &join.relation
522 {
523 self.check_table_with_joins_conditions(table_with_joins, scope_id, cte_names);
524 }
525 self.check_join(join, &left_bindings, scope_id, cte_names);
526 collect_table_factor_bindings(
527 &join.relation,
528 cte_names,
529 self.dialect,
530 &mut left_bindings,
531 );
532 }
533 }
534
535 fn check_join(
536 &mut self,
537 join: &Join,
538 left_bindings: &[TableBindingDef],
539 full_scope: u32,
540 cte_names: &BTreeSet<String>,
541 ) {
542 let empty = BTreeSet::new();
543 match &join.join_operator {
544 JoinOperator::Join(constraint)
545 | JoinOperator::Inner(constraint)
546 | JoinOperator::Left(constraint)
547 | JoinOperator::LeftOuter(constraint)
548 | JoinOperator::Right(constraint)
549 | JoinOperator::RightOuter(constraint)
550 | JoinOperator::FullOuter(constraint)
551 | JoinOperator::CrossJoin(constraint)
552 | JoinOperator::Semi(constraint)
553 | JoinOperator::LeftSemi(constraint)
554 | JoinOperator::RightSemi(constraint)
555 | JoinOperator::Anti(constraint)
556 | JoinOperator::LeftAnti(constraint)
557 | JoinOperator::RightAnti(constraint) => {
558 self.check_join_constraint(
559 constraint,
560 &join.relation,
561 left_bindings,
562 full_scope,
563 cte_names,
564 );
565 }
566 JoinOperator::AsOf {
567 match_condition,
568 constraint,
569 } => {
570 extract_filter_expr(
571 self,
572 match_condition,
573 ExprContext::new(full_scope, cte_names, &empty, ClauseKind::JoinOn, &[]),
574 );
575 self.check_join_constraint(
576 constraint,
577 &join.relation,
578 left_bindings,
579 full_scope,
580 cte_names,
581 );
582 }
583 _ => {}
584 }
585 }
586
587 fn check_join_constraint(
588 &mut self,
589 constraint: &JoinConstraint,
590 right_relation: &TableFactor,
591 left_bindings: &[TableBindingDef],
592 full_scope: u32,
593 cte_names: &BTreeSet<String>,
594 ) {
595 let empty = BTreeSet::new();
596 match constraint {
597 JoinConstraint::On(expr) => {
598 extract_filter_expr(
599 self,
600 expr,
601 ExprContext::new(full_scope, cte_names, &empty, ClauseKind::JoinOn, &[]),
602 );
603 }
604 JoinConstraint::Using(columns) | JoinConstraint::UsingAlias(columns, _) => {
605 let left_scope = self.alloc_scope(None, left_bindings.to_vec());
606 let right_table =
607 extract_single_factor_table(right_relation, cte_names, self.dialect);
608 let using_cols: Vec<String> = columns
609 .iter()
610 .filter_map(|col_obj| object_name_last_ident(col_obj, self.dialect))
611 .collect();
612 for col_obj in columns {
613 let Some(column) = object_name_last_ident(col_obj, self.dialect) else {
614 continue;
615 };
616 let line =
617 self.resolve_object_name_line(col_obj, &column, Some(Keyword::USING));
618 self.checks.push(SchemaCheck::UsingColumn {
619 left_scope,
620 right_table: right_table.clone(),
621 column,
622 using_cols: using_cols.clone(),
623 line,
624 });
625 }
626 }
627 JoinConstraint::Natural | JoinConstraint::None => {}
628 }
629 }
630
631 fn record_assignment_target(
632 &mut self,
633 table_schema: &Option<String>,
634 table_name: &str,
635 target: &AssignmentTarget,
636 ) {
637 match target {
638 AssignmentTarget::ColumnName(col_obj) => {
639 self.record_target_column(table_schema, table_name, col_obj);
640 }
641 AssignmentTarget::Tuple(cols) => {
642 for col_obj in cols {
643 self.record_target_column(table_schema, table_name, col_obj);
644 }
645 }
646 }
647 }
648
649 fn record_target_column(
650 &mut self,
651 table_schema: &Option<String>,
652 table_name: &str,
653 col_obj: &ObjectName,
654 ) {
655 let Some(column) = object_name_last_ident(col_obj, self.dialect) else {
656 return;
657 };
658 let line = self.resolve_object_name_line(col_obj, &column, None);
659 self.checks.push(SchemaCheck::TargetColumn {
660 table_schema: table_schema.clone(),
661 table_name: table_name.to_owned(),
662 column,
663 line,
664 });
665 }
666
667 fn resolve_object_name_line(
668 &self,
669 obj: &ObjectName,
670 ident_hint: &str,
671 keyword_hint: Option<Keyword>,
672 ) -> u32 {
673 let span_line = crate::ast_loc::object_name_start_loc(obj).line as u32;
674 if span_line > 0 {
675 return span_line;
676 }
677 resolve_fallback_line(
678 self.tokens,
679 self.stmt_start_line,
680 Some(ident_hint),
681 keyword_hint,
682 )
683 }
684}
685
686fn collect_table_with_joins_bindings(
687 twj: &TableWithJoins,
688 cte_names: &BTreeSet<String>,
689 dialect: SqlDialect,
690 out: &mut Vec<TableBindingDef>,
691) {
692 collect_table_factor_bindings(&twj.relation, cte_names, dialect, out);
693 for join in &twj.joins {
694 collect_table_factor_bindings(&join.relation, cte_names, dialect, out);
695 }
696}
697
698fn collect_table_factor_bindings(
699 factor: &TableFactor,
700 cte_names: &BTreeSet<String>,
701 dialect: SqlDialect,
702 out: &mut Vec<TableBindingDef>,
703) {
704 match factor {
705 TableFactor::Table {
706 name, alias, args, ..
707 } => {
708 let alias_name = alias.as_ref().map(|a| normalize_ident(&a.name, dialect));
709 if args.is_some() {
710 out.push(TableBindingDef {
711 schema: None,
712 table_name: None,
713 alias: alias_name,
714 resolvable: false,
715 });
716 return;
717 }
718 let Some((table_schema, table_name)) = split_object_name(name, dialect) else {
719 out.push(TableBindingDef {
720 schema: None,
721 table_name: None,
722 alias: alias_name,
723 resolvable: false,
724 });
725 return;
726 };
727 let is_cte = table_schema.is_none() && cte_names.contains(&table_name);
728 out.push(TableBindingDef {
729 schema: table_schema,
730 table_name: Some(table_name),
731 alias: alias_name,
732 resolvable: !is_cte,
733 });
734 }
735 TableFactor::Derived { alias, .. } => {
736 out.push(TableBindingDef {
737 schema: None,
738 table_name: None,
739 alias: alias.as_ref().map(|a| normalize_ident(&a.name, dialect)),
740 resolvable: false,
741 });
742 }
743 TableFactor::NestedJoin {
744 table_with_joins, ..
745 } => collect_table_with_joins_bindings(table_with_joins, cte_names, dialect, out),
746 _ => {
747 out.push(TableBindingDef {
748 schema: None,
749 table_name: None,
750 alias: None,
751 resolvable: false,
752 });
753 }
754 }
755}
756
757fn extract_single_factor_table(
758 factor: &TableFactor,
759 cte_names: &BTreeSet<String>,
760 dialect: SqlDialect,
761) -> Option<(Option<String>, String)> {
762 let TableFactor::Table {
763 name, args: None, ..
764 } = factor
765 else {
766 return None;
767 };
768 let (table_schema, table_name) = split_object_name(name, dialect)?;
769 if table_schema.is_none() && cte_names.contains(&table_name) {
770 return None;
771 }
772 Some((table_schema, table_name))
773}
774
775fn select_has_grouping_or_aggregates(select: &Select) -> bool {
776 select_has_group_by(select) || projection_contains_aggregate(&select.projection)
777}
778
779fn collect_select_order_prefix(select: &Select, dialect: SqlDialect) -> 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, dialect, &mut prefix);
784 }
785 if let Some(selection) = &select.selection {
786 collect_conjunct_refs(selection, &empty, true, dialect, &mut prefix);
787 }
788 for twj in &select.from {
789 collect_inner_join_order_prefix(twj, &empty, dialect, &mut prefix);
790 }
791 prefix
792}
793
794fn collect_inner_join_order_prefix(
795 twj: &TableWithJoins,
796 excluded: &BTreeSet<String>,
797 dialect: SqlDialect,
798 prefix: &mut Vec<ConstrainedRef>,
799) {
800 if let TableFactor::NestedJoin {
801 table_with_joins, ..
802 } = &twj.relation
803 {
804 collect_inner_join_order_prefix(table_with_joins, excluded, dialect, prefix);
805 }
806 for join in &twj.joins {
807 if let TableFactor::NestedJoin {
808 table_with_joins, ..
809 } = &join.relation
810 {
811 collect_inner_join_order_prefix(table_with_joins, excluded, dialect, prefix);
812 }
813 if let JoinOperator::Inner(JoinConstraint::On(expr))
814 | JoinOperator::Join(JoinConstraint::On(expr))
815 | JoinOperator::StraightJoin(JoinConstraint::On(expr)) = &join.join_operator
816 {
817 collect_conjunct_refs(expr, excluded, true, dialect, prefix);
818 }
819 }
820}