icydb-core 0.68.4

IcyDB — A type-safe, embedded ORM and schema system for the Internet Computer
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
//! Module: db::query::plan::planner::tests
//! Responsibility: module-local ownership and contracts for db::query::plan::planner::tests.
//! Does not own: cross-module orchestration outside this module.
//! Boundary: exposes this module API while keeping implementation details internal.

use super::*;
use crate::{
    db::{
        access::{AccessPath, SemanticIndexRangeSpec, normalize_access_plan_value},
        predicate::{CoercionId, CompareOp, ComparePredicate, Predicate, normalize},
        query::{
            intent::{KeyAccess, build_access_plan_from_keys},
            plan::{OrderDirection, OrderSpec},
        },
    },
    model::{
        field::{FieldKind, FieldModel},
        index::{IndexExpression, IndexKeyItem, IndexModel},
    },
    testing::entity_model_from_static,
    types::Ulid,
};
use std::ops::Bound;

static PLANNER_CANONICAL_FIELDS: [FieldModel; 1] = [FieldModel::new("id", FieldKind::Ulid)];
static PLANNER_CANONICAL_INDEXES: [&IndexModel; 0] = [];
static PLANNER_CANONICAL_MODEL: EntityModel = entity_model_from_static(
    "planner::canonical_test_entity",
    "PlannerCanonicalTestEntity",
    &PLANNER_CANONICAL_FIELDS[0],
    &PLANNER_CANONICAL_FIELDS,
    &PLANNER_CANONICAL_INDEXES,
);

static PLANNER_IN_EMPTY_FIELDS: [FieldModel; 2] = [
    FieldModel::new("id", FieldKind::Ulid),
    FieldModel::new("email", FieldKind::Text),
];
static PLANNER_IN_EMPTY_INDEX_FIELDS: [&str; 1] = ["email"];
static PLANNER_IN_EMPTY_INDEXES: [IndexModel; 1] = [IndexModel::new(
    "email_idx",
    "planner::in_empty_test_entity",
    &PLANNER_IN_EMPTY_INDEX_FIELDS,
    false,
)];
static PLANNER_IN_EMPTY_INDEX_REFS: [&IndexModel; 1] = [&PLANNER_IN_EMPTY_INDEXES[0]];
static PLANNER_IN_EMPTY_MODEL: EntityModel = entity_model_from_static(
    "planner::in_empty_test_entity",
    "PlannerInEmptyTestEntity",
    &PLANNER_IN_EMPTY_FIELDS[0],
    &PLANNER_IN_EMPTY_FIELDS,
    &PLANNER_IN_EMPTY_INDEX_REFS,
);
static PLANNER_ORDER_FIELDS: [FieldModel; 3] = [
    FieldModel::new("id", FieldKind::Ulid),
    FieldModel::new("name", FieldKind::Text),
    FieldModel::new("active", FieldKind::Bool),
];
static PLANNER_ORDER_INDEX_FIELDS: [&str; 1] = ["name"];
static PLANNER_ORDER_INDEXES: [IndexModel; 1] = [IndexModel::new(
    "name_idx",
    "planner::order_test_entity",
    &PLANNER_ORDER_INDEX_FIELDS,
    false,
)];
static PLANNER_ORDER_INDEX_REFS: [&IndexModel; 1] = [&PLANNER_ORDER_INDEXES[0]];
static PLANNER_ORDER_MODEL: EntityModel = entity_model_from_static(
    "planner::order_test_entity",
    "PlannerOrderTestEntity",
    &PLANNER_ORDER_FIELDS[0],
    &PLANNER_ORDER_FIELDS,
    &PLANNER_ORDER_INDEX_REFS,
);
static PLANNER_ORDER_FILTERED_INDEXES: [IndexModel; 1] = [IndexModel::new_with_predicate(
    "name_idx_active_only",
    "planner::order_filtered_test_entity",
    &PLANNER_ORDER_INDEX_FIELDS,
    false,
    Some("active = true"),
)];
static PLANNER_ORDER_FILTERED_INDEX_REFS: [&IndexModel; 1] = [&PLANNER_ORDER_FILTERED_INDEXES[0]];
static PLANNER_ORDER_FILTERED_MODEL: EntityModel = entity_model_from_static(
    "planner::order_filtered_test_entity",
    "PlannerOrderFilteredTestEntity",
    &PLANNER_ORDER_FIELDS[0],
    &PLANNER_ORDER_FIELDS,
    &PLANNER_ORDER_FILTERED_INDEX_REFS,
);
static PLANNER_ORDER_COMPOSITE_FIELDS: [FieldModel; 4] = [
    FieldModel::new("id", FieldKind::Ulid),
    FieldModel::new("code", FieldKind::Text),
    FieldModel::new("serial", FieldKind::Uint),
    FieldModel::new("note", FieldKind::Text),
];
static PLANNER_ORDER_COMPOSITE_INDEX_FIELDS: [&str; 2] = ["code", "serial"];
static PLANNER_ORDER_COMPOSITE_INDEXES: [IndexModel; 1] = [IndexModel::new(
    "code_serial_idx",
    "planner::order_composite_test_entity",
    &PLANNER_ORDER_COMPOSITE_INDEX_FIELDS,
    false,
)];
static PLANNER_ORDER_COMPOSITE_INDEX_REFS: [&IndexModel; 1] = [&PLANNER_ORDER_COMPOSITE_INDEXES[0]];
static PLANNER_ORDER_COMPOSITE_MODEL: EntityModel = entity_model_from_static(
    "planner::order_composite_test_entity",
    "PlannerOrderCompositeTestEntity",
    &PLANNER_ORDER_COMPOSITE_FIELDS[0],
    &PLANNER_ORDER_COMPOSITE_FIELDS,
    &PLANNER_ORDER_COMPOSITE_INDEX_REFS,
);
static PLANNER_ORDER_EXPRESSION_KEY_ITEMS: [IndexKeyItem; 1] =
    [IndexKeyItem::Expression(IndexExpression::Lower("name"))];
