corium-forms 0.1.45

Boundary conversion between schema/transaction forms and engine types
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
//! Hierarchical TOML schema declarations.
//!
//! `[[entity]]` declarations are authoring sugar: their names become keyword
//! namespaces, but they do not install or enforce entity types. `[[attribute]]`
//! declarations expose the same model without an entity block.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use corium_core::{Cardinality, Keyword, Unique, ValueType};
use corium_query::edn::Edn;
use serde::de::value::MapAccessDeserializer;
use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Deserializer};
use thiserror::Error;

/// One normalized attribute declaration, independent of its source syntax.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttributeDefinition {
    /// Optional authoring group, mapped to the keyword namespace.
    pub group: Option<String>,
    /// Attribute name within its group, or its complete unnamespaced name.
    pub name: String,
    /// Stored value type.
    pub value_type: ValueType,
    /// Whether entities may hold one or many values for the attribute.
    pub cardinality: Cardinality,
    /// Optional uniqueness behavior.
    pub unique: Option<Unique>,
    /// Whether the attribute requests AVET coverage.
    pub indexed: bool,
    /// Whether a reference is a component of its parent.
    pub component: bool,
    /// Whether history storage is disabled for the attribute.
    pub no_history: bool,
}

impl AttributeDefinition {
    /// Returns the canonical Corium keyword ident.
    #[must_use]
    pub fn ident(&self) -> Keyword {
        Keyword::new(self.group.as_deref(), &self.name)
    }

    /// Converts the declaration to the existing Datomic-style EDN schema form.
    #[must_use]
    pub fn to_edn(&self) -> Edn {
        let mut pairs = vec![
            (kw("db/ident"), Edn::Keyword(self.ident())),
            (
                kw("db/valueType"),
                kw(&format!("db.type/{}", value_type_name(self.value_type))),
            ),
            (
                kw("db/cardinality"),
                kw(match self.cardinality {
                    Cardinality::One => "db.cardinality/one",
                    Cardinality::Many => "db.cardinality/many",
                }),
            ),
        ];
        if let Some(unique) = self.unique {
            pairs.push((
                kw("db/unique"),
                kw(match unique {
                    Unique::Identity => "db.unique/identity",
                    Unique::Value => "db.unique/value",
                }),
            ));
        }
        if self.indexed {
            pairs.push((kw("db/index"), Edn::Bool(true)));
        }
        if self.component {
            pairs.push((kw("db/isComponent"), Edn::Bool(true)));
        }
        if self.no_history {
            pairs.push((kw("db/noHistory"), Edn::Bool(true)));
        }
        pairs.sort_unstable();
        Edn::Map(pairs)
    }
}

/// TOML schema parsing or normalization failure.
#[derive(Debug, Error)]
pub enum TomlSchemaError {
    /// The input is not valid TOML or does not match the schema document shape.
    #[error("invalid TOML schema: {0}")]
    Parse(#[from] toml::de::Error),
    /// The document declares an unsupported format version.
    #[error("unsupported schema-version {0}; expected 1")]
    UnsupportedVersion(u32),
    /// A group or attribute name is not a valid EDN keyword component.
    #[error(
        "invalid {kind} name {name:?}: expected a non-empty EDN keyword component \
         without reserved punctuation, whitespace, or a leading digit"
    )]
    InvalidName {
        /// Kind of declaration containing the name.
        kind: &'static str,
        /// Invalid source name.
        name: String,
    },
    /// A value type name is not part of Corium's schema model.
    #[error("unknown value type {value:?} for {ident}")]
    UnknownValueType {
        /// Attribute being normalized.
        ident: String,
        /// Unknown source value.
        value: String,
    },
    /// A cardinality name is neither `one` nor `many`.
    #[error("unknown cardinality {value:?} for {ident}")]
    UnknownCardinality {
        /// Attribute being normalized.
        ident: String,
        /// Unknown source value.
        value: String,
    },
    /// A uniqueness mode is neither `identity` nor `value`.
    #[error("unknown unique mode {value:?} for {ident}")]
    UnknownUnique {
        /// Attribute being normalized.
        ident: String,
        /// Unknown source value.
        value: String,
    },
    /// Both cardinality spellings were supplied for one declaration.
    #[error("{ident} specifies both `cardinality` and `many`; use only one")]
    ConflictingCardinality {
        /// Attribute being normalized.
        ident: String,
    },
    /// Grouped and/or flat syntax declared the same canonical attribute twice.
    #[error("duplicate attribute {0}")]
    DuplicateAttribute(String),
    /// Two entity authoring blocks use the same group name.
    #[error("duplicate entity group {0:?}")]
    DuplicateEntity(String),
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
struct SchemaDocument {
    #[serde(default = "default_schema_version")]
    schema_version: u32,
    #[serde(default, rename = "entity")]
    entities: Vec<EntityDeclaration>,
    #[serde(default, rename = "attribute")]
    attributes: Vec<FlatAttributeDeclaration>,
}

