icydb-core 0.145.12

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Module: query::plan::expr::ast
//! Responsibility: planner expression AST domain types and field/operator identifiers.
//! Does not own: expression type inference policy or runtime expression evaluation.
//! Boundary: defines canonical expression tree structures consumed by planner validation/lowering.

use crate::{db::query::builder::aggregate::AggregateExpr, value::Value};

///
/// FieldId
///
/// Canonical planner-owned field identity token for expression trees.
/// This wrapper carries the declared field name and avoids ad-hoc string use.
///

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(in crate::db) struct FieldId(String);

impl FieldId {
    /// Build one field-id token from a field name.
    #[must_use]
    pub(in crate::db) fn new(field: impl Into<String>) -> Self {
        Self(field.into())
    }

    /// Borrow the canonical field name.
    #[must_use]
    pub(in crate::db) const fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl From<&str> for FieldId {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for FieldId {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

///
/// PathSpec
///
/// Planner-owned nested path descriptor rooted at one top-level model field.
/// This exists as the shared capability hook for future path optimization:
/// current execution only needs root plus segments, while later planner/index
/// work can hang scalar-leaf or indexability metadata from this boundary.
///

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(in crate::db) struct PathSpec {
    root: FieldId,
    path: Vec<String>,
}

impl PathSpec {
    /// Build one nested field path from a root field and non-empty path tail.
    #[must_use]
    pub(in crate::db) fn new(root: impl Into<FieldId>, segments: Vec<String>) -> Self {
        debug_assert!(
            !segments.is_empty(),
            "field paths must contain at least one nested segment"
        );

        Self {
            root: root.into(),
            path: segments,
        }
    }

    /// Borrow the top-level model field that owns this nested path.
    #[must_use]
    pub(in crate::db) const fn root(&self) -> &FieldId {
        &self.root
    }

    /// Borrow the nested path segments below the root field.
    #[must_use]
    pub(in crate::db) const fn segments(&self) -> &[String] {
        self.path.as_slice()
    }

    /// Return whether this path is expected to resolve to a scalar leaf.
    #[must_use]
    pub(in crate::db) const fn is_scalar_leaf(&self) -> bool {
        !self.path.is_empty()
    }
}

///
/// FieldPath
///
/// Planner-owned nested field path expression rooted at one top-level model
/// field.
/// The expression wrapper preserves AST identity while delegating path
/// capability details to `PathSpec`.
///

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(in crate::db) struct FieldPath {
    path: PathSpec,
}

impl FieldPath {
    /// Build one nested field path from a root field and non-empty path tail.
    #[must_use]
    pub(in crate::db) fn new(root: impl Into<FieldId>, segments: Vec<String>) -> Self {
        Self {
            path: PathSpec::new(root, segments),
        }
    }

    /// Borrow the path capability descriptor.
    #[must_use]
    pub(in crate::db) const fn path_spec(&self) -> &PathSpec {
        &self.path
    }

    /// Borrow the top-level model field that owns this nested path.
    #[must_use]
    pub(in crate::db) const fn root(&self) -> &FieldId {
        self.path.root()
    }

    /// Borrow the nested path segments below the root field.
    #[must_use]
    pub(in crate::db) const fn segments(&self) -> &[String] {
        self.path.segments()
    }
}

///
/// Alias
///
/// Canonical planner-owned alias token attached to expression projections.
/// Alias remains presentation metadata and does not affect semantic identity.
///

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(in crate::db) struct Alias(String);

impl Alias {
    /// Build one alias token from owned/borrowed text.
    #[must_use]
    pub(in crate::db) fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    /// Borrow the alias as text.
    #[must_use]
    pub(in crate::db) const fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl From<&str> for Alias {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

impl From<String> for Alias {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

///
/// UnaryOp
///
/// Canonical unary expression operator taxonomy.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum UnaryOp {
    Not,
}

///
/// BinaryOp
///
/// Canonical binary expression operator taxonomy.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum BinaryOp {
    Or,
    And,
    Eq,
    Ne,
    Lt,
    Lte,
    Gt,
    Gte,
    Add,
    Sub,
    Mul,
    Div,
}

impl BinaryOp {
    /// Return the stable planner-owned lowercase label for this binary operator.
    #[must_use]
    pub(in crate::db) const fn canonical_label(self) -> &'static str {
        match self {
            Self::Or => "or",
            Self::And => "and",
            Self::Eq => "eq",
            Self::Ne => "ne",
            Self::Lt => "lt",
            Self::Lte => "lte",
            Self::Gt => "gt",
            Self::Gte => "gte",
            Self::Add => "add",
            Self::Sub => "sub",
            Self::Mul => "mul",
            Self::Div => "div",
        }
    }

    /// Report whether this operator belongs to the numeric arithmetic family.
    #[must_use]
    pub(in crate::db) const fn is_numeric_arithmetic(self) -> bool {
        matches!(self, Self::Add | Self::Sub | Self::Mul | Self::Div)
    }
}

///
/// Function
///
/// Canonical bounded function taxonomy admitted by planner-owned projection
/// expressions.
/// This intentionally stays limited to the shipped scalar-function surface.
///

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[remain::sorted]
pub(in crate::db) enum Function {
    Abs,
    Cbrt,
    Ceiling,
    Coalesce,
    CollectionContains,
    Contains,
    EndsWith,
    Exp,
    Floor,
    IsEmpty,
    IsMissing,
    IsNotEmpty,
    IsNotNull,
    IsNull,
    Left,
    Length,
    Ln,
    Log,
    Log2,
    Log10,
    Lower,
    Ltrim,
    Mod,
    NullIf,
    OctetLength,
    Position,
    Power,
    Replace,
    Right,
    Round,
    Rtrim,
    Sign,
    Sqrt,
    StartsWith,
    Substring,
    Trim,
    Trunc,
    Upper,
}

impl Function {
    /// Return the stable uppercase canonical label for this bounded function.
    #[must_use]
    pub(in crate::db) const fn canonical_label(self) -> &'static str {
        match self {
            Self::Abs => "ABS",
            Self::Cbrt => "CBRT",
            Self::Ceiling => "CEILING",
            Self::Coalesce => "COALESCE",
            Self::CollectionContains => "COLLECTION_CONTAINS",
            Self::Contains => "CONTAINS",
            Self::EndsWith => "ENDS_WITH",
            Self::Exp => "EXP",
            Self::Floor => "FLOOR",
            Self::IsEmpty => "IS_EMPTY",
            Self::IsMissing => "IS_MISSING",
            Self::IsNotEmpty => "IS_NOT_EMPTY",
            Self::IsNotNull => "IS_NOT_NULL",
            Self::IsNull => "IS_NULL",
            Self::Left => "LEFT",
            Self::Length => "LENGTH",
            Self::Ln => "LN",
            Self::Log => "LOG",
            Self::Log10 => "LOG10",
            Self::Log2 => "LOG2",
            Self::Lower => "LOWER",
            Self::Ltrim => "LTRIM",
            Self::Mod => "MOD",
            Self::NullIf => "NULLIF",
            Self::OctetLength => "OCTET_LENGTH",
            Self::Position => "POSITION",
            Self::Power => "POWER",
            Self::Replace => "REPLACE",
            Self::Round => "ROUND",
            Self::Right => "RIGHT",
            Self::Rtrim => "RTRIM",
            Self::Sign => "SIGN",
            Self::StartsWith => "STARTS_WITH",
            Self::Substring => "SUBSTRING",
            Self::Sqrt => "SQRT",
            Self::Trim => "TRIM",
            Self::Trunc => "TRUNC",
            Self::Upper => "UPPER",
        }
    }
}

///
/// CaseWhenArm
///
/// Planner-owned searched-CASE branch pairing one boolean condition with the
/// scalar result expression selected when that condition evaluates true.
/// CASE normalization keeps the missing-ELSE rule outside this type by always
/// pairing searched arms with an explicit planner-owned fallback expression.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) struct CaseWhenArm {
    condition: Expr,
    result: Expr,
}

impl CaseWhenArm {
    /// Build one planner-owned searched-CASE arm.
    #[must_use]
    pub(in crate::db) const fn new(condition: Expr, result: Expr) -> Self {
        Self { condition, result }
    }

