icydb-core 0.178.5

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
//! Module: cursor::boundary
//! Responsibility: cursor boundary slot modeling and deterministic cursor boundary handling.
//! Does not own: planner query validation policy or access-path execution routing.
//! Boundary: defines cursor-boundary domain types shared by cursor planning/runtime paths.

use crate::db::{
    data::primary_key_value_from_structural_value,
    key_taxonomy::{PrimaryKeyComponent, PrimaryKeyValue},
};
use crate::{
    db::{
        cursor::CursorPlanError,
        direction::Direction,
        query::plan::{
            OrderDirection, OrderSpec,
            expr::{Expr, ExprType, infer_expr_type},
        },
        schema::{FieldType, SchemaInfo, literal_matches_type},
    },
    value::Value,
};
use serde::Deserialize;
use std::cmp::Ordering;

///
/// CursorBoundarySlot
/// Slot value used for deterministic cursor boundaries.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub(crate) enum CursorBoundarySlot {
    Missing,
    Present(Value),
}

///
/// CursorBoundary
/// Ordered boundary tuple for continuation pagination.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub(crate) struct CursorBoundary {
    pub(crate) slots: Vec<CursorBoundarySlot>,
}

/// Apply one order direction to one base slot ordering.
#[must_use]
pub(in crate::db) const fn apply_order_direction(
    ordering: Ordering,
    direction: OrderDirection,
) -> Ordering {
    match direction {
        OrderDirection::Asc => ordering,
        OrderDirection::Desc => ordering.reverse(),
    }
}

/// Validate continuation direction compatibility.
pub(in crate::db) fn validate_cursor_direction(
    expected_direction: Direction,
    actual_direction: Direction,
) -> Result<(), CursorPlanError> {
    if actual_direction != expected_direction {
        return Err(CursorPlanError::continuation_cursor_direction_mismatch());
    }

    Ok(())
}

/// Validate continuation initial-offset compatibility.
pub(in crate::db) const fn validate_cursor_window_offset(
    expected_initial_offset: u32,
    actual_initial_offset: u32,
) -> Result<(), CursorPlanError> {
    if actual_initial_offset != expected_initial_offset {
        return Err(CursorPlanError::continuation_cursor_window_mismatch(
            expected_initial_offset,
            actual_initial_offset,
        ));
    }

    Ok(())
}

/// Validate one cursor boundary arity against canonical order width.
pub(in crate::db) const fn validate_cursor_boundary_arity(
    boundary: &CursorBoundary,
    expected_arity: usize,
) -> Result<(), CursorPlanError> {
    if boundary.slots.len() != expected_arity {
        return Err(
            CursorPlanError::continuation_cursor_boundary_arity_mismatch(
                expected_arity,
                boundary.slots.len(),
            ),
        );
    }

    Ok(())
}

/// Validate one cursor boundary against canonical order fields and return typed PK key.
pub(in crate::db) fn validate_cursor_boundary_for_order(
    schema: &SchemaInfo,
    order: &OrderSpec,
    boundary: &CursorBoundary,
) -> Result<PrimaryKeyValue, CursorPlanError> {
    validate_cursor_boundary_arity(boundary, order.fields.len())?;
    validate_cursor_boundary_types(schema, order, boundary)?;

    decode_structural_primary_key_cursor_slots(schema, order, boundary)
}

// Resolve one plain order field type from canonical schema info.
fn boundary_order_field_type<'a>(
    schema: &'a SchemaInfo,
    field: &str,
) -> Result<&'a FieldType, CursorPlanError> {
    schema
        .field(field)
        .ok_or_else(|| CursorPlanError::continuation_cursor_unknown_order_field(field))
}

// Resolve the deterministic primary-key tie-break position from one order spec.
fn primary_key_boundary_index(order: &OrderSpec, pk_field: &str) -> Result<usize, CursorPlanError> {
    order
        .fields
        .iter()
        .position(|term| term.direct_field() == Some(pk_field))
        .ok_or_else(|| {
            CursorPlanError::continuation_cursor_primary_key_tie_break_required(pk_field)
        })
}

