relate-model 1.0.2

Data model types (CypherValue) for the Relate graph database
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
//! Schema constraint types shared by Relate and (historically) GraphStore.
use std::fmt;
use std::str::FromStr;

/// The kind of a schema [`Constraint`], persisted as
/// `Constraint::constraint_type`.
///
/// Replaces the previous stringly-typed `constraint_type: String`. The serde
/// representation is the exact tag written by earlier versions, so pre-enum
/// databases load unchanged, and an unknown tag is a hard deserialization
/// error instead of being silently ignored by a `_ => {}` catch-all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ConstraintType {
    #[serde(rename = "unique")]
    Unique,
    #[serde(rename = "key")]
    Key,
    #[serde(rename = "exists")]
    Exists,
    #[serde(rename = "propertyType")]
    PropertyType,
    /// A node label-existence constraint derived from a graph type
    /// (`ALTER CURRENT GRAPH TYPE`).
    #[serde(rename = "labelExistence")]
    LabelExistence,
    /// The standalone `REQUIRE alias:Label` node label-existence form.
    #[serde(rename = "nodeLabelExistence")]
    NodeLabelExistence,
    /// A relationship source-label constraint derived from a graph type.
    #[serde(rename = "sourceLabel")]
    SourceLabel,
    /// The standalone relationship source-label form.
    #[serde(rename = "sourceLabelExistence")]
    SourceLabelExistence,
    /// A relationship target-label constraint derived from a graph type.
    #[serde(rename = "targetLabel")]
    TargetLabel,
    /// The standalone relationship target-label form.
    #[serde(rename = "targetLabelExistence")]
    TargetLabelExistence,
}

impl ConstraintType {
    /// The canonical stored tag — identical to the serde representation and to
    /// the pre-enum `Constraint::constraint_type` string.
    pub fn as_str(&self) -> &'static str {
        match self {
            ConstraintType::Unique => "unique",
            ConstraintType::Key => "key",
            ConstraintType::Exists => "exists",
            ConstraintType::PropertyType => "propertyType",
            ConstraintType::LabelExistence => "labelExistence",
            ConstraintType::NodeLabelExistence => "nodeLabelExistence",
            ConstraintType::SourceLabel => "sourceLabel",
            ConstraintType::SourceLabelExistence => "sourceLabelExistence",
            ConstraintType::TargetLabel => "targetLabel",
            ConstraintType::TargetLabelExistence => "targetLabelExistence",
        }
    }

    /// Whether this constraint kind is backed by a range index — the two kinds
    /// (`unique`/`key`) that share one physical backing index per schema.
    pub fn is_index_backed(&self) -> bool {
        matches!(self, ConstraintType::Unique | ConstraintType::Key)
    }

    /// Whether this kind is one of the six label/endpoint-label existence kinds
    /// that carry an enforced label (CIP-187): `labelExistence`,
    /// `nodeLabelExistence`, `sourceLabel`, `sourceLabelExistence`,
    /// `targetLabel`, `targetLabelExistence`. Single source of truth for the
    /// string check in the executor's `requires_enforced_label`.
    pub fn is_enforced_label_kind(&self) -> bool {
        self.enforced_label_site().is_some()
    }

    /// Where an enforced-label kind checks its enforced label: on the
    /// constrained node, or on the start or end node of the constrained
    /// relationship. `None` for every kind that carries no enforced label.
    /// This is the typed form of the enforced-label entity split: the kind
    /// attaches to a relationship iff the site is not
    /// [`EnforcedLabelSite::Node`].
    pub fn enforced_label_site(&self) -> Option<EnforcedLabelSite> {
        match self {
            ConstraintType::LabelExistence | ConstraintType::NodeLabelExistence => {
                Some(EnforcedLabelSite::Node)
            }
            ConstraintType::SourceLabel | ConstraintType::SourceLabelExistence => {
                Some(EnforcedLabelSite::Start)
            }
            ConstraintType::TargetLabel | ConstraintType::TargetLabelExistence => {
                Some(EnforcedLabelSite::End)
            }
            ConstraintType::Unique
            | ConstraintType::Key
            | ConstraintType::Exists
            | ConstraintType::PropertyType => None,
        }
    }

    /// Whether this kind enforces uniqueness of the constrained properties:
    /// `unique` and `key` (a key constraint is uniqueness + existence).
    /// Today this is exactly the index-backed set, but the predicate is
    /// named for the semantic guarantee, not the physical backing.
    pub fn enforces_uniqueness(&self) -> bool {
        matches!(self, ConstraintType::Unique | ConstraintType::Key)
    }

    /// Whether this kind requires the constrained properties to be present
    /// (non-null) on every matching entity: `exists`, and `key` (a key
    /// property must exist). The enforced-label kinds
    /// ([`ConstraintType::is_enforced_label_kind`]) enforce label presence,
    /// not property presence, so they are excluded.
    pub fn enforces_property_presence(&self) -> bool {
        matches!(self, ConstraintType::Exists | ConstraintType::Key)
    }
}

