Skip to main content

uqa_sql/semantics/sets/
rewrite.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Set-returning and aggregate dependency expression rewrites.
8
9use crate::plan::{ProjectionPlan, QueryBlockPlan};
10use crate::{FunctionTypeResolver, RowSchema, ScalarExpr, ScalarFrameBound};
11use crate::{SQLError, SQLParam};
12use uqa_core::Value;
13
14use super::validation::{
15    expression_may_return_set, function_may_return_set, resolve_set_function_binding,
16};
17use super::{
18    AggregateOutputProjectionPlan, GroupSetProjectionPlan, ProjectionTarget, SetFunctionCall,
19    SetFunctionCatalog,
20};
21use crate::semantics::aggregates::{exprs_match, is_aggregate};
22use crate::semantics::projection_columns;
23
24#[expect(
25    clippy::too_many_lines,
26    reason = "preserves SELECT schema and row identity"
27)]
28pub fn rewrite_set_calls(
29    engine: &dyn SetFunctionCatalog,
30    resolver: &dyn FunctionTypeResolver,
31    mut expression: ScalarExpr,
32    calls: &mut Vec<SetFunctionCall>,
33    call_relation: crate::ast::InternalRelationId,
34    schema: &RowSchema,
35    params: &[SQLParam],
36) -> Result<ScalarExpr, SQLError> {
37    let descendant_start = calls.len();
38    match &mut expression {
39        ScalarExpr::Func {
40            args,
41            order_by,
42            filter,
43            ..
44        } => {
45            for argument in args {
46                *argument = rewrite_set_calls(
47                    engine,
48                    resolver,
49                    argument.clone(),
50                    calls,
51                    call_relation,
52                    schema,
53                    params,
54                )?;
55            }
56            for order in order_by {
57                order.expr = rewrite_set_calls(
58                    engine,
59                    resolver,
60                    order.expr.clone(),
61                    calls,
62                    call_relation,
63                    schema,
64                    params,
65                )?;
66            }
67            if let Some(filter) = filter {
68                **filter = rewrite_set_calls(
69                    engine,
70                    resolver,
71                    (**filter).clone(),
72                    calls,
73                    call_relation,
74                    schema,
75                    params,
76                )?;
77            }
78        }
79        ScalarExpr::Array(items)
80        | ScalarExpr::Row(items)
81        | ScalarExpr::CompositeRow { items, .. }
82        | ScalarExpr::And(items)
83        | ScalarExpr::Or(items) => {
84            for item in items {
85                *item = rewrite_set_calls(
86                    engine,
87                    resolver,
88                    item.clone(),
89                    calls,
90                    call_relation,
91                    schema,
92                    params,
93                )?;
94            }
95        }
96        ScalarExpr::Binary { lhs, rhs, .. } => {
97            **lhs = rewrite_set_calls(
98                engine,
99                resolver,
100                (**lhs).clone(),
101                calls,
102                call_relation,
103                schema,
104                params,
105            )?;
106            **rhs = rewrite_set_calls(
107                engine,
108                resolver,
109                (**rhs).clone(),
110                calls,
111                call_relation,
112                schema,
113                params,
114            )?;
115        }
116        ScalarExpr::Not(inner)
117        | ScalarExpr::UnaryMinus(inner)
118        | ScalarExpr::IsNull { expr: inner, .. }
119        | ScalarExpr::Cast { expr: inner, .. }
120        | ScalarExpr::Collated { expr: inner, .. } => {
121            **inner = rewrite_set_calls(
122                engine,
123                resolver,
124                (**inner).clone(),
125                calls,
126                call_relation,
127                schema,
128                params,
129            )?;
130        }
131        ScalarExpr::Between { expr, low, high } => {
132            **expr = rewrite_set_calls(
133                engine,
134                resolver,
135                (**expr).clone(),
136                calls,
137                call_relation,
138                schema,
139                params,
140            )?;
141            **low = rewrite_set_calls(
142                engine,
143                resolver,
144                (**low).clone(),
145                calls,
146                call_relation,
147                schema,
148                params,
149            )?;
150            **high = rewrite_set_calls(
151                engine,
152                resolver,
153                (**high).clone(),
154                calls,
155                call_relation,
156                schema,
157                params,
158            )?;
159        }
160        ScalarExpr::InList { expr, list, .. } => {
161            **expr = rewrite_set_calls(
162                engine,
163                resolver,
164                (**expr).clone(),
165                calls,
166                call_relation,
167                schema,
168                params,
169            )?;
170            for item in list {
171                *item = rewrite_set_calls(
172                    engine,
173                    resolver,
174                    item.clone(),
175                    calls,
176                    call_relation,
177                    schema,
178                    params,
179                )?;
180            }
181        }
182        ScalarExpr::WindowCall {
183            args, spec, filter, ..
184        } => {
185            for argument in args {
186                *argument = rewrite_set_calls(
187                    engine,
188                    resolver,
189                    argument.clone(),
190                    calls,
191                    call_relation,
192                    schema,
193                    params,
194                )?;
195            }
196            if let Some(filter) = filter {
197                **filter = rewrite_set_calls(
198                    engine,
199                    resolver,
200                    (**filter).clone(),
201                    calls,
202                    call_relation,
203                    schema,
204                    params,
205                )?;
206            }
207            for item in &mut spec.partition_by {
208                *item = rewrite_set_calls(
209                    engine,
210                    resolver,
211                    item.clone(),
212                    calls,
213                    call_relation,
214                    schema,
215                    params,
216                )?;
217            }
218            for order in &mut spec.order_by {
219                order.expr = rewrite_set_calls(
220                    engine,
221                    resolver,
222                    order.expr.clone(),
223                    calls,
224                    call_relation,
225                    schema,
226                    params,
227                )?;
228            }
229            if let Some(frame) = &mut spec.frame {
230                rewrite_set_frame_bound(
231                    engine,
232                    resolver,
233                    &mut frame.start,
234                    calls,
235                    call_relation,
236                    schema,
237                    params,
238                )?;
239                rewrite_set_frame_bound(
240                    engine,
241                    resolver,
242                    &mut frame.end,
243                    calls,
244                    call_relation,
245                    schema,
246                    params,
247                )?;
248            }
249        }
250        ScalarExpr::Case {
251            base,
252            when,
253            else_branch,
254        } => {
255            if let Some(base) = base {
256                **base = rewrite_set_calls(
257                    engine,
258                    resolver,
259                    (**base).clone(),
260                    calls,
261                    call_relation,
262                    schema,
263                    params,
264                )?;
265            }
266            for (condition, result) in when {
267                *condition = rewrite_set_calls(
268                    engine,
269                    resolver,
270                    condition.clone(),
271                    calls,
272                    call_relation,
273                    schema,
274                    params,
275                )?;
276                *result = rewrite_set_calls(
277                    engine,
278                    resolver,
279                    result.clone(),
280                    calls,
281                    call_relation,
282                    schema,
283                    params,
284                )?;
285            }
286            if let Some(branch) = else_branch {
287                **branch = rewrite_set_calls(
288                    engine,
289                    resolver,
290                    (**branch).clone(),
291                    calls,
292                    call_relation,
293                    schema,
294                    params,
295                )?;
296            }
297        }
298        ScalarExpr::InSubquery { expr, .. } => {
299            **expr = rewrite_set_calls(
300                engine,
301                resolver,
302                (**expr).clone(),
303                calls,
304                call_relation,
305                schema,
306                params,
307            )?;
308        }
309        ScalarExpr::Default
310        | ScalarExpr::Star
311        | ScalarExpr::QualifiedStar(_)
312        | ScalarExpr::Column(_)
313        | ScalarExpr::Position(_)
314        | ScalarExpr::InternalColumn(_)
315        | ScalarExpr::QualifiedColumn { .. }
316        | ScalarExpr::Literal(_)
317        | ScalarExpr::TypedLiteral { .. }
318        | ScalarExpr::RetainedLiteral(_)
319        | ScalarExpr::Param(_)
320        | ScalarExpr::ScalarSubquery(_)
321        | ScalarExpr::Exists { .. } => {}
322    }
323    if let ScalarExpr::Func {
324        name,
325        binding,
326        args,
327        ..
328    } = &expression
329    {
330        if function_may_return_set(
331            engine,
332            resolver,
333            name,
334            binding.as_ref(),
335            args,
336            schema,
337            params,
338        )? {
339            let binding = resolve_set_function_binding(
340                engine,
341                resolver,
342                name,
343                binding.as_ref(),
344                args,
345                schema,
346                params,
347            )?
348            .or_else(|| binding.clone());
349            let level = calls[descendant_start..]
350                .iter()
351                .map(|call| call.level + 1)
352                .max()
353                .unwrap_or(0);
354            let placeholder = call_relation.column(calls.len());
355            calls.push(SetFunctionCall {
356                placeholder,
357                name: name.clone(),
358                binding,
359                args: args.clone(),
360                level,
361            });
362            return Ok(ScalarExpr::InternalColumn(placeholder));
363        }
364    }
365    Ok(expression)
366}
367
368fn rewrite_set_frame_bound(
369    engine: &dyn SetFunctionCatalog,
370    resolver: &dyn FunctionTypeResolver,
371    bound: &mut ScalarFrameBound,
372    calls: &mut Vec<SetFunctionCall>,
373    call_relation: crate::ast::InternalRelationId,
374    schema: &RowSchema,
375    params: &[SQLParam],
376) -> Result<(), SQLError> {
377    match bound {
378        ScalarFrameBound::Preceding(expression) | ScalarFrameBound::Following(expression) => {
379            **expression = rewrite_set_calls(
380                engine,
381                resolver,
382                (**expression).clone(),
383                calls,
384                call_relation,
385                schema,
386                params,
387            )?;
388        }
389        ScalarFrameBound::UnboundedPreceding
390        | ScalarFrameBound::UnboundedFollowing
391        | ScalarFrameBound::CurrentRow => {}
392    }
393    Ok(())
394}
395
396fn replace_group_set_expression(
397    expression: &mut ScalarExpr,
398    mappings: &[(ScalarExpr, crate::ast::InternalColumnRef)],
399) {
400    if let Some((_, column)) = mappings
401        .iter()
402        .find(|(group, _)| exprs_match(expression, group))
403    {
404        *expression = ScalarExpr::InternalColumn(*column);
405        return;
406    }
407    match expression {
408        ScalarExpr::Func {
409            args,
410            order_by,
411            filter,
412            ..
413        } => {
414            for expression in args
415                .iter_mut()
416                .chain(order_by.iter_mut().map(|order| &mut order.expr))
417                .chain(filter.as_deref_mut())
418            {
419                replace_group_set_expression(expression, mappings);
420            }
421        }
422        ScalarExpr::Array(items)
423        | ScalarExpr::Row(items)
424        | ScalarExpr::CompositeRow { items, .. }
425        | ScalarExpr::And(items)
426        | ScalarExpr::Or(items) => {
427            for item in items {
428                replace_group_set_expression(item, mappings);
429            }
430        }
431        ScalarExpr::Binary { lhs, rhs, .. } => {
432            replace_group_set_expression(lhs, mappings);
433            replace_group_set_expression(rhs, mappings);
434        }
435        ScalarExpr::Not(inner)
436        | ScalarExpr::UnaryMinus(inner)
437        | ScalarExpr::IsNull { expr: inner, .. }
438        | ScalarExpr::Cast { expr: inner, .. }
439        | ScalarExpr::Collated { expr: inner, .. }
440        | ScalarExpr::InSubquery { expr: inner, .. } => {
441            replace_group_set_expression(inner, mappings);
442        }
443        ScalarExpr::Between { expr, low, high } => {
444            replace_group_set_expression(expr, mappings);
445            replace_group_set_expression(low, mappings);
446            replace_group_set_expression(high, mappings);
447        }
448        ScalarExpr::InList { expr, list, .. } => {
449            replace_group_set_expression(expr, mappings);
450            for item in list {
451                replace_group_set_expression(item, mappings);
452            }
453        }
454        ScalarExpr::WindowCall {
455            args, spec, filter, ..
456        } => {
457            for expression in args
458                .iter_mut()
459                .chain(filter.as_deref_mut())
460                .chain(&mut spec.partition_by)
461                .chain(spec.order_by.iter_mut().map(|order| &mut order.expr))
462            {
463                replace_group_set_expression(expression, mappings);
464            }
465            if let Some(frame) = &mut spec.frame {
466                replace_group_set_frame_bound(&mut frame.start, mappings);
467                replace_group_set_frame_bound(&mut frame.end, mappings);
468            }
469        }
470        ScalarExpr::Case {
471            base,
472            when,
473            else_branch,
474        } => {
475            if let Some(base) = base {
476                replace_group_set_expression(base, mappings);
477            }
478            for (condition, result) in when {
479                replace_group_set_expression(condition, mappings);
480                replace_group_set_expression(result, mappings);
481            }
482            if let Some(branch) = else_branch {
483                replace_group_set_expression(branch, mappings);
484            }
485        }
486        ScalarExpr::Default
487        | ScalarExpr::Star
488        | ScalarExpr::QualifiedStar(_)
489        | ScalarExpr::Column(_)
490        | ScalarExpr::Position(_)
491        | ScalarExpr::InternalColumn(_)
492        | ScalarExpr::QualifiedColumn { .. }
493        | ScalarExpr::Literal(_)
494        | ScalarExpr::TypedLiteral { .. }
495        | ScalarExpr::RetainedLiteral(_)
496        | ScalarExpr::Param(_)
497        | ScalarExpr::ScalarSubquery(_)
498        | ScalarExpr::Exists { .. } => {}
499    }
500}
501
502fn replace_group_set_frame_bound(
503    bound: &mut ScalarFrameBound,
504    mappings: &[(ScalarExpr, crate::ast::InternalColumnRef)],
505) {
506    match bound {
507        ScalarFrameBound::Preceding(expression) | ScalarFrameBound::Following(expression) => {
508            replace_group_set_expression(expression, mappings);
509        }
510        ScalarFrameBound::UnboundedPreceding
511        | ScalarFrameBound::UnboundedFollowing
512        | ScalarFrameBound::CurrentRow => {}
513    }
514}
515
516pub fn prepare_group_set_projection(
517    engine: &dyn SetFunctionCatalog,
518    resolver: &dyn FunctionTypeResolver,
519    statement: &QueryBlockPlan,
520    schema: &RowSchema,
521    params: &[SQLParam],
522) -> Result<Option<GroupSetProjectionPlan>, SQLError> {
523    let mut groups = Vec::new();
524    for expression in statement
525        .group_by
526        .iter()
527        .chain(statement.grouping_sets.iter().flatten())
528    {
529        if expression_may_return_set(engine, resolver, expression, schema, params)?
530            && !groups
531                .iter()
532                .any(|existing| exprs_match(existing, expression))
533        {
534            groups.push(expression.clone());
535        }
536    }
537    if groups.is_empty() {
538        return Ok(None);
539    }
540
541    let relation = crate::ast::InternalRelationId::allocate();
542    let mappings = groups
543        .iter()
544        .enumerate()
545        .map(|(index, expression)| (expression.clone(), relation.column(index)))
546        .collect::<Vec<_>>();
547    let projections = mappings
548        .iter()
549        .map(|(expression, column)| (ProjectionTarget::Internal(*column), expression.clone()))
550        .collect();
551    let mut rewritten = statement.clone();
552    let projection_labels = projection_columns(&rewritten.projections);
553    for expression in &mut rewritten.group_by {
554        replace_group_set_expression(expression, &mappings);
555    }
556    for set in &mut rewritten.grouping_sets {
557        for expression in set {
558            replace_group_set_expression(expression, &mappings);
559        }
560    }
561    for (projection, label) in rewritten.projections.iter_mut().zip(projection_labels) {
562        if projection.alias.is_none() {
563            projection.alias = Some(label);
564        }
565        replace_group_set_expression(&mut projection.expr, &mappings);
566    }
567    if let Some(having) = &mut rewritten.having {
568        replace_group_set_expression(having, &mappings);
569    }
570    for order in &mut rewritten.order_by {
571        replace_group_set_expression(&mut order.expr, &mappings);
572    }
573    for expression in &mut rewritten.distinct_on {
574        replace_group_set_expression(expression, &mappings);
575    }
576    Ok(Some(GroupSetProjectionPlan {
577        statement: rewritten,
578        projections,
579    }))
580}
581
582fn capture_aggregate_dependency(
583    expression: &ScalarExpr,
584    dependencies: &mut Vec<ProjectionPlan>,
585) -> ScalarExpr {
586    let position = dependencies.len();
587    dependencies.push(ProjectionPlan {
588        expr: expression.clone(),
589        alias: None,
590    });
591    ScalarExpr::Position(position)
592}
593
594#[expect(
595    clippy::too_many_lines,
596    reason = "preserves SELECT schema and row identity"
597)]
598fn rewrite_aggregate_dependencies(
599    engine: &dyn SetFunctionCatalog,
600    group_by: &[&ScalarExpr],
601    expression: &ScalarExpr,
602    dependencies: &mut Vec<ProjectionPlan>,
603) -> ScalarExpr {
604    if is_aggregate(engine, expression)
605        || group_by.iter().any(|group| exprs_match(expression, group))
606    {
607        return capture_aggregate_dependency(expression, dependencies);
608    }
609    match expression {
610        ScalarExpr::Column(_)
611        | ScalarExpr::Position(_)
612        | ScalarExpr::InternalColumn(_)
613        | ScalarExpr::QualifiedColumn { .. } => {
614            capture_aggregate_dependency(expression, dependencies)
615        }
616        ScalarExpr::Func {
617            order_syntax,
618            name,
619            binding,
620            args,
621            distinct,
622            order_by,
623            filter,
624        } => ScalarExpr::Func {
625            order_syntax: *order_syntax,
626            name: name.clone(),
627            binding: binding.clone(),
628            args: args
629                .iter()
630                .map(|argument| {
631                    rewrite_aggregate_dependencies(engine, group_by, argument, dependencies)
632                })
633                .collect(),
634            distinct: *distinct,
635            order_by: order_by
636                .iter()
637                .map(|order| {
638                    let mut order = order.clone();
639                    order.expr =
640                        rewrite_aggregate_dependencies(engine, group_by, &order.expr, dependencies);
641                    order
642                })
643                .collect(),
644            filter: filter.as_deref().map(|filter| {
645                Box::new(rewrite_aggregate_dependencies(
646                    engine,
647                    group_by,
648                    filter,
649                    dependencies,
650                ))
651            }),
652        },
653        ScalarExpr::Array(items) => ScalarExpr::Array(
654            items
655                .iter()
656                .map(|item| rewrite_aggregate_dependencies(engine, group_by, item, dependencies))
657                .collect(),
658        ),
659        ScalarExpr::Row(items) => ScalarExpr::Row(
660            items
661                .iter()
662                .map(|item| rewrite_aggregate_dependencies(engine, group_by, item, dependencies))
663                .collect(),
664        ),
665        ScalarExpr::CompositeRow {
666            items,
667            binding,
668            bound_type,
669        } => ScalarExpr::CompositeRow {
670            items: items
671                .iter()
672                .map(|item| rewrite_aggregate_dependencies(engine, group_by, item, dependencies))
673                .collect(),
674            binding: binding.clone(),
675            bound_type: bound_type.clone(),
676        },
677        ScalarExpr::Binary { op, lhs, rhs } => ScalarExpr::Binary {
678            op: *op,
679            lhs: Box::new(rewrite_aggregate_dependencies(
680                engine,
681                group_by,
682                lhs,
683                dependencies,
684            )),
685            rhs: Box::new(rewrite_aggregate_dependencies(
686                engine,
687                group_by,
688                rhs,
689                dependencies,
690            )),
691        },
692        ScalarExpr::Not(inner) => ScalarExpr::Not(Box::new(rewrite_aggregate_dependencies(
693            engine,
694            group_by,
695            inner,
696            dependencies,
697        ))),
698        ScalarExpr::UnaryMinus(inner) => ScalarExpr::UnaryMinus(Box::new(
699            rewrite_aggregate_dependencies(engine, group_by, inner, dependencies),
700        )),
701        ScalarExpr::And(items) => ScalarExpr::And(
702            items
703                .iter()
704                .map(|item| rewrite_aggregate_dependencies(engine, group_by, item, dependencies))
705                .collect(),
706        ),
707        ScalarExpr::Or(items) => ScalarExpr::Or(
708            items
709                .iter()
710                .map(|item| rewrite_aggregate_dependencies(engine, group_by, item, dependencies))
711                .collect(),
712        ),
713        ScalarExpr::IsNull { expr, negated } => ScalarExpr::IsNull {
714            expr: Box::new(rewrite_aggregate_dependencies(
715                engine,
716                group_by,
717                expr,
718                dependencies,
719            )),
720            negated: *negated,
721        },
722        ScalarExpr::Between { expr, low, high } => ScalarExpr::Between {
723            expr: Box::new(rewrite_aggregate_dependencies(
724                engine,
725                group_by,
726                expr,
727                dependencies,
728            )),
729            low: Box::new(rewrite_aggregate_dependencies(
730                engine,
731                group_by,
732                low,
733                dependencies,
734            )),
735            high: Box::new(rewrite_aggregate_dependencies(
736                engine,
737                group_by,
738                high,
739                dependencies,
740            )),
741        },
742        ScalarExpr::InList {
743            expr,
744            list,
745            negated,
746        } => ScalarExpr::InList {
747            expr: Box::new(rewrite_aggregate_dependencies(
748                engine,
749                group_by,
750                expr,
751                dependencies,
752            )),
753            list: list
754                .iter()
755                .map(|item| rewrite_aggregate_dependencies(engine, group_by, item, dependencies))
756                .collect(),
757            negated: *negated,
758        },
759        ScalarExpr::WindowCall {
760            name,
761            args,
762            spec,
763            filter,
764            modifiers,
765        } => {
766            let mut spec = spec.clone();
767            spec.partition_by = spec
768                .partition_by
769                .iter()
770                .map(|item| rewrite_aggregate_dependencies(engine, group_by, item, dependencies))
771                .collect();
772            for order in &mut spec.order_by {
773                order.expr =
774                    rewrite_aggregate_dependencies(engine, group_by, &order.expr, dependencies);
775            }
776            if let Some(frame) = &mut spec.frame {
777                rewrite_aggregate_frame_bound(engine, group_by, &mut frame.start, dependencies);
778                rewrite_aggregate_frame_bound(engine, group_by, &mut frame.end, dependencies);
779            }
780            ScalarExpr::WindowCall {
781                modifiers: *modifiers,
782                name: name.clone(),
783                args: args
784                    .iter()
785                    .map(|argument| {
786                        rewrite_aggregate_dependencies(engine, group_by, argument, dependencies)
787                    })
788                    .collect(),
789                spec,
790                filter: filter.as_deref().map(|filter| {
791                    Box::new(rewrite_aggregate_dependencies(
792                        engine,
793                        group_by,
794                        filter,
795                        dependencies,
796                    ))
797                }),
798            }
799        }
800        ScalarExpr::Case {
801            base,
802            when,
803            else_branch,
804        } => ScalarExpr::Case {
805            base: base.as_deref().map(|base| {
806                Box::new(rewrite_aggregate_dependencies(
807                    engine,
808                    group_by,
809                    base,
810                    dependencies,
811                ))
812            }),
813            when: when
814                .iter()
815                .map(|(condition, result)| {
816                    (
817                        rewrite_aggregate_dependencies(engine, group_by, condition, dependencies),
818                        rewrite_aggregate_dependencies(engine, group_by, result, dependencies),
819                    )
820                })
821                .collect(),
822            else_branch: else_branch.as_deref().map(|branch| {
823                Box::new(rewrite_aggregate_dependencies(
824                    engine,
825                    group_by,
826                    branch,
827                    dependencies,
828                ))
829            }),
830        },
831        ScalarExpr::Collated {
832            expr,
833            ty,
834            collation,
835        } => ScalarExpr::Collated {
836            expr: Box::new(rewrite_aggregate_dependencies(
837                engine,
838                group_by,
839                expr,
840                dependencies,
841            )),
842            ty: ty.clone(),
843            collation: *collation,
844        },
845        ScalarExpr::Cast { expr, ty, implicit } => ScalarExpr::Cast {
846            implicit: *implicit,
847            expr: Box::new(rewrite_aggregate_dependencies(
848                engine,
849                group_by,
850                expr,
851                dependencies,
852            )),
853            ty: ty.clone(),
854        },
855        ScalarExpr::InSubquery {
856            expr,
857            subquery,
858            negated,
859        } => ScalarExpr::InSubquery {
860            expr: Box::new(rewrite_aggregate_dependencies(
861                engine,
862                group_by,
863                expr,
864                dependencies,
865            )),
866            subquery: *subquery,
867            negated: *negated,
868        },
869        ScalarExpr::Default
870        | ScalarExpr::Star
871        | ScalarExpr::QualifiedStar(_)
872        | ScalarExpr::Literal(_)
873        | ScalarExpr::TypedLiteral { .. }
874        | ScalarExpr::RetainedLiteral(_)
875        | ScalarExpr::Param(_)
876        | ScalarExpr::ScalarSubquery(_)
877        | ScalarExpr::Exists { .. } => expression.clone(),
878    }
879}
880
881fn rewrite_aggregate_frame_bound(
882    engine: &dyn SetFunctionCatalog,
883    group_by: &[&ScalarExpr],
884    bound: &mut ScalarFrameBound,
885    dependencies: &mut Vec<ProjectionPlan>,
886) {
887    match bound {
888        ScalarFrameBound::Preceding(expression) | ScalarFrameBound::Following(expression) => {
889            **expression =
890                rewrite_aggregate_dependencies(engine, group_by, expression, dependencies);
891        }
892        ScalarFrameBound::UnboundedPreceding
893        | ScalarFrameBound::UnboundedFollowing
894        | ScalarFrameBound::CurrentRow => {}
895    }
896}
897
898pub fn prepare_aggregate_output_projection(
899    engine: &dyn SetFunctionCatalog,
900    statement: &QueryBlockPlan,
901    internal_targets: &[(usize, crate::ast::InternalColumnRef)],
902) -> AggregateOutputProjectionPlan {
903    let labels = projection_columns(&statement.projections);
904    // A grouping-set expression remains one aggregate dependency. Splitting it into its input columns would replace those ungrouped inputs with NULL before evaluating the final projection.
905    let group_by = statement
906        .group_by
907        .iter()
908        .chain(statement.grouping_sets.iter().flatten())
909        .collect::<Vec<_>>();
910    let mut dependencies = Vec::new();
911    let projections = statement
912        .projections
913        .iter()
914        .enumerate()
915        .zip(labels)
916        .map(|((position, projection), label)| {
917            let target = internal_targets
918                .iter()
919                .find(|(target_position, _)| *target_position == position)
920                .map_or_else(
921                    || ProjectionTarget::Column(label),
922                    |(_, column)| ProjectionTarget::Internal(*column),
923                );
924            (
925                target,
926                rewrite_aggregate_dependencies(
927                    engine,
928                    &group_by,
929                    &projection.expr,
930                    &mut dependencies,
931                ),
932            )
933        })
934        .collect();
935    if dependencies.is_empty() {
936        dependencies.push(ProjectionPlan {
937            expr: ScalarExpr::Literal(Value::Int(1)),
938            alias: None,
939        });
940    }
941    let mut aggregate_statement = statement.clone();
942    aggregate_statement.projections = dependencies;
943    AggregateOutputProjectionPlan {
944        statement: aggregate_statement,
945        projections,
946    }
947}