icydb-core 0.144.7

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
//! Module: db::query::intent::tests::cache_key
//! Covers structural cache-key normalization across equivalent fluent query
//! shapes.
//! Does not own: shared query-intent test fixtures outside this focused cache
//! identity surface.
//! Boundary: exercises query-intent cache identity from the owner `tests/`
//! boundary rather than from the leaf implementation file.

use crate::{
    db::{
        CoercionId, CompareOp, ComparePredicate, MissingRowPolicy, Predicate,
        query::{
            intent::{Query, StructuralQuery, StructuralQueryCacheKey, model::QueryModel},
            plan::expr::{
                BinaryOp, CaseWhenArm, Expr, FieldId, Function,
                canonicalize_grouped_having_bool_expr,
            },
        },
    },
    model::{entity::EntityModel, field::FieldKind},
    testing::PLAN_ENTITY_TAG,
    traits::{EntitySchema, Path, RuntimeValueEncode},
    types::Ulid,
    value::Value,
};
use icydb_derive::FieldProjection;
use serde::Deserialize;

#[derive(Clone, Debug, Default, Deserialize, FieldProjection, PartialEq)]
struct CacheKeyEntity {
    id: Ulid,
    name: String,
}

struct CacheKeyCanister;

impl Path for CacheKeyCanister {
    const PATH: &'static str = concat!(module_path!(), "::CacheKeyCanister");
}

impl crate::traits::CanisterKind for CacheKeyCanister {
    const COMMIT_MEMORY_ID: u8 = crate::testing::test_commit_memory_id();
}

struct CacheKeyStore;

impl Path for CacheKeyStore {
    const PATH: &'static str = concat!(module_path!(), "::CacheKeyStore");
}

impl crate::traits::StoreKind for CacheKeyStore {
    type Canister = CacheKeyCanister;
}

crate::test_entity_schema! {
    ident = CacheKeyEntity,
    id = Ulid,
    id_field = id,
    entity_name = "CacheKeyEntity",
    entity_tag = PLAN_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("name", FieldKind::Text { max_len: None }),
    ],
    indexes = [],
    store = CacheKeyStore,
    canister = CacheKeyCanister,
}

fn basic_model() -> &'static EntityModel {
    <CacheKeyEntity as EntitySchema>::MODEL
}

#[test]
fn structural_query_cache_key_matches_for_identical_scalar_queries() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore)
        .filter_predicate(crate::db::Predicate::eq(
            "name".to_string(),
            Value::Text("Ada".to_string()),
        ))
        .order_term(crate::db::asc("name"))
        .limit(2);
    let right = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore)
        .order_term(crate::db::asc("name"))
        .filter_predicate(crate::db::Predicate::eq(
            "name".to_string(),
            Value::Text("Ada".to_string()),
        ))
        .limit(2);

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "equivalent scalar fluent queries must normalize onto one shared cache key",
    );
}

#[test]
fn structural_query_cache_key_distinguishes_order_direction() {
    let asc = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .order_term(crate::db::asc("name"));
    let desc = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .order_term(crate::db::desc("name"));

    assert_ne!(
        asc.structural_cache_key(),
        desc.structural_cache_key(),
        "order direction must remain part of shared query cache identity",
    );
}

#[test]
fn structural_query_cache_key_distinguishes_expression_owned_filter_expr() {
    let left = QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore).filter_expr(
        Expr::FunctionCall {
            function: Function::StartsWith,
            args: vec![
                Expr::FunctionCall {
                    function: Function::Replace,
                    args: vec![
                        Expr::Field(FieldId::new("name")),
                        Expr::Literal(Value::Text("a".to_string())),
                        Expr::Literal(Value::Text("A".to_string())),
                    ],
                },
                Expr::Literal(Value::Text("A".to_string())),
            ],
        },
    );
    let right = QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore).filter_expr(
        Expr::FunctionCall {
            function: Function::StartsWith,
            args: vec![
                Expr::FunctionCall {
                    function: Function::Replace,
                    args: vec![
                        Expr::Field(FieldId::new("name")),
                        Expr::Literal(Value::Text("a".to_string())),
                        Expr::Literal(Value::Text("A".to_string())),
                    ],
                },
                Expr::Literal(Value::Text("B".to_string())),
            ],
        },
    );

    assert_ne!(
        StructuralQueryCacheKey::from_query_model(&left),
        StructuralQueryCacheKey::from_query_model(&right),
        "expression-owned scalar filter expressions must remain part of shared query cache identity",
    );
}

