icydb-core 0.187.10

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
//! Module: query::plan::semantics::access_projection
//! Responsibility: project access-plan/access-path semantics into diagnostics-facing shapes.
//! Does not own: access-path construction or planner route-selection decisions.
//! Boundary: provides visitor-based projection adapters for explain/diagnostic consumers.

use crate::{
    db::{
        access::{
            AccessPath, AccessPlan, IndexBranchSetOrderedSuffix, SemanticIndexAccessContract,
        },
        query::explain::ExplainAccessPath,
    },
    model::index::IndexKeyItemsRef,
    value::Value,
};
use std::{fmt::Write, ops::Bound};

///
/// AccessPlanProjection
///
/// Shared visitor for projecting `AccessPlan` / `AccessPath` into
/// diagnostics-specific representations.
///

pub(in crate::db) trait AccessPlanProjection<K> {
    type Output;

    fn by_key(&mut self, key: &K) -> Self::Output;
    fn by_keys(&mut self, keys: &[K]) -> Self::Output;
    fn key_range(&mut self, start: &K, end: &K) -> Self::Output;
    fn index_prefix(
        &mut self,
        index_name: &str,
        index_fields: &[String],
        prefix_len: usize,
        values: &[Value],
    ) -> Self::Output;
    fn index_multi_lookup(
        &mut self,
        index_name: &str,
        index_fields: &[String],
        values: &[Value],
    ) -> Self::Output;
    fn index_branch_set(
        &mut self,
        index_name: &str,
        index_fields: &[String],
        fixed_values: &[Value],
        branch_values: &[Value],
        ordered_suffix: IndexBranchSetOrderedSuffix,
    ) -> Self::Output;
    fn index_range(
        &mut self,
        index_name: &str,
        index_fields: &[String],
        prefix_len: usize,
        prefix: &[Value],
        lower: &Bound<Value>,
        upper: &Bound<Value>,
    ) -> Self::Output;
    fn full_scan(&mut self) -> Self::Output;
    fn union(&mut self, children: Vec<Self::Output>) -> Self::Output;
    fn intersection(&mut self, children: Vec<Self::Output>) -> Self::Output;
}

/// Project an access plan by exhaustively walking canonical access variants.
pub(in crate::db) fn project_access_plan<K, P>(
    plan: &AccessPlan<K>,
    projection: &mut P,
) -> P::Output
where
    P: AccessPlanProjection<K>,
{
    plan.project(projection)
}

impl<K> AccessPlan<K> {
    // Project this plan by recursively visiting all access nodes.
    fn project<P>(&self, projection: &mut P) -> P::Output
    where
        P: AccessPlanProjection<K>,
    {
        match self {
            Self::Path(path) => path.project(projection),
            Self::Union(children) => {
                let child_projections =
                    project_projection_children(children.iter(), projection, Self::project);

                projection.union(child_projections)
            }
            Self::Intersection(children) => {
                let child_projections =
                    project_projection_children(children.iter(), projection, Self::project);

                projection.intersection(child_projections)
            }
        }
    }
}

impl<K> AccessPath<K> {
    // Project one concrete path variant via the shared projection surface.
    fn project<P>(&self, projection: &mut P) -> P::Output
    where
        P: AccessPlanProjection<K>,
    {
        match self {
            Self::ByKey(key) => projection.by_key(key),
            Self::ByKeys(keys) => projection.by_keys(keys),
            Self::KeyRange { start, end } => projection.key_range(start, end),
            Self::IndexPrefix { index, values } => {
                let fields = index_contract_key_fields(index);

                projection.index_prefix(index.name(), fields.as_slice(), values.len(), values)
            }
            Self::IndexMultiLookup { index, values } => {
                let fields = index_contract_key_fields(index);

                projection.index_multi_lookup(index.name(), fields.as_slice(), values)
            }
            Self::IndexBranchSet { spec } => {
                let fields = index_contract_key_fields(spec.index_ref());

                projection.index_branch_set(
                    spec.index_ref().name(),
                    fields.as_slice(),
                    spec.fixed_values(),
                    spec.branch_values(),
                    spec.ordered_suffix(),
                )
            }
            Self::IndexRange { spec } => {
                let contract = spec.index();
                let fields = index_contract_key_fields(&contract);

                projection.index_range(
                    contract.name(),
                    fields.as_slice(),
                    spec.prefix_values().len(),
                    spec.prefix_values(),
                    spec.lower(),
                    spec.upper(),
                )
            }
            Self::FullScan => projection.full_scan(),
        }
    }
}