/// Validate cursor boundary slot types against canonical order fields.
pub(in crate::db) fn validate_cursor_boundary_types(
    schema: &SchemaInfo,
    order: &OrderSpec,
    boundary: &CursorBoundary,
) -> Result<(), CursorPlanError> {
    for (term, slot) in order.fields.iter().zip(boundary.slots.iter()) {
        let field = term.direct_field();
        let expression = field.is_none().then(|| term.expr().clone());
        let field_type = match field {
            Some(field) => Some(boundary_order_field_type(schema, field)?),
            None => None,
        };
        let rendered = expression.as_ref().map_or_else(
            || {
                field
                    .expect("field-backed order term should have field")
                    .to_owned()
            },
            |_| term.rendered_label(),
        );

        match slot {
            CursorBoundarySlot::Missing => {
                if field.is_some_and(|field| is_primary_key_field(schema, field)) {
                    return Err(
                        CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                            rendered,
                            boundary_order_expected_type_name(
                                schema,
                                field_type,
                                expression.as_ref(),
                            ),
                            None,
                        ),
                    );
                }
            }
            CursorBoundarySlot::Present(value) => {
                let type_matches = match (field_type, expression.as_ref()) {
                    (Some(field_type), None) => literal_matches_type(value, field_type),
                    (None, Some(expression)) => {
                        boundary_order_expression_value_matches(schema, expression, value)?
                    }
                    _ => false,
                };

                if !type_matches {
                    let expected =
                        boundary_order_expected_type_name(schema, field_type, expression.as_ref());

                    if field.is_some_and(|field| is_primary_key_field(schema, field)) {
                        return Err(
                            CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                                rendered,
                                expected,
                                Some(value.clone()),
                            ),
                        );
                    }

                    return Err(CursorPlanError::continuation_cursor_boundary_type_mismatch(
                        rendered,
                        expected,
                        value.clone(),
                    ));
                }

                if field.is_some_and(|field| is_primary_key_field(schema, field))
                    && PrimaryKeyComponent::from_runtime_value(value).is_none()
                {
                    return Err(
                        CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                            rendered,
                            boundary_order_expected_type_name(
                                schema,
                                field_type,
                                expression.as_ref(),
                            ),
                            Some(value.clone()),
                        ),
                    );
                }
            }
        }
    }

    Ok(())
}

fn is_primary_key_field(schema: &SchemaInfo, field: &str) -> bool {
    schema
        .primary_key_names()
        .iter()
        .any(|primary_key_field| primary_key_field == field)
}

fn boundary_order_expected_type_name(
    schema: &SchemaInfo,
    field_type: Option<&FieldType>,
    expression: Option<&Expr>,
) -> String {
    if let Some(field_type) = field_type {
        return field_type.to_string();
    }

    let Some(expression) = expression else {
        return "unknown".to_string();
    };

    match infer_expr_type(expression, schema) {
        Ok(ExprType::Bool) => "bool".to_string(),
        Ok(ExprType::Blob) => "blob".to_string(),
        Ok(ExprType::Text) => "text".to_string(),
        Ok(ExprType::Numeric(_)) => "numeric".to_string(),
        Ok(ExprType::Collection) => "collection".to_string(),
        Ok(ExprType::Structured) => "structured".to_string(),
        Ok(ExprType::Opaque) => "opaque".to_string(),
        Ok(ExprType::Unknown) | Err(_) => "unknown".to_string(),
        #[cfg(test)]
        Ok(ExprType::Null) => "null".to_string(),
    }
}

fn boundary_order_expression_value_matches(
    schema: &SchemaInfo,
    expression: &Expr,
    value: &Value,
) -> Result<bool, CursorPlanError> {
    let inferred = infer_expr_type(expression, schema)
        .map_err(|_| CursorPlanError::continuation_cursor_unknown_order_field("expression"))?;

    Ok(match inferred {
        ExprType::Bool => matches!(value, Value::Bool(_)),
        ExprType::Blob => matches!(value, Value::Blob(_)),
        ExprType::Text => matches!(value, Value::Text(_) | Value::Enum(_)),
        ExprType::Numeric(_) => matches!(
            value,
            Value::Int64(_)
                | Value::Int128(_)
                | Value::IntBig(_)
                | Value::Nat64(_)
                | Value::Nat128(_)
                | Value::NatBig(_)
                | Value::Decimal(_)
                | Value::Float32(_)
                | Value::Float64(_)
                | Value::Date(_)
                | Value::Duration(_)
                | Value::Timestamp(_)
        ),
        ExprType::Collection | ExprType::Structured | ExprType::Opaque | ExprType::Unknown => false,
        #[cfg(test)]
        ExprType::Null => matches!(value, Value::Null),
    })
}

