Skip to main content

uqa_sql/ir/
traversal.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Complete scalar IR traversal.
8
9use super::{ScalarExpr, ScalarFrameBound};
10
11impl ScalarExpr {
12    /// Visit this expression and every nested scalar expression in pre-order.
13    pub fn visit(&self, visitor: &mut impl FnMut(&Self)) {
14        self.try_visit(&mut |expression| {
15            visitor(expression);
16            Ok::<_, std::convert::Infallible>(true)
17        })
18        .unwrap_or_else(|never| match never {});
19    }
20
21    /// Visit a window call's arguments, `FILTER` condition, partition and ordering keys, and frame offsets.
22    fn try_visit_window<'a, E>(
23        args: &'a [Self],
24        filter: Option<&'a Self>,
25        spec: &'a super::ScalarWindowSpec,
26        visitor: &mut impl FnMut(&'a Self) -> Result<bool, E>,
27    ) -> Result<(), E> {
28        for expression in args
29            .iter()
30            .chain(filter)
31            .chain(&spec.partition_by)
32            .chain(spec.order_by.iter().map(|order| &order.expr))
33        {
34            expression.try_visit(visitor)?;
35        }
36        for bound in spec
37            .frame
38            .iter()
39            .flat_map(|frame| [&frame.start, &frame.end])
40        {
41            if let ScalarFrameBound::Preceding(expression)
42            | ScalarFrameBound::Following(expression) = bound
43            {
44                expression.try_visit(visitor)?;
45            }
46        }
47        Ok(())
48    }
49
50    /// Visit in pre-order, skipping a subtree when the visitor returns false and stopping immediately on its first error.
51    pub fn try_visit<'a, E>(
52        &'a self,
53        visitor: &mut impl FnMut(&'a Self) -> Result<bool, E>,
54    ) -> Result<(), E> {
55        if !visitor(self)? {
56            return Ok(());
57        }
58        match self {
59            Self::And(parts)
60            | Self::Or(parts)
61            | Self::Array(parts)
62            | Self::Row(parts)
63            | Self::CompositeRow { items: parts, .. } => {
64                for part in parts {
65                    part.try_visit(visitor)?;
66                }
67            }
68            Self::Not(inner)
69            | Self::UnaryMinus(inner)
70            | Self::Cast { expr: inner, .. }
71            | Self::Collated { expr: inner, .. }
72            | Self::IsNull { expr: inner, .. }
73            | Self::InSubquery { expr: inner, .. } => inner.try_visit(visitor)?,
74            Self::Binary { lhs, rhs, .. } => {
75                lhs.try_visit(visitor)?;
76                rhs.try_visit(visitor)?;
77            }
78            Self::Between { expr, low, high } => {
79                expr.try_visit(visitor)?;
80                low.try_visit(visitor)?;
81                high.try_visit(visitor)?;
82            }
83            Self::InList { expr, list, .. } => {
84                expr.try_visit(visitor)?;
85                for part in list {
86                    part.try_visit(visitor)?;
87                }
88            }
89            Self::Func {
90                args,
91                order_by,
92                filter,
93                ..
94            } => {
95                for argument in args {
96                    argument.try_visit(visitor)?;
97                }
98                for order in order_by {
99                    order.expr.try_visit(visitor)?;
100                }
101                if let Some(filter) = filter {
102                    filter.try_visit(visitor)?;
103                }
104            }
105            Self::WindowCall {
106                args, spec, filter, ..
107            } => Self::try_visit_window(args, filter.as_deref(), spec, visitor)?,
108            Self::Case {
109                base,
110                when,
111                else_branch,
112            } => {
113                if let Some(base) = base {
114                    base.try_visit(visitor)?;
115                }
116                for (condition, result) in when {
117                    condition.try_visit(visitor)?;
118                    result.try_visit(visitor)?;
119                }
120                if let Some(else_branch) = else_branch {
121                    else_branch.try_visit(visitor)?;
122                }
123            }
124            Self::Default
125            | Self::Star
126            | Self::QualifiedStar(_)
127            | Self::Column(_)
128            | Self::Position(_)
129            | Self::InternalColumn(_)
130            | Self::QualifiedColumn { .. }
131            | Self::Literal(_)
132            | Self::TypedLiteral { .. }
133            | Self::RetainedLiteral(_)
134            | Self::Param(_)
135            | Self::ScalarSubquery(_)
136            | Self::Exists { .. } => {}
137        }
138        Ok(())
139    }
140
141    /// Visit a window call's arguments, `FILTER` condition, partition and ordering keys, and frame offsets mutably.
142    fn visit_window_mut(
143        args: &mut [Self],
144        filter: Option<&mut Self>,
145        spec: &mut super::ScalarWindowSpec,
146        visitor: &mut impl FnMut(&mut Self),
147    ) {
148        for expression in args
149            .iter_mut()
150            .chain(filter)
151            .chain(&mut spec.partition_by)
152            .chain(spec.order_by.iter_mut().map(|order| &mut order.expr))
153        {
154            expression.visit_mut(visitor);
155        }
156        for bound in spec
157            .frame
158            .iter_mut()
159            .flat_map(|frame| [&mut frame.start, &mut frame.end])
160        {
161            if let ScalarFrameBound::Preceding(expression)
162            | ScalarFrameBound::Following(expression) = bound
163            {
164                expression.visit_mut(visitor);
165            }
166        }
167    }
168
169    /// Visit this expression and every nested scalar expression mutably in pre-order: a node is visited before its children, so the children of a node the visitor replaces are those of the replacement.
170    pub fn visit_mut(&mut self, visitor: &mut impl FnMut(&mut Self)) {
171        visitor(self);
172        match self {
173            Self::And(parts)
174            | Self::Or(parts)
175            | Self::Array(parts)
176            | Self::Row(parts)
177            | Self::CompositeRow { items: parts, .. } => {
178                for part in parts {
179                    part.visit_mut(visitor);
180                }
181            }
182            Self::Not(inner)
183            | Self::UnaryMinus(inner)
184            | Self::Cast { expr: inner, .. }
185            | Self::Collated { expr: inner, .. }
186            | Self::IsNull { expr: inner, .. }
187            | Self::InSubquery { expr: inner, .. } => inner.visit_mut(visitor),
188            Self::Binary { lhs, rhs, .. } => {
189                lhs.visit_mut(visitor);
190                rhs.visit_mut(visitor);
191            }
192            Self::Between { expr, low, high } => {
193                expr.visit_mut(visitor);
194                low.visit_mut(visitor);
195                high.visit_mut(visitor);
196            }
197            Self::InList { expr, list, .. } => {
198                expr.visit_mut(visitor);
199                for part in list {
200                    part.visit_mut(visitor);
201                }
202            }
203            Self::Func {
204                args,
205                order_by,
206                filter,
207                ..
208            } => {
209                for argument in args {
210                    argument.visit_mut(visitor);
211                }
212                for order in order_by {
213                    order.expr.visit_mut(visitor);
214                }
215                if let Some(filter) = filter {
216                    filter.visit_mut(visitor);
217                }
218            }
219            Self::WindowCall {
220                args, spec, filter, ..
221            } => Self::visit_window_mut(args, filter.as_deref_mut(), spec, visitor),
222            Self::Case {
223                base,
224                when,
225                else_branch,
226            } => {
227                if let Some(base) = base {
228                    base.visit_mut(visitor);
229                }
230                for (condition, result) in when {
231                    condition.visit_mut(visitor);
232                    result.visit_mut(visitor);
233                }
234                if let Some(else_branch) = else_branch {
235                    else_branch.visit_mut(visitor);
236                }
237            }
238            Self::Default
239            | Self::Star
240            | Self::QualifiedStar(_)
241            | Self::Column(_)
242            | Self::Position(_)
243            | Self::InternalColumn(_)
244            | Self::QualifiedColumn { .. }
245            | Self::Literal(_)
246            | Self::TypedLiteral { .. }
247            | Self::RetainedLiteral(_)
248            | Self::Param(_)
249            | Self::ScalarSubquery(_)
250            | Self::Exists { .. } => {}
251        }
252    }
253
254    /// Collect every column needed to evaluate this expression. Returns `false` when evaluation needs row shape or a relational child that a projected field scan cannot provide.
255    pub fn collect_columns(&self, output: &mut std::collections::BTreeSet<String>) -> bool {
256        match self.try_visit_columns(&mut |name| {
257            output.insert(name.to_owned());
258            Ok::<_, std::convert::Infallible>(())
259        }) {
260            Ok(projectable) => projectable,
261            Err(never) => match never {},
262        }
263    }
264
265    /// Borrow referenced column names in evaluation-tree order, stopping at the first visitor failure or unprojectable expression. Qualified references yield their column component, matching `collect_columns`; repeated references remain visible to the visitor. No name or result container is allocated by this traversal.
266    pub fn try_visit_columns<'a, E>(
267        &'a self,
268        visitor: &mut impl FnMut(&'a str) -> Result<(), E>,
269    ) -> Result<bool, E> {
270        match self {
271            Self::Column(name) | Self::QualifiedColumn { column: name, .. } => {
272                visitor(name)?;
273                Ok(true)
274            }
275            Self::Literal(_)
276            | Self::TypedLiteral { .. }
277            | Self::RetainedLiteral(_)
278            | Self::Param(_)
279            | Self::InternalColumn(_) => Ok(true),
280            Self::Func {
281                args,
282                order_by,
283                filter,
284                ..
285            } => {
286                for expression in args
287                    .iter()
288                    .chain(order_by.iter().map(|order| &order.expr))
289                    .chain(filter.as_deref())
290                {
291                    if !expression.try_visit_columns(visitor)? {
292                        return Ok(false);
293                    }
294                }
295                Ok(true)
296            }
297            Self::Array(items)
298            | Self::Row(items)
299            | Self::CompositeRow { items, .. }
300            | Self::And(items)
301            | Self::Or(items) => {
302                for item in items {
303                    if !item.try_visit_columns(visitor)? {
304                        return Ok(false);
305                    }
306                }
307                Ok(true)
308            }
309            Self::Binary { lhs, rhs, .. } => {
310                Ok(lhs.try_visit_columns(visitor)? && rhs.try_visit_columns(visitor)?)
311            }
312            Self::UnaryMinus(expr)
313            | Self::Not(expr)
314            | Self::IsNull { expr, .. }
315            | Self::Cast { expr, .. }
316            | Self::Collated { expr, .. } => expr.try_visit_columns(visitor),
317            Self::Between { expr, low, high } => Ok(expr.try_visit_columns(visitor)?
318                && low.try_visit_columns(visitor)?
319                && high.try_visit_columns(visitor)?),
320            Self::InList { expr, list, .. } => {
321                for item in std::iter::once(expr.as_ref()).chain(list) {
322                    if !item.try_visit_columns(visitor)? {
323                        return Ok(false);
324                    }
325                }
326                Ok(true)
327            }
328            Self::Case {
329                base,
330                when,
331                else_branch,
332            } => {
333                for expression in base
334                    .as_deref()
335                    .into_iter()
336                    .chain(
337                        when.iter()
338                            .flat_map(|(condition, result)| [condition, result]),
339                    )
340                    .chain(else_branch.as_deref())
341                {
342                    if !expression.try_visit_columns(visitor)? {
343                        return Ok(false);
344                    }
345                }
346                Ok(true)
347            }
348            Self::Default
349            | Self::Star
350            | Self::QualifiedStar(_)
351            | Self::Position(_)
352            | Self::WindowCall { .. }
353            | Self::ScalarSubquery(_)
354            | Self::Exists { .. }
355            | Self::InSubquery { .. } => Ok(false),
356        }
357    }
358
359    #[must_use]
360    pub fn contains_window(&self) -> bool {
361        match self {
362            Self::WindowCall { .. } => true,
363            Self::Func {
364                args,
365                order_by,
366                filter,
367                ..
368            } => {
369                args.iter().any(Self::contains_window)
370                    || order_by.iter().any(|order| order.expr.contains_window())
371                    || filter.as_deref().is_some_and(Self::contains_window)
372            }
373            Self::Array(items)
374            | Self::Row(items)
375            | Self::CompositeRow { items, .. }
376            | Self::And(items)
377            | Self::Or(items) => items.iter().any(Self::contains_window),
378            Self::Binary { lhs, rhs, .. } => lhs.contains_window() || rhs.contains_window(),
379            Self::UnaryMinus(expr)
380            | Self::Not(expr)
381            | Self::IsNull { expr, .. }
382            | Self::Cast { expr, .. }
383            | Self::Collated { expr, .. }
384            | Self::InSubquery { expr, .. } => expr.contains_window(),
385            Self::Between { expr, low, high } => {
386                expr.contains_window() || low.contains_window() || high.contains_window()
387            }
388            Self::InList { expr, list, .. } => {
389                expr.contains_window() || list.iter().any(Self::contains_window)
390            }
391            Self::Case {
392                base,
393                when,
394                else_branch,
395            } => {
396                base.as_deref().is_some_and(Self::contains_window)
397                    || when.iter().any(|(condition, result)| {
398                        condition.contains_window() || result.contains_window()
399                    })
400                    || else_branch.as_deref().is_some_and(Self::contains_window)
401            }
402            Self::Default
403            | Self::Star
404            | Self::QualifiedStar(_)
405            | Self::Column(_)
406            | Self::QualifiedColumn { .. }
407            | Self::Position(_)
408            | Self::InternalColumn(_)
409            | Self::Literal(_)
410            | Self::TypedLiteral { .. }
411            | Self::RetainedLiteral(_)
412            | Self::Param(_)
413            | Self::ScalarSubquery(_)
414            | Self::Exists { .. } => false,
415        }
416    }
417
418    #[must_use]
419    pub fn contains_subquery(&self) -> bool {
420        match self {
421            Self::ScalarSubquery(_) | Self::Exists { .. } | Self::InSubquery { .. } => true,
422            Self::Func {
423                args,
424                order_by,
425                filter,
426                ..
427            } => {
428                args.iter().any(Self::contains_subquery)
429                    || order_by.iter().any(|order| order.expr.contains_subquery())
430                    || filter.as_deref().is_some_and(Self::contains_subquery)
431            }
432            Self::Array(items)
433            | Self::Row(items)
434            | Self::CompositeRow { items, .. }
435            | Self::And(items)
436            | Self::Or(items) => items.iter().any(Self::contains_subquery),
437            Self::Binary { lhs, rhs, .. } => lhs.contains_subquery() || rhs.contains_subquery(),
438            Self::UnaryMinus(expr)
439            | Self::Not(expr)
440            | Self::IsNull { expr, .. }
441            | Self::Cast { expr, .. }
442            | Self::Collated { expr, .. } => expr.contains_subquery(),
443            Self::Between { expr, low, high } => {
444                expr.contains_subquery() || low.contains_subquery() || high.contains_subquery()
445            }
446            Self::InList { expr, list, .. } => {
447                expr.contains_subquery() || list.iter().any(Self::contains_subquery)
448            }
449            Self::WindowCall {
450                args, spec, filter, ..
451            } => {
452                args.iter().any(Self::contains_subquery)
453                    || filter.as_deref().is_some_and(Self::contains_subquery)
454                    || spec.partition_by.iter().any(Self::contains_subquery)
455                    || spec
456                        .order_by
457                        .iter()
458                        .any(|order| order.expr.contains_subquery())
459                    || spec.frame.as_ref().is_some_and(|frame| {
460                        frame_has(&frame.start, Self::contains_subquery)
461                            || frame_has(&frame.end, Self::contains_subquery)
462                    })
463            }
464            Self::Case {
465                base,
466                when,
467                else_branch,
468            } => {
469                base.as_deref().is_some_and(Self::contains_subquery)
470                    || when.iter().any(|(condition, result)| {
471                        condition.contains_subquery() || result.contains_subquery()
472                    })
473                    || else_branch.as_deref().is_some_and(Self::contains_subquery)
474            }
475            Self::Default
476            | Self::Star
477            | Self::QualifiedStar(_)
478            | Self::Column(_)
479            | Self::QualifiedColumn { .. }
480            | Self::Position(_)
481            | Self::InternalColumn(_)
482            | Self::Literal(_)
483            | Self::TypedLiteral { .. }
484            | Self::RetainedLiteral(_)
485            | Self::Param(_) => false,
486        }
487    }
488
489    #[must_use]
490    pub fn contains_parameter(&self) -> bool {
491        match self {
492            Self::Param(_) => true,
493            Self::Func {
494                args,
495                order_by,
496                filter,
497                ..
498            } => {
499                args.iter().any(Self::contains_parameter)
500                    || order_by.iter().any(|order| order.expr.contains_parameter())
501                    || filter.as_deref().is_some_and(Self::contains_parameter)
502            }
503            Self::Array(items)
504            | Self::Row(items)
505            | Self::CompositeRow { items, .. }
506            | Self::And(items)
507            | Self::Or(items) => items.iter().any(Self::contains_parameter),
508            Self::Binary { lhs, rhs, .. } => lhs.contains_parameter() || rhs.contains_parameter(),
509            Self::UnaryMinus(expr)
510            | Self::Not(expr)
511            | Self::IsNull { expr, .. }
512            | Self::Cast { expr, .. }
513            | Self::Collated { expr, .. }
514            | Self::InSubquery { expr, .. } => expr.contains_parameter(),
515            Self::Between { expr, low, high } => {
516                expr.contains_parameter() || low.contains_parameter() || high.contains_parameter()
517            }
518            Self::InList { expr, list, .. } => {
519                expr.contains_parameter() || list.iter().any(Self::contains_parameter)
520            }
521            Self::WindowCall {
522                args, spec, filter, ..
523            } => {
524                args.iter().any(Self::contains_parameter)
525                    || filter.as_deref().is_some_and(Self::contains_parameter)
526                    || spec.partition_by.iter().any(Self::contains_parameter)
527                    || spec
528                        .order_by
529                        .iter()
530                        .any(|order| order.expr.contains_parameter())
531                    || spec.frame.as_ref().is_some_and(|frame| {
532                        frame_has(&frame.start, Self::contains_parameter)
533                            || frame_has(&frame.end, Self::contains_parameter)
534                    })
535            }
536            Self::Case {
537                base,
538                when,
539                else_branch,
540            } => {
541                base.as_deref().is_some_and(Self::contains_parameter)
542                    || when.iter().any(|(condition, result)| {
543                        condition.contains_parameter() || result.contains_parameter()
544                    })
545                    || else_branch.as_deref().is_some_and(Self::contains_parameter)
546            }
547            Self::Default
548            | Self::Star
549            | Self::QualifiedStar(_)
550            | Self::Column(_)
551            | Self::QualifiedColumn { .. }
552            | Self::Position(_)
553            | Self::InternalColumn(_)
554            | Self::Literal(_)
555            | Self::TypedLiteral { .. }
556            | Self::RetainedLiteral(_)
557            | Self::ScalarSubquery(_)
558            | Self::Exists { .. } => false,
559        }
560    }
561
562    #[must_use]
563    pub fn contains_aggregate(&self, is_aggregate: &dyn Fn(&str) -> bool) -> bool {
564        match self {
565            Self::Func {
566                name,
567                args,
568                order_by,
569                filter,
570                ..
571            } => {
572                is_aggregate(name)
573                    || args
574                        .iter()
575                        .any(|expression| expression.contains_aggregate(is_aggregate))
576                    || order_by
577                        .iter()
578                        .any(|order| order.expr.contains_aggregate(is_aggregate))
579                    || filter
580                        .as_deref()
581                        .is_some_and(|expression| expression.contains_aggregate(is_aggregate))
582            }
583            Self::Array(items)
584            | Self::Row(items)
585            | Self::CompositeRow { items, .. }
586            | Self::And(items)
587            | Self::Or(items) => items
588                .iter()
589                .any(|expression| expression.contains_aggregate(is_aggregate)),
590            Self::Binary { lhs, rhs, .. } => {
591                lhs.contains_aggregate(is_aggregate) || rhs.contains_aggregate(is_aggregate)
592            }
593            Self::UnaryMinus(expr)
594            | Self::Not(expr)
595            | Self::IsNull { expr, .. }
596            | Self::Cast { expr, .. }
597            | Self::Collated { expr, .. }
598            | Self::InSubquery { expr, .. } => expr.contains_aggregate(is_aggregate),
599            Self::Between { expr, low, high } => {
600                expr.contains_aggregate(is_aggregate)
601                    || low.contains_aggregate(is_aggregate)
602                    || high.contains_aggregate(is_aggregate)
603            }
604            Self::InList { expr, list, .. } => {
605                expr.contains_aggregate(is_aggregate)
606                    || list
607                        .iter()
608                        .any(|item| item.contains_aggregate(is_aggregate))
609            }
610            Self::Case {
611                base,
612                when,
613                else_branch,
614            } => {
615                base.as_deref()
616                    .is_some_and(|expression| expression.contains_aggregate(is_aggregate))
617                    || when.iter().any(|(condition, result)| {
618                        condition.contains_aggregate(is_aggregate)
619                            || result.contains_aggregate(is_aggregate)
620                    })
621                    || else_branch
622                        .as_deref()
623                        .is_some_and(|expression| expression.contains_aggregate(is_aggregate))
624            }
625            Self::Default
626            | Self::Star
627            | Self::QualifiedStar(_)
628            | Self::Column(_)
629            | Self::QualifiedColumn { .. }
630            | Self::Position(_)
631            | Self::InternalColumn(_)
632            | Self::Literal(_)
633            | Self::TypedLiteral { .. }
634            | Self::RetainedLiteral(_)
635            | Self::Param(_)
636            | Self::ScalarSubquery(_)
637            | Self::Exists { .. }
638            | Self::WindowCall { .. } => false,
639        }
640    }
641}
642
643fn frame_has(bound: &ScalarFrameBound, predicate: fn(&ScalarExpr) -> bool) -> bool {
644    match bound {
645        ScalarFrameBound::Preceding(expression) | ScalarFrameBound::Following(expression) => {
646            predicate(expression)
647        }
648        ScalarFrameBound::UnboundedPreceding
649        | ScalarFrameBound::UnboundedFollowing
650        | ScalarFrameBound::CurrentRow => false,
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use super::{ScalarExpr, ScalarFrameBound};
657    use crate::ast::{FrameExclusion, FrameMode};
658    use uqa_core::Value;
659
660    #[test]
661    fn visit_includes_root_and_nested_expressions() {
662        let expression = ScalarExpr::Binary {
663            op: crate::ast::BinaryOp::Add,
664            lhs: Box::new(ScalarExpr::Column("amount".into())),
665            rhs: Box::new(ScalarExpr::Literal(Value::Int(1))),
666        };
667        let mut visited = Vec::new();
668        expression.visit(&mut |part| visited.push(part.clone()));
669        assert_eq!(visited.len(), 3);
670        assert_eq!(visited[0], expression);
671    }
672
673    #[test]
674    fn fallible_visits_skip_selected_subtrees_and_stop_before_later_siblings() {
675        let expression = ScalarExpr::Row(vec![
676            ScalarExpr::Array(vec![ScalarExpr::Column("hidden".into())]),
677            ScalarExpr::Column("reject".into()),
678            ScalarExpr::Column("unvisited".into()),
679        ]);
680        let mut visited = Vec::new();
681        let result = expression.try_visit(&mut |part| {
682            visited.push(part.clone());
683            match part {
684                ScalarExpr::Array(_) => Ok(false),
685                ScalarExpr::Column(name) if name == "reject" => Err("grouping"),
686                _ => Ok(true),
687            }
688        });
689        assert_eq!(result, Err("grouping"));
690        assert_eq!(visited.len(), 3);
691        assert!(matches!(&visited[2], ScalarExpr::Column(name) if name == "reject"));
692    }
693
694    #[test]
695    fn traversal_includes_window_frame_expressions() {
696        let expression = ScalarExpr::WindowCall {
697            name: "sum".into(),
698            args: vec![ScalarExpr::Column("amount".into())],
699            spec: super::super::ScalarWindowSpec {
700                definition: None,
701                partition_by: vec![ScalarExpr::QualifiedColumn {
702                    qualifier: "orders".into(),
703                    column: "account_id".into(),
704                }],
705                order_by: Vec::new(),
706                frame: Some(super::super::ScalarWindowFrame {
707                    mode: FrameMode::Rows,
708                    start: ScalarFrameBound::Preceding(Box::new(ScalarExpr::Param(0))),
709                    end: ScalarFrameBound::CurrentRow,
710                    between: true,
711                    exclusion: FrameExclusion::NoOthers,
712                }),
713            },
714            filter: None,
715            modifiers: crate::ast::WindowCallModifiers::default(),
716        };
717        let mut visited_parameter = false;
718        expression.visit(&mut |part| {
719            visited_parameter |= matches!(part, ScalarExpr::Param(0));
720        });
721        assert!(visited_parameter);
722        assert!(expression.contains_window());
723        assert!(expression.contains_parameter());
724    }
725
726    #[test]
727    fn mutable_visits_rewrite_nested_expressions() {
728        let literal = || ScalarExpr::Literal(Value::Str("t".into()));
729        let mut expression = ScalarExpr::Cast {
730            implicit: false,
731            expr: Box::new(ScalarExpr::Case {
732                base: None,
733                when: vec![(
734                    literal(),
735                    ScalarExpr::Cast {
736                        implicit: false,
737                        expr: Box::new(literal()),
738                        ty: "regclass".into(),
739                    },
740                )],
741                else_branch: Some(Box::new(ScalarExpr::WindowCall {
742                    name: "sum".into(),
743                    args: vec![literal()],
744                    spec: super::super::ScalarWindowSpec {
745                        definition: None,
746                        partition_by: Vec::new(),
747                        order_by: Vec::new(),
748                        frame: Some(super::super::ScalarWindowFrame {
749                            mode: FrameMode::Rows,
750                            start: ScalarFrameBound::Preceding(Box::new(literal())),
751                            end: ScalarFrameBound::CurrentRow,
752                            between: true,
753                            exclusion: FrameExclusion::NoOthers,
754                        }),
755                    },
756                    filter: Some(Box::new(literal())),
757                    modifiers: crate::ast::WindowCallModifiers::default(),
758                })),
759            }),
760            ty: "text".into(),
761        };
762        let mut rewritten = 0;
763        expression.visit_mut(&mut |part| {
764            if matches!(part, ScalarExpr::Literal(Value::Str(_))) {
765                *part = ScalarExpr::Literal(Value::Int(1));
766                rewritten += 1;
767            }
768        });
769        assert_eq!(rewritten, 5);
770        let mut remaining = 0;
771        expression.visit(&mut |part| {
772            remaining += usize::from(matches!(part, ScalarExpr::Literal(Value::Str(_))));
773        });
774        assert_eq!(remaining, 0);
775    }
776
777    #[test]
778    fn owned_walkers_preserve_column_and_aggregate_policy() {
779        let expression = ScalarExpr::Func {
780            order_syntax: crate::ast::FunctionOrderSyntax::Ordinary,
781            name: "sum".into(),
782            binding: None,
783            args: vec![ScalarExpr::QualifiedColumn {
784                qualifier: "orders".into(),
785                column: "amount".into(),
786            }],
787            distinct: false,
788            order_by: Vec::new(),
789            filter: None,
790        };
791        let mut columns = std::collections::BTreeSet::new();
792        assert!(expression.collect_columns(&mut columns));
793        assert_eq!(columns, std::collections::BTreeSet::from(["amount".into()]));
794        assert!(expression.contains_aggregate(&|name| name == "sum"));
795        assert!(!expression.contains_subquery());
796    }
797
798    #[test]
799    fn borrowed_column_visits_keep_names_and_stop_at_the_first_failure() {
800        let expression = ScalarExpr::Row(vec![
801            ScalarExpr::Column("first".into()),
802            ScalarExpr::QualifiedColumn {
803                qualifier: "table".into(),
804                column: "second".into(),
805            },
806            ScalarExpr::Column("first".into()),
807        ]);
808        let mut borrowed = Vec::new();
809        assert!(expression
810            .try_visit_columns(&mut |name| {
811                borrowed.push(name);
812                Ok::<_, &str>(())
813            })
814            .unwrap());
815        assert_eq!(borrowed, ["first", "second", "first"]);
816        let ScalarExpr::Row(items) = &expression else {
817            unreachable!()
818        };
819        let ScalarExpr::Column(first) = &items[0] else {
820            unreachable!()
821        };
822        assert_eq!(borrowed[0].as_ptr(), first.as_ptr());
823        let mut visits = 0;
824        let result = expression.try_visit_columns(&mut |_| {
825            visits += 1;
826            if visits == 2 {
827                Err("quota")
828            } else {
829                Ok(())
830            }
831        });
832        assert_eq!(result, Err("quota"));
833        assert_eq!(visits, 2);
834    }
835
836    #[test]
837    fn borrowed_column_visits_preserve_unprojectable_prefix_semantics() {
838        let expression = ScalarExpr::Array(vec![
839            ScalarExpr::Column("before".into()),
840            ScalarExpr::Position(0),
841            ScalarExpr::Column("after".into()),
842        ]);
843        let mut borrowed = Vec::new();
844        assert!(!expression
845            .try_visit_columns(&mut |name| {
846                borrowed.push(name);
847                Ok::<_, &str>(())
848            })
849            .unwrap());
850        let mut owned = std::collections::BTreeSet::new();
851        assert!(!expression.collect_columns(&mut owned));
852        assert_eq!(borrowed, ["before"]);
853        assert_eq!(owned, std::collections::BTreeSet::from(["before".into()]));
854    }
855}