const fn default_schema_version() -> u32 {
    1
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct EntityDeclaration {
    name: String,
    // TOML tables are unordered. Sorting local names makes initial attribute-id
    // allocation deterministic rather than dependent on parser insertion order.
    #[serde(default)]
    attributes: BTreeMap<String, RawAttribute>,
}

#[derive(Debug)]
enum RawAttribute {
    Shorthand(String),
    Detailed(AttributeOptions),
}

impl<'de> Deserialize<'de> for RawAttribute {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct RawAttributeVisitor;

        impl<'de> Visitor<'de> for RawAttributeVisitor {
            type Value = RawAttribute;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a value type string or an attribute options table")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(RawAttribute::Shorthand(value.to_owned()))
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(RawAttribute::Shorthand(value))
            }

            fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                AttributeOptions::deserialize(MapAccessDeserializer::new(map))
                    .map(RawAttribute::Detailed)
            }
        }

        deserializer.deserialize_any(RawAttributeVisitor)
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
struct FlatAttributeDeclaration {
    #[serde(default)]
    group: Option<String>,
    name: String,
    #[serde(flatten)]
    options: AttributeOptions,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
struct AttributeOptions {
    #[serde(rename = "type")]
    value_type: String,
    #[serde(default)]
    cardinality: Option<String>,
    #[serde(default)]
    many: Option<bool>,
    #[serde(default)]
    unique: Option<String>,
    #[serde(default)]
    index: bool,
    #[serde(default)]
    component: bool,
    #[serde(default)]
    no_history: bool,
}

impl RawAttribute {
    fn into_options(self) -> AttributeOptions {
        match self {
            Self::Shorthand(value_type) => AttributeOptions {
                value_type,
                cardinality: None,
                many: None,
                unique: None,
                index: false,
                component: false,
                no_history: false,
            },
            Self::Detailed(options) => options,
        }
    }
}

/// Parses hierarchical TOML into normalized attribute declarations.
///
/// Grouped syntax uses `[[entity]]` followed by `[entity.attributes]`. The
/// entity name supplies the attribute group. Flat syntax uses `[[attribute]]`
/// with an optional `group`. Entity groups are not persisted as types.
///
/// # Errors
/// Returns [`TomlSchemaError`] for invalid TOML, unsupported values, invalid
/// names, conflicting cardinality spellings, or duplicate canonical idents.
pub fn parse(input: &str) -> Result<Vec<AttributeDefinition>, TomlSchemaError> {
    let document: SchemaDocument = toml::from_str(input)?;
    if document.schema_version != 1 {
        return Err(TomlSchemaError::UnsupportedVersion(document.schema_version));
    }

    let mut definitions = Vec::new();
    let mut seen_entities = BTreeSet::new();
    for entity in document.entities {
        validate_name("entity", &entity.name)?;
        if !seen_entities.insert(entity.name.clone()) {
            return Err(TomlSchemaError::DuplicateEntity(entity.name));
        }
        for (name, raw) in entity.attributes {
            definitions.push(normalize(
                Some(entity.name.clone()),
                name,
                raw.into_options(),
            )?);
        }
    }
    for attribute in document.attributes {
        definitions.push(normalize(
            attribute.group,
            attribute.name,
            attribute.options,
        )?);
    }

    let mut seen = BTreeSet::new();
    for definition in &definitions {
        let ident = definition.ident().to_string();
        if !seen.insert(ident.clone()) {
            return Err(TomlSchemaError::DuplicateAttribute(ident));
        }
    }
    Ok(definitions)
}

/// Parses TOML and emits equivalent EDN attribute maps for existing APIs.
///
/// # Errors
/// Returns the same failures as [`parse`].
pub fn parse_edn(input: &str) -> Result<Vec<Edn>, TomlSchemaError> {
    parse(input).map(|definitions| {
        definitions
            .into_iter()
            .map(|definition| definition.to_edn())
            .collect()
    })
}

fn normalize(
    group: Option<String>,
    name: String,
    options: AttributeOptions,
) -> Result<AttributeDefinition, TomlSchemaError> {
    if let Some(group) = &group {
        validate_name("group", group)?;
    }
    validate_name("attribute", &name)?;
    let ident = display_ident(group.as_deref(), &name);
    let value_type =
        parse_value_type(&options.value_type).ok_or_else(|| TomlSchemaError::UnknownValueType {
            ident: ident.clone(),
            value: options.value_type,
        })?;
    let cardinality = match (options.cardinality, options.many) {
        (Some(_), Some(_)) => {
            return Err(TomlSchemaError::ConflictingCardinality { ident });
        }
        (Some(value), None) => {
            parse_cardinality(&value).ok_or_else(|| TomlSchemaError::UnknownCardinality {
                ident: ident.clone(),
                value,
            })?
        }
        (None, Some(true)) => Cardinality::Many,
        (None, Some(false) | None) => Cardinality::One,
    };
    let unique = options
        .unique
        .map(|value| {
            parse_unique(&value).ok_or_else(|| TomlSchemaError::UnknownUnique {
                ident: ident.clone(),
                value,
            })
        })
        .transpose()?;
    let indexed = options.index || unique.is_some();

    Ok(AttributeDefinition {
        group,
        name,
        value_type,
        cardinality,
        unique,
        indexed,
        component: options.component,
        no_history: options.no_history,
    })
}

fn validate_name(kind: &'static str, name: &str) -> Result<(), TomlSchemaError> {
    if is_valid_edn_keyword_component(name) {
        Ok(())
    } else {
        Err(TomlSchemaError::InvalidName {
            kind,
            name: name.to_owned(),
        })
    }
}

fn is_valid_edn_keyword_component(name: &str) -> bool {
    let Some(first) = name.chars().next() else {
        return false;
    };
    if first.is_ascii_digit() {
        return false;
    }
    !name.chars().any(|character| {
        character.is_whitespace()
            || character.is_control()
            || matches!(
                character,
                '/' | ':'
                    | ';'
                    | '"'
                    | '('
                    | ')'
                    | '['
                    | ']'
                    | '{'
                    | '}'
                    | ','
                    | '`'
                    | '~'
                    | '@'
                    | '^'
                    | '\\'
            )
    })
}

fn display_ident(group: Option<&str>, name: &str) -> String {
    group.map_or_else(|| format!(":{name}"), |group| format!(":{group}/{name}"))
}

fn parse_value_type(value: &str) -> Option<ValueType> {
    match value {
        "boolean" => Some(ValueType::Bool),
        "long" => Some(ValueType::Long),
        "double" => Some(ValueType::Double),
        "instant" => Some(ValueType::Instant),
        "uuid" => Some(ValueType::Uuid),
        "keyword" => Some(ValueType::Keyword),
        "string" => Some(ValueType::Str),
        "bytes" => Some(ValueType::Bytes),
        "ref" => Some(ValueType::Ref),
        _ => None,
    }
}

const fn value_type_name(value_type: ValueType) -> &'static str {
    match value_type {
        ValueType::Bool => "boolean",
        ValueType::Long => "long",
        ValueType::Double => "double",
        ValueType::Instant => "instant",
        ValueType::Uuid => "uuid",
        ValueType::Keyword => "keyword",
        ValueType::Str => "string",
        ValueType::Bytes => "bytes",
        ValueType::Ref => "ref",
    }
}