#[test]
fn structural_query_cache_key_treats_equivalent_expression_owned_boolean_shapes_as_identical() {
    let left = QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore).filter_expr(
        Expr::Binary {
            op: crate::db::query::plan::expr::BinaryOp::And,
            left: Box::new(Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("name"))),
                right: Box::new(Expr::Literal(Value::Text("Ada".to_string()))),
            }),
            right: Box::new(Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("id"))),
                right: Box::new(Expr::Literal(Ulid::default().to_value())),
            }),
        },
    );
    let right = QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore).filter_expr(
        Expr::Binary {
            op: crate::db::query::plan::expr::BinaryOp::And,
            left: Box::new(Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("id"))),
                right: Box::new(Expr::Literal(Ulid::default().to_value())),
            }),
            right: Box::new(Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("name"))),
                right: Box::new(Expr::Literal(Value::Text("Ada".to_string()))),
            }),
        },
    );

    assert_eq!(
        StructuralQueryCacheKey::from_query_model(&left),
        StructuralQueryCacheKey::from_query_model(&right),
        "equivalent normalized expression-owned boolean filters must share one structural query cache key",
    );
}

#[test]
fn structural_query_cache_key_distinguishes_unary_boolean_filter_expr() {
    let positive = QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore).filter_expr(
        Expr::Binary {
            op: crate::db::query::plan::expr::BinaryOp::Eq,
            left: Box::new(Expr::Field(FieldId::new("name"))),
            right: Box::new(Expr::Literal(Value::Text("Ada".to_string()))),
        },
    );
    let negated =
        QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore).filter_expr(Expr::Unary {
            op: crate::db::query::plan::expr::UnaryOp::Not,
            expr: Box::new(Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("name"))),
                right: Box::new(Expr::Literal(Value::Text("Ada".to_string()))),
            }),
        });

    assert_ne!(
        StructuralQueryCacheKey::from_query_model(&positive),
        StructuralQueryCacheKey::from_query_model(&negated),
        "unary boolean operators must remain part of structural query cache identity",
    );
}

#[test]
fn structural_query_cache_key_ignores_predicate_fingerprint_when_filter_expr_exists() {
    let model = QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore).filter_expr(
        Expr::Binary {
            op: crate::db::query::plan::expr::BinaryOp::And,
            left: Box::new(Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("name"))),
                right: Box::new(Expr::Literal(Value::Text("Ada".to_string()))),
            }),
            right: Box::new(Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Eq,
                left: Box::new(Expr::Field(FieldId::new("id"))),
                right: Box::new(Expr::Literal(Ulid::default().to_value())),
            }),
        },
    );

    assert_eq!(
        model.structural_cache_key_with_normalized_predicate_fingerprint(Some([0x11; 32])),
        model.structural_cache_key_with_normalized_predicate_fingerprint(Some([0x22; 32])),
        "canonical scalar filter expressions must be the sole structural filter identity owner when present",
    );
}

#[test]
fn structural_query_cache_key_keeps_predicate_identity_when_filter_expr_is_absent() {
    let model = QueryModel::<Ulid>::new(basic_model(), MissingRowPolicy::Ignore);

    assert_ne!(
        model.structural_cache_key_with_normalized_predicate_fingerprint(Some([0x11; 32])),
        model.structural_cache_key_with_normalized_predicate_fingerprint(Some([0x22; 32])),
        "predicate-only queries must still key shared structural identity by predicate when no semantic filter expression exists",
    );
}

#[test]
fn structural_query_cache_key_treats_extrema_distinct_as_semantic_noop() {
    let plain_min = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::min_by("name"));
    let distinct_min = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::min_by("name").distinct());

    assert_eq!(
        plain_min.structural_cache_key(),
        distinct_min.structural_cache_key(),
        "shared structural query cache identity must follow aggregate semantics: MIN(DISTINCT field) and MIN(field) are equivalent",
    );
}

#[test]
fn structural_query_cache_key_keeps_count_distinct_semantically_distinct() {
    let plain_count = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::count_by("name"));
    let distinct_count = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::count_by("name").distinct());

    assert_ne!(
        plain_count.structural_cache_key(),
        distinct_count.structural_cache_key(),
        "shared structural query cache identity must keep COUNT(DISTINCT field) distinct from COUNT(field)",
    );
}

#[test]
fn structural_query_cache_key_keeps_sum_distinct_semantically_distinct() {
    let plain_sum = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::sum("name"));
    let distinct_sum = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::sum("name").distinct());

    assert_ne!(
        plain_sum.structural_cache_key(),
        distinct_sum.structural_cache_key(),
        "shared structural query cache identity must keep SUM(DISTINCT field) distinct from SUM(field)",
    );
}