    /// Borrow the boolean branch condition.
    #[must_use]
    pub(in crate::db) const fn condition(&self) -> &Expr {
        &self.condition
    }

    /// Borrow the scalar branch result expression.
    #[must_use]
    pub(in crate::db) const fn result(&self) -> &Expr {
        &self.result
    }
}

/// Return whether one admitted `ORDER BY` expression is only a plain field.
#[must_use]
#[cfg(test)]
pub(in crate::db) const fn supported_order_expr_is_plain_field(expr: &Expr) -> bool {
    matches!(expr, Expr::Field(_))
}

/// Borrow the referenced field when one expression is an admitted `ORDER BY`
/// function term.
#[must_use]
#[cfg(test)]
pub(in crate::db) fn supported_order_expr_field(expr: &Expr) -> Option<&FieldId> {
    match expr {
        Expr::FunctionCall {
            function:
                Function::Trim
                | Function::Ltrim
                | Function::Rtrim
                | Function::Abs
                | Function::Ceiling
                | Function::Floor
                | Function::Sign
                | Function::Sqrt
                | Function::Lower
                | Function::Upper
                | Function::Length
                | Function::OctetLength,
            args,
        } => match args.as_slice() {
            [Expr::Field(field)] => Some(field),
            _ => None,
        },
        _ => None,
    }
}

/// Render one admitted canonical `ORDER BY` expression term back into its stable
/// text form.
#[must_use]
#[cfg(test)]
pub(in crate::db) fn render_supported_order_expr(expr: &Expr) -> Option<String> {
    render_supported_order_expr_with_parent(expr, None)
}

/// Return whether one admitted `ORDER BY` expression must still satisfy the
/// current index-backed expression-order contract.
#[must_use]
pub(in crate::db) const fn supported_order_expr_requires_index_satisfied_access(
    expr: &Expr,
) -> bool {
    matches!(
        expr,
        Expr::FunctionCall {
            function,
            args,
        } if function.is_casefold_transform() && matches!(args.as_slice(), [Expr::Field(_)])
    )
}

#[cfg(test)]
fn render_supported_order_function(function: Function, args: &[Expr]) -> Option<String> {
    match supported_order_function_shape(function)? {
        SupportedOrderFunctionShape::UnaryExpr => match args {
            [arg] => Some(format!(
                "{}({})",
                function.canonical_label(),
                render_supported_order_expr_with_parent(arg, None)?
            )),
            _ => None,
        },
        SupportedOrderFunctionShape::VariadicExprMin2 => {
            if args.len() < 2 {
                return None;
            }

            let rendered = args
                .iter()
                .map(|arg| render_supported_order_expr_with_parent(arg, None))
                .collect::<Option<Vec<_>>>()?;

            Some(format!(
                "{}({})",
                function.canonical_label(),
                rendered.join(", ")
            ))
        }
        SupportedOrderFunctionShape::BinaryExpr => match args {
            [left, right] => Some(format!(
                "{}({}, {})",
                function.canonical_label(),
                render_supported_order_expr_with_parent(left, None)?,
                render_supported_order_expr_with_parent(right, None)?
            )),
            _ => None,
        },
        SupportedOrderFunctionShape::FieldLiteral => match args {
            [Expr::Field(field), Expr::Literal(literal)] => Some(format!(
                "{}({}, {})",
                function.canonical_label(),
                field.as_str(),
                render_supported_order_literal(literal)?
            )),
            _ => None,
        },
        SupportedOrderFunctionShape::LiteralField => match args {
            [Expr::Literal(literal), Expr::Field(field)] => Some(format!(
                "{}({}, {})",
                function.canonical_label(),
                render_supported_order_literal(literal)?,
                field.as_str(),
            )),
            _ => None,
        },
        SupportedOrderFunctionShape::FieldTwoLiterals => match args {
            [Expr::Field(field), Expr::Literal(from), Expr::Literal(to)] => Some(format!(
                "{}({}, {}, {})",
                function.canonical_label(),
                field.as_str(),
                render_supported_order_literal(from)?,
                render_supported_order_literal(to)?,
            )),
            _ => None,
        },
        SupportedOrderFunctionShape::FieldOneOrTwoLiterals => match args {
            [Expr::Field(field), Expr::Literal(start)] => Some(format!(
                "{}({}, {})",
                function.canonical_label(),
                field.as_str(),
                render_supported_order_literal(start)?,
            )),
            [
                Expr::Field(field),
                Expr::Literal(start),
                Expr::Literal(length),
            ] => Some(format!(
                "{}({}, {}, {})",
                function.canonical_label(),
                field.as_str(),
                render_supported_order_literal(start)?,
                render_supported_order_literal(length)?,
            )),
            _ => None,
        },
        SupportedOrderFunctionShape::Round => None,
    }
}

#[cfg(test)]
fn render_supported_order_expr_with_parent(
    expr: &Expr,
    parent_op: Option<BinaryOp>,
) -> Option<String> {
    match expr {
        Expr::Binary { op, left, right }
            if matches!(
                op,
                BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div
            ) =>
        {
            let left = render_supported_order_expr_with_parent(left.as_ref(), Some(*op))?;
            let right = render_supported_order_expr_with_parent(right.as_ref(), Some(*op))?;
            let rendered = format!("{left} {} {right}", binary_op_symbol(*op));

            if binary_expr_requires_parentheses(*op, parent_op) {
                Some(format!("({rendered})"))
            } else {
                Some(rendered)
            }
        }
        Expr::FunctionCall {
            function: Function::Round,
            args,
        } => match args.as_slice() {
            [base, Expr::Literal(scale)] => Some(format!(
                "ROUND({}, {})",
                render_supported_order_expr_with_parent(base, None)?,
                render_supported_order_literal(scale)?
            )),
            _ => None,
        },
        Expr::FunctionCall { function, args } => render_supported_order_function(*function, args),
        Expr::Field(field) => Some(field.as_str().to_string()),
        Expr::Literal(value) => render_supported_order_literal(value),
        Expr::FieldPath(_) | Expr::Binary { .. } | Expr::Aggregate(_) | Expr::Case { .. } => None,
        Expr::Unary { .. } => None,
        #[cfg(test)]
        Expr::Alias { .. } => None,
    }
}

#[cfg(test)]
const fn binary_expr_requires_parentheses(op: BinaryOp, parent_op: Option<BinaryOp>) -> bool {
    let Some(parent_op) = parent_op else {
        return false;
    };

    binary_op_precedence(op) < binary_op_precedence(parent_op)
}

#[cfg(test)]
const fn binary_op_precedence(op: BinaryOp) -> u8 {
    match op {
        BinaryOp::Or => 0,
        BinaryOp::And => 1,
        BinaryOp::Eq
        | BinaryOp::Ne
        | BinaryOp::Lt
        | BinaryOp::Lte
        | BinaryOp::Gt
        | BinaryOp::Gte => 2,
        BinaryOp::Add | BinaryOp::Sub => 3,
        BinaryOp::Mul | BinaryOp::Div => 4,
    }
}

#[cfg(test)]
const fn binary_op_symbol(op: BinaryOp) -> &'static str {
    match op {
        BinaryOp::Or => "OR",
        BinaryOp::And => "AND",
        BinaryOp::Eq => "=",
        BinaryOp::Ne => "!=",
        BinaryOp::Lt => "<",
        BinaryOp::Lte => "<=",
        BinaryOp::Gt => ">",
        BinaryOp::Gte => ">=",
        BinaryOp::Add => "+",
        BinaryOp::Sub => "-",
        BinaryOp::Mul => "*",
        BinaryOp::Div => "/",
    }
}