static PLANNER_ORDER_EXPRESSION_INDEXES: [IndexModel; 1] = [IndexModel::new_with_key_items(
    "name_lower_idx",
    "planner::order_expression_test_entity",
    &PLANNER_ORDER_INDEX_FIELDS,
    &PLANNER_ORDER_EXPRESSION_KEY_ITEMS,
    false,
)];
static PLANNER_ORDER_EXPRESSION_INDEX_REFS: [&IndexModel; 1] =
    [&PLANNER_ORDER_EXPRESSION_INDEXES[0]];
static PLANNER_ORDER_EXPRESSION_MODEL: EntityModel = entity_model_from_static(
    "planner::order_expression_test_entity",
    "PlannerOrderExpressionTestEntity",
    &PLANNER_ORDER_FIELDS[0],
    &PLANNER_ORDER_FIELDS,
    &PLANNER_ORDER_EXPRESSION_INDEX_REFS,
);

fn plan_access_for_test(
    model: &EntityModel,
    schema: &SchemaInfo,
    predicate: Option<&Predicate>,
) -> Result<AccessPlan<Value>, PlannerError> {
    let normalized = predicate.map(normalize);

    plan_access(model, schema, normalized.as_ref())
}

fn plan_access_for_test_with_order(
    model: &EntityModel,
    schema: &SchemaInfo,
    predicate: Option<&Predicate>,
    order: Option<OrderSpec>,
) -> Result<AccessPlan<Value>, PlannerError> {
    let normalized = predicate.map(normalize);

    plan_access_with_order(model, schema, normalized.as_ref(), order.as_ref())
}

fn canonical_order(fields: &[(&str, OrderDirection)]) -> OrderSpec {
    OrderSpec {
        fields: fields
            .iter()
            .map(|(field, direction)| ((*field).to_string(), *direction))
            .collect(),
    }
}