#[test]
fn structural_query_cache_key_keeps_aggregate_filter_expr_distinct() {
    let active_filter = Expr::Binary {
        op: crate::db::query::plan::expr::BinaryOp::Eq,
        left: Box::new(Expr::Field(FieldId::new("name"))),
        right: Box::new(Expr::Literal(Value::Text("Ada".to_string()))),
    };
    let archived_filter = Expr::Binary {
        op: crate::db::query::plan::expr::BinaryOp::Eq,
        left: Box::new(Expr::Field(FieldId::new("name"))),
        right: Box::new(Expr::Literal(Value::Text("Grace".to_string()))),
    };
    let active_sum = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::sum("name").with_filter_expr(active_filter));
    let archived_sum = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .aggregate(crate::db::sum("name").with_filter_expr(archived_filter));

    assert_ne!(
        active_sum.structural_cache_key(),
        archived_sum.structural_cache_key(),
        "shared structural query cache identity must keep aggregate-local FILTER expressions distinct",
    );
}

#[test]
fn structural_query_cache_key_distinguishes_grouped_having_expr() {
    let left = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(crate::db::query::plan::expr::Expr::Binary {
            op: crate::db::query::plan::expr::BinaryOp::Gt,
            left: Box::new(crate::db::query::plan::expr::Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Add,
                left: Box::new(crate::db::query::plan::expr::Expr::Aggregate(
                    crate::db::count(),
                )),
                right: Box::new(crate::db::query::plan::expr::Expr::Literal(Value::Uint(1))),
            }),
            right: Box::new(crate::db::query::plan::expr::Expr::Literal(Value::Uint(5))),
        })
        .expect("widened grouped having should append");
    let right = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(crate::db::query::plan::expr::Expr::Binary {
            op: crate::db::query::plan::expr::BinaryOp::Gt,
            left: Box::new(crate::db::query::plan::expr::Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Add,
                left: Box::new(crate::db::query::plan::expr::Expr::Aggregate(
                    crate::db::count(),
                )),
                right: Box::new(crate::db::query::plan::expr::Expr::Literal(Value::Uint(2))),
            }),
            right: Box::new(crate::db::query::plan::expr::Expr::Literal(Value::Uint(5))),
        })
        .expect("widened grouped having should append");

    assert_ne!(
        left.structural_cache_key(),
        right.structural_cache_key(),
        "grouped having expressions must remain part of shared grouped cache identity",
    );
}

#[test]
fn structural_query_cache_key_treats_equivalent_grouped_having_boolean_shapes_as_identical() {
    let left = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_group("name", CompareOp::Eq, Value::Text("Ada".to_string()))
        .expect("grouped HAVING group-field compare should append")
        .having_aggregate(0, CompareOp::Gt, Value::Uint(0))
        .expect("grouped HAVING aggregate compare should append");
    let right = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_aggregate(0, CompareOp::Gt, Value::Uint(0))
        .expect("grouped HAVING aggregate compare should append")
        .having_group("name", CompareOp::Eq, Value::Text("Ada".to_string()))
        .expect("grouped HAVING group-field compare should append");

    assert_eq!(
        left.structural_cache_key(),
        right.structural_cache_key(),
        "canonical-equivalent grouped HAVING boolean shapes must share one structural cache key",
    );
}

#[test]
fn structural_query_cache_key_treats_explicit_else_grouped_case_as_canonical_equivalent() {
    let case = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(Expr::Case {
            when_then_arms: vec![CaseWhenArm::new(
                Expr::Binary {
                    op: BinaryOp::Gt,
                    left: Box::new(Expr::Aggregate(crate::db::count())),
                    right: Box::new(Expr::Literal(Value::Uint(1))),
                },
                Expr::Literal(Value::Bool(true)),
            )],
            else_expr: Box::new(Expr::Literal(Value::Bool(false))),
        })
        .expect("grouped searched CASE HAVING should append");
    let canonical = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(Expr::Binary {
            op: BinaryOp::Or,
            left: Box::new(Expr::FunctionCall {
                function: Function::Coalesce,
                args: vec![
                    Expr::Binary {
                        op: BinaryOp::Gt,
                        left: Box::new(Expr::Aggregate(crate::db::count())),
                        right: Box::new(Expr::Literal(Value::Uint(1))),
                    },
                    Expr::Literal(Value::Bool(false)),
                ],
            }),
            right: Box::new(Expr::Literal(Value::Bool(false))),
        })
        .expect("canonical grouped boolean HAVING should append");

    assert_eq!(
        case.structural_cache_key(),
        canonical.structural_cache_key(),
        "explicit-ELSE grouped searched CASE HAVING must share one structural cache key with its shipped canonical grouped boolean form",
    );
}