#[cfg(test)]
fn render_supported_order_literal(value: &Value) -> Option<String> {
    Some(match value {
        Value::Null => "NULL".to_string(),
        Value::Text(text) => format!("'{}'", text.replace('\'', "''")),
        Value::Int(value) => value.to_string(),
        Value::Int128(value) => value.to_string(),
        Value::IntBig(value) => value.to_string(),
        Value::Uint(value) => value.to_string(),
        Value::Uint128(value) => value.to_string(),
        Value::UintBig(value) => value.to_string(),
        Value::Decimal(value) => value.to_string(),
        Value::Float32(value) => value.to_string(),
        Value::Float64(value) => value.to_string(),
        Value::Bool(value) => value.to_string().to_uppercase(),
        _ => return None,
    })
}

///
/// SupportedOrderFunctionShape
///
/// Clause-owned argument-shape taxonomy for the reduced `ORDER BY` function
/// surface.
/// This exists so the plain parser, grouped parser, and test-only renderer
/// share one local definition of admitted wrapper forms.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg(test)]
enum SupportedOrderFunctionShape {
    UnaryExpr,
    VariadicExprMin2,
    BinaryExpr,
    FieldLiteral,
    LiteralField,
    FieldTwoLiterals,
    FieldOneOrTwoLiterals,
    Round,
}