#[test]
fn normalize_union_dedups_identical_paths() {
    let key = Value::Ulid(Ulid::from_u128(1));
    let plan = AccessPlan::Union(vec![
        AccessPlan::by_key(key.clone()),
        AccessPlan::by_key(key),
    ]);

    let normalized = normalize_access_plan_value(plan);

    assert_eq!(
        normalized,
        AccessPlan::by_key(Value::Ulid(Ulid::from_u128(1)))
    );
}

#[test]
fn normalize_union_sorts_by_key() {
    let a = Value::Ulid(Ulid::from_u128(1));
    let b = Value::Ulid(Ulid::from_u128(2));
    let plan = AccessPlan::Union(vec![
        AccessPlan::by_key(b.clone()),
        AccessPlan::by_key(a.clone()),
    ]);

    let normalized = normalize_access_plan_value(plan);
    let AccessPlan::Union(children) = normalized else {
        panic!("expected union");
    };

    assert_eq!(children.len(), 2);
    assert_eq!(children[0], AccessPlan::by_key(a));
    assert_eq!(children[1], AccessPlan::by_key(b));
}

#[test]
fn normalize_intersection_removes_full_scan() {
    let key = Value::Ulid(Ulid::from_u128(7));
    let plan = AccessPlan::Intersection(vec![AccessPlan::full_scan(), AccessPlan::by_key(key)]);

    let normalized = normalize_access_plan_value(plan);

    assert_eq!(
        normalized,
        AccessPlan::by_key(Value::Ulid(Ulid::from_u128(7)))
    );
}

#[test]
fn planner_and_intent_access_canonicalization_match_for_single_key_set() {
    let key = Ulid::from_u128(42);
    let predicate = Predicate::Compare(ComparePredicate::with_coercion(
        "id",
        CompareOp::In,
        Value::List(vec![Value::Ulid(key)]),
        CoercionId::Strict,
    ));
    let schema = SchemaInfo::from_entity_model(&PLANNER_CANONICAL_MODEL)
        .expect("planner canonicalization test model should produce schema info");

    let planner_shape = plan_access_for_test(&PLANNER_CANONICAL_MODEL, &schema, Some(&predicate))
        .expect("planner access shape should build for strict single-key IN predicate");
    let intent_shape = build_access_plan_from_keys(&KeyAccess::Many(vec![key]));

    assert_eq!(
        planner_shape, intent_shape,
        "planner and intent canonical access shape should agree for one-key sets",
    );
    assert_eq!(
        planner_shape,
        AccessPlan::by_key(Value::Ulid(key)),
        "one-key set canonicalization should collapse to ByKey",
    );
}

#[test]
fn planner_non_pk_in_empty_lowers_to_empty_by_keys() {
    let predicate = Predicate::Compare(ComparePredicate::with_coercion(
        "email",
        CompareOp::In,
        Value::List(Vec::new()),
        CoercionId::Strict,
    ));
    let schema = SchemaInfo::from_entity_model(&PLANNER_IN_EMPTY_MODEL)
        .expect("IN-empty planner test model should produce schema info");

    let planner_shape = plan_access_for_test(&PLANNER_IN_EMPTY_MODEL, &schema, Some(&predicate))
        .expect("planner access shape should build for strict IN-empty predicate");

    assert_eq!(
        planner_shape,
        AccessPlan::by_keys(Vec::new()),
        "IN-empty predicates must lower to an empty access shape instead of full scan",
    );
}

#[test]
fn planner_order_only_single_field_index_falls_back_to_index_range() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_MODEL)
        .expect("planner order-only test model should produce schema info");
    let order = canonical_order(&[("name", OrderDirection::Asc), ("id", OrderDirection::Asc)]);

    let planner_shape =
        plan_access_for_test_with_order(&PLANNER_ORDER_MODEL, &schema, None, Some(order))
            .expect("order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::index_range(SemanticIndexRangeSpec::new(
            PLANNER_ORDER_INDEXES[0],
            vec![0usize],
            Vec::new(),
            Bound::Unbounded,
            Bound::Unbounded,
        )),
        "canonical order-only secondary scans should fall back to one whole-index range",
    );
}

