Skip to main content

datafusion_match_recognize/planning/source/
expr.rs

1// Licensed under the Apache License, Version 2.0 (the
2// "License"); you may not use this file except in compliance
3// with the License.  You may obtain a copy of the License at
4//
5//   http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing,
8// software distributed under the License is distributed on an
9// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10// KIND, either express or implied.  See the License for the
11// specific language governing permissions and limitations
12// under the License.
13//
14// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.
15
16use std::fmt;
17
18use datafusion::arrow::datatypes::DataType;
19use datafusion::common::{Column, Result, ScalarValue};
20use datafusion::logical_expr::{Expr, Operator, expr};
21
22type MatchCaseBranch<Input, InputColumn, PatternField, CastType> = (
23    MatchExpr<Input, InputColumn, PatternField, CastType>,
24    MatchExpr<Input, InputColumn, PatternField, CastType>,
25);
26
27/// Expression syntax shared by all importers before and after binding.
28///
29/// The type parameters describe the format-specific leaves: an input
30/// expression, an input column, a pattern-qualified field, and a cast type. SQL
31/// uses parser values for those leaves. After binding, the same tree contains
32/// DataFusion expressions, resolved columns, and Arrow data types. Importers
33/// therefore share one recursive expression structure.
34#[derive(Clone, Debug, PartialEq)]
35pub enum MatchExpr<Input, InputColumn, PatternField, CastType = DataType> {
36    /// An importer-native expression over ordinary input columns.
37    InputExpr(Input),
38    /// One ordinary input-column reference represented by the importer.
39    InputColumn(InputColumn),
40    /// One input field qualified by a row-pattern symbol.
41    PatternField(PatternField),
42    /// A `MATCH_RECOGNIZE` metadata function call.
43    Metadata(MatchMetadataFunction),
44    /// A pattern-aware navigation call.
45    Navigation(MatchNavigation<Input, InputColumn, PatternField, CastType>),
46    /// A match-aware aggregate call.
47    Aggregate(MatchAggregateCall<Input, InputColumn, PatternField, CastType>),
48    /// An expression with an output alias.
49    Alias {
50        /// Expression being named.
51        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
52        /// Alias assigned to the expression.
53        name: String,
54    },
55    /// A scalar function resolved during lowering.
56    ScalarFunction {
57        /// Registry name or reserved built-in identity.
58        name: String,
59        /// Function arguments in source order.
60        args: Vec<MatchExpr<Input, InputColumn, PatternField, CastType>>,
61    },
62    /// A unary Boolean or arithmetic expression.
63    Unary {
64        /// Unary operator.
65        op: MatchUnaryOperator,
66        /// Operand.
67        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
68    },
69    /// A binary expression using a DataFusion operator.
70    Binary {
71        /// Left operand.
72        left: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
73        /// DataFusion binary operator.
74        op: Operator,
75        /// Right operand.
76        right: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
77    },
78    /// A SQL `LIKE`, `ILIKE`, or `SIMILAR TO` predicate.
79    Like {
80        /// Whether the predicate is negated.
81        negated: bool,
82        /// Value being tested.
83        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
84        /// Pattern expression.
85        pattern: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
86        /// Optional single-character escape.
87        escape_char: Option<char>,
88        /// Whether the comparison ignores case.
89        case_insensitive: bool,
90        /// Whether this uses `SIMILAR TO` rather than `LIKE`.
91        similar: bool,
92    },
93    /// A searched or simple SQL `CASE` expression.
94    Case {
95        /// Simple-`CASE` base expression; `None` denotes searched `CASE`.
96        expr: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
97        /// Ordered `(WHEN, THEN)` branches.
98        when_then: Vec<MatchCaseBranch<Input, InputColumn, PatternField, CastType>>,
99        /// Optional `ELSE` expression.
100        else_expr: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
101    },
102    /// An SQL null or truth-value predicate.
103    Predicate {
104        /// Predicate applied to `expr`.
105        kind: MatchPredicateKind,
106        /// Predicate input.
107        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
108    },
109    /// An inclusive range predicate.
110    Between {
111        /// Value being tested.
112        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
113        /// Whether this is `NOT BETWEEN`.
114        negated: bool,
115        /// Inclusive lower bound.
116        low: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
117        /// Inclusive upper bound.
118        high: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
119    },
120    /// A list-membership predicate.
121    InList {
122        /// Value being tested.
123        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
124        /// Candidate values.
125        list: Vec<MatchExpr<Input, InputColumn, PatternField, CastType>>,
126        /// Whether this is `NOT IN`.
127        negated: bool,
128    },
129    /// An explicit cast with DataFusion SQL semantics after binding.
130    ///
131    /// In particular, an Int64 value cast to a nanosecond timestamp counts as
132    /// seconds. This applies to every frontend supplying [`BoundMatchExpr`].
133    Cast {
134        /// Value being cast.
135        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
136        /// Importer-specific target type, resolved to Arrow [`DataType`] by binding.
137        data_type: CastType,
138    },
139    /// A typed DataFusion scalar literal.
140    Literal(ScalarValue),
141}
142
143/// Source expression after every importer-specific leaf has been bound to
144/// DataFusion and Arrow types.
145pub type BoundMatchExpr = MatchExpr<Expr, Column, MatchPatternFieldRef>;
146
147/// A bound input column qualified by a row-pattern symbol.
148#[derive(Clone, Debug, PartialEq, Eq, Hash)]
149pub struct MatchPatternFieldRef {
150    /// Declared pattern-symbol name.
151    pub symbol: String,
152    /// Resolved input column.
153    pub column: Column,
154}
155
156/// Metadata values available inside a `MATCH_RECOGNIZE` request.
157#[derive(Clone, Debug, PartialEq, Eq, Hash)]
158pub enum MatchMetadataFunction {
159    /// Name of the symbol that classified the row.
160    Classifier,
161    /// One-based selected-match number within the partition.
162    MatchNumber,
163    /// One-based row position within the match.
164    MatchSequenceNumber,
165    /// Whether the row was consumed inside an exclusion block.
166    Excluded,
167}
168
169/// Pattern-aware navigation syntax shared by source importers.
170#[derive(Clone, Debug, PartialEq)]
171pub enum MatchNavigation<Input, InputColumn, PatternField, CastType = DataType> {
172    /// First value in the call's row domain.
173    First {
174        /// Navigated value expression.
175        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
176        /// Optional logical offset expression; `None` defaults to `0`.
177        offset: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
178    },
179    /// Last value in the call's row domain.
180    Last {
181        /// Navigated value expression.
182        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
183        /// Optional logical offset expression; `None` defaults to `0`.
184        offset: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
185    },
186    /// Value at an earlier row.
187    Prev {
188        /// Navigated value expression.
189        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
190        /// Optional offset expression; `None` selects the function default.
191        offset: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
192        /// Optional out-of-range result; `None` means a typed SQL null.
193        default: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
194    },
195    /// Value at a later row.
196    Next {
197        /// Navigated value expression.
198        expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
199        /// Optional offset expression; `None` selects the function default.
200        offset: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
201        /// Optional out-of-range result; `None` means a typed SQL null.
202        default: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
203    },
204}
205
206/// Source representation of one match-aware aggregate call.
207#[derive(Clone, Debug, PartialEq)]
208pub struct MatchAggregateCall<Input, InputColumn, PatternField, CastType = DataType> {
209    /// Function name resolved through the planning context during lowering.
210    pub name: String,
211    /// Positional arguments in source order.
212    pub args: Vec<MatchExpr<Input, InputColumn, PatternField, CastType>>,
213    /// Whether duplicate input values are removed.
214    pub distinct: bool,
215    /// Optional aggregate filter.
216    pub filter: Option<Box<MatchExpr<Input, InputColumn, PatternField, CastType>>>,
217    /// Aggregate-local ordering.
218    pub order_by: Vec<MatchExprSort<Input, InputColumn, PatternField, CastType>>,
219    /// Explicit `IGNORE NULLS` or `RESPECT NULLS`, when supplied.
220    pub null_treatment: Option<expr::NullTreatment>,
221    /// Symbol for `COUNT(symbol.*)`; when present, `args` must be empty and
222    /// `distinct` must be false.
223    pub wildcard_symbol: Option<String>,
224}
225
226/// Source expression plus aggregate-local sort options.
227#[derive(Clone, Debug, PartialEq)]
228pub struct MatchExprSort<Input, InputColumn, PatternField, CastType = DataType> {
229    /// Sort-key expression.
230    pub expr: Box<MatchExpr<Input, InputColumn, PatternField, CastType>>,
231    /// `true` for ascending order, `false` for descending order.
232    pub asc: bool,
233    /// `true` when null keys sort first.
234    pub nulls_first: bool,
235}
236
237/// Bound pattern-aware navigation call.
238pub type BoundMatchNavigation = MatchNavigation<Expr, Column, MatchPatternFieldRef>;
239/// Bound match-aware aggregate call.
240pub type BoundMatchAggregateCall = MatchAggregateCall<Expr, Column, MatchPatternFieldRef>;
241/// Bound aggregate-local sort expression.
242pub type BoundMatchExprSort = MatchExprSort<Expr, Column, MatchPatternFieldRef>;
243
244/// SQL null and truth-value predicates represented independently of a parser.
245#[derive(Clone, Debug, PartialEq, Eq, Hash)]
246pub enum MatchPredicateKind {
247    /// `IS NULL`.
248    IsNull,
249    /// `IS NOT NULL`.
250    IsNotNull,
251    /// `IS TRUE`.
252    IsTrue,
253    /// `IS FALSE`.
254    IsFalse,
255    /// `IS UNKNOWN`.
256    IsUnknown,
257    /// `IS NOT TRUE`.
258    IsNotTrue,
259    /// `IS NOT FALSE`.
260    IsNotFalse,
261    /// `IS NOT UNKNOWN`.
262    IsNotUnknown,
263}
264
265/// Unary operators represented independently of a parser.
266#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
267pub enum MatchUnaryOperator {
268    /// Boolean `NOT`.
269    Not,
270    /// Arithmetic unary minus.
271    Minus,
272    /// Arithmetic unary plus.
273    Plus,
274}
275
276/// Guard one expression so early errors tear down deep binary trees iteratively.
277struct ExprDropGuard<I, C, P, T>(Option<MatchExpr<I, C, P, T>>);
278
279impl<I, C, P, T> ExprDropGuard<I, C, P, T> {
280    fn new(expr: MatchExpr<I, C, P, T>) -> Self {
281        Self(Some(expr))
282    }
283
284    fn as_mut(&mut self) -> &mut MatchExpr<I, C, P, T> {
285        self.0.as_mut().expect("guarded expression")
286    }
287
288    fn into_inner(mut self) -> MatchExpr<I, C, P, T> {
289        self.0.take().expect("guarded expression")
290    }
291}
292
293impl<I, C, P, T> Drop for ExprDropGuard<I, C, P, T> {
294    fn drop(&mut self) {
295        if let Some(expr) = self.0.take() {
296            expr.drop_binary_tree();
297        }
298    }
299}
300
301/// Keep pending and completed structured children safe on fallible traversals.
302struct SourceChildren<I, C, P, T>(Vec<MatchExpr<I, C, P, T>>);
303
304impl<I, C, P, T> Drop for SourceChildren<I, C, P, T> {
305    fn drop(&mut self) {
306        for expr in self.0.drain(..) {
307            expr.drop_binary_tree();
308        }
309    }
310}
311
312impl<I, C, P, T> SourceChildren<I, C, P, T> {
313    fn try_map<BI, BC, BP, BT>(
314        mut self,
315        mut map: impl FnMut(MatchExpr<I, C, P, T>) -> Result<MatchExpr<BI, BC, BP, BT>>,
316    ) -> Result<Vec<MatchExpr<BI, BC, BP, BT>>> {
317        self.0.reverse();
318        let mut completed = SourceChildren(Vec::with_capacity(self.0.len()));
319        while let Some(child) = self.0.pop() {
320            completed.0.push(map(child)?);
321        }
322        Ok(std::mem::take(&mut completed.0))
323    }
324}
325
326impl<Input, InputColumn, PatternField, CastType>
327    MatchExpr<Input, InputColumn, PatternField, CastType>
328{
329    /// Consume a binary tree without recursive descent through binary operators.
330    /// Nonbinary operands reach `leaf` in left-to-right order; `combine` preserves
331    /// the original tree shape. The first leaf error stops the fold and tears down
332    /// unvisited operands and partially combined values iteratively.
333    pub(crate) fn try_fold_binary<T>(
334        self,
335        mut leaf: impl FnMut(Self) -> Result<T>,
336        mut combine: impl FnMut(T, Operator, T) -> T,
337        mut drop_value: impl FnMut(T),
338    ) -> Result<T> {
339        enum Work<E> {
340            Visit(Box<E>),
341            Combine(Operator),
342        }
343
344        let Self::Binary { left, op, right } = self else {
345            return leaf(self);
346        };
347        let mut pending = vec![Work::Combine(op), Work::Visit(right), Work::Visit(left)];
348        let mut values = Vec::new();
349        while let Some(work) = pending.pop() {
350            match work {
351                Work::Visit(expr) => match *expr {
352                    Self::Binary { left, op, right } => {
353                        pending.push(Work::Combine(op));
354                        pending.push(Work::Visit(right));
355                        pending.push(Work::Visit(left));
356                    }
357                    expr => match leaf(expr) {
358                        Ok(value) => values.push(value),
359                        Err(err) => {
360                            for work in pending {
361                                if let Work::Visit(expr) = work {
362                                    expr.drop_binary_tree();
363                                }
364                            }
365                            for value in values {
366                                drop_value(value);
367                            }
368                            return Err(err);
369                        }
370                    },
371                },
372                Work::Combine(op) => {
373                    let right = values.pop().expect("binary right operand");
374                    let left = values.pop().expect("binary left operand");
375                    values.push(combine(left, op, right));
376                }
377            }
378        }
379        Ok(values.pop().expect("binary expression"))
380    }
381
382    /// Visit immediate structured children in order, stopping at the first error.
383    ///
384    /// Aggregate arguments precede the filter and ordering expressions; navigation
385    /// visits the value, offset, then default. Importer-native `InputExpr` is opaque.
386    pub fn try_for_each_child<'a>(
387        &'a self,
388        mut visit: impl FnMut(&'a Self) -> Result<()>,
389    ) -> Result<()> {
390        match self {
391            Self::InputExpr(_)
392            | Self::InputColumn(_)
393            | Self::PatternField(_)
394            | Self::Metadata(_)
395            | Self::Literal(_) => {}
396            Self::Navigation(navigation) => match navigation {
397                MatchNavigation::First { expr, offset }
398                | MatchNavigation::Last { expr, offset } => {
399                    visit(expr)?;
400                    if let Some(offset) = offset {
401                        visit(offset)?;
402                    }
403                }
404                MatchNavigation::Prev {
405                    expr,
406                    offset,
407                    default,
408                }
409                | MatchNavigation::Next {
410                    expr,
411                    offset,
412                    default,
413                } => {
414                    visit(expr)?;
415                    if let Some(offset) = offset {
416                        visit(offset)?;
417                    }
418                    if let Some(default) = default {
419                        visit(default)?;
420                    }
421                }
422            },
423            Self::Aggregate(aggregate) => {
424                for arg in &aggregate.args {
425                    visit(arg)?;
426                }
427                if let Some(filter) = &aggregate.filter {
428                    visit(filter)?;
429                }
430                for sort in &aggregate.order_by {
431                    visit(&sort.expr)?;
432                }
433            }
434            Self::Alias { expr, .. }
435            | Self::Unary { expr, .. }
436            | Self::Predicate { expr, .. }
437            | Self::Cast { expr, .. } => visit(expr)?,
438            Self::ScalarFunction { args, .. } => {
439                for arg in args {
440                    visit(arg)?;
441                }
442            }
443            Self::Binary { left, right, .. } => {
444                visit(left)?;
445                visit(right)?;
446            }
447            Self::Like { expr, pattern, .. } => {
448                visit(expr)?;
449                visit(pattern)?;
450            }
451            Self::Case {
452                expr,
453                when_then,
454                else_expr,
455            } => {
456                if let Some(expr) = expr {
457                    visit(expr)?;
458                }
459                for (when, then) in when_then {
460                    visit(when)?;
461                    visit(then)?;
462                }
463                if let Some(else_expr) = else_expr {
464                    visit(else_expr)?;
465                }
466            }
467            Self::Between {
468                expr, low, high, ..
469            } => {
470                visit(expr)?;
471                visit(low)?;
472                visit(high)?;
473            }
474            Self::InList { expr, list, .. } => {
475                visit(expr)?;
476                for item in list {
477                    visit(item)?;
478                }
479            }
480        }
481        Ok(())
482    }
483
484    /// Convert all format-specific leaves while preserving the expression tree.
485    /// Binary trees use an explicit stack and visit operands in
486    /// source order, without a recursive mapping frame per binary operator.
487    pub fn try_map_adapter_parts<BoundInput, BoundColumn, BoundPattern, BoundCast>(
488        self,
489        map_input: &mut impl FnMut(Input) -> Result<BoundInput>,
490        map_column: &mut impl FnMut(InputColumn) -> Result<BoundColumn>,
491        map_pattern: &mut impl FnMut(PatternField) -> Result<BoundPattern>,
492        map_cast: &mut impl FnMut(CastType) -> Result<BoundCast>,
493    ) -> Result<MatchExpr<BoundInput, BoundColumn, BoundPattern, BoundCast>> {
494        self.try_map_parts_with(
495            &mut |_| Ok(()),
496            map_input,
497            map_column,
498            map_pattern,
499            map_cast,
500        )
501    }
502
503    /// Convert all format-specific leaves while preserving the expression tree,
504    /// running `before_node` on each nonbinary node before mapping its children.
505    ///
506    /// If `before_node` or a child mapper fails, unvisited and partially mapped
507    /// subtrees are torn down iteratively via [`Self::drop_binary_tree`].
508    pub(super) fn try_map_parts_with<BoundInput, BoundColumn, BoundPattern, BoundCast>(
509        self,
510        before_node: &mut impl FnMut(&mut Self) -> Result<()>,
511        map_input: &mut impl FnMut(Input) -> Result<BoundInput>,
512        map_column: &mut impl FnMut(InputColumn) -> Result<BoundColumn>,
513        map_pattern: &mut impl FnMut(PatternField) -> Result<BoundPattern>,
514        map_cast: &mut impl FnMut(CastType) -> Result<BoundCast>,
515    ) -> Result<MatchExpr<BoundInput, BoundColumn, BoundPattern, BoundCast>> {
516        self.try_fold_binary(
517            |expr| {
518                expr.try_map_node_with(
519                    before_node,
520                    map_input,
521                    map_column,
522                    map_pattern,
523                    map_cast,
524                )
525            },
526            |left, op, right| MatchExpr::Binary {
527                left: Box::new(left),
528                op,
529                right: Box::new(right),
530            },
531            MatchExpr::drop_binary_tree,
532        )
533    }
534
535    /// Tear down all structured children iteratively, including binary chains
536    /// nested inside nonbinary operands. Importer-native leaves remain opaque.
537    pub(crate) fn drop_binary_tree(self) {
538        let mut pending = vec![self];
539        while let Some(expr) = pending.pop() {
540            match expr {
541                Self::InputExpr(_)
542                | Self::InputColumn(_)
543                | Self::PatternField(_)
544                | Self::Metadata(_)
545                | Self::Literal(_) => {}
546                Self::Binary { left, right, .. } => {
547                    pending.push(*left);
548                    pending.push(*right);
549                }
550                Self::Navigation(nav) => match nav {
551                    MatchNavigation::First { expr, offset }
552                    | MatchNavigation::Last { expr, offset } => {
553                        pending.push(*expr);
554                        pending.extend(offset.map(|expr| *expr));
555                    }
556                    MatchNavigation::Prev {
557                        expr,
558                        offset,
559                        default,
560                    }
561                    | MatchNavigation::Next {
562                        expr,
563                        offset,
564                        default,
565                    } => {
566                        pending.push(*expr);
567                        pending.extend(offset.map(|expr| *expr));
568                        pending.extend(default.map(|expr| *expr));
569                    }
570                },
571                Self::Aggregate(aggregate) => {
572                    pending.extend(aggregate.args);
573                    pending.extend(aggregate.filter.map(|expr| *expr));
574                    pending.extend(aggregate.order_by.into_iter().map(|sort| *sort.expr));
575                }
576                Self::Alias { expr, .. }
577                | Self::Unary { expr, .. }
578                | Self::Predicate { expr, .. }
579                | Self::Cast { expr, .. } => pending.push(*expr),
580                Self::ScalarFunction { args, .. } => pending.extend(args),
581                Self::Like { expr, pattern, .. } => {
582                    pending.push(*expr);
583                    pending.push(*pattern);
584                }
585                Self::Case {
586                    expr,
587                    when_then,
588                    else_expr,
589                } => {
590                    pending.extend(expr.map(|expr| *expr));
591                    pending.extend(
592                        when_then.into_iter().flat_map(|(when, then)| [when, then]),
593                    );
594                    pending.extend(else_expr.map(|expr| *expr));
595                }
596                Self::Between {
597                    expr, low, high, ..
598                } => {
599                    pending.push(*expr);
600                    pending.push(*low);
601                    pending.push(*high);
602                }
603                Self::InList { expr, list, .. } => {
604                    pending.push(*expr);
605                    pending.extend(list);
606                }
607            }
608        }
609    }
610
611    fn try_map_node_with<BoundInput, BoundColumn, BoundPattern, BoundCast>(
612        self,
613        before_node: &mut impl FnMut(&mut Self) -> Result<()>,
614        map_input: &mut impl FnMut(Input) -> Result<BoundInput>,
615        map_column: &mut impl FnMut(InputColumn) -> Result<BoundColumn>,
616        map_pattern: &mut impl FnMut(PatternField) -> Result<BoundPattern>,
617        map_cast: &mut impl FnMut(CastType) -> Result<BoundCast>,
618    ) -> Result<MatchExpr<BoundInput, BoundColumn, BoundPattern, BoundCast>> {
619        let mut expr = ExprDropGuard::new(self);
620        before_node(expr.as_mut())?;
621        let expr = expr.into_inner();
622        let mut map_child = |child: Self| {
623            child.try_map_parts_with(
624                before_node,
625                map_input,
626                map_column,
627                map_pattern,
628                map_cast,
629            )
630        };
631        Ok(match expr {
632            Self::InputExpr(expr) => MatchExpr::InputExpr(map_input(expr)?),
633            Self::InputColumn(column) => MatchExpr::InputColumn(map_column(column)?),
634            Self::PatternField(field) => MatchExpr::PatternField(map_pattern(field)?),
635            Self::Metadata(metadata) => MatchExpr::Metadata(metadata),
636            Self::Navigation(navigation) => {
637                enum NavKind {
638                    First,
639                    Last,
640                    Prev,
641                    Next,
642                }
643                let (kind, expr, offset, default) = match navigation {
644                    MatchNavigation::First { expr, offset } => {
645                        (NavKind::First, expr, offset, None)
646                    }
647                    MatchNavigation::Last { expr, offset } => {
648                        (NavKind::Last, expr, offset, None)
649                    }
650                    MatchNavigation::Prev {
651                        expr,
652                        offset,
653                        default,
654                    } => (NavKind::Prev, expr, offset, default),
655                    MatchNavigation::Next {
656                        expr,
657                        offset,
658                        default,
659                    } => (NavKind::Next, expr, offset, default),
660                };
661                let has_offset = offset.is_some();
662                let children = std::iter::once(*expr)
663                    .chain(offset.map(|expr| *expr))
664                    .chain(default.map(|expr| *expr))
665                    .collect();
666                let mut children =
667                    SourceChildren(children).try_map(map_child)?.into_iter();
668                let expr = Box::new(children.next().expect("navigation value"));
669                let offset = has_offset
670                    .then(|| Box::new(children.next().expect("navigation offset")));
671                let default = children.next().map(Box::new);
672                MatchExpr::Navigation(match kind {
673                    NavKind::First => MatchNavigation::First { expr, offset },
674                    NavKind::Last => MatchNavigation::Last { expr, offset },
675                    NavKind::Prev => MatchNavigation::Prev {
676                        expr,
677                        offset,
678                        default,
679                    },
680                    NavKind::Next => MatchNavigation::Next {
681                        expr,
682                        offset,
683                        default,
684                    },
685                })
686            }
687            Self::Aggregate(aggregate) => {
688                let arg_count = aggregate.args.len();
689                let has_filter = aggregate.filter.is_some();
690                let (order_exprs, order_options): (Vec<_>, Vec<_>) = aggregate
691                    .order_by
692                    .into_iter()
693                    .map(|sort| (*sort.expr, (sort.asc, sort.nulls_first)))
694                    .unzip();
695                let children = aggregate
696                    .args
697                    .into_iter()
698                    .chain(aggregate.filter.map(|expr| *expr))
699                    .chain(order_exprs)
700                    .collect();
701                let mut children =
702                    SourceChildren(children).try_map(map_child)?.into_iter();
703                MatchExpr::Aggregate(MatchAggregateCall {
704                    name: aggregate.name,
705                    args: children.by_ref().take(arg_count).collect(),
706                    distinct: aggregate.distinct,
707                    filter: has_filter
708                        .then(|| Box::new(children.next().expect("aggregate filter"))),
709                    order_by: children
710                        .zip(order_options)
711                        .map(|(expr, (asc, nulls_first))| MatchExprSort {
712                            expr: Box::new(expr),
713                            asc,
714                            nulls_first,
715                        })
716                        .collect(),
717                    null_treatment: aggregate.null_treatment,
718                    wildcard_symbol: aggregate.wildcard_symbol,
719                })
720            }
721            Self::Alias { expr, name } => MatchExpr::Alias {
722                expr: Box::new(map_child(*expr)?),
723                name,
724            },
725            Self::ScalarFunction { name, args } => MatchExpr::ScalarFunction {
726                name,
727                args: SourceChildren(args).try_map(map_child)?,
728            },
729            Self::Unary { op, expr } => MatchExpr::Unary {
730                op,
731                expr: Box::new(map_child(*expr)?),
732            },
733            Self::Binary { .. } => unreachable!("binary operators use the work stack"),
734            Self::Like {
735                negated,
736                expr,
737                pattern,
738                escape_char,
739                case_insensitive,
740                similar,
741            } => {
742                let mut children = SourceChildren(vec![*expr, *pattern])
743                    .try_map(map_child)?
744                    .into_iter();
745                MatchExpr::Like {
746                    negated,
747                    expr: Box::new(children.next().expect("LIKE operand")),
748                    pattern: Box::new(children.next().expect("LIKE pattern")),
749                    escape_char,
750                    case_insensitive,
751                    similar,
752                }
753            }
754            Self::Case {
755                expr,
756                when_then,
757                else_expr,
758            } => {
759                let has_expr = expr.is_some();
760                let pairs = when_then.len();
761                let children = expr
762                    .into_iter()
763                    .map(|expr| *expr)
764                    .chain(when_then.into_iter().flat_map(|(when, then)| [when, then]))
765                    .chain(else_expr.map(|expr| *expr))
766                    .collect();
767                let mut children =
768                    SourceChildren(children).try_map(map_child)?.into_iter();
769                MatchExpr::Case {
770                    expr: has_expr
771                        .then(|| Box::new(children.next().expect("CASE operand"))),
772                    when_then: (0..pairs)
773                        .map(|_| {
774                            (
775                                children.next().expect("CASE condition"),
776                                children.next().expect("CASE result"),
777                            )
778                        })
779                        .collect(),
780                    else_expr: children.next().map(Box::new),
781                }
782            }
783            Self::Predicate { kind, expr } => MatchExpr::Predicate {
784                kind,
785                expr: Box::new(map_child(*expr)?),
786            },
787            Self::Between {
788                expr,
789                negated,
790                low,
791                high,
792            } => {
793                let mut children = SourceChildren(vec![*expr, *low, *high])
794                    .try_map(map_child)?
795                    .into_iter();
796                MatchExpr::Between {
797                    expr: Box::new(children.next().expect("BETWEEN operand")),
798                    negated,
799                    low: Box::new(children.next().expect("BETWEEN low")),
800                    high: Box::new(children.next().expect("BETWEEN high")),
801                }
802            }
803            Self::InList {
804                expr,
805                list,
806                negated,
807            } => {
808                let children = std::iter::once(*expr).chain(list).collect();
809                let mut children =
810                    SourceChildren(children).try_map(map_child)?.into_iter();
811                MatchExpr::InList {
812                    expr: Box::new(children.next().expect("IN operand")),
813                    list: children.collect(),
814                    negated,
815                }
816            }
817            Self::Cast { expr, data_type } => {
818                let mapped = ExprDropGuard::new(map_child(*expr)?);
819                // Keep the completed operand guarded if mapping the target fails.
820                let data_type = map_cast(data_type)?;
821                MatchExpr::Cast {
822                    expr: Box::new(mapped.into_inner()),
823                    data_type,
824                }
825            }
826            Self::Literal(value) => MatchExpr::Literal(value),
827        })
828    }
829}
830
831impl From<Expr> for BoundMatchExpr {
832    fn from(value: Expr) -> Self {
833        Self::InputExpr(value)
834    }
835}
836
837impl From<&str> for BoundMatchExpr {
838    fn from(value: &str) -> Self {
839        Self::InputColumn(Column::from_name(value))
840    }
841}
842
843impl From<String> for BoundMatchExpr {
844    fn from(value: String) -> Self {
845        Self::InputColumn(Column::from_name(value))
846    }
847}
848
849impl fmt::Display for MatchPatternFieldRef {
850    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851        write!(f, "{}.{}", self.symbol, self.column)
852    }
853}
854
855impl fmt::Display for MatchMetadataFunction {
856    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857        f.write_str(match self {
858            Self::Classifier => "CLASSIFIER",
859            Self::MatchNumber => "MATCH_NUMBER",
860            Self::MatchSequenceNumber => "MATCH_SEQUENCE_NUMBER",
861            Self::Excluded => "EXCLUDED",
862        })
863    }
864}
865
866impl fmt::Display for MatchPredicateKind {
867    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
868        f.write_str(match self {
869            Self::IsNull => "IS NULL",
870            Self::IsNotNull => "IS NOT NULL",
871            Self::IsTrue => "IS TRUE",
872            Self::IsFalse => "IS FALSE",
873            Self::IsUnknown => "IS UNKNOWN",
874            Self::IsNotTrue => "IS NOT TRUE",
875            Self::IsNotFalse => "IS NOT FALSE",
876            Self::IsNotUnknown => "IS NOT UNKNOWN",
877        })
878    }
879}
880
881impl fmt::Display for MatchUnaryOperator {
882    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883        f.write_str(match self {
884            Self::Not => "NOT",
885            Self::Minus => "-",
886            Self::Plus => "+",
887        })
888    }
889}
890
891impl<Input, InputColumn, PatternField, CastType> fmt::Display
892    for MatchExpr<Input, InputColumn, PatternField, CastType>
893where
894    Input: fmt::Display,
895    InputColumn: fmt::Display,
896    PatternField: fmt::Display,
897    CastType: fmt::Display,
898{
899    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
900        match self {
901            Self::InputExpr(expr) => write!(f, "{expr}"),
902            Self::InputColumn(column) => write!(f, "{column}"),
903            Self::PatternField(field) => write!(f, "{field}"),
904            Self::Literal(value) => write!(f, "{value}"),
905            Self::Metadata(metadata) => write!(f, "{metadata}()"),
906            Self::Navigation(navigation) => write!(f, "{navigation}"),
907            Self::Aggregate(aggregate) => write!(f, "{aggregate}"),
908            Self::Alias { expr, name } => write!(f, "{expr} AS {name}"),
909            Self::ScalarFunction { name, args } => {
910                let name = if name == crate::planning::BUILTIN_SUBSTRING_NAME {
911                    "substr"
912                } else {
913                    name
914                };
915                write!(f, "{}(", name.to_ascii_uppercase())?;
916                write_joined(f, args)?;
917                write!(f, ")")
918            }
919            // NOT binds less tightly than postfix predicates such as IS TRUE.
920            // Group it so a parent predicate tests the result of the negation.
921            Self::Unary {
922                op: MatchUnaryOperator::Not,
923                expr,
924            } => write!(f, "(NOT {expr})"),
925            Self::Unary { op, expr } => write!(f, "{op} {expr}"),
926            Self::Binary { left, op, right } => write!(f, "({left} {op} {right})"),
927            Self::Like {
928                negated,
929                expr,
930                pattern,
931                escape_char,
932                case_insensitive,
933                similar,
934            } => {
935                let operator = if *similar {
936                    "SIMILAR TO"
937                } else if *case_insensitive {
938                    "ILIKE"
939                } else {
940                    "LIKE"
941                };
942                write!(
943                    f,
944                    "{expr} {}{operator} {pattern}",
945                    if *negated { "NOT " } else { "" }
946                )?;
947                if let Some(escape_char) = escape_char {
948                    write!(
949                        f,
950                        " ESCAPE '{}'",
951                        escape_char.to_string().replace('\'', "''")
952                    )?;
953                }
954                Ok(())
955            }
956            Self::Case {
957                expr,
958                when_then,
959                else_expr,
960            } => {
961                write!(f, "CASE")?;
962                if let Some(expr) = expr {
963                    write!(f, " {expr}")?;
964                }
965                for (when, then) in when_then {
966                    write!(f, " WHEN {when} THEN {then}")?;
967                }
968                if let Some(else_expr) = else_expr {
969                    write!(f, " ELSE {else_expr}")?;
970                }
971                write!(f, " END")
972            }
973            Self::Predicate { kind, expr } => write!(f, "{expr} {kind}"),
974            Self::Between {
975                expr,
976                negated,
977                low,
978                high,
979            } => write!(
980                f,
981                "{expr} {}BETWEEN {low} AND {high}",
982                if *negated { "NOT " } else { "" }
983            ),
984            Self::InList {
985                expr,
986                list,
987                negated,
988            } => {
989                write!(f, "{expr} {}IN (", if *negated { "NOT " } else { "" })?;
990                write_joined(f, list)?;
991                write!(f, ")")
992            }
993            Self::Cast { expr, data_type } => write!(f, "CAST({expr} AS {data_type})"),
994        }
995    }
996}
997
998impl<Input, InputColumn, PatternField, CastType> fmt::Display
999    for MatchNavigation<Input, InputColumn, PatternField, CastType>
1000where
1001    Input: fmt::Display,
1002    InputColumn: fmt::Display,
1003    PatternField: fmt::Display,
1004    CastType: fmt::Display,
1005{
1006    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1007        let (name, expr, offset, default) = match self {
1008            Self::First { expr, offset } => ("FIRST", expr, offset.as_ref(), None),
1009            Self::Last { expr, offset } => ("LAST", expr, offset.as_ref(), None),
1010            Self::Prev {
1011                expr,
1012                offset,
1013                default,
1014            } => ("PREV", expr, offset.as_ref(), default.as_ref()),
1015            Self::Next {
1016                expr,
1017                offset,
1018                default,
1019            } => ("NEXT", expr, offset.as_ref(), default.as_ref()),
1020        };
1021        write!(f, "{name}({expr}")?;
1022        if let Some(offset) = offset {
1023            write!(f, ", {offset}")?;
1024        } else if default.is_some() {
1025            write!(f, ", 1")?;
1026        }
1027        if let Some(default) = default {
1028            write!(f, ", {default}")?;
1029        }
1030        write!(f, ")")
1031    }
1032}
1033
1034impl<Input, InputColumn, PatternField, CastType> fmt::Display
1035    for MatchAggregateCall<Input, InputColumn, PatternField, CastType>
1036where
1037    Input: fmt::Display,
1038    InputColumn: fmt::Display,
1039    PatternField: fmt::Display,
1040    CastType: fmt::Display,
1041{
1042    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043        write!(f, "{}(", self.name.to_ascii_uppercase())?;
1044        if self.distinct {
1045            write!(f, "DISTINCT ")?;
1046        }
1047        if let Some(symbol) = &self.wildcard_symbol {
1048            write!(f, "{symbol}.*")?;
1049        } else if self.args.is_empty() && self.name.eq_ignore_ascii_case("count") {
1050            write!(f, "*")?;
1051        } else {
1052            write_joined(f, &self.args)?;
1053        }
1054        if !self.order_by.is_empty() {
1055            write!(f, " ORDER BY ")?;
1056            write_joined(f, &self.order_by)?;
1057        }
1058        if let Some(null_treatment) = self.null_treatment {
1059            write!(f, " {null_treatment}")?;
1060        }
1061        write!(f, ")")?;
1062        if let Some(filter) = &self.filter {
1063            write!(f, " FILTER (WHERE {filter})")?;
1064        }
1065        Ok(())
1066    }
1067}
1068
1069impl<Input, InputColumn, PatternField, CastType> fmt::Display
1070    for MatchExprSort<Input, InputColumn, PatternField, CastType>
1071where
1072    Input: fmt::Display,
1073    InputColumn: fmt::Display,
1074    PatternField: fmt::Display,
1075    CastType: fmt::Display,
1076{
1077    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1078        write!(
1079            f,
1080            "{} {} {}",
1081            self.expr,
1082            if self.asc { "ASC" } else { "DESC" },
1083            if self.nulls_first {
1084                "NULLS FIRST"
1085            } else {
1086                "NULLS LAST"
1087            }
1088        )
1089    }
1090}
1091
1092fn write_joined<T: fmt::Display>(f: &mut fmt::Formatter<'_>, items: &[T]) -> fmt::Result {
1093    let mut first = true;
1094    for item in items {
1095        if !first {
1096            write!(f, ", ")?;
1097        }
1098        first = false;
1099        write!(f, "{item}")?;
1100    }
1101    Ok(())
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use super::*;
1107
1108    #[test]
1109    fn empty_aggregate_display_uses_wildcard_only_for_count() {
1110        for (name, expected) in [("f", "F()"), ("CoUnT", "COUNT(*)")] {
1111            let call = MatchAggregateCall::<&str, &str, &str, &str> {
1112                name: name.to_string(),
1113                args: vec![],
1114                distinct: false,
1115                filter: None,
1116                order_by: vec![],
1117                null_treatment: None,
1118                wildcard_symbol: None,
1119            };
1120            assert_eq!(call.to_string(), expected);
1121        }
1122    }
1123
1124    #[test]
1125    fn navigation_display_preserves_argument_positions() {
1126        let input =
1127            |value| Box::new(MatchExpr::<&str, &str, &str, &str>::InputExpr(value));
1128        for (offset, default, prev, next) in [
1129            (None, Some("7"), "PREV(x, 1, 7)", "NEXT(x, 1, 7)"),
1130            (Some("2"), Some("7"), "PREV(x, 2, 7)", "NEXT(x, 2, 7)"),
1131            (None, None, "PREV(x)", "NEXT(x)"),
1132        ] {
1133            assert_eq!(
1134                MatchNavigation::Prev {
1135                    expr: input("x"),
1136                    offset: offset.map(input),
1137                    default: default.map(input),
1138                }
1139                .to_string(),
1140                prev
1141            );
1142            assert_eq!(
1143                MatchNavigation::Next {
1144                    expr: input("x"),
1145                    offset: offset.map(input),
1146                    default: default.map(input),
1147                }
1148                .to_string(),
1149                next
1150            );
1151        }
1152        for (offset, first, last) in [
1153            (None, "FIRST(x)", "LAST(x)"),
1154            (Some("2"), "FIRST(x, 2)", "LAST(x, 2)"),
1155        ] {
1156            assert_eq!(
1157                MatchNavigation::First {
1158                    expr: input("x"),
1159                    offset: offset.map(input),
1160                }
1161                .to_string(),
1162                first
1163            );
1164            assert_eq!(
1165                MatchNavigation::Last {
1166                    expr: input("x"),
1167                    offset: offset.map(input),
1168                }
1169                .to_string(),
1170                last
1171            );
1172        }
1173    }
1174}