// Keep the reduced `ORDER BY` function family clause-owned by describing the
// admitted argument shape locally instead of re-encoding it in each parser.
#[cfg(test)]
const fn supported_order_function_shape(function: Function) -> Option<SupportedOrderFunctionShape> {
    match function {
        Function::IsNull
        | Function::IsNotNull
        | Function::IsMissing
        | Function::IsEmpty
        | Function::IsNotEmpty
        | Function::Trim
        | Function::Ltrim
        | Function::Rtrim
        | Function::Abs
        | Function::Cbrt
        | Function::Ceiling
        | Function::Exp
        | Function::Floor
        | Function::Ln
        | Function::Log2
        | Function::Log10
        | Function::Sign
        | Function::Sqrt
        | Function::Lower
        | Function::Upper
        | Function::Length
        | Function::OctetLength => Some(SupportedOrderFunctionShape::UnaryExpr),
        Function::Coalesce => Some(SupportedOrderFunctionShape::VariadicExprMin2),
        Function::NullIf | Function::Log | Function::Mod | Function::Power => {
            Some(SupportedOrderFunctionShape::BinaryExpr)
        }
        Function::Left
        | Function::Right
        | Function::StartsWith
        | Function::EndsWith
        | Function::Contains => Some(SupportedOrderFunctionShape::FieldLiteral),
        Function::Position => Some(SupportedOrderFunctionShape::LiteralField),
        Function::Replace => Some(SupportedOrderFunctionShape::FieldTwoLiterals),
        Function::Substring => Some(SupportedOrderFunctionShape::FieldOneOrTwoLiterals),
        Function::Round | Function::Trunc => Some(SupportedOrderFunctionShape::Round),
        Function::CollectionContains => None,
    }
}