/// Decode the structural primary-key cursor slot from one validated cursor boundary.
pub(in crate::db) fn decode_structural_primary_key_cursor_slots(
    schema: &SchemaInfo,
    order: &OrderSpec,
    boundary: &CursorBoundary,
) -> Result<PrimaryKeyValue, CursorPlanError> {
    let primary_key_fields: Vec<&str> = schema
        .primary_key_names()
        .iter()
        .map(String::as_str)
        .collect();

    if let [primary_key_field] = primary_key_fields.as_slice() {
        return decode_structural_primary_key_cursor_slot_from_name(
            primary_key_field,
            order,
            boundary,
        );
    }

    let mut values = Vec::with_capacity(primary_key_fields.len());
    for primary_key_field in &primary_key_fields {
        let index = primary_key_boundary_index(order, primary_key_field)?;
        let slot = &boundary.slots[index];
        match slot {
            CursorBoundarySlot::Missing => {
                return Err(
                    CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                        primary_key_field.to_string(),
                        "primary key value".to_string(),
                        None,
                    ),
                );
            }
            CursorBoundarySlot::Present(value) => values.push(value.clone()),
        }
    }

    primary_key_value_from_structural_value(&Value::List(values)).map_err(|_| {
        CursorPlanError::continuation_cursor_primary_key_type_mismatch(
            primary_key_fields.join(", "),
            "primary key value".to_string(),
            None,
        )
    })
}

/// Decode one scalar structural primary-key cursor slot from one validated cursor boundary.
pub(in crate::db) fn decode_structural_primary_key_cursor_slot_from_name(
    pk_field: &str,
    order: &OrderSpec,
    boundary: &CursorBoundary,
) -> Result<PrimaryKeyValue, CursorPlanError> {
    let pk_index = primary_key_boundary_index(order, pk_field)?;
    let expected = "primary key value".to_string();
    let pk_slot = &boundary.slots[pk_index];

    match pk_slot {
        CursorBoundarySlot::Missing => Err(
            CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                pk_field.to_string(),
                expected,
                None,
            ),
        ),
        CursorBoundarySlot::Present(value) => primary_key_value_from_structural_value(value)
            .map_err(|_| {
                CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                    pk_field.to_string(),
                    expected,
                    Some(value.clone()),
                )
            }),
    }
}

/// Decode one structural primary-key boundary for PK-ordered executor paths.
pub(in crate::db) fn decode_pk_cursor_boundary_primary_key_value_for_names(
    boundary: Option<&CursorBoundary>,
    primary_key_names: &[&str],
) -> Result<Option<PrimaryKeyValue>, CursorPlanError> {
    let Some(boundary) = boundary else {
        return Ok(None);
    };

    debug_assert_eq!(
        boundary.slots.len(),
        primary_key_names.len(),
        "pk-ordered continuation boundaries are validated by the cursor spine",
    );

    let order = OrderSpec {
        fields: primary_key_names
            .iter()
            .map(|field| crate::db::query::plan::OrderTerm::field(*field, OrderDirection::Asc))
            .collect(),
    };

    if let [primary_key_name] = primary_key_names {
        return decode_structural_primary_key_cursor_slot_from_name(
            primary_key_name,
            &order,
            boundary,
        )
        .map(Some);
    }

    let mut values = Vec::with_capacity(primary_key_names.len());
    for primary_key_name in primary_key_names {
        let index = primary_key_boundary_index(&order, primary_key_name)?;
        let slot = &boundary.slots[index];
        match slot {
            CursorBoundarySlot::Missing => {
                return Err(
                    CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                        (*primary_key_name).to_string(),
                        "primary key value".to_string(),
                        None,
                    ),
                );
            }
            CursorBoundarySlot::Present(value) => values.push(value.clone()),
        }
    }

    primary_key_value_from_structural_value(&Value::List(values))
        .map(Some)
        .map_err(|_| {
            CursorPlanError::continuation_cursor_primary_key_type_mismatch(
                primary_key_names.join(", "),
                "primary key value".to_string(),
                None,
            )
        })
}

#[cfg(test)]
mod tests {
    use super::{
        CursorBoundary, CursorBoundarySlot, decode_pk_cursor_boundary_primary_key_value_for_names,
    };
    use crate::{
        db::key_taxonomy::{CompositePrimaryKeyValue, PrimaryKeyComponent, PrimaryKeyValue},
        value::Value,
    };

    #[test]
    fn pk_ordered_boundary_decode_accepts_ordered_composite_primary_key_fields() {
        let boundary = CursorBoundary {
            slots: vec![
                CursorBoundarySlot::Present(Value::Nat64(7)),
                CursorBoundarySlot::Present(Value::Int64(-3)),
            ],
        };
        let composite = CompositePrimaryKeyValue::try_from_components(&[
            PrimaryKeyComponent::Nat64(7),
            PrimaryKeyComponent::Int64(-3),
        ])
        .expect("fixture components should form composite key");

        let decoded = decode_pk_cursor_boundary_primary_key_value_for_names(
            Some(&boundary),
            &["tenant", "id"],
        )
        .expect("composite pk cursor boundary should decode");

        assert_eq!(decoded, Some(PrimaryKeyValue::Composite(composite)));
    }
}