#[test]
fn planner_order_only_single_field_desc_index_falls_back_to_index_range() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_MODEL)
        .expect("planner descending order-only test model should produce schema info");
    let order = canonical_order(&[("name", OrderDirection::Desc), ("id", OrderDirection::Desc)]);

    let planner_shape =
        plan_access_for_test_with_order(&PLANNER_ORDER_MODEL, &schema, None, Some(order))
            .expect("descending order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::index_range(SemanticIndexRangeSpec::new(
            PLANNER_ORDER_INDEXES[0],
            vec![0usize],
            Vec::new(),
            Bound::Unbounded,
            Bound::Unbounded,
        )),
        "canonical descending order-only secondary scans should fall back to one whole-index range",
    );
}

#[test]
fn planner_order_only_composite_index_falls_back_to_index_range() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_COMPOSITE_MODEL)
        .expect("planner composite order-only test model should produce schema info");
    let order = canonical_order(&[
        ("code", OrderDirection::Asc),
        ("serial", OrderDirection::Asc),
        ("id", OrderDirection::Asc),
    ]);

    let planner_shape =
        plan_access_for_test_with_order(&PLANNER_ORDER_COMPOSITE_MODEL, &schema, None, Some(order))
            .expect("composite order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::index_range(SemanticIndexRangeSpec::new(
            PLANNER_ORDER_COMPOSITE_INDEXES[0],
            vec![0usize],
            Vec::new(),
            Bound::Unbounded,
            Bound::Unbounded,
        )),
        "canonical composite order-only scans should use one whole-index range fallback",
    );
}

#[test]
fn planner_order_only_composite_desc_index_falls_back_to_index_range() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_COMPOSITE_MODEL)
        .expect("planner descending composite order-only test model should produce schema info");
    let order = canonical_order(&[
        ("code", OrderDirection::Desc),
        ("serial", OrderDirection::Desc),
        ("id", OrderDirection::Desc),
    ]);

    let planner_shape =
        plan_access_for_test_with_order(&PLANNER_ORDER_COMPOSITE_MODEL, &schema, None, Some(order))
            .expect("descending composite order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::index_range(SemanticIndexRangeSpec::new(
            PLANNER_ORDER_COMPOSITE_INDEXES[0],
            vec![0usize],
            Vec::new(),
            Bound::Unbounded,
            Bound::Unbounded,
        )),
        "canonical descending composite order-only scans should use one whole-index range fallback",
    );
}

#[test]
fn planner_order_only_filtered_index_fails_closed_without_guard_predicate() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_FILTERED_MODEL)
        .expect("planner filtered order-only test model should produce schema info");
    let order = canonical_order(&[("name", OrderDirection::Asc), ("id", OrderDirection::Asc)]);

    let planner_shape =
        plan_access_for_test_with_order(&PLANNER_ORDER_FILTERED_MODEL, &schema, None, Some(order))
            .expect("filtered order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::full_scan(),
        "filtered indexes must not satisfy order-only access when the query does not imply the guard",
    );
}

#[test]
fn planner_order_only_filtered_index_uses_index_range_when_query_implies_guard() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_FILTERED_MODEL)
        .expect("planner filtered order-only test model should produce schema info");
    let predicate = Predicate::Compare(ComparePredicate::with_coercion(
        "active",
        CompareOp::Eq,
        Value::Bool(true),
        CoercionId::Strict,
    ));
    let order = canonical_order(&[("name", OrderDirection::Asc), ("id", OrderDirection::Asc)]);

    let planner_shape = plan_access_for_test_with_order(
        &PLANNER_ORDER_FILTERED_MODEL,
        &schema,
        Some(&predicate),
        Some(order),
    )
    .expect("guarded filtered order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::index_range(SemanticIndexRangeSpec::new(
            PLANNER_ORDER_FILTERED_INDEXES[0],
            vec![0usize],
            Vec::new(),
            Bound::Unbounded,
            Bound::Unbounded,
        )),
        "filtered indexes should satisfy order-only access once the query implies their guard",
    );
}