fn index_contract_key_fields(index: &SemanticIndexAccessContract) -> Vec<String> {
    match index.key_items() {
        crate::db::access::SemanticIndexKeyItemsRef::Fields(fields) => fields.to_vec(),
        crate::db::access::SemanticIndexKeyItemsRef::Accepted(items) => items
            .iter()
            .map(|item| item.as_ref().field().to_string())
            .collect(),
        crate::db::access::SemanticIndexKeyItemsRef::Static(IndexKeyItemsRef::Fields(fields)) => {
            fields.iter().copied().map(str::to_string).collect()
        }
        crate::db::access::SemanticIndexKeyItemsRef::Static(IndexKeyItemsRef::Items(items)) => {
            items.iter().map(|item| item.field().to_string()).collect()
        }
    }
}

pub(in crate::db) fn project_explain_access_path<P>(
    access: &ExplainAccessPath,
    projection: &mut P,
) -> P::Output
where
    P: AccessPlanProjection<Value>,
{
    match access {
        ExplainAccessPath::ByKey { key } => projection.by_key(key),
        ExplainAccessPath::ByKeys { keys } => projection.by_keys(keys),
        ExplainAccessPath::KeyRange { start, end } => projection.key_range(start, end),
        ExplainAccessPath::IndexPrefix {
            name,
            fields,
            prefix_len,
            values,
        } => projection.index_prefix(name, fields, *prefix_len, values),
        ExplainAccessPath::IndexMultiLookup {
            name,
            fields,
            values,
        } => projection.index_multi_lookup(name, fields, values),
        ExplainAccessPath::IndexBranchSet {
            name,
            fields,
            fixed_values,
            branch_values,
            branch_field,
            ordered_suffix,
        } => {
            debug_assert_eq!(
                branch_field.as_deref(),
                fields.get(fixed_values.len()).map(String::as_str)
            );
            debug_assert_eq!(
                ordered_suffix,
                IndexBranchSetOrderedSuffix::PrimaryKeyAsc.label()
            );
            projection.index_branch_set(
                name,
                fields,
                fixed_values,
                branch_values,
                IndexBranchSetOrderedSuffix::PrimaryKeyAsc,
            )
        }
        ExplainAccessPath::IndexRange {
            name,
            fields,
            prefix_len,
            prefix,
            lower,
            upper,
        } => projection.index_range(name, fields, *prefix_len, prefix, lower, upper),
        ExplainAccessPath::FullScan => projection.full_scan(),
        ExplainAccessPath::Union(children) => {
            let child_projections = project_projection_children(
                children.iter(),
                projection,
                project_explain_access_path,
            );

            projection.union(child_projections)
        }
        ExplainAccessPath::Intersection(children) => {
            let child_projections = project_projection_children(
                children.iter(),
                projection,
                project_explain_access_path,
            );

            projection.intersection(child_projections)
        }
    }
}

///
/// AccessStrategyLabelProjection
///
/// Shared projection adapter that renders one stable label for canonical
/// access-plan and explain-access variants from the same projection contract.
/// This keeps access strategy label ownership on one semantic seam instead of
/// duplicating the label ladder in planner and explain consumers.
///

struct AccessStrategyLabelProjection;

impl<K> AccessPlanProjection<K> for AccessStrategyLabelProjection {
    type Output = String;

    fn by_key(&mut self, _key: &K) -> Self::Output {
        "ByKey".to_string()
    }

    fn by_keys(&mut self, _keys: &[K]) -> Self::Output {
        "ByKeys".to_string()
    }

    fn key_range(&mut self, _start: &K, _end: &K) -> Self::Output {
        "KeyRange".to_string()
    }

    fn index_prefix(
        &mut self,
        index_name: &str,
        _index_fields: &[String],
        _prefix_len: usize,
        _values: &[Value],
    ) -> Self::Output {
        let mut label = String::new();
        let _ = write!(&mut label, "IndexPrefix({index_name})");

        label
    }

    fn index_multi_lookup(
        &mut self,
        index_name: &str,
        _index_fields: &[String],
        _values: &[Value],
    ) -> Self::Output {
        let mut label = String::new();
        let _ = write!(&mut label, "IndexMultiLookup({index_name})");

        label
    }

