icydb-schema 0.165.9

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
use crate::prelude::*;

///
/// RelationComponentContract
///
/// Schema-side type contract for one relation key component.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct RelationComponentContract<'a> {
    target: &'a ItemTarget,
    scale: Option<u32>,
    max_len: Option<u32>,
    max_bytes: Option<u32>,
}

impl<'a> RelationComponentContract<'a> {
    pub(crate) const fn from_field(field: &'a Field) -> Self {
        Self::from_item(field.value().item())
    }

    pub(crate) const fn from_item(item: &'a Item) -> Self {
        Self {
            target: item.target(),
            scale: item.scale(),
            max_len: item.max_len(),
            max_bytes: item.max_bytes(),
        }
    }

    pub(crate) const fn target(&self) -> &'a ItemTarget {
        self.target
    }

    pub(crate) const fn scale(&self) -> Option<u32> {
        self.scale
    }

    pub(crate) const fn max_len(&self) -> Option<u32> {
        self.max_len
    }

    pub(crate) const fn max_bytes(&self) -> Option<u32> {
        self.max_bytes
    }

    pub(crate) fn mismatches(self, other: Self) -> bool {
        self != other
    }
}

///
/// RelationEdge
///
/// Schema-side relation edge declaration over one or more local component
/// fields. Runtime acceptance still owns durable field IDs and slots; this
/// helper proves arity/order/kind compatibility before a tuple relation shape
/// can be admitted.
///

#[derive(Clone, Debug, Serialize)]
pub struct RelationEdge {
    ident: &'static str,
    target: &'static str,
    local_fields: &'static [&'static str],
}

impl RelationEdge {
    /// Build one relation-edge declaration from a relation name, target entity
    /// path, and ordered local component fields.
    #[must_use]
    pub const fn new(
        ident: &'static str,
        target: &'static str,
        local_fields: &'static [&'static str],
    ) -> Self {
        Self {
            ident,
            target,
            local_fields,
        }
    }

    /// Borrow the relation-edge name used by diagnostics.
    #[must_use]
    pub const fn ident(&self) -> &'static str {
        self.ident
    }

    /// Borrow the target entity path.
    #[must_use]
    pub const fn target(&self) -> &'static str {
        self.target
    }

    /// Borrow ordered local source fields that map to the target primary key.
    #[must_use]
    pub const fn local_fields(&self) -> &'static [&'static str] {
        self.local_fields
    }

    /// Validate this edge against one source entity and the target entity
    /// stored in the current schema graph.
    pub fn validate_for_source(&self, source: &Entity) -> Result<(), ErrorTree> {
        let schema = schema_read();

        match schema.cast_node::<Entity>(self.target()) {
            Ok(target) => self.validate_against_entities(source, target),
            Err(_) => Err(ErrorTree::from(format!(
                "relation edge '{}' target entity '{}' not found",
                self.ident(),
                self.target()
            ))),
        }
    }

    /// Validate this edge against explicit source and target entity metadata.
    pub fn validate_against_entities(
        &self,
        source: &Entity,
        target: &Entity,
    ) -> Result<(), ErrorTree> {
        let mut errs = ErrorTree::new();
        let target_fields = target.primary_key().fields();

        if self.local_fields().is_empty() {
            err!(
                errs,
                "relation edge '{}' must declare at least one local field",
                self.ident()
            );
        }

        if self.local_fields().len() != target_fields.len() {
            err!(
                errs,
                "relation edge '{}' arity mismatch: local fields {:?} target primary key fields {:?}",
                self.ident(),
                self.local_fields(),
                target_fields,
            );
            return errs.result();
        }

        let mut local_component_cardinality = None;
        for (index, (local_name, target_name)) in self
            .local_fields()
            .iter()
            .zip(target_fields.iter())
            .enumerate()
        {
            let Some(local_field) = source.fields().get(local_name) else {
                err!(
                    errs,
                    "relation edge '{}' local field '{}' not found",
                    self.ident(),
                    local_name
                );
                continue;
            };
            let Some(target_field) = target.fields().get(target_name) else {
                err!(
                    errs,
                    "relation edge '{}' target primary key field '{}' not found",
                    self.ident(),
                    target_name
                );
                continue;
            };

            if !self.validate_local_component_shape(
                &mut errs,
                local_name,
                local_field,
                &mut local_component_cardinality,
            ) {
                continue;
            }

            self.validate_component_contract(
                &mut errs,
                index,
                local_name,
                local_field,
                target_name,
                target_field,
            );
        }

        errs.result()
    }

    fn validate_local_component_shape(
        &self,
        errs: &mut ErrorTree,
        local_name: &str,
        local_field: &Field,
        local_component_cardinality: &mut Option<Cardinality>,
    ) -> bool {
        let local_cardinality = local_field.value().cardinality();
        if local_cardinality == Cardinality::Many {
            err!(
                errs,
                "relation edge '{}' local field '{}' cannot have many cardinality",
                self.ident(),
                local_name
            );
            return false;
        }
        match *local_component_cardinality {
            Some(expected) if expected != local_cardinality => {
                err!(
                    errs,
                    "relation edge '{}' local field '{}' cardinality mismatch: all local component fields must be required or all optional",
                    self.ident(),
                    local_name
                );
                return false;
            }
            Some(_) => {}
            None => *local_component_cardinality = Some(local_cardinality),
        }

        if local_field.generated().is_some() {
            err!(
                errs,
                "relation edge '{}' local field '{}' is generated and cannot be a relation component",
                self.ident(),
                local_name
            );
            return false;
        }

        true
    }

    fn validate_component_contract(
        &self,
        errs: &mut ErrorTree,
        index: usize,
        local_name: &str,
        local_field: &Field,
        target_name: &str,
        target_field: &Field,
    ) {
        let expected = RelationComponentContract::from_field(target_field);
        if !target_primary_key_component_is_admissible(expected) {
            err!(
                errs,
                "relation edge '{}' target primary key field '{}' uses non-admissible component {:?}",
                self.ident(),
                target_name,
                expected.target(),
            );
            return;
        }

        let actual = RelationComponentContract::from_field(local_field);
        if expected.mismatches(actual) {
            err!(
                errs,
                "relation edge '{}' component {index} type mismatch: local field '{}' has ({:?}, scale={:?}, max_len={:?}, max_bytes={:?}); target field '{}' requires ({:?}, scale={:?}, max_len={:?}, max_bytes={:?})",
                self.ident(),
                local_name,
                actual.target(),
                actual.scale(),
                actual.max_len(),
                actual.max_bytes(),
                target_name,
                expected.target(),
                expected.scale(),
                expected.max_len(),
                expected.max_bytes(),
            );
        }
    }
}