#[test]
fn structural_query_cache_key_treats_omitted_else_grouped_case_as_explicit_null_equivalent() {
    let omitted_else = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(Expr::Case {
            when_then_arms: vec![CaseWhenArm::new(
                Expr::Binary {
                    op: BinaryOp::Gt,
                    left: Box::new(Expr::Aggregate(crate::db::count())),
                    right: Box::new(Expr::Literal(Value::Uint(1))),
                },
                Expr::Literal(Value::Bool(true)),
            )],
            else_expr: Box::new(Expr::Literal(Value::Null)),
        })
        .expect("grouped searched CASE HAVING without ELSE should append");
    let explicit_null_canonical = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(canonicalize_grouped_having_bool_expr(Expr::Case {
            when_then_arms: vec![CaseWhenArm::new(
                Expr::Binary {
                    op: BinaryOp::Gt,
                    left: Box::new(Expr::Aggregate(crate::db::count())),
                    right: Box::new(Expr::Literal(Value::Uint(1))),
                },
                Expr::Literal(Value::Bool(true)),
            )],
            else_expr: Box::new(Expr::Literal(Value::Null)),
        }))
        .expect("canonical grouped boolean HAVING with explicit ELSE NULL should append");

    assert_eq!(
        omitted_else.structural_cache_key(),
        explicit_null_canonical.structural_cache_key(),
        "omitted-ELSE grouped searched CASE HAVING must share one structural cache key with the explicit ELSE NULL grouped boolean family once canonicalization proof succeeds",
    );
}

#[test]
fn structural_query_cache_key_keeps_omitted_else_grouped_case_distinct_from_false_family() {
    let omitted_else = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(Expr::Case {
            when_then_arms: vec![CaseWhenArm::new(
                Expr::Binary {
                    op: BinaryOp::Gt,
                    left: Box::new(Expr::Aggregate(crate::db::count())),
                    right: Box::new(Expr::Literal(Value::Uint(1))),
                },
                Expr::Literal(Value::Bool(true)),
            )],
            else_expr: Box::new(Expr::Literal(Value::Null)),
        })
        .expect("grouped searched CASE HAVING without ELSE should append");
    let canonical_false = StructuralQuery::new(basic_model(), MissingRowPolicy::Ignore)
        .group_by("name")
        .expect("grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(Expr::Binary {
            op: BinaryOp::Or,
            left: Box::new(Expr::FunctionCall {
                function: Function::Coalesce,
                args: vec![
                    Expr::Binary {
                        op: BinaryOp::Gt,
                        left: Box::new(Expr::Aggregate(crate::db::count())),
                        right: Box::new(Expr::Literal(Value::Uint(1))),
                    },
                    Expr::Literal(Value::Bool(false)),
                ],
            }),
            right: Box::new(Expr::Literal(Value::Bool(false))),
        })
        .expect("canonical grouped boolean HAVING should append");

    assert_ne!(
        omitted_else.structural_cache_key(),
        canonical_false.structural_cache_key(),
        "omitted-ELSE grouped searched CASE HAVING must stay distinct from the explicit-ELSE FALSE grouped boolean family",
    );
}

#[test]
fn structural_query_cache_key_treats_equivalent_in_list_permutations_as_identical() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::in_(
            "name".to_string(),
            vec![
                Value::Text("Ada".to_string()),
                Value::Text("Bob".to_string()),
                Value::Text("Cara".to_string()),
            ],
        )),
    );
    let right = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::in_(
            "name".to_string(),
            vec![
                Value::Text("Cara".to_string()),
                Value::Text("Ada".to_string()),
                Value::Text("Bob".to_string()),
            ],
        )),
    );

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "equivalent IN-list permutations must collapse onto one shared structural query cache key",
    );
}

#[test]
fn structural_query_cache_key_treats_duplicate_in_list_literals_as_identical() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::in_(
            "name".to_string(),
            vec![
                Value::Text("Ada".to_string()),
                Value::Text("Bob".to_string()),
                Value::Text("Ada".to_string()),
            ],
        )),
    );
    let right = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::in_(
            "name".to_string(),
            vec![
                Value::Text("Bob".to_string()),
                Value::Text("Ada".to_string()),
            ],
        )),
    );

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "duplicate literals in one canonical IN-list must not grow distinct shared cache keys",
    );
}