#[test]
fn planner_single_field_index_accepts_strict_text_prefix_predicate() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_MODEL)
        .expect("planner strict text-prefix order-only test model should produce schema info");
    let predicate = Predicate::Compare(ComparePredicate::with_coercion(
        "name",
        CompareOp::StartsWith,
        Value::Text("sam".to_string()),
        CoercionId::Strict,
    ));
    let order = canonical_order(&[("name", OrderDirection::Asc), ("id", OrderDirection::Asc)]);

    let planner_shape = plan_access_for_test_with_order(
        &PLANNER_ORDER_MODEL,
        &schema,
        Some(&predicate),
        Some(order),
    )
    .expect("strict text-prefix order-only access planning should succeed");

    let AccessPlan::Path(path) = planner_shape else {
        panic!("strict raw-field text-prefix predicate should lower to one index path");
    };
    let AccessPath::IndexRange { spec } = path.as_ref() else {
        panic!("strict raw-field text-prefix predicate should lower to one index range");
    };

    assert_eq!(spec.index().name(), "name_idx");
    assert!(spec.prefix_values().is_empty());
    assert_eq!(
        spec.lower(),
        &Bound::Included(Value::Text("sam".to_string()))
    );
    assert_eq!(
        spec.upper(),
        &Bound::Excluded(Value::Text("san".to_string()))
    );
}

#[test]
fn planner_order_only_expression_index_falls_back_to_index_range() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_EXPRESSION_MODEL)
        .expect("planner expression order-only test model should produce schema info");
    let order = canonical_order(&[
        ("LOWER(name)", OrderDirection::Asc),
        ("id", OrderDirection::Asc),
    ]);

    let planner_shape = plan_access_for_test_with_order(
        &PLANNER_ORDER_EXPRESSION_MODEL,
        &schema,
        None,
        Some(order),
    )
    .expect("expression order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::index_range(SemanticIndexRangeSpec::new(
            PLANNER_ORDER_EXPRESSION_INDEXES[0],
            vec![0usize],
            Vec::new(),
            Bound::Unbounded,
            Bound::Unbounded,
        )),
        "canonical LOWER(field) order-only scans should use the matching expression index range",
    );
}

#[test]
fn planner_order_only_expression_desc_index_falls_back_to_index_range() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_EXPRESSION_MODEL)
        .expect("planner descending expression order-only test model should produce schema info");
    let order = canonical_order(&[
        ("LOWER(name)", OrderDirection::Desc),
        ("id", OrderDirection::Desc),
    ]);

    let planner_shape = plan_access_for_test_with_order(
        &PLANNER_ORDER_EXPRESSION_MODEL,
        &schema,
        None,
        Some(order),
    )
    .expect("descending expression order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::index_range(SemanticIndexRangeSpec::new(
            PLANNER_ORDER_EXPRESSION_INDEXES[0],
            vec![0usize],
            Vec::new(),
            Bound::Unbounded,
            Bound::Unbounded,
        )),
        "canonical descending LOWER(field) order-only scans should use the matching expression index range",
    );
}

#[test]
fn planner_order_only_expression_index_fails_closed_for_raw_field_order() {
    let schema = SchemaInfo::from_entity_model(&PLANNER_ORDER_EXPRESSION_MODEL)
        .expect("planner expression order-only test model should produce schema info");
    let order = canonical_order(&[("name", OrderDirection::Asc), ("id", OrderDirection::Asc)]);

    let planner_shape = plan_access_for_test_with_order(
        &PLANNER_ORDER_EXPRESSION_MODEL,
        &schema,
        None,
        Some(order),
    )
    .expect("expression order-only access planning should succeed");

    assert_eq!(
        planner_shape,
        AccessPlan::full_scan(),
        "raw field ORDER BY must not silently treat expression-key indexes as field-order-compatible",
    );
}