const fn target_primary_key_component_is_admissible(
    contract: RelationComponentContract<'_>,
) -> bool {
    match contract.target() {
        ItemTarget::Primitive(primitive) => primitive.is_primary_key_component_encodable(),
        ItemTarget::Is(_) => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::build::schema_write;

    fn primitive_item(primitive: Primitive) -> Item {
        Item::new(
            ItemTarget::Primitive(primitive),
            None,
            None,
            None,
            None,
            &[],
            &[],
            false,
        )
    }

    fn item_with_metadata(
        primitive: Primitive,
        scale: Option<u32>,
        max_len: Option<u32>,
        max_bytes: Option<u32>,
    ) -> Item {
        Item::new(
            ItemTarget::Primitive(primitive),
            None,
            scale,
            max_len,
            max_bytes,
            &[],
            &[],
            false,
        )
    }

    fn field(ident: &'static str, primitive: Primitive) -> Field {
        field_with_item(ident, primitive_item(primitive))
    }

    fn generated_field(ident: &'static str, primitive: Primitive) -> Field {
        Field::new(
            ident,
            Value::new(Cardinality::One, primitive_item(primitive)),
            None,
            Some(FieldGeneration::Insert(Arg::FuncPath(
                "generate_relation_component",
            ))),
            None,
        )
    }

    fn field_with_item(ident: &'static str, item: Item) -> Field {
        Field::new(ident, Value::new(Cardinality::One, item), None, None, None)
    }

    fn optional_field(ident: &'static str, primitive: Primitive) -> Field {
        Field::new(
            ident,
            Value::new(Cardinality::Opt, primitive_item(primitive)),
            None,
            None,
            None,
        )
    }

    fn entity(
        module: &'static str,
        ident: &'static str,
        pk_fields: &'static [&'static str],
        fields: &'static [Field],
    ) -> Entity {
        Entity::new(
            Def::new(module, ident),
            "RelationEdgeStore",
            PrimaryKey::new(pk_fields, PrimaryKeySource::External),
            None,
            &[],
            &[],
            FieldList::new(fields),
            Type::new(&[], &[]),
        )
    }

    fn insert_entity(
        module: &'static str,
        ident: &'static str,
        pk_fields: &'static [&'static str],
        fields: &'static [Field],
    ) -> (&'static str, Entity) {
        let path = Box::leak(format!("{module}::{ident}").into_boxed_str());
        let entity = entity(module, ident, pk_fields, fields);
        schema_write().insert_node(SchemaNode::Entity(entity.clone()));
        (path, entity)
    }

    #[test]
    fn relation_edge_accepts_ordered_composite_target_tuple() {
        let source_fields = Box::leak(
            vec![
                field("author_tenant_id", Primitive::Nat64),
                field("author_user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let target_fields = Box::leak(
            vec![
                field("tenant_id", Primitive::Nat64),
                field("user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let source = entity(
            "schema_relation_edge_accepts_tuple",
            "Post",
            &["author_user_id"],
            source_fields,
        );
        let target = entity(
            "schema_relation_edge_accepts_tuple",
            "User",
            &["tenant_id", "user_id"],
            target_fields,
        );

        RelationEdge::new(
            "author",
            "schema_relation_edge_accepts_tuple::User",
            &["author_tenant_id", "author_user_id"],
        )
        .validate_against_entities(&source, &target)
        .expect("matching ordered composite relation tuple should validate");
    }

    #[test]
    fn relation_edge_rejects_scalar_local_field_for_composite_target() {
        let source_fields =
            Box::leak(vec![field("author_user_id", Primitive::Ulid)].into_boxed_slice());
        let target_fields = Box::leak(
            vec![
                field("tenant_id", Primitive::Nat64),
                field("user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let source = entity(
            "schema_relation_edge_rejects_scalar_for_composite",
            "Post",
            &["author_user_id"],
            source_fields,
        );
        let target = entity(
            "schema_relation_edge_rejects_scalar_for_composite",
            "User",
            &["tenant_id", "user_id"],
            target_fields,
        );

        let err = RelationEdge::new(
            "author",
            "schema_relation_edge_rejects_scalar_for_composite::User",
            &["author_user_id"],
        )
        .validate_against_entities(&source, &target)
        .expect_err("scalar local component must not validate as composite target tuple");

        assert!(
            err.messages()
                .iter()
                .any(|message| message.contains("arity mismatch")),
            "unexpected relation edge validation errors: {err}",
        );
    }

    #[test]
    fn relation_edge_rejects_wrong_component_order() {
        let source_fields = Box::leak(
            vec![
                field("author_tenant_id", Primitive::Nat64),
                field("author_user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let target_fields = Box::leak(
            vec![
                field("tenant_id", Primitive::Nat64),
                field("user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let source = entity(
            "schema_relation_edge_rejects_order",
            "Post",
            &["author_user_id"],
            source_fields,
        );
        let target = entity(
            "schema_relation_edge_rejects_order",
            "User",
            &["tenant_id", "user_id"],
            target_fields,
        );

        let err = RelationEdge::new(
            "author",
            "schema_relation_edge_rejects_order::User",
            &["author_user_id", "author_tenant_id"],
        )
        .validate_against_entities(&source, &target)
        .expect_err("local tuple order must match target primary-key order");

        assert!(
            err.messages()
                .iter()
                .any(|message| message.contains("component 0 type mismatch")),
            "unexpected relation edge validation errors: {err}",
        );
    }

    #[test]
    fn relation_edge_rejects_missing_local_component_field() {
        let source_fields =
            Box::leak(vec![field("author_tenant_id", Primitive::Nat64)].into_boxed_slice());
        let target_fields = Box::leak(
            vec![
                field("tenant_id", Primitive::Nat64),
                field("user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let source = entity(
            "schema_relation_edge_rejects_missing_local",
            "Post",
            &["author_tenant_id"],
            source_fields,
        );
        let target = entity(
            "schema_relation_edge_rejects_missing_local",
            "User",
            &["tenant_id", "user_id"],
            target_fields,
        );

        let err = RelationEdge::new(
            "author",
            "schema_relation_edge_rejects_missing_local::User",
            &["author_tenant_id", "author_user_id"],
        )
        .validate_against_entities(&source, &target)
        .expect_err("missing local tuple component should reject");

        assert!(
            err.messages()
                .iter()
                .any(|message| message.contains("local field 'author_user_id' not found")),
            "unexpected relation edge validation errors: {err}",
        );
    }

    #[test]
    fn relation_edge_rejects_non_admissible_target_primary_key_component() {
        let source_fields =
            Box::leak(vec![field("author_score", Primitive::IntBig)].into_boxed_slice());
        let target_fields = Box::leak(vec![field("score", Primitive::IntBig)].into_boxed_slice());
        let source = entity(
            "schema_relation_edge_rejects_int_big_target",
            "Post",
            &["author_score"],
            source_fields,
        );
        let target = entity(
            "schema_relation_edge_rejects_int_big_target",
            "User",
            &["score"],
            target_fields,
        );

        let err = RelationEdge::new(
            "author",
            "schema_relation_edge_rejects_int_big_target::User",
            &["author_score"],
        )
        .validate_against_entities(&source, &target)
        .expect_err("int_big target primary key component should reject");

        assert!(
            err.messages()
                .iter()
                .any(|message| message.contains("non-admissible component")),
            "unexpected relation edge validation errors: {err}",
        );
    }

    #[test]
    fn relation_edge_rejects_generated_local_component_field() {
        let source_fields =
            Box::leak(vec![generated_field("author_id", Primitive::Ulid)].into_boxed_slice());
        let target_fields = Box::leak(vec![field("id", Primitive::Ulid)].into_boxed_slice());
        let source = entity(
            "schema_relation_edge_rejects_generated_local",
            "Post",
            &["author_id"],
            source_fields,
        );
        let target = entity(
            "schema_relation_edge_rejects_generated_local",
            "User",
            &["id"],
            target_fields,
        );

        let err = RelationEdge::new(
            "author",
            "schema_relation_edge_rejects_generated_local::User",
            &["author_id"],
        )
        .validate_against_entities(&source, &target)
        .expect_err("generated local component field should reject");

        assert!(
            err.messages()
                .iter()
                .any(|message| message.contains("is generated")),
            "unexpected relation edge validation errors: {err}",
        );
    }

    #[test]
    fn relation_edge_rejects_mixed_local_component_cardinality() {
        let source_fields = Box::leak(
            vec![
                field("author_tenant_id", Primitive::Nat64),
                optional_field("author_user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let target_fields = Box::leak(
            vec![
                field("tenant_id", Primitive::Nat64),
                field("user_id", Primitive::Ulid),
            ]
            .into_boxed_slice(),
        );
        let source = entity(
            "schema_relation_edge_rejects_mixed_cardinality",
            "Post",
            &["author_tenant_id"],
            source_fields,
        );
        let target = entity(
            "schema_relation_edge_rejects_mixed_cardinality",
            "User",
            &["tenant_id", "user_id"],
            target_fields,
        );

        let err = RelationEdge::new(
            "author",
            "schema_relation_edge_rejects_mixed_cardinality::User",
            &["author_tenant_id", "author_user_id"],
        )
        .validate_against_entities(&source, &target)
        .expect_err("mixed local tuple cardinality should reject");

        assert!(
            err.messages()
                .iter()
                .any(|message| message.contains("cardinality mismatch")),
            "unexpected relation edge validation errors: {err}",
        );
    }

    #[test]
    fn relation_edge_validate_for_source_uses_schema_target_lookup() {
        let source_fields = Box::leak(vec![field("author_id", Primitive::Ulid)].into_boxed_slice());
        let target_fields = Box::leak(vec![field("id", Primitive::Ulid)].into_boxed_slice());
        let source = entity(
            "schema_relation_edge_lookup",
            "Post",
            &["author_id"],
            source_fields,
        );
        let (target_path, _) = insert_entity(
            "schema_relation_edge_lookup",
            "User",
            &["id"],
            target_fields,
        );

        RelationEdge::new("author", target_path, &["author_id"])
            .validate_for_source(&source)
            .expect("schema target lookup should validate matching scalar edge");
    }

    #[test]
    fn relation_edge_component_contract_preserves_bounds() {
        let expected = field_with_item(
            "body",
            item_with_metadata(Primitive::Text, None, Some(64), None),
        );
        let same = field_with_item(
            "body_copy",
            item_with_metadata(Primitive::Text, None, Some(64), None),
        );
        let wrong = field_with_item(
            "body_short",
            item_with_metadata(Primitive::Text, None, Some(32), None),
        );

        let expected = RelationComponentContract::from_field(&expected);
        assert!(!expected.mismatches(RelationComponentContract::from_field(&same)));
        assert!(expected.mismatches(RelationComponentContract::from_field(&wrong)));
    }
}