impl fmt::Display for ConstraintType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl ConstraintType {
    /// The one spelling of the pinned unknown-kind reply
    /// (`ConstraintValidationFailed: `<name>` unknown constraint type "…"`),
    /// shared by the catalog's durable-row gate and the executor's validator.
    pub fn unknown_kind_message(name: &str, reason: &str) -> String {
        format!("ConstraintValidationFailed: `{name}` {reason}")
    }
}

impl FromStr for ConstraintType {
    type Err = String;
    /// Parse a stored tag. Unknown tags are rejected rather than silently
    /// defaulting.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "unique" => Ok(ConstraintType::Unique),
            "key" => Ok(ConstraintType::Key),
            "exists" => Ok(ConstraintType::Exists),
            "propertyType" => Ok(ConstraintType::PropertyType),
            "labelExistence" => Ok(ConstraintType::LabelExistence),
            "nodeLabelExistence" => Ok(ConstraintType::NodeLabelExistence),
            "sourceLabel" => Ok(ConstraintType::SourceLabel),
            "sourceLabelExistence" => Ok(ConstraintType::SourceLabelExistence),
            "targetLabel" => Ok(ConstraintType::TargetLabel),
            "targetLabelExistence" => Ok(ConstraintType::TargetLabelExistence),
            other => Err(format!("unknown constraint type {other:?}")),
        }
    }
}

impl PartialEq<str> for ConstraintType {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&str> for ConstraintType {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

/// Which node an enforced-label constraint kind requires to carry its
/// enforced label ([`ConstraintType::enforced_label_site`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EnforcedLabelSite {
    /// The constrained node itself (`labelExistence`, `nodeLabelExistence`).
    Node,
    /// The start node of the constrained relationship (`sourceLabel`,
    /// `sourceLabelExistence`).
    Start,
    /// The end node of the constrained relationship (`targetLabel`,
    /// `targetLabelExistence`).
    End,
}

impl EnforcedLabelSite {
    /// Whether the enforced label is checked on an endpoint of the
    /// constrained relationship (`Start`/`End`) rather than on the
    /// constrained node itself — the named form of the "the kind attaches
    /// to a relationship iff the site is not [`EnforcedLabelSite::Node`]"
    /// polarity rule ([`ConstraintType::enforced_label_site`]), so call
    /// sites compare against a `relationship` flag without hand-rolled
    /// boolean algebra.
    pub fn is_relationship(&self) -> bool {
        !matches!(self, EnforcedLabelSite::Node)
    }
}

fn default_node_entity_type() -> String {
    "NODE".to_string()
}

/// Node-vs-relationship entity kind: the typed form of the catalog's
/// `relationship: bool` flag and of the `"NODE"`/`"RELATIONSHIP"`
/// `entityType` string ([`Constraint::entity_type`], the `SHOW INDEXES` /
/// `SHOW CONSTRAINTS` `entityType` column, CIP-11).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntityKind {
    Node,
    Relationship,
}

impl EntityKind {
    /// The kind for a catalog `relationship` flag (`false` → node).
    pub fn from_relationship_flag(relationship: bool) -> Self {
        if relationship {
            EntityKind::Relationship
        } else {
            EntityKind::Node
        }
    }

