icydb-core 0.144.11

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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! Module: query::expr
//! Responsibility: schema-agnostic filter/order expression wrappers and lowering.
//! Does not own: planner route selection or executor evaluation.
//! Boundary: intent boundary lowers these to validated predicate/order forms.

use crate::db::query::{
    builder::FieldRef,
    builder::{AggregateExpr, NumericProjectionExpr, RoundProjectionExpr, TextProjectionExpr},
    plan::canonicalize_filter_literal_for_kind,
    plan::{
        OrderDirection, OrderTerm as PlannedOrderTerm,
        expr::{BinaryOp, Expr, FieldId, Function, UnaryOp},
    },
};
use crate::{
    model::EntityModel,
    value::{InputValue, Value},
};
use candid::CandidType;
use serde::Deserialize;

///
/// FilterValue
///
/// Serialized frontend-safe filter literal payload.
/// This keeps the public filter wire surface narrow and string-backed while
/// the intent boundary still rehydrates typed runtime values from schema.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub enum FilterValue {
    String(String),
    Bool(bool),
    Null,
    List(Vec<Self>),
}

impl FilterValue {
    // Convert one typed runtime value onto the narrowed public filter wire
    // contract. Non-bool scalar values travel as canonical strings so the
    // schema-aware intent boundary can rehydrate the exact field kind later.
    fn from_typed_value(value: Value) -> Self {
        match value {
            Value::Bool(value) => Self::Bool(value),
            Value::List(values) => {
                Self::List(values.into_iter().map(Self::from_typed_value).collect())
            }
            Value::Null | Value::Unit => Self::Null,
            Value::Text(value) => Self::String(value),
            Value::Enum(value) => Self::String(value.variant().to_string()),
            Value::Account(value) => Self::String(value.to_string()),
            Value::Blob(value) => Self::String(format!("{value:?}")),
            Value::Date(value) => Self::String(value.to_string()),
            Value::Decimal(value) => Self::String(value.to_string()),
            Value::Duration(value) => Self::String(format!("{value:?}")),
            Value::Float32(value) => Self::String(value.to_string()),
            Value::Float64(value) => Self::String(value.to_string()),
            Value::Int(value) => Self::String(value.to_string()),
            Value::Int128(value) => Self::String(value.to_string()),
            Value::IntBig(value) => Self::String(value.to_string()),
            Value::Map(value) => Self::String(format!("{value:?}")),
            Value::Principal(value) => Self::String(value.to_string()),
            Value::Subaccount(value) => Self::String(value.to_string()),
            Value::Timestamp(value) => Self::String(value.to_string()),
            Value::Uint(value) => Self::String(value.to_string()),
            Value::Uint128(value) => Self::String(value.to_string()),
            Value::UintBig(value) => Self::String(value.to_string()),
            Value::Ulid(value) => Self::String(value.to_string()),
        }
    }

    // Lower one public wire literal back onto the runtime value model before
    // adjacent schema-aware callers optionally canonicalize it to the target field kind.
    fn lower_value(&self) -> Value {
        match self {
            Self::String(value) => Value::Text(value.clone()),
            Self::Bool(value) => Value::Bool(*value),
            Self::Null => Value::Null,
            Self::List(values) => Value::List(values.iter().map(Self::lower_value).collect()),
        }
    }

    fn from_input_value(value: InputValue) -> Self {
        Self::from_typed_value(Value::from(value))
    }
}

impl<T> From<T> for FilterValue
where
    T: Into<InputValue>,
{
    fn from(value: T) -> Self {
        Self::from_input_value(value.into())
    }
}

///
/// FilterExpr
///
/// Serialized, planner-agnostic filter language.
/// This is the shared frontend-facing filter input model for fluent callers
/// and lowers onto planner-owned boolean expressions at the intent boundary.
///