    fn index_branch_set(
        &mut self,
        index_name: &str,
        _index_fields: &[String],
        _fixed_values: &[Value],
        _branch_values: &[Value],
        _ordered_suffix: IndexBranchSetOrderedSuffix,
    ) -> Self::Output {
        let mut label = String::new();
        let _ = write!(&mut label, "IndexBranchSet({index_name})");

        label
    }

    fn index_range(
        &mut self,
        index_name: &str,
        _index_fields: &[String],
        _prefix_len: usize,
        _prefix: &[Value],
        _lower: &Bound<Value>,
        _upper: &Bound<Value>,
    ) -> Self::Output {
        let mut label = String::new();
        let _ = write!(&mut label, "IndexRange({index_name})");

        label
    }

    fn full_scan(&mut self) -> Self::Output {
        "FullScan".to_string()
    }

    fn union(&mut self, children: Vec<Self::Output>) -> Self::Output {
        let mut label = String::new();
        let _ = write!(&mut label, "Union({})", children.len());

        label
    }

    fn intersection(&mut self, children: Vec<Self::Output>) -> Self::Output {
        let mut label = String::new();
        let _ = write!(&mut label, "Intersection({})", children.len());

        label
    }
}

/// Render one stable planner-owned access label without routing through explain transport.
pub(in crate::db) fn access_plan_label<K>(plan: &AccessPlan<K>) -> String {
    project_access_plan(plan, &mut AccessStrategyLabelProjection)
}

/// Render one stable explain access label from the canonical explain-access DTO.
pub(in crate::db) fn explain_access_strategy_label(access: &ExplainAccessPath) -> String {
    project_explain_access_path(access, &mut AccessStrategyLabelProjection)
}

///
/// ExplainAccessKindProjection
///
/// Shared explain-access classifier for consumers that only need one stable
/// access-kind code from the transport DTO surface.
///

#[cfg(test)]
struct ExplainAccessKindProjection;

#[cfg(test)]
impl AccessPlanProjection<Value> for ExplainAccessKindProjection {
    type Output = &'static str;

    fn by_key(&mut self, _key: &Value) -> Self::Output {
        "by_key"
    }

    fn by_keys(&mut self, keys: &[Value]) -> Self::Output {
        if keys.is_empty() {
            "empty_access_contract"
        } else {
            "by_keys"
        }
    }

    fn key_range(&mut self, _start: &Value, _end: &Value) -> Self::Output {
        "key_range"
    }

    fn index_prefix(
        &mut self,
        _index_name: &str,
        _index_fields: &[String],
        _prefix_len: usize,
        _values: &[Value],
    ) -> Self::Output {
        "index_prefix"
    }

    fn index_multi_lookup(
        &mut self,
        _index_name: &str,
        _index_fields: &[String],
        _values: &[Value],
    ) -> Self::Output {
        "index_multi_lookup"
    }

    fn index_branch_set(
        &mut self,
        _index_name: &str,
        _index_fields: &[String],
        _fixed_values: &[Value],
        _branch_values: &[Value],
        _ordered_suffix: IndexBranchSetOrderedSuffix,
    ) -> Self::Output {
        "index_branch_set"
    }

    fn index_range(
        &mut self,
        _index_name: &str,
        _index_fields: &[String],
        _prefix_len: usize,
        _prefix: &[Value],
        _lower: &Bound<Value>,
        _upper: &Bound<Value>,
    ) -> Self::Output {
        "index_range"
    }

    fn full_scan(&mut self) -> Self::Output {
        "full_scan"
    }

    fn union(&mut self, _children: Vec<Self::Output>) -> Self::Output {
        "union"
    }

    fn intersection(&mut self, _children: Vec<Self::Output>) -> Self::Output {
        "intersection"
    }
}

/// Classify one explain access DTO into the stable access-kind code used by
/// intent/debug labels without rebuilding a local branch ladder elsewhere.
#[cfg(test)]
pub(in crate::db) fn explain_access_kind_label(access: &ExplainAccessPath) -> &'static str {
    project_explain_access_path(access, &mut ExplainAccessKindProjection)
}

// Recurse over one child collection with the caller-owned projection adapter so
// access-plan and explain-path walkers share the same union/intersection child
// traversal contract.
fn project_projection_children<'a, T: 'a, P, I, F, O>(
    children: I,
    projection: &mut P,
    project_child: F,
) -> Vec<O>
where
    I: Iterator<Item = &'a T>,
    F: Fn(&'a T, &mut P) -> O,
{
    children
        .map(|child| project_child(child, projection))
        .collect()
}

///
/// TESTS
///

#[cfg(test)]
mod tests;