    /// The catalog `relationship` flag for this kind — the inverse of
    /// [`EntityKind::from_relationship_flag`].
    pub fn is_relationship(&self) -> bool {
        matches!(self, EntityKind::Relationship)
    }

    /// The `entityType` display name (`"NODE"` / `"RELATIONSHIP"`).
    pub fn display_name(&self) -> &'static str {
        match self {
            EntityKind::Node => "NODE",
            EntityKind::Relationship => "RELATIONSHIP",
        }
    }

    /// Parse an `entityType` display name back into the kind — the inverse
    /// of [`EntityKind::display_name`]. Unknown names are rejected.
    pub fn from_display_name(name: &str) -> Option<Self> {
        match name {
            "NODE" => Some(EntityKind::Node),
            "RELATIONSHIP" => Some(EntityKind::Relationship),
            _ => None,
        }
    }
}

impl fmt::Display for EntityKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.display_name())
    }
}

/// CIP-186's three-way constraint classification: whether a constraint is
/// `undesignated` (a uniqueness/key constraint — never depends on the
/// current graph type), `dependent` (graph-type-derived, or an
/// existence/property-type constraint whose label identifies a node/edge
/// type), or `independent` (every other constraint). The typed form of the
/// strings `classify_constraint` returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConstraintClassification {
    Undesignated,
    Dependent,
    Independent,
}

impl ConstraintClassification {
    /// The `SHOW CONSTRAINTS` `classification` column value.
    pub fn as_str(&self) -> &'static str {
        match self {
            ConstraintClassification::Undesignated => "undesignated",
            ConstraintClassification::Dependent => "dependent",
            ConstraintClassification::Independent => "independent",
        }
    }
}

impl fmt::Display for ConstraintClassification {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A schema constraint (unique, exists, key, propertyType, or -- CIP-186/
/// CIP-187 -- one of the graph-type-derived kinds labelExistence/
/// sourceLabel/targetLabel).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Constraint {
    pub name: String,
    pub label: String,
    pub properties: Vec<String>,
    /// The constraint kind ([`ConstraintType`]). Serialized as the exact tag
    /// (`"unique"`, `"propertyType"`, ...).
    #[serde(rename = "type")]
    pub constraint_type: ConstraintType,
    /// The CIP-100-normalized type string for a `"propertyType"`
    /// constraint (CIP-85), `None` for every other `constraint_type`.
    /// `#[serde(default)]` keeps JSON databases written before this field
    /// existed loadable.
    #[serde(default)]
    pub property_type: Option<String>,
    /// "NODE" or "RELATIONSHIP" (CIP-11). `#[serde(default)]` keeps JSON
    /// databases written before this field existed loadable.
    #[serde(default = "default_node_entity_type")]
    pub entity_type: String,
    /// The label a `"labelExistence"`/`"sourceLabel"`/`"targetLabel"`
    /// graph-type-derived constraint (CIP-187) requires to be present --
    /// `SHOW CONSTRAINTS`'s `enforcedLabel` column. `None` for every other
    /// `constraint_type`. `#[serde(default)]` keeps JSON databases written
    /// before this field existed loadable.
    #[serde(default)]
    pub enforced_label: Option<String>,
}

impl Constraint {
    /// The entity kind this constraint names. The one classifier every
    /// durable boundary (WAL preflight, checkpoint theater, JSON decode)
    /// routes through, so a value naming neither kind has one message.
    pub fn entity_kind(&self) -> Result<EntityKind, String> {
        EntityKind::parse(&self.name, &self.entity_type)
    }
}

impl EntityKind {
    /// Classify a stored `entity_type` for the named record, with the one
    /// unknown-kind message. The row-agnostic spelling
    /// [`Constraint::entity_kind`] delegates to.
    pub fn parse(name: &str, entity_type: &str) -> Result<EntityKind, String> {
        EntityKind::from_display_name(entity_type)
            .ok_or_else(|| EntityKind::unknown_message(name, entity_type))
    }