///
/// Expr
///
/// Canonical planner-owned expression tree for projection semantics.
/// This model is semantic-only and intentionally excludes execution logic.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::db) enum Expr {
    Field(FieldId),
    FieldPath(FieldPath),
    Literal(Value),
    FunctionCall {
        function: Function,
        args: Vec<Self>,
    },
    Unary {
        op: UnaryOp,
        expr: Box<Self>,
    },
    Binary {
        op: BinaryOp,
        left: Box<Self>,
        right: Box<Self>,
    },
    Case {
        when_then_arms: Vec<CaseWhenArm>,
        else_expr: Box<Self>,
    },
    Aggregate(AggregateExpr),
    #[cfg(test)]
    Alias {
        expr: Box<Self>,
        name: Alias,
    },
}

impl Expr {
    /// Return true when this planner expression tree contains any aggregate
    /// leaf.
    #[must_use]
    pub(in crate::db) fn contains_aggregate(&self) -> bool {
        self.any_tree_expr(&mut |expr| matches!(expr, Self::Aggregate(_)))
    }

    /// Return true when this planner expression tree still contains any raw
    /// searched `CASE` node after owner-local canonicalization.
    #[must_use]
    pub(in crate::db) fn contains_case(&self) -> bool {
        self.any_tree_expr(&mut |expr| matches!(expr, Self::Case { .. }))
    }

    /// Return true when any visited planner expression node satisfies the
    /// supplied predicate.
    #[must_use]
    pub(in crate::db) fn any_tree_expr(&self, predicate: &mut impl FnMut(&Self) -> bool) -> bool {
        if predicate(self) {
            return true;
        }

        match self {
            Self::Field(_) | Self::FieldPath(_) | Self::Literal(_) | Self::Aggregate(_) => false,
            Self::FunctionCall { args, .. } => args.iter().any(|arg| arg.any_tree_expr(predicate)),
            Self::Unary { expr, .. } => expr.any_tree_expr(predicate),
            Self::Binary { left, right, .. } => {
                left.any_tree_expr(predicate) || right.any_tree_expr(predicate)
            }
            Self::Case {
                when_then_arms,
                else_expr,
            } => {
                when_then_arms.iter().any(|arm| {
                    arm.condition().any_tree_expr(predicate)
                        || arm.result().any_tree_expr(predicate)
                }) || else_expr.any_tree_expr(predicate)
            }
            #[cfg(test)]
            Self::Alias { expr, .. } => expr.any_tree_expr(predicate),
        }
    }

    /// Return true when every visited planner expression node satisfies the
    /// supplied predicate.
    #[must_use]
    pub(in crate::db) fn all_tree_expr(&self, predicate: &mut impl FnMut(&Self) -> bool) -> bool {
        if !predicate(self) {
            return false;
        }

        match self {
            Self::Field(_) | Self::FieldPath(_) | Self::Literal(_) | Self::Aggregate(_) => true,
            Self::FunctionCall { args, .. } => args.iter().all(|arg| arg.all_tree_expr(predicate)),
            Self::Unary { expr, .. } => expr.all_tree_expr(predicate),
            Self::Binary { left, right, .. } => {
                left.all_tree_expr(predicate) && right.all_tree_expr(predicate)
            }
            Self::Case {
                when_then_arms,
                else_expr,
            } => {
                when_then_arms.iter().all(|arm| {
                    arm.condition().all_tree_expr(predicate)
                        && arm.result().all_tree_expr(predicate)
                }) && else_expr.all_tree_expr(predicate)
            }
            #[cfg(test)]
            Self::Alias { expr, .. } => expr.all_tree_expr(predicate),
        }
    }