#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq)]
pub enum FilterExpr {
    True,
    False,
    And(Vec<Self>),
    Or(Vec<Self>),
    Not(Box<Self>),
    Eq {
        field: String,
        value: FilterValue,
    },
    EqCi {
        field: String,
        value: FilterValue,
    },
    Ne {
        field: String,
        value: FilterValue,
    },
    Lt {
        field: String,
        value: FilterValue,
    },
    Lte {
        field: String,
        value: FilterValue,
    },
    Gt {
        field: String,
        value: FilterValue,
    },
    Gte {
        field: String,
        value: FilterValue,
    },
    EqField {
        left_field: String,
        right_field: String,
    },
    NeField {
        left_field: String,
        right_field: String,
    },
    LtField {
        left_field: String,
        right_field: String,
    },
    LteField {
        left_field: String,
        right_field: String,
    },
    GtField {
        left_field: String,
        right_field: String,
    },
    GteField {
        left_field: String,
        right_field: String,
    },
    In {
        field: String,
        values: Vec<FilterValue>,
    },
    NotIn {
        field: String,
        values: Vec<FilterValue>,
    },
    Contains {
        field: String,
        value: FilterValue,
    },
    TextContains {
        field: String,
        value: FilterValue,
    },
    TextContainsCi {
        field: String,
        value: FilterValue,
    },
    StartsWith {
        field: String,
        value: FilterValue,
    },
    StartsWithCi {
        field: String,
        value: FilterValue,
    },
    EndsWith {
        field: String,
        value: FilterValue,
    },
    EndsWithCi {
        field: String,
        value: FilterValue,
    },
    IsNull {
        field: String,
    },
    IsNotNull {
        field: String,
    },
    IsMissing {
        field: String,
    },
    IsEmpty {
        field: String,
    },
    IsNotEmpty {
        field: String,
    },
}

impl FilterExpr {
    /// Lower this typed filter expression into the shared planner-owned boolean expression model.
    #[must_use]
    #[expect(clippy::too_many_lines)]
    pub(in crate::db) fn lower_bool_expr_for_model(&self, model: &EntityModel) -> Expr {
        match self {
            Self::True => Expr::Literal(Value::Bool(true)),
            Self::False => Expr::Literal(Value::Bool(false)),
            Self::And(xs) => fold_filter_bool_chain(BinaryOp::And, xs, model),
            Self::Or(xs) => fold_filter_bool_chain(BinaryOp::Or, xs, model),
            Self::Not(x) => Expr::Unary {
                op: UnaryOp::Not,
                expr: Box::new(x.lower_bool_expr_for_model(model)),
            },
            Self::Eq { field, value } => field_compare_expr(
                BinaryOp::Eq,
                field,
                lower_compare_filter_value_for_field(model, field, value),
            ),
            Self::EqCi { field, value } => Expr::Binary {
                op: BinaryOp::Eq,
                left: Box::new(casefold_field_expr(field)),
                right: Box::new(Expr::Literal(value.lower_value())),
            },
            Self::Ne { field, value } => field_compare_expr(
                BinaryOp::Ne,
                field,
                lower_compare_filter_value_for_field(model, field, value),
            ),
            Self::Lt { field, value } => field_compare_expr(
                BinaryOp::Lt,
                field,
                lower_compare_filter_value_for_field(model, field, value),
            ),
            Self::Lte { field, value } => field_compare_expr(
                BinaryOp::Lte,
                field,
                lower_compare_filter_value_for_field(model, field, value),
            ),
            Self::Gt { field, value } => field_compare_expr(
                BinaryOp::Gt,
                field,
                lower_compare_filter_value_for_field(model, field, value),
            ),
            Self::Gte { field, value } => field_compare_expr(
                BinaryOp::Gte,
                field,
                lower_compare_filter_value_for_field(model, field, value),
            ),
            Self::EqField {
                left_field,
                right_field,
            } => field_compare_field_expr(BinaryOp::Eq, left_field, right_field),
            Self::NeField {
                left_field,
                right_field,
            } => field_compare_field_expr(BinaryOp::Ne, left_field, right_field),
            Self::LtField {
                left_field,
                right_field,
            } => field_compare_field_expr(BinaryOp::Lt, left_field, right_field),
            Self::LteField {
                left_field,
                right_field,
            } => field_compare_field_expr(BinaryOp::Lte, left_field, right_field),
            Self::GtField {
                left_field,
                right_field,
            } => field_compare_field_expr(BinaryOp::Gt, left_field, right_field),
            Self::GteField {
                left_field,
                right_field,
            } => field_compare_field_expr(BinaryOp::Gte, left_field, right_field),
            Self::In { field, values } => membership_expr(
                field,
                lower_membership_filter_values_for_field(model, field, values).as_slice(),
                false,
            ),
            Self::NotIn { field, values } => membership_expr(
                field,
                lower_membership_filter_values_for_field(model, field, values).as_slice(),
                true,
            ),
            Self::Contains { field, value } => Expr::FunctionCall {
                function: Function::CollectionContains,
                args: vec![
                    Expr::Field(FieldId::new(field.clone())),
                    Expr::Literal(lower_contains_filter_value_for_field(model, field, value)),
                ],
            },
            Self::TextContains { field, value } => text_function_expr(
                Function::Contains,
                Expr::Field(FieldId::new(field.clone())),
                value.lower_value(),
            ),
            Self::TextContainsCi { field, value } => text_function_expr(
                Function::Contains,
                casefold_field_expr(field),
                value.lower_value(),
            ),
            Self::StartsWith { field, value } => text_function_expr(
                Function::StartsWith,
                Expr::Field(FieldId::new(field.clone())),
                value.lower_value(),
            ),
            Self::StartsWithCi { field, value } => text_function_expr(
                Function::StartsWith,
                casefold_field_expr(field),
                value.lower_value(),
            ),
            Self::EndsWith { field, value } => text_function_expr(
                Function::EndsWith,
                Expr::Field(FieldId::new(field.clone())),
                value.lower_value(),
            ),
            Self::EndsWithCi { field, value } => text_function_expr(
                Function::EndsWith,
                casefold_field_expr(field),
                value.lower_value(),
            ),
            Self::IsNull { field } => field_function_expr(Function::IsNull, field),
            Self::IsNotNull { field } => field_function_expr(Function::IsNotNull, field),
            Self::IsMissing { field } => field_function_expr(Function::IsMissing, field),
            Self::IsEmpty { field } => field_function_expr(Function::IsEmpty, field),
            Self::IsNotEmpty { field } => field_function_expr(Function::IsNotEmpty, field),
        }
    }

