1use super::rewrite::rewrite_query_scalars;
10use super::scalar::lower_scalar_expression;
11use super::{
12 AccessPathPlan, AggregateClassifier, AssignmentPlan, ComputePlan, CteCyclePlan, CtePlan,
13 CteSearchPlan, Expr, ExpressionPlan, FromClause, JoinExecutionStrategy, MergeWhenPlan,
14 NoRegisteredAggregates, OrderBy, OrderPlan, Projection, ProjectionPlan, QueryBlockPlan,
15 QueryPlan, RelationalPlan, ScalarExpr, SelectStmt, SourcePlan, TableFunctionPlan, CTE,
16};
17
18impl QueryBlockPlan {
19 pub fn compute_kind(&self, aggregates: &dyn AggregateClassifier) -> ComputePlan {
21 let contains_aggregate = |expression: &ScalarExpr| {
22 crate::semantics::aggregates::contains_aggregate(aggregates, expression)
23 };
24 let has_aggregate = !self.group_by.is_empty()
25 || !self.grouping_sets.is_empty()
26 || self.having.is_some()
27 || self
28 .projections
29 .iter()
30 .any(|projection| contains_aggregate(&projection.expr))
31 || self
32 .windows
33 .iter()
34 .flat_map(|window| window.spec.expressions())
35 .any(contains_aggregate);
36 let has_window = self
37 .projections
38 .iter()
39 .any(|projection| projection.expr.contains_window());
40 if has_aggregate {
41 ComputePlan::Aggregate
42 } else if has_window {
43 ComputePlan::Window
44 } else {
45 ComputePlan::Project
46 }
47 }
48
49 pub fn is_single_expression(&self) -> bool {
51 self.deferred_outer_rewrites.is_empty()
52 && matches!(self.compute, ComputePlan::Project)
53 && self.from.is_none()
54 && self.r#where.is_none()
55 && self.group_by.is_empty()
56 && self.grouping_sets.is_empty()
57 && self.having.is_none()
58 && self.windows.is_empty()
59 && !self.distinct
60 && self.distinct_on.is_empty()
61 && self.order_by.is_empty()
62 && self.limit.is_none()
63 && self.offset.is_none()
64 && self.locking.is_empty()
65 && self.subqueries.is_empty()
66 && self.projections.len() == 1
67 && {
68 let mut window = false;
69 self.projections[0]
70 .expr
71 .visit(&mut |node| window |= matches!(node, ScalarExpr::WindowCall { .. }));
72 !window
73 }
74 }
75}
76
77impl QueryPlan {
78 pub fn rewrite_scalar_expressions(&mut self, rewrite: &mut dyn FnMut(&mut ScalarExpr)) {
81 rewrite_query_scalars(self, rewrite);
82 }
83
84 pub fn visit_sources_mut(&mut self, visit: &mut dyn FnMut(&mut SourcePlan)) {
86 super::rewrite::visit_query_sources(self, visit);
87 }
88
89 #[must_use]
90 pub fn lower(statement: SelectStmt) -> Self {
91 Self::lower_with(statement, &NoRegisteredAggregates)
92 }
93
94 #[must_use]
95 pub fn lower_with(mut statement: SelectStmt, aggregates: &dyn AggregateClassifier) -> Self {
96 let ctes = lower_ctes(&statement.with, aggregates);
97 statement.with.clear();
98 let root = lower_relational_root(statement, aggregates);
99 let mut plan = Self {
100 analyzed_output: None,
101 analyzed_source: None,
102 analyzed_grouping: None,
103 relation_privilege_subject: None,
104 relations_bound: false,
105 ctes,
106 root,
107 };
108 plan.normalize_window_definitions()
109 .expect("compiler windows belong to their query block");
110 plan
111 }
112}
113
114pub(super) fn lower_ctes(ctes: &[CTE], aggregates: &dyn AggregateClassifier) -> Vec<CtePlan> {
115 ctes.iter()
116 .map(|cte| CtePlan {
117 name: cte.name.clone(),
118 columns: cte.columns.clone(),
119 recursive: cte.recursive,
120 materialization: cte.materialization,
121 search: cte.search.as_ref().map(|search| CteSearchPlan {
122 columns: search.columns.clone(),
123 breadth_first: search.breadth_first,
124 sequence_column: search.sequence_column.clone(),
125 }),
126 cycle: cte.cycle.as_ref().map(|cycle| CteCyclePlan {
127 columns: cycle.columns.clone(),
128 mark_column: cycle.mark_column.clone(),
129 mark_value: lower_scalar_expression(
130 cycle.mark_value.clone(),
131 aggregates,
132 &mut Vec::new(),
133 ),
134 mark_default: lower_scalar_expression(
135 cycle.mark_default.clone(),
136 aggregates,
137 &mut Vec::new(),
138 ),
139 path_column: cycle.path_column.clone(),
140 }),
141 body: super::CtePlanBody::from(super::UnifiedPlan::lower_with(
142 cte.body.clone().into_statement(),
143 aggregates,
144 )),
145 })
146 .collect()
147}
148
149pub(super) fn lower_assignments(
150 assignments: Vec<(crate::ast::AssignmentTargets, Expr)>,
151 aggregates: &dyn AggregateClassifier,
152 subqueries: &mut Vec<QueryPlan>,
153) -> Vec<AssignmentPlan> {
154 assignments
155 .into_iter()
156 .map(|(target, expression)| AssignmentPlan {
157 target: target
158 .map(|expression| lower_scalar_expression(expression, aggregates, subqueries)),
159 value: lower_scalar_expression(expression, aggregates, subqueries),
160 })
161 .collect()
162}
163
164pub(super) fn lower_targets(
165 targets: Vec<crate::ast::AssignmentTarget>,
166 aggregates: &dyn AggregateClassifier,
167 subqueries: &mut Vec<QueryPlan>,
168) -> Vec<crate::ast::AssignmentTarget<ScalarExpr>> {
169 targets
170 .into_iter()
171 .map(|target| {
172 target.map(|expression| lower_scalar_expression(expression, aggregates, subqueries))
173 })
174 .collect()
175}
176
177pub(super) fn lower_merge_when(
178 clause: crate::ast::MergeWhen,
179 aggregates: &dyn AggregateClassifier,
180 subqueries: &mut Vec<QueryPlan>,
181) -> MergeWhenPlan {
182 let mut lower_optional = |expression: Option<Expr>| {
183 expression.map(|expression| lower_scalar_expression(expression, aggregates, subqueries))
184 };
185 match clause {
186 crate::ast::MergeWhen::UpdateMatched {
187 condition,
188 assignments,
189 } => {
190 let condition = lower_optional(condition);
191 let assignments = lower_assignments(assignments, aggregates, subqueries);
192 MergeWhenPlan::UpdateMatched {
193 condition,
194 assignments,
195 }
196 }
197 crate::ast::MergeWhen::DeleteMatched { condition } => MergeWhenPlan::DeleteMatched {
198 condition: lower_optional(condition),
199 },
200 crate::ast::MergeWhen::UpdateNotMatchedBySource {
201 condition,
202 assignments,
203 } => {
204 let condition = lower_optional(condition);
205 let assignments = lower_assignments(assignments, aggregates, subqueries);
206 MergeWhenPlan::UpdateNotMatchedBySource {
207 condition,
208 assignments,
209 }
210 }
211 crate::ast::MergeWhen::DeleteNotMatchedBySource { condition } => {
212 MergeWhenPlan::DeleteNotMatchedBySource {
213 condition: lower_optional(condition),
214 }
215 }
216 crate::ast::MergeWhen::InsertNotMatched {
217 condition,
218 columns,
219 overriding,
220 values,
221 } => {
222 let condition = lower_optional(condition);
223 let values = values
224 .into_iter()
225 .map(|value| lower_scalar_expression(value, aggregates, subqueries))
226 .collect();
227 MergeWhenPlan::InsertNotMatched {
228 condition,
229 columns: lower_targets(columns, aggregates, subqueries),
230 overriding,
231 values,
232 }
233 }
234 crate::ast::MergeWhen::NothingMatched { condition } => MergeWhenPlan::NothingMatched {
235 condition: lower_optional(condition),
236 },
237 crate::ast::MergeWhen::NothingNotMatched { condition } => {
238 MergeWhenPlan::NothingNotMatched {
239 condition: lower_optional(condition),
240 }
241 }
242 crate::ast::MergeWhen::NothingNotMatchedBySource { condition } => {
243 MergeWhenPlan::NothingNotMatchedBySource {
244 condition: lower_optional(condition),
245 }
246 }
247 }
248}
249pub(super) fn lower_relational_root(
250 mut statement: SelectStmt,
251 aggregates: &dyn AggregateClassifier,
252) -> RelationalPlan {
253 if statement.set_op.is_none() && !statement.values.is_empty() {
254 let mut subqueries = Vec::new();
255 let rows = statement
256 .values
257 .into_iter()
258 .map(|row| {
259 row.into_iter()
260 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
261 .collect()
262 })
263 .collect();
264 return RelationalPlan::Values { rows, subqueries };
265 }
266 let Some(set_op) = statement.set_op.take() else {
267 return RelationalPlan::QueryBlock(Box::new(QueryBlockPlan::lower_with(
268 statement, aggregates,
269 )));
270 };
271
272 let left = if let Some(left) = set_op.left {
273 QueryPlan::lower_with(*left, aggregates)
274 } else {
275 QueryPlan {
276 analyzed_output: None,
277 analyzed_source: None,
278 analyzed_grouping: None,
279 relation_privilege_subject: None,
280 relations_bound: false,
281 ctes: Vec::new(),
282 root: RelationalPlan::QueryBlock(Box::new(QueryBlockPlan::lower_with(
283 statement, aggregates,
284 ))),
285 }
286 };
287 let right = QueryPlan::lower_with(set_op.right, aggregates);
288 let mut subqueries = Vec::new();
289 RelationalPlan::SetOp {
290 kind: set_op.kind,
291 all: set_op.all,
292 left: Box::new(left),
293 right: Box::new(right),
294 order_by: set_op
295 .combined_order_by
296 .into_iter()
297 .map(|order| OrderPlan::lower_with(order, aggregates, &mut subqueries))
298 .collect(),
299 limit: set_op
300 .combined_limit
301 .map(|expr| Box::new(lower_scalar_expression(expr, aggregates, &mut subqueries))),
302 with_ties: set_op.combined_with_ties,
303 offset: set_op
304 .combined_offset
305 .map(|expr| Box::new(lower_scalar_expression(expr, aggregates, &mut subqueries))),
306 subqueries,
307 }
308}
309
310impl QueryBlockPlan {
311 fn lower_with(statement: SelectStmt, aggregates: &dyn AggregateClassifier) -> Self {
312 debug_assert_eq!(statement.with.len(), 0);
313 debug_assert!(statement.set_op.is_none());
314 let mut subqueries = Vec::new();
315 let projections: Vec<ProjectionPlan> = statement
316 .projections
317 .into_iter()
318 .map(|projection| ProjectionPlan::lower_with(projection, aggregates, &mut subqueries))
319 .collect();
320 let windows: Vec<_> = statement
321 .windows
322 .into_iter()
323 .map(|definition| crate::ast::WindowDefinition {
324 name: definition.name,
325 inherited: definition.inherited,
326 spec: super::scalar::lower_window_spec(
327 definition.spec,
328 aggregates,
329 &mut subqueries,
330 ),
331 })
332 .collect();
333 let mut block = Self {
334 deferred_outer_rewrites: Vec::new(),
335 windows,
336 projections,
337 privilege_columns: uqa_core::memory::OwnedSet::new(),
338 from: statement
339 .from
340 .map(|source| SourcePlan::lower_with(source, aggregates, &mut subqueries)),
341 r#where: statement
342 .r#where
343 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries)),
344 compute: ComputePlan::Project,
345 group_by: statement
346 .group_by
347 .into_iter()
348 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
349 .collect(),
350 grouping_sets: statement
351 .grouping_sets
352 .into_iter()
353 .map(|set| {
354 set.into_iter()
355 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
356 .collect()
357 })
358 .collect(),
359 group_distinct: statement.group_distinct,
360 having: statement
361 .having
362 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries)),
363 order_by: statement
364 .order_by
365 .into_iter()
366 .map(|order| OrderPlan::lower_with(order, aggregates, &mut subqueries))
367 .collect(),
368 limit: statement
369 .limit
370 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries)),
371 with_ties: statement.with_ties,
372 offset: statement
373 .offset
374 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries)),
375 distinct: statement.distinct,
376 distinct_on: statement
377 .distinct_on
378 .into_iter()
379 .map(|expr| lower_scalar_expression(expr, aggregates, &mut subqueries))
380 .collect(),
381 subqueries,
382 access: AccessPathPlan::Row,
383 locking: statement.locking,
384 };
385 block.compute = block.compute_kind(aggregates);
386 block
387 }
388
389 #[must_use]
393 pub fn expressions(&self) -> Vec<&ScalarExpr> {
394 let mut expressions = Vec::new();
395 self.visit_expressions(&mut |expression| expressions.push(expression));
396 expressions
397 }
398
399 pub fn visit_expressions<'a>(&'a self, visit: &mut dyn FnMut(&'a ScalarExpr)) {
401 self.try_visit_expressions(&mut |expression| {
402 visit(expression);
403 Ok::<_, std::convert::Infallible>(true)
404 })
405 .unwrap_or_else(|never| match never {});
406 }
407
408 pub fn try_visit_expressions<'a, E>(
410 &'a self,
411 visit: &mut dyn FnMut(&'a ScalarExpr) -> Result<bool, E>,
412 ) -> Result<bool, E> {
413 if let Some(source) = &self.from {
414 if !source.try_visit_expressions(visit)? {
415 return Ok(false);
416 }
417 }
418 for expression in self.query_expressions() {
419 if !visit(expression)? {
420 return Ok(false);
421 }
422 }
423 Ok(true)
424 }
425
426 pub fn query_expressions(&self) -> impl Iterator<Item = &ScalarExpr> {
428 let (before, after): (&[ProjectionPlan], &[ProjectionPlan]) =
430 if matches!(self.compute, ComputePlan::Project) {
431 (&self.projections, &[])
432 } else {
433 (&[], &self.projections)
434 };
435 before
436 .iter()
437 .map(|projection| &projection.expr)
438 .chain(self.r#where.as_ref())
439 .chain(after.iter().map(|projection| &projection.expr))
440 .chain(&self.group_by)
441 .chain(self.grouping_sets.iter().flatten())
442 .chain(self.having.as_ref())
443 .chain(self.order_by.iter().map(|order| &order.expr))
444 .chain(self.limit.as_ref())
445 .chain(self.offset.as_ref())
446 .chain(&self.distinct_on)
447 .chain(
448 self.windows
449 .iter()
450 .flat_map(|window| window.spec.expressions()),
451 )
452 }
453}
454
455impl SourcePlan {
456 #[must_use]
458 pub fn visible_qualifier(&self) -> Option<&str> {
459 match self {
460 crate::plan::SourcePlan::RetainedRows(_) => None,
461 Self::Table {
462 qualifier, alias, ..
463 } => Some(alias.as_deref().unwrap_or(qualifier)),
464 Self::Function {
465 output_name, alias, ..
466 } => Some(alias.as_deref().unwrap_or(output_name)),
467 Self::FunctionGroup {
468 functions, alias, ..
469 } => alias.as_deref().or_else(|| {
470 functions
471 .first()
472 .map(|function| function.output_name.as_str())
473 }),
474 Self::Values {
475 alias,
476 internal_relation,
477 ..
478 } => internal_relation
479 .is_none()
480 .then_some(alias.as_deref())
481 .flatten(),
482 Self::Subquery { alias, .. } => alias.as_deref(),
483 Self::Join { alias, .. } => alias.as_deref(),
484 }
485 }
486
487 #[expect(
488 clippy::too_many_lines,
489 reason = "plan lowering preserves exhaustive variants and structural identities"
490 )]
491 pub(super) fn lower_with(
492 source: FromClause,
493 aggregates: &dyn AggregateClassifier,
494 subqueries: &mut Vec<QueryPlan>,
495 ) -> Self {
496 match source {
497 FromClause::RetainedRows(source) => Self::RetainedRows(source),
498 FromClause::Table {
499 name,
500 qualifier,
501 alias,
502 column_aliases,
503 bound_columns,
504 include_descendants,
505 } => Self::Table {
506 executable_query: None,
507 name,
508 qualifier,
509 alias,
510 column_aliases,
511 bound_columns,
512 include_descendants,
513 },
514 FromClause::Join {
515 comma,
516 left,
517 right,
518 kind,
519 on,
520 using,
521 natural,
522 alias,
523 column_aliases,
524 lateral,
525 } => Self::Join {
526 comma,
527 left: Box::new(Self::lower_with(*left, aggregates, subqueries)),
528 right: Box::new(Self::lower_with(*right, aggregates, subqueries)),
529 kind,
530 on: on.map(|expr| lower_scalar_expression(expr, aggregates, subqueries)),
531 using,
532 natural,
533 alias,
534 column_aliases,
535 lateral,
536 strategy: JoinExecutionStrategy::Auto,
537 },
538 FromClause::Values {
539 lateral,
540 rows,
541 alias,
542 column_aliases,
543 internal_relation,
544 internal_column_types,
545 internal_column_collations,
546 } => Self::Values {
547 lateral,
548 rows: rows
549 .into_iter()
550 .map(|row| {
551 row.into_iter()
552 .map(|expr| lower_scalar_expression(expr, aggregates, subqueries))
553 .collect()
554 })
555 .collect(),
556 alias,
557 column_aliases,
558 internal_relation,
559 internal_column_types,
560 internal_column_collations,
561 },
562 FromClause::Function {
563 name,
564 binding,
565 output_name,
566 relations,
567 args,
568 alias,
569 column_aliases,
570 ordinality,
571 column_types,
572 } => Self::Function {
573 name,
574 binding,
575 output_name,
576 relations,
577 args: args
578 .into_iter()
579 .map(|expr| lower_scalar_expression(expr, aggregates, subqueries))
580 .collect(),
581 alias,
582 column_aliases,
583 ordinality,
584 column_types,
585 },
586 FromClause::FunctionGroup {
587 functions,
588 alias,
589 column_aliases,
590 ordinality,
591 } => Self::FunctionGroup {
592 functions: functions
593 .into_iter()
594 .map(|function| TableFunctionPlan {
595 name: function.name,
596 binding: function.binding,
597 output_name: function.output_name,
598 relations: function.relations,
599 args: function
600 .args
601 .into_iter()
602 .map(|expr| lower_scalar_expression(expr, aggregates, subqueries))
603 .collect(),
604 column_aliases: function.column_aliases,
605 column_types: function.column_types,
606 })
607 .collect(),
608 alias,
609 column_aliases,
610 ordinality,
611 },
612 FromClause::Subquery {
613 lateral,
614 body,
615 alias,
616 column_aliases,
617 } => Self::Subquery {
618 captured_output: None,
619 lateral,
620 body: Box::new(QueryPlan::lower_with(*body, aggregates)),
621 alias,
622 column_aliases,
623 },
624 }
625 }
626
627 pub fn try_visit_expressions<'a, E>(
629 &'a self,
630 visit: &mut dyn FnMut(&'a ScalarExpr) -> Result<bool, E>,
631 ) -> Result<bool, E> {
632 match self {
633 Self::RetainedRows(_) | Self::Table { .. } | Self::Subquery { .. } => {}
634 Self::Join {
635 left, right, on, ..
636 } => {
637 if !left.try_visit_expressions(visit)? || !right.try_visit_expressions(visit)? {
638 return Ok(false);
639 }
640 if let Some(on) = on {
641 if !visit(on)? {
642 return Ok(false);
643 }
644 }
645 }
646 Self::Values { rows, .. } => {
647 for expression in rows.iter().flatten() {
648 if !visit(expression)? {
649 return Ok(false);
650 }
651 }
652 }
653 Self::Function { args, .. } => {
654 for expression in args {
655 if !visit(expression)? {
656 return Ok(false);
657 }
658 }
659 }
660 Self::FunctionGroup { functions, .. } => {
661 for expression in functions.iter().flat_map(|function| &function.args) {
662 if !visit(expression)? {
663 return Ok(false);
664 }
665 }
666 }
667 }
668 Ok(true)
669 }
670
671 pub fn push_expressions<'a>(&'a self, output: &mut Vec<&'a ScalarExpr>) {
673 self.try_visit_expressions(&mut |expression| {
674 output.push(expression);
675 Ok::<_, std::convert::Infallible>(true)
676 })
677 .unwrap_or_else(|never| match never {});
678 }
679
680 pub fn collect_tables(&self, output: &mut Vec<(String, Option<String>)>) {
681 match self {
682 crate::plan::SourcePlan::RetainedRows(_) => {}
683 Self::Table {
684 name,
685 qualifier,
686 alias,
687 ..
688 } => output.push((
689 name.clone(),
690 Some(alias.as_ref().unwrap_or(qualifier).clone()),
691 )),
692 Self::Join { left, right, .. } => {
693 left.collect_tables(output);
694 right.collect_tables(output);
695 }
696 Self::Values { .. }
697 | Self::Function { .. }
698 | Self::FunctionGroup { .. }
699 | Self::Subquery { .. } => {}
700 }
701 }
702}
703
704impl ProjectionPlan {
705 pub(super) fn lower_with(
706 projection: Projection,
707 aggregates: &dyn AggregateClassifier,
708 subqueries: &mut Vec<QueryPlan>,
709 ) -> Self {
710 Self {
711 expr: lower_scalar_expression(projection.expr, aggregates, subqueries),
712 alias: projection.alias,
713 }
714 }
715}
716
717impl OrderPlan {
718 fn lower_with(
719 order: OrderBy,
720 aggregates: &dyn AggregateClassifier,
721 subqueries: &mut Vec<QueryPlan>,
722 ) -> Self {
723 Self {
724 expr: lower_scalar_expression(order.expr, aggregates, subqueries),
725 descending: order.descending,
726 nulls: order.nulls,
727 }
728 }
729}
730
731impl ExpressionPlan {
732 pub fn upgrade_legacy_range_predicates(&mut self) -> Result<bool, crate::SQLError> {
734 crate::type_resolution::between::restore_expression(self)
735 }
736
737 #[must_use]
738 pub fn lower(expression: Expr) -> Self {
739 Self::lower_with(expression, &NoRegisteredAggregates)
740 }
741
742 pub fn lower_with(expression: Expr, aggregates: &dyn AggregateClassifier) -> Self {
743 let mut subqueries = Vec::new();
744 let scalar = lower_scalar_expression(expression, aggregates, &mut subqueries);
745 Self { scalar, subqueries }
746 }
747}