    /// The one message for a stored `entity_type` naming neither kind.
    pub fn unknown_message(name: &str, entity_type: &str) -> String {
        format!(
            "derived constraint {name} entity_type '{entity_type}' names neither NODE nor RELATIONSHIP"
        )
    }
}

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

    const ALL_CONSTRAINT_TYPES: [ConstraintType; 10] = [
        ConstraintType::Unique,
        ConstraintType::Key,
        ConstraintType::Exists,
        ConstraintType::PropertyType,
        ConstraintType::LabelExistence,
        ConstraintType::NodeLabelExistence,
        ConstraintType::SourceLabel,
        ConstraintType::SourceLabelExistence,
        ConstraintType::TargetLabel,
        ConstraintType::TargetLabelExistence,
    ];

    #[test]
    fn enforces_uniqueness_is_unique_and_key_only() {
        for kind in ALL_CONSTRAINT_TYPES {
            assert_eq!(
                kind.enforces_uniqueness(),
                matches!(kind, ConstraintType::Unique | ConstraintType::Key),
                "{kind}"
            );
        }
    }

    #[test]
    fn enforces_property_presence_is_exists_and_key_only() {
        for kind in ALL_CONSTRAINT_TYPES {
            assert_eq!(
                kind.enforces_property_presence(),
                matches!(kind, ConstraintType::Exists | ConstraintType::Key),
                "{kind}"
            );
        }
    }

    #[test]
    fn enforced_label_site_follows_the_kind_tag() {
        for kind in ALL_CONSTRAINT_TYPES {
            let expected = match kind.as_str() {
                "labelExistence" | "nodeLabelExistence" => Some(EnforcedLabelSite::Node),
                "sourceLabel" | "sourceLabelExistence" => Some(EnforcedLabelSite::Start),
                "targetLabel" | "targetLabelExistence" => Some(EnforcedLabelSite::End),
                _ => None,
            };
            assert_eq!(kind.enforced_label_site(), expected, "{kind}");
            assert_eq!(kind.is_enforced_label_kind(), expected.is_some(), "{kind}");
        }
    }

    #[test]
    fn enforced_label_site_is_relationship_pins_the_polarity() {
        assert!(!EnforcedLabelSite::Node.is_relationship());
        assert!(EnforcedLabelSite::Start.is_relationship());
        assert!(EnforcedLabelSite::End.is_relationship());
    }

    #[test]
    fn constraint_classification_strings() {
        assert_eq!(
            ConstraintClassification::Undesignated.as_str(),
            "undesignated"
        );
        assert_eq!(ConstraintClassification::Dependent.as_str(), "dependent");
        assert_eq!(
            ConstraintClassification::Independent.as_str(),
            "independent"
        );
        assert_eq!(
            ConstraintClassification::Undesignated.to_string(),
            "undesignated"
        );
        assert_eq!(ConstraintClassification::Dependent.to_string(), "dependent");
        assert_eq!(
            ConstraintClassification::Independent.to_string(),
            "independent"
        );
    }

    #[test]
    fn entity_kind_relationship_flag_round_trips() {
        assert_eq!(EntityKind::from_relationship_flag(false), EntityKind::Node);
        assert_eq!(
            EntityKind::from_relationship_flag(true),
            EntityKind::Relationship
        );
        for kind in [EntityKind::Node, EntityKind::Relationship] {
            assert_eq!(
                EntityKind::from_relationship_flag(kind.is_relationship()),
                kind
            );
        }
    }

    #[test]
    fn entity_kind_display_name_round_trips() {
        assert_eq!(EntityKind::Node.display_name(), "NODE");
        assert_eq!(EntityKind::Relationship.display_name(), "RELATIONSHIP");
        assert_eq!(EntityKind::Node.to_string(), "NODE");
        for kind in [EntityKind::Node, EntityKind::Relationship] {
            assert_eq!(
                EntityKind::from_display_name(kind.display_name()),
                Some(kind)
            );
        }
        assert_eq!(EntityKind::from_display_name("node"), None);
        assert_eq!(EntityKind::from_display_name("EDGE"), None);
    }
}