#[test]
fn structural_query_cache_key_treats_same_field_or_eq_and_in_as_identical() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Or(vec![
            Predicate::Compare(ComparePredicate::with_coercion(
                "name",
                CompareOp::Eq,
                Value::Text("Ada".to_string()),
                CoercionId::Strict,
            )),
            Predicate::Compare(ComparePredicate::with_coercion(
                "name",
                CompareOp::Eq,
                Value::Text("Bob".to_string()),
                CoercionId::Strict,
            )),
            Predicate::Compare(ComparePredicate::with_coercion(
                "name",
                CompareOp::Eq,
                Value::Text("Ada".to_string()),
                CoercionId::Strict,
            )),
        ]),
    );
    let right = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::In,
            Value::List(vec![
                Value::Text("Bob".to_string()),
                Value::Text("Ada".to_string()),
            ]),
            CoercionId::Strict,
        )),
    );

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "same-field OR-of-EQ and IN forms must collapse onto one shared structural query cache key",
    );
}

#[test]
fn structural_query_cache_key_distinguishes_in_and_not_in() {
    let in_list = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::in_(
            "name".to_string(),
            vec![
                Value::Text("Ada".to_string()),
                Value::Text("Bob".to_string()),
            ],
        )),
    );
    let not_in_list = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::not_in(
            "name".to_string(),
            vec![
                Value::Text("Ada".to_string()),
                Value::Text("Bob".to_string()),
            ],
        )),
    );

    assert_ne!(
        in_list.structural().structural_cache_key(),
        not_in_list.structural().structural_cache_key(),
        "shared structural query cache identity must keep IN and NOT IN semantically distinct",
    );
}

#[test]
fn structural_query_cache_key_treats_duplicate_and_children_as_identical() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::And(vec![
            Predicate::Compare(ComparePredicate::eq(
                "name".to_string(),
                Value::Text("Ada".to_string()),
            )),
            Predicate::Compare(ComparePredicate::eq(
                "name".to_string(),
                Value::Text("Ada".to_string()),
            )),
        ]),
    );
    let right = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::eq(
            "name".to_string(),
            Value::Text("Ada".to_string()),
        )),
    );

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "duplicate AND children must collapse onto one shared structural query cache key",
    );
}

#[test]
fn structural_query_cache_key_treats_duplicate_or_children_as_identical() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Or(vec![
            Predicate::Compare(ComparePredicate::eq(
                "name".to_string(),
                Value::Text("Ada".to_string()),
            )),
            Predicate::Compare(ComparePredicate::eq(
                "name".to_string(),
                Value::Text("Ada".to_string()),
            )),
        ]),
    );
    let right = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::eq(
            "name".to_string(),
            Value::Text("Ada".to_string()),
        )),
    );

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "duplicate OR children must collapse onto one shared structural query cache key",
    );
}

#[test]
fn structural_query_cache_key_treats_equal_bounds_as_eq() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::And(vec![
            Predicate::Compare(ComparePredicate::gte(
                "name".to_string(),
                Value::Text("Ada".to_string()),
            )),
            Predicate::Compare(ComparePredicate::lte(
                "name".to_string(),
                Value::Text("Ada".to_string()),
            )),
        ]),
    );
    let right = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::eq(
            "name".to_string(),
            Value::Text("Ada".to_string()),
        )),
    );

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "equal lower and upper bounds must collapse onto one shared structural query cache key",
    );
}

#[test]
fn structural_query_cache_key_treats_conflicting_equalities_as_false() {
    let left = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::And(vec![
            Predicate::Compare(ComparePredicate::eq(
                "name".to_string(),
                Value::Text("Ada".to_string()),
            )),
            Predicate::Compare(ComparePredicate::eq(
                "name".to_string(),
                Value::Text("Bob".to_string()),
            )),
        ]),
    );
    let right =
        Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(Predicate::False);

    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "conflicting equalities must collapse onto the same shared structural query cache key as FALSE",
    );
}

#[test]
fn structural_query_cache_key_treats_text_casefold_case_variants_as_identical() {
    let lower = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("ada".to_string()),
            CoercionId::TextCasefold,
        )),
    );
    let upper = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("ADA".to_string()),
            CoercionId::TextCasefold,
        )),
    );

    assert_eq!(
        lower.structural().structural_cache_key(),
        upper.structural().structural_cache_key(),
        "text-casefold case-only literal variants must collapse onto one shared structural query cache key",
    );
}

#[test]
fn structural_query_cache_key_distinguishes_strict_from_text_casefold_coercion() {
    let strict = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("ada".to_string()),
            CoercionId::Strict,
        )),
    );
    let casefold = Query::<CacheKeyEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("ada".to_string()),
            CoercionId::TextCasefold,
        )),
    );

    assert_ne!(
        strict.structural().structural_cache_key(),
        casefold.structural().structural_cache_key(),
        "shared structural query cache identity must keep strict and text-casefold coercion distinct",
    );
}