    /// Visit every planner expression node in this tree through the owner-local
    /// child traversal contract, stopping early on the first error.
    pub(in crate::db) fn try_for_each_tree_expr<E>(
        &self,
        visit: &mut impl FnMut(&Self) -> Result<(), E>,
    ) -> Result<(), E> {
        visit(self)?;

        match self {
            Self::Field(_) | Self::FieldPath(_) | Self::Literal(_) | Self::Aggregate(_) => Ok(()),
            Self::FunctionCall { args, .. } => {
                for arg in args {
                    arg.try_for_each_tree_expr(visit)?;
                }

                Ok(())
            }
            Self::Unary { expr, .. } => expr.try_for_each_tree_expr(visit),
            Self::Binary { left, right, .. } => {
                left.try_for_each_tree_expr(visit)?;
                right.try_for_each_tree_expr(visit)
            }
            Self::Case {
                when_then_arms,
                else_expr,
            } => {
                for arm in when_then_arms {
                    arm.condition().try_for_each_tree_expr(visit)?;
                    arm.result().try_for_each_tree_expr(visit)?;
                }

                else_expr.try_for_each_tree_expr(visit)
            }
            #[cfg(test)]
            Self::Alias { expr, .. } => expr.try_for_each_tree_expr(visit),
        }
    }

    /// Visit every aggregate leaf owned by this planner expression tree through
    /// the canonical traversal contract.
    pub(in crate::db) fn try_for_each_tree_aggregate<E>(
        &self,
        visit: &mut impl FnMut(&AggregateExpr) -> Result<(), E>,
    ) -> Result<(), E> {
        self.try_for_each_tree_expr(&mut |expr| match expr {
            Self::Aggregate(aggregate) => visit(aggregate),
            _ => Ok(()),
        })
    }

    /// Visit every planner expression node through the canonical traversal
    /// contract while tracking compare-family nodes in post-order.
    pub(in crate::db) fn try_for_each_tree_expr_with_compare_index<E>(
        &self,
        next_compare_index: &mut usize,
        visit: &mut impl FnMut(usize, &Self) -> Result<(), E>,
    ) -> Result<(), E> {
        match self {
            Self::Field(_) | Self::FieldPath(_) | Self::Literal(_) | Self::Aggregate(_) => {}
            Self::FunctionCall { args, .. } => {
                for arg in args {
                    arg.try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
                }
            }
            Self::Unary { expr, .. } => {
                expr.try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
            }
            Self::Binary { left, right, .. } => {
                left.try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
                right.try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
            }
            Self::Case {
                when_then_arms,
                else_expr,
            } => {
                for arm in when_then_arms {
                    arm.condition()
                        .try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
                    arm.result()
                        .try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
                }

                else_expr.try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
            }
            #[cfg(test)]
            Self::Alias { expr, .. } => {
                expr.try_for_each_tree_expr_with_compare_index(next_compare_index, visit)?;
            }
        }

        let current_index = *next_compare_index;
        visit(current_index, self)?;

        if matches!(
            self,
            Self::Binary {
                op: BinaryOp::Eq
                    | BinaryOp::Ne
                    | BinaryOp::Lt
                    | BinaryOp::Lte
                    | BinaryOp::Gt
                    | BinaryOp::Gte,
                ..
            }
        ) {
            *next_compare_index = next_compare_index.saturating_add(1);
        }

        Ok(())
    }

    /// Return true when every field leaf referenced by this expression is
    /// present in the supplied allowlist.
    #[must_use]
    pub(in crate::db) fn references_only_fields(&self, allowed: &[&str]) -> bool {
        self.all_tree_expr(&mut |expr| match expr {
            Self::Field(field) => allowed.iter().any(|allowed| *allowed == field.as_str()),
            Self::FieldPath(_) => false,
            Self::Aggregate(_) | Self::Literal(_) => true,
            Self::FunctionCall { .. }
            | Self::Unary { .. }
            | Self::Binary { .. }
            | Self::Case { .. } => true,
            #[cfg(test)]
            Self::Alias { .. } => true,
        })
    }
}