fn parse_cardinality(value: &str) -> Option<Cardinality> {
    match value {
        "one" => Some(Cardinality::One),
        "many" => Some(Cardinality::Many),
        _ => None,
    }
}

fn parse_unique(value: &str) -> Option<Unique> {
    match value {
        "identity" => Some(Unique::Identity),
        "value" => Some(Unique::Value),
        _ => None,
    }
}

fn kw(text: &str) -> Edn {
    Edn::keyword(text)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schemaform::schema_from_edn;
    use corium_query::edn::read_one;

    const SCHEMA: &str = r#"
schema-version = 1

[[entity]]
name = "person"

[entity.attributes]
age = "long"
id = { type = "uuid", unique = "identity" }
name = { type = "string", index = true }
tags = { type = "keyword", many = true }
address = { type = "ref", component = true }

[[entity]]
name = "organization"

[entity.attributes]
name = "string"
employees = { type = "ref", cardinality = "many", no-history = true }

[[attribute]]
name = "created-at"
type = "instant"
index = true

[[attribute]]
group = "audit"
name = "created-by"
type = "ref"
"#;

    #[test]
    fn parses_grouped_and_flat_attributes() {
        let definitions = parse(SCHEMA).expect("schema parses");
        assert_eq!(definitions.len(), 9);
        assert_eq!(definitions[0].ident().to_string(), ":person/address");
        assert_eq!(definitions[1].ident().to_string(), ":person/age");
        assert_eq!(definitions[3].ident().to_string(), ":person/name");
        assert_eq!(
            definitions[5].ident().to_string(),
            ":organization/employees"
        );
        assert_eq!(definitions[7].ident().to_string(), ":created-at");
        assert_eq!(definitions[8].ident().to_string(), ":audit/created-by");
        assert_eq!(definitions[2].unique, Some(Unique::Identity));
        assert!(definitions[2].indexed);
        assert_eq!(definitions[4].cardinality, Cardinality::Many);
        assert!(definitions[5].no_history);
    }

    #[test]
    fn generated_edn_installs_through_existing_schema_path() {
        let forms = parse_edn(SCHEMA).expect("schema parses");
        let (schema, idents) = schema_from_edn(&forms).expect("schema installs");
        assert_eq!(schema.iter().count(), forms.len() + 1);
        assert_eq!(
            idents.entid(&corium_db::bootstrap::tx_instant_ident()),
            Some(corium_db::bootstrap::TX_INSTANT)
        );
        let tags = idents
            .entid(&Keyword::new(Some("person"), "tags"))
            .expect("tags ident");
        assert_eq!(
            schema.get(tags).expect("tags attribute").cardinality,
            Cardinality::Many
        );
        let id = idents
            .entid(&Keyword::new(Some("person"), "id"))
            .expect("id ident");
        let id_meta = schema.get(id).expect("id attribute");
        assert_eq!(id_meta.unique, Some(Unique::Identity));
        assert!(id_meta.indexed);
        let address = idents
            .entid(&Keyword::new(Some("person"), "address"))
            .expect("address ident");
        assert!(schema.get(address).expect("address attribute").is_component);
        let employees = idents
            .entid(&Keyword::new(Some("organization"), "employees"))
            .expect("employees ident");
        assert!(
            schema
                .get(employees)
                .expect("employees attribute")
                .no_history
        );
    }

    #[test]
    fn rejects_duplicate_canonical_attributes() {
        let error = parse(
            r#"
[[entity]]
name = "person"
[entity.attributes]
name = "string"

[[attribute]]
group = "person"
name = "name"
type = "string"
"#,
        )
        .expect_err("duplicate must fail");
        assert_eq!(error.to_string(), "duplicate attribute :person/name");
    }

    #[test]
    fn rejects_unknown_fields_and_values() {
        let unknown_field = parse(
            r#"
[[entity]]
name = "person"
[entity.attributes]
name = { type = "string", required = true }
"#,
        )
        .expect_err("unknown option must fail");
        assert!(
            unknown_field
                .to_string()
                .contains("unknown field `required`"),
            "{unknown_field}"
        );

        let unknown_type = parse(
            r#"
[[attribute]]
name = "score"
type = "integer"
"#,
        )
        .expect_err("unknown type must fail");
        assert_eq!(
            unknown_type.to_string(),
            "unknown value type \"integer\" for :score"
        );
    }

    #[test]
    fn rejects_names_that_cannot_round_trip_through_edn() {
        for name in [
            "",
            "123name",
            "my attr",
            "a:b[c]",
            "semi;colon",
            "quoted\"name",
            "person/legacy",
        ] {
            let input = format!(
                r#"
[[attribute]]
name = {name:?}
type = "string"
"#
            );
            let error = parse(&input).expect_err("invalid name must fail");
            assert!(
                error
                    .to_string()
                    .contains("expected a non-empty EDN keyword component"),
                "{error}"
            );
        }

        let group_error = parse(
            r#"
[[attribute]]
group = "group name"
name = "value"
type = "string"
"#,
        )
        .expect_err("invalid group must fail");
        assert!(
            group_error
                .to_string()
                .contains("invalid group name \"group name\"")
        );
    }

    #[test]
    fn quoted_toml_keys_still_round_trip_as_edn_keywords() {
        let forms = parse_edn(
            r#"
[[entity]]
name = "person"
[entity.attributes]
"active?" = "boolean"
"#,
        )
        .expect("valid quoted key");
        let printed = forms[0].to_string();
        assert_eq!(read_one(&printed).expect("printed EDN parses"), forms[0]);
    }

    #[test]
    fn rejects_conflicting_cardinality_spellings() {
        let error = parse(
            r#"
[[attribute]]
name = "tags"
type = "string"
cardinality = "many"
many = true
"#,
        )
        .expect_err("conflict must fail");
        assert_eq!(
            error.to_string(),
            ":tags specifies both `cardinality` and `many`; use only one"
        );
    }

    #[test]
    fn rejects_unsupported_version_and_unknown_unique_mode() {
        let version = parse("schema-version = 2").expect_err("version must fail");
        assert_eq!(
            version.to_string(),
            "unsupported schema-version 2; expected 1"
        );

        let unique = parse(
            r#"
[[attribute]]
name = "id"
type = "uuid"
unique = "primary"
"#,
        )
        .expect_err("unique mode must fail");
        assert_eq!(
            unique.to_string(),
            "unknown unique mode \"primary\" for :id"
        );
    }

    #[test]
    fn allows_empty_entity_groups_but_rejects_duplicate_groups() {
        let definitions = parse(
            r#"
[[entity]]
name = "person"

[[attribute]]
group = "person"
name = "name"
type = "string"
"#,
        )
        .expect("empty group is authoring-only");
        assert_eq!(definitions.len(), 1);

        let duplicate = parse(
            r#"
[[entity]]
name = "person"

[[entity]]
name = "person"
"#,
        )
        .expect_err("duplicate entity group must fail");
        assert_eq!(duplicate.to_string(), "duplicate entity group \"person\"");
    }
}