    /// Build an `And` expression from a list of child expressions.
    #[must_use]
    pub const fn and(exprs: Vec<Self>) -> Self {
        Self::And(exprs)
    }

    /// Build an `Or` expression from a list of child expressions.
    #[must_use]
    pub const fn or(exprs: Vec<Self>) -> Self {
        Self::Or(exprs)
    }

    /// Negate one child expression.
    #[must_use]
    #[expect(clippy::should_implement_trait)]
    pub fn not(expr: Self) -> Self {
        Self::Not(Box::new(expr))
    }

    /// Compare `field == value`.
    #[must_use]
    pub fn eq(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::Eq {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare `field != value`.
    #[must_use]
    pub fn ne(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::Ne {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare `field < value`.
    #[must_use]
    pub fn lt(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::Lt {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare `field <= value`.
    #[must_use]
    pub fn lte(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::Lte {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare `field > value`.
    #[must_use]
    pub fn gt(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::Gt {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare `field >= value`.
    #[must_use]
    pub fn gte(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::Gte {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare `field == value` with casefolded text equality.
    #[must_use]
    pub fn eq_ci(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::EqCi {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare `left_field == right_field`.
    #[must_use]
    pub fn eq_field(left_field: impl Into<String>, right_field: impl Into<String>) -> Self {
        Self::EqField {
            left_field: left_field.into(),
            right_field: right_field.into(),
        }
    }

    /// Compare `left_field != right_field`.
    #[must_use]
    pub fn ne_field(left_field: impl Into<String>, right_field: impl Into<String>) -> Self {
        Self::NeField {
            left_field: left_field.into(),
            right_field: right_field.into(),
        }
    }

    /// Compare `left_field < right_field`.
    #[must_use]
    pub fn lt_field(left_field: impl Into<String>, right_field: impl Into<String>) -> Self {
        Self::LtField {
            left_field: left_field.into(),
            right_field: right_field.into(),
        }
    }

    /// Compare `left_field <= right_field`.
    #[must_use]
    pub fn lte_field(left_field: impl Into<String>, right_field: impl Into<String>) -> Self {
        Self::LteField {
            left_field: left_field.into(),
            right_field: right_field.into(),
        }
    }

    /// Compare `left_field > right_field`.
    #[must_use]
    pub fn gt_field(left_field: impl Into<String>, right_field: impl Into<String>) -> Self {
        Self::GtField {
            left_field: left_field.into(),
            right_field: right_field.into(),
        }
    }

    /// Compare `left_field >= right_field`.
    #[must_use]
    pub fn gte_field(left_field: impl Into<String>, right_field: impl Into<String>) -> Self {
        Self::GteField {
            left_field: left_field.into(),
            right_field: right_field.into(),
        }
    }

    /// Compare `field IN values`.
    #[must_use]
    pub fn in_list(
        field: impl Into<String>,
        values: impl IntoIterator<Item = impl Into<FilterValue>>,
    ) -> Self {
        Self::In {
            field: field.into(),
            values: values.into_iter().map(Into::into).collect(),
        }
    }

    /// Compare `field NOT IN values`.
    #[must_use]
    pub fn not_in(
        field: impl Into<String>,
        values: impl IntoIterator<Item = impl Into<FilterValue>>,
    ) -> Self {
        Self::NotIn {
            field: field.into(),
            values: values.into_iter().map(Into::into).collect(),
        }
    }

    /// Compare collection `field CONTAINS value`.
    #[must_use]
    pub fn contains(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::Contains {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare case-sensitive substring containment.
    #[must_use]
    pub fn text_contains(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::TextContains {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare case-insensitive substring containment.
    #[must_use]
    pub fn text_contains_ci(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::TextContainsCi {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare case-sensitive prefix match.
    #[must_use]
    pub fn starts_with(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::StartsWith {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare case-insensitive prefix match.
    #[must_use]
    pub fn starts_with_ci(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::StartsWithCi {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare case-sensitive suffix match.
    #[must_use]
    pub fn ends_with(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::EndsWith {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Compare case-insensitive suffix match.
    #[must_use]
    pub fn ends_with_ci(field: impl Into<String>, value: impl Into<FilterValue>) -> Self {
        Self::EndsWithCi {
            field: field.into(),
            value: value.into(),
        }
    }

    /// Match rows where `field` is present and null.
    #[must_use]
    pub fn is_null(field: impl Into<String>) -> Self {
        Self::IsNull {
            field: field.into(),
        }
    }

    /// Match rows where `field` is present and non-null.
    #[must_use]
    pub fn is_not_null(field: impl Into<String>) -> Self {
        Self::IsNotNull {
            field: field.into(),
        }
    }

    /// Match rows where `field` is absent.
    #[must_use]
    pub fn is_missing(field: impl Into<String>) -> Self {
        Self::IsMissing {
            field: field.into(),
        }
    }

    /// Match rows where `field` is present and empty.
    #[must_use]
    pub fn is_empty(field: impl Into<String>) -> Self {
        Self::IsEmpty {
            field: field.into(),
        }
    }

    /// Match rows where `field` is present and non-empty.
    #[must_use]
    pub fn is_not_empty(field: impl Into<String>) -> Self {
        Self::IsNotEmpty {
            field: field.into(),
        }
    }
}

fn fold_filter_bool_chain(op: BinaryOp, exprs: &[FilterExpr], model: &EntityModel) -> Expr {
    let mut exprs = exprs.iter();
    let Some(first) = exprs.next() else {
        return Expr::Literal(Value::Bool(matches!(op, BinaryOp::And)));
    };

    let first = first.lower_bool_expr_for_model(model);

    exprs.fold(first, |left, expr| Expr::Binary {
        op,
        left: Box::new(left),
        right: Box::new(expr.lower_bool_expr_for_model(model)),
    })
}

fn lower_compare_filter_value_for_field(
    model: &EntityModel,
    field: &str,
    value: &FilterValue,
) -> Value {
    lower_filter_value_for_field_kind(model, field, value, false)
}

fn lower_contains_filter_value_for_field(
    model: &EntityModel,
    field: &str,
    value: &FilterValue,
) -> Value {
    lower_filter_value_for_field_kind(model, field, value, true)
}

fn lower_filter_value_for_field_kind(
    model: &EntityModel,
    field: &str,
    value: &FilterValue,
    collection_element: bool,
) -> Value {
    let raw = value.lower_value();
    let Some(field_slot) = model.resolve_field_slot(field) else {
        return raw;
    };

    let mut kind = model.fields()[field_slot].kind();
    if collection_element {
        kind = match kind {
            crate::model::field::FieldKind::List(inner)
            | crate::model::field::FieldKind::Set(inner) => *inner,
            _ => kind,
        };
    }

    canonicalize_filter_literal_for_kind(&kind, &raw).unwrap_or(raw)
}

fn lower_membership_filter_values_for_field(
    model: &EntityModel,
    field: &str,
    values: &[FilterValue],
) -> Vec<Value> {
    values
        .iter()
        .map(|value| lower_compare_filter_value_for_field(model, field, value))
        .collect()
}

fn field_compare_expr(op: BinaryOp, field: &str, value: Value) -> Expr {
    Expr::Binary {
        op,
        left: Box::new(Expr::Field(FieldId::new(field.to_string()))),
        right: Box::new(Expr::Literal(value)),
    }
}

fn field_compare_field_expr(op: BinaryOp, left_field: &str, right_field: &str) -> Expr {
    Expr::Binary {
        op,
        left: Box::new(Expr::Field(FieldId::new(left_field.to_string()))),
        right: Box::new(Expr::Field(FieldId::new(right_field.to_string()))),
    }
}

fn membership_expr(field: &str, values: &[Value], negated: bool) -> Expr {
    let compare_op = if negated { BinaryOp::Ne } else { BinaryOp::Eq };
    let join_op = if negated { BinaryOp::And } else { BinaryOp::Or };
    let mut values = values.iter();
    let Some(first) = values.next() else {
        return Expr::Literal(Value::Bool(negated));
    };

    let field = Expr::Field(FieldId::new(field.to_string()));
    let mut expr = Expr::Binary {
        op: compare_op,
        left: Box::new(field.clone()),
        right: Box::new(Expr::Literal(first.clone())),
    };

    for value in values {
        expr = Expr::Binary {
            op: join_op,
            left: Box::new(expr),
            right: Box::new(Expr::Binary {
                op: compare_op,
                left: Box::new(field.clone()),
                right: Box::new(Expr::Literal(value.clone())),
            }),
        };
    }

    expr
}

fn field_function_expr(function: Function, field: &str) -> Expr {
    Expr::FunctionCall {
        function,
        args: vec![Expr::Field(FieldId::new(field.to_string()))],
    }
}

fn text_function_expr(function: Function, left: Expr, value: Value) -> Expr {
    Expr::FunctionCall {
        function,
        args: vec![left, Expr::Literal(value)],
    }
}

fn casefold_field_expr(field: &str) -> Expr {
    Expr::FunctionCall {
        function: Function::Lower,
        args: vec![Expr::Field(FieldId::new(field.to_string()))],
    }
}

///
/// OrderExpr
///
/// Typed fluent ORDER BY expression wrapper.
/// This exists so fluent code can construct planner-owned ORDER BY
/// semantics directly at the query boundary.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OrderExpr {
    expr: Expr,
}

impl OrderExpr {
    /// Build one direct field ORDER BY expression.
    #[must_use]
    pub fn field(field: impl Into<String>) -> Self {
        let field = field.into();

        Self {
            expr: Expr::Field(FieldId::new(field)),
        }
    }

    // Freeze one typed fluent order expression onto the planner-owned
    // semantic expression now that labels are derived only at explain/hash
    // edges instead of being stored in fluent order shells.
    const fn new(expr: Expr) -> Self {
        Self { expr }
    }

    // Lower one typed fluent order expression into the planner-owned order
    // contract now that ordering is expression-based end to end.
    pub(in crate::db) fn lower(&self, direction: OrderDirection) -> PlannedOrderTerm {
        PlannedOrderTerm::new(self.expr.clone(), direction)
    }
}

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

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

impl From<FieldRef> for OrderExpr {
    fn from(value: FieldRef) -> Self {
        Self::field(value.as_str())
    }
}

impl From<TextProjectionExpr> for OrderExpr {
    fn from(value: TextProjectionExpr) -> Self {
        Self::new(value.expr().clone())
    }
}

impl From<NumericProjectionExpr> for OrderExpr {
    fn from(value: NumericProjectionExpr) -> Self {
        Self::new(value.expr().clone())
    }
}

impl From<RoundProjectionExpr> for OrderExpr {
    fn from(value: RoundProjectionExpr) -> Self {
        Self::new(value.expr().clone())
    }
}

impl From<AggregateExpr> for OrderExpr {
    fn from(value: AggregateExpr) -> Self {
        Self::new(Expr::Aggregate(value))
    }
}

///
/// OrderTerm
///
/// Typed fluent ORDER BY term.
/// Carries one typed ORDER BY expression plus direction so fluent builders can
/// express deterministic ordering directly at the query boundary.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OrderTerm {
    expr: OrderExpr,
    direction: OrderDirection,
}

impl OrderTerm {
    /// Build one ascending ORDER BY term from one typed expression.
    #[must_use]
    pub fn asc(expr: impl Into<OrderExpr>) -> Self {
        Self {
            expr: expr.into(),
            direction: OrderDirection::Asc,
        }
    }

    /// Build one descending ORDER BY term from one typed expression.
    #[must_use]
    pub fn desc(expr: impl Into<OrderExpr>) -> Self {
        Self {
            expr: expr.into(),
            direction: OrderDirection::Desc,
        }
    }

    // Lower one typed fluent order term directly into the planner-owned
    // `OrderTerm` contract.
    pub(in crate::db) fn lower(&self) -> PlannedOrderTerm {
        self.expr.lower(self.direction)
    }
}

/// Build one typed direct-field ORDER BY expression.
#[must_use]
pub fn field(field: impl Into<String>) -> OrderExpr {
    OrderExpr::field(field)
}

/// Build one ascending typed ORDER BY term.
#[must_use]
pub fn asc(expr: impl Into<OrderExpr>) -> OrderTerm {
    OrderTerm::asc(expr)
}

/// Build one descending typed ORDER BY term.
#[must_use]
pub fn desc(expr: impl Into<OrderExpr>) -> OrderTerm {
    OrderTerm::desc(expr)
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use super::{FilterExpr, FilterValue};
    use crate::{
        db::query::plan::expr::{BinaryOp, Expr, FieldId},
        model::{EntityModel, field::FieldKind, field::FieldModel},
        types::Ulid,
        value::Value,
    };
    use candid::types::{CandidType, Label, Type, TypeInner};

    static FILTER_TEST_FIELDS: [FieldModel; 3] = [
        FieldModel::generated("id", FieldKind::Ulid),
        FieldModel::generated("rank", FieldKind::Uint),
        FieldModel::generated("active", FieldKind::Bool),
    ];
    static FILTER_TEST_MODEL: EntityModel = EntityModel::generated(
        "tests::FilterEntity",
        "FilterEntity",
        &FILTER_TEST_FIELDS[0],
        0,
        &FILTER_TEST_FIELDS,
        &[],
    );

    fn expect_record_fields(ty: Type) -> Vec<String> {
        match ty.as_ref() {
            TypeInner::Record(fields) => fields
                .iter()
                .map(|field| match field.id.as_ref() {
                    Label::Named(name) => name.clone(),
                    other => panic!("expected named record field, got {other:?}"),
                })
                .collect(),
            other => panic!("expected candid record, got {other:?}"),
        }
    }

    fn expect_variant_labels(ty: Type) -> Vec<String> {
        match ty.as_ref() {
            TypeInner::Variant(fields) => fields
                .iter()
                .map(|field| match field.id.as_ref() {
                    Label::Named(name) => name.clone(),
                    other => panic!("expected named variant label, got {other:?}"),
                })
                .collect(),
            other => panic!("expected candid variant, got {other:?}"),
        }
    }

    fn expect_variant_field_type(ty: Type, variant_name: &str) -> Type {
        match ty.as_ref() {
            TypeInner::Variant(fields) => fields
                .iter()
                .find_map(|field| match field.id.as_ref() {
                    Label::Named(name) if name == variant_name => Some(field.ty.clone()),
                    _ => None,
                })
                .unwrap_or_else(|| panic!("expected variant label `{variant_name}`")),
            other => panic!("expected candid variant, got {other:?}"),
        }
    }

    #[test]
    fn filter_expr_eq_candid_payload_shape_is_stable() {
        let fields = expect_record_fields(expect_variant_field_type(FilterExpr::ty(), "Eq"));

        for field in ["field", "value"] {
            assert!(
                fields.iter().any(|candidate| candidate == field),
                "Eq payload must keep `{field}` field key in Candid shape",
            );
        }
    }

    #[test]
    fn filter_value_variant_labels_are_stable() {
        let labels = expect_variant_labels(FilterValue::ty());

        for label in ["String", "Bool", "Null", "List"] {
            assert!(
                labels.iter().any(|candidate| candidate == label),
                "FilterValue must keep `{label}` variant label",
            );
        }
    }

    #[test]
    fn filter_expr_and_candid_payload_shape_is_stable() {
        match expect_variant_field_type(FilterExpr::ty(), "And").as_ref() {
            TypeInner::Vec(_) => {}
            other => panic!("And payload must remain a Candid vec payload, got {other:?}"),
        }
    }

    #[test]
    fn filter_expr_text_contains_ci_candid_payload_shape_is_stable() {
        let fields = expect_record_fields(expect_variant_field_type(
            FilterExpr::ty(),
            "TextContainsCi",
        ));

        for field in ["field", "value"] {
            assert!(
                fields.iter().any(|candidate| candidate == field),
                "TextContainsCi payload must keep `{field}` field key in Candid shape",
            );
        }
    }

    #[test]
    fn filter_expr_not_payload_shape_is_stable() {
        match expect_variant_field_type(FilterExpr::ty(), "Not").as_ref() {
            TypeInner::Var(_) | TypeInner::Knot(_) | TypeInner::Variant(_) => {}
            other => panic!("Not payload must keep nested predicate payload, got {other:?}"),
        }
    }

    #[test]
    fn filter_expr_variant_labels_are_stable() {
        let labels = expect_variant_labels(FilterExpr::ty());

        for label in ["Eq", "And", "Not", "TextContainsCi", "IsMissing"] {
            assert!(
                labels.iter().any(|candidate| candidate == label),
                "FilterExpr must keep `{label}` variant label",
            );
        }
    }

    #[test]
    fn query_expr_fixture_constructors_stay_usable() {
        let expr = FilterExpr::and(vec![
            FilterExpr::is_null("deleted_at"),
            FilterExpr::not(FilterExpr::is_missing("name")),
        ]);

        match expr {
            FilterExpr::And(items) => assert_eq!(items.len(), 2),
            other => panic!("expected And fixture, got {other:?}"),
        }
    }

    #[test]
    fn filter_expr_model_lowering_rehydrates_string_ulid_literal() {
        let ulid = Ulid::default();
        let expr =
            FilterExpr::eq("id", ulid.to_string()).lower_bool_expr_for_model(&FILTER_TEST_MODEL);

        assert_eq!(
            expr,
            Expr::Binary {
                op: BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("id".to_string()))),
                right: Box::new(Expr::Literal(Value::Ulid(ulid))),
            }
        );
    }

    #[test]
    fn filter_expr_model_lowering_rehydrates_numeric_membership_literals() {
        let expr = FilterExpr::in_list("rank", [7_u64, 9_u64])
            .lower_bool_expr_for_model(&FILTER_TEST_MODEL);

        assert_eq!(
            expr,
            Expr::Binary {
                op: BinaryOp::Or,
                left: Box::new(Expr::Binary {
                    op: BinaryOp::Eq,
                    left: Box::new(Expr::Field(FieldId::new("rank".to_string()))),
                    right: Box::new(Expr::Literal(Value::Uint(7))),
                }),
                right: Box::new(Expr::Binary {
                    op: BinaryOp::Eq,
                    left: Box::new(Expr::Field(FieldId::new("rank".to_string()))),
                    right: Box::new(Expr::Literal(Value::Uint(9))),
                }),
            }
        );
    }
}