Skip to main content

relate_model/
schema.rs

1//! Schema constraint types shared by Relate and (historically) GraphStore.
2use std::fmt;
3use std::str::FromStr;
4
5/// The kind of a schema [`Constraint`], persisted as
6/// `Constraint::constraint_type`.
7///
8/// Replaces the previous stringly-typed `constraint_type: String`. The serde
9/// representation is the exact tag written by earlier versions, so pre-enum
10/// databases load unchanged, and an unknown tag is a hard deserialization
11/// error instead of being silently ignored by a `_ => {}` catch-all.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
13pub enum ConstraintType {
14    #[serde(rename = "unique")]
15    Unique,
16    #[serde(rename = "key")]
17    Key,
18    #[serde(rename = "exists")]
19    Exists,
20    #[serde(rename = "propertyType")]
21    PropertyType,
22    /// A node label-existence constraint derived from a graph type
23    /// (`ALTER CURRENT GRAPH TYPE`).
24    #[serde(rename = "labelExistence")]
25    LabelExistence,
26    /// The standalone `REQUIRE alias:Label` node label-existence form.
27    #[serde(rename = "nodeLabelExistence")]
28    NodeLabelExistence,
29    /// A relationship source-label constraint derived from a graph type.
30    #[serde(rename = "sourceLabel")]
31    SourceLabel,
32    /// The standalone relationship source-label form.
33    #[serde(rename = "sourceLabelExistence")]
34    SourceLabelExistence,
35    /// A relationship target-label constraint derived from a graph type.
36    #[serde(rename = "targetLabel")]
37    TargetLabel,
38    /// The standalone relationship target-label form.
39    #[serde(rename = "targetLabelExistence")]
40    TargetLabelExistence,
41}
42
43impl ConstraintType {
44    /// The canonical stored tag — identical to the serde representation and to
45    /// the pre-enum `Constraint::constraint_type` string.
46    pub fn as_str(&self) -> &'static str {
47        match self {
48            ConstraintType::Unique => "unique",
49            ConstraintType::Key => "key",
50            ConstraintType::Exists => "exists",
51            ConstraintType::PropertyType => "propertyType",
52            ConstraintType::LabelExistence => "labelExistence",
53            ConstraintType::NodeLabelExistence => "nodeLabelExistence",
54            ConstraintType::SourceLabel => "sourceLabel",
55            ConstraintType::SourceLabelExistence => "sourceLabelExistence",
56            ConstraintType::TargetLabel => "targetLabel",
57            ConstraintType::TargetLabelExistence => "targetLabelExistence",
58        }
59    }
60
61    /// Whether this constraint kind is backed by a range index — the two kinds
62    /// (`unique`/`key`) that share one physical backing index per schema.
63    pub fn is_index_backed(&self) -> bool {
64        matches!(self, ConstraintType::Unique | ConstraintType::Key)
65    }
66
67    /// Whether this kind is one of the six label/endpoint-label existence kinds
68    /// that carry an enforced label (CIP-187): `labelExistence`,
69    /// `nodeLabelExistence`, `sourceLabel`, `sourceLabelExistence`,
70    /// `targetLabel`, `targetLabelExistence`. Single source of truth for the
71    /// string check in the executor's `requires_enforced_label`.
72    pub fn is_enforced_label_kind(&self) -> bool {
73        self.enforced_label_site().is_some()
74    }
75
76    /// Where an enforced-label kind checks its enforced label: on the
77    /// constrained node, or on the start or end node of the constrained
78    /// relationship. `None` for every kind that carries no enforced label.
79    /// This is the typed form of the enforced-label entity split: the kind
80    /// attaches to a relationship iff the site is not
81    /// [`EnforcedLabelSite::Node`].
82    pub fn enforced_label_site(&self) -> Option<EnforcedLabelSite> {
83        match self {
84            ConstraintType::LabelExistence | ConstraintType::NodeLabelExistence => {
85                Some(EnforcedLabelSite::Node)
86            }
87            ConstraintType::SourceLabel | ConstraintType::SourceLabelExistence => {
88                Some(EnforcedLabelSite::Start)
89            }
90            ConstraintType::TargetLabel | ConstraintType::TargetLabelExistence => {
91                Some(EnforcedLabelSite::End)
92            }
93            ConstraintType::Unique
94            | ConstraintType::Key
95            | ConstraintType::Exists
96            | ConstraintType::PropertyType => None,
97        }
98    }
99
100    /// Whether this kind enforces uniqueness of the constrained properties:
101    /// `unique` and `key` (a key constraint is uniqueness + existence).
102    /// Today this is exactly the index-backed set, but the predicate is
103    /// named for the semantic guarantee, not the physical backing.
104    pub fn enforces_uniqueness(&self) -> bool {
105        matches!(self, ConstraintType::Unique | ConstraintType::Key)
106    }
107
108    /// Whether this kind requires the constrained properties to be present
109    /// (non-null) on every matching entity: `exists`, and `key` (a key
110    /// property must exist). The enforced-label kinds
111    /// ([`ConstraintType::is_enforced_label_kind`]) enforce label presence,
112    /// not property presence, so they are excluded.
113    pub fn enforces_property_presence(&self) -> bool {
114        matches!(self, ConstraintType::Exists | ConstraintType::Key)
115    }
116}
117
118impl fmt::Display for ConstraintType {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.write_str(self.as_str())
121    }
122}
123
124impl ConstraintType {
125    /// The one spelling of the pinned unknown-kind reply
126    /// (`ConstraintValidationFailed: `<name>` unknown constraint type "…"`),
127    /// shared by the catalog's durable-row gate and the executor's validator.
128    pub fn unknown_kind_message(name: &str, reason: &str) -> String {
129        format!("ConstraintValidationFailed: `{name}` {reason}")
130    }
131}
132
133impl FromStr for ConstraintType {
134    type Err = String;
135    /// Parse a stored tag. Unknown tags are rejected rather than silently
136    /// defaulting.
137    fn from_str(s: &str) -> Result<Self, Self::Err> {
138        match s {
139            "unique" => Ok(ConstraintType::Unique),
140            "key" => Ok(ConstraintType::Key),
141            "exists" => Ok(ConstraintType::Exists),
142            "propertyType" => Ok(ConstraintType::PropertyType),
143            "labelExistence" => Ok(ConstraintType::LabelExistence),
144            "nodeLabelExistence" => Ok(ConstraintType::NodeLabelExistence),
145            "sourceLabel" => Ok(ConstraintType::SourceLabel),
146            "sourceLabelExistence" => Ok(ConstraintType::SourceLabelExistence),
147            "targetLabel" => Ok(ConstraintType::TargetLabel),
148            "targetLabelExistence" => Ok(ConstraintType::TargetLabelExistence),
149            other => Err(format!("unknown constraint type {other:?}")),
150        }
151    }
152}
153
154impl PartialEq<str> for ConstraintType {
155    fn eq(&self, other: &str) -> bool {
156        self.as_str() == other
157    }
158}
159
160impl PartialEq<&str> for ConstraintType {
161    fn eq(&self, other: &&str) -> bool {
162        self.as_str() == *other
163    }
164}
165
166/// Which node an enforced-label constraint kind requires to carry its
167/// enforced label ([`ConstraintType::enforced_label_site`]).
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
169pub enum EnforcedLabelSite {
170    /// The constrained node itself (`labelExistence`, `nodeLabelExistence`).
171    Node,
172    /// The start node of the constrained relationship (`sourceLabel`,
173    /// `sourceLabelExistence`).
174    Start,
175    /// The end node of the constrained relationship (`targetLabel`,
176    /// `targetLabelExistence`).
177    End,
178}
179
180impl EnforcedLabelSite {
181    /// Whether the enforced label is checked on an endpoint of the
182    /// constrained relationship (`Start`/`End`) rather than on the
183    /// constrained node itself — the named form of the "the kind attaches
184    /// to a relationship iff the site is not [`EnforcedLabelSite::Node`]"
185    /// polarity rule ([`ConstraintType::enforced_label_site`]), so call
186    /// sites compare against a `relationship` flag without hand-rolled
187    /// boolean algebra.
188    pub fn is_relationship(&self) -> bool {
189        !matches!(self, EnforcedLabelSite::Node)
190    }
191}
192
193fn default_node_entity_type() -> String {
194    "NODE".to_string()
195}
196
197/// Node-vs-relationship entity kind: the typed form of the catalog's
198/// `relationship: bool` flag and of the `"NODE"`/`"RELATIONSHIP"`
199/// `entityType` string ([`Constraint::entity_type`], the `SHOW INDEXES` /
200/// `SHOW CONSTRAINTS` `entityType` column, CIP-11).
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
202pub enum EntityKind {
203    Node,
204    Relationship,
205}
206
207impl EntityKind {
208    /// The kind for a catalog `relationship` flag (`false` → node).
209    pub fn from_relationship_flag(relationship: bool) -> Self {
210        if relationship {
211            EntityKind::Relationship
212        } else {
213            EntityKind::Node
214        }
215    }
216
217    /// The catalog `relationship` flag for this kind — the inverse of
218    /// [`EntityKind::from_relationship_flag`].
219    pub fn is_relationship(&self) -> bool {
220        matches!(self, EntityKind::Relationship)
221    }
222
223    /// The `entityType` display name (`"NODE"` / `"RELATIONSHIP"`).
224    pub fn display_name(&self) -> &'static str {
225        match self {
226            EntityKind::Node => "NODE",
227            EntityKind::Relationship => "RELATIONSHIP",
228        }
229    }
230
231    /// Parse an `entityType` display name back into the kind — the inverse
232    /// of [`EntityKind::display_name`]. Unknown names are rejected.
233    pub fn from_display_name(name: &str) -> Option<Self> {
234        match name {
235            "NODE" => Some(EntityKind::Node),
236            "RELATIONSHIP" => Some(EntityKind::Relationship),
237            _ => None,
238        }
239    }
240}
241
242impl fmt::Display for EntityKind {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.write_str(self.display_name())
245    }
246}
247
248/// CIP-186's three-way constraint classification: whether a constraint is
249/// `undesignated` (a uniqueness/key constraint — never depends on the
250/// current graph type), `dependent` (graph-type-derived, or an
251/// existence/property-type constraint whose label identifies a node/edge
252/// type), or `independent` (every other constraint). The typed form of the
253/// strings `classify_constraint` returns.
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
255pub enum ConstraintClassification {
256    Undesignated,
257    Dependent,
258    Independent,
259}
260
261impl ConstraintClassification {
262    /// The `SHOW CONSTRAINTS` `classification` column value.
263    pub fn as_str(&self) -> &'static str {
264        match self {
265            ConstraintClassification::Undesignated => "undesignated",
266            ConstraintClassification::Dependent => "dependent",
267            ConstraintClassification::Independent => "independent",
268        }
269    }
270}
271
272impl fmt::Display for ConstraintClassification {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.write_str(self.as_str())
275    }
276}
277
278/// A schema constraint (unique, exists, key, propertyType, or -- CIP-186/
279/// CIP-187 -- one of the graph-type-derived kinds labelExistence/
280/// sourceLabel/targetLabel).
281#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
282pub struct Constraint {
283    pub name: String,
284    pub label: String,
285    pub properties: Vec<String>,
286    /// The constraint kind ([`ConstraintType`]). Serialized as the exact tag
287    /// (`"unique"`, `"propertyType"`, ...).
288    #[serde(rename = "type")]
289    pub constraint_type: ConstraintType,
290    /// The CIP-100-normalized type string for a `"propertyType"`
291    /// constraint (CIP-85), `None` for every other `constraint_type`.
292    /// `#[serde(default)]` keeps JSON databases written before this field
293    /// existed loadable.
294    #[serde(default)]
295    pub property_type: Option<String>,
296    /// "NODE" or "RELATIONSHIP" (CIP-11). `#[serde(default)]` keeps JSON
297    /// databases written before this field existed loadable.
298    #[serde(default = "default_node_entity_type")]
299    pub entity_type: String,
300    /// The label a `"labelExistence"`/`"sourceLabel"`/`"targetLabel"`
301    /// graph-type-derived constraint (CIP-187) requires to be present --
302    /// `SHOW CONSTRAINTS`'s `enforcedLabel` column. `None` for every other
303    /// `constraint_type`. `#[serde(default)]` keeps JSON databases written
304    /// before this field existed loadable.
305    #[serde(default)]
306    pub enforced_label: Option<String>,
307}
308
309impl Constraint {
310    /// The entity kind this constraint names. The one classifier every
311    /// durable boundary (WAL preflight, checkpoint theater, JSON decode)
312    /// routes through, so a value naming neither kind has one message.
313    pub fn entity_kind(&self) -> Result<EntityKind, String> {
314        EntityKind::parse(&self.name, &self.entity_type)
315    }
316}
317
318impl EntityKind {
319    /// Classify a stored `entity_type` for the named record, with the one
320    /// unknown-kind message. The row-agnostic spelling
321    /// [`Constraint::entity_kind`] delegates to.
322    pub fn parse(name: &str, entity_type: &str) -> Result<EntityKind, String> {
323        EntityKind::from_display_name(entity_type)
324            .ok_or_else(|| EntityKind::unknown_message(name, entity_type))
325    }
326
327    /// The one message for a stored `entity_type` naming neither kind.
328    pub fn unknown_message(name: &str, entity_type: &str) -> String {
329        format!(
330            "derived constraint {name} entity_type '{entity_type}' names neither NODE nor RELATIONSHIP"
331        )
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338
339    const ALL_CONSTRAINT_TYPES: [ConstraintType; 10] = [
340        ConstraintType::Unique,
341        ConstraintType::Key,
342        ConstraintType::Exists,
343        ConstraintType::PropertyType,
344        ConstraintType::LabelExistence,
345        ConstraintType::NodeLabelExistence,
346        ConstraintType::SourceLabel,
347        ConstraintType::SourceLabelExistence,
348        ConstraintType::TargetLabel,
349        ConstraintType::TargetLabelExistence,
350    ];
351
352    #[test]
353    fn enforces_uniqueness_is_unique_and_key_only() {
354        for kind in ALL_CONSTRAINT_TYPES {
355            assert_eq!(
356                kind.enforces_uniqueness(),
357                matches!(kind, ConstraintType::Unique | ConstraintType::Key),
358                "{kind}"
359            );
360        }
361    }
362
363    #[test]
364    fn enforces_property_presence_is_exists_and_key_only() {
365        for kind in ALL_CONSTRAINT_TYPES {
366            assert_eq!(
367                kind.enforces_property_presence(),
368                matches!(kind, ConstraintType::Exists | ConstraintType::Key),
369                "{kind}"
370            );
371        }
372    }
373
374    #[test]
375    fn enforced_label_site_follows_the_kind_tag() {
376        for kind in ALL_CONSTRAINT_TYPES {
377            let expected = match kind.as_str() {
378                "labelExistence" | "nodeLabelExistence" => Some(EnforcedLabelSite::Node),
379                "sourceLabel" | "sourceLabelExistence" => Some(EnforcedLabelSite::Start),
380                "targetLabel" | "targetLabelExistence" => Some(EnforcedLabelSite::End),
381                _ => None,
382            };
383            assert_eq!(kind.enforced_label_site(), expected, "{kind}");
384            assert_eq!(kind.is_enforced_label_kind(), expected.is_some(), "{kind}");
385        }
386    }
387
388    #[test]
389    fn enforced_label_site_is_relationship_pins_the_polarity() {
390        assert!(!EnforcedLabelSite::Node.is_relationship());
391        assert!(EnforcedLabelSite::Start.is_relationship());
392        assert!(EnforcedLabelSite::End.is_relationship());
393    }
394
395    #[test]
396    fn constraint_classification_strings() {
397        assert_eq!(
398            ConstraintClassification::Undesignated.as_str(),
399            "undesignated"
400        );
401        assert_eq!(ConstraintClassification::Dependent.as_str(), "dependent");
402        assert_eq!(
403            ConstraintClassification::Independent.as_str(),
404            "independent"
405        );
406        assert_eq!(
407            ConstraintClassification::Undesignated.to_string(),
408            "undesignated"
409        );
410        assert_eq!(ConstraintClassification::Dependent.to_string(), "dependent");
411        assert_eq!(
412            ConstraintClassification::Independent.to_string(),
413            "independent"
414        );
415    }
416
417    #[test]
418    fn entity_kind_relationship_flag_round_trips() {
419        assert_eq!(EntityKind::from_relationship_flag(false), EntityKind::Node);
420        assert_eq!(
421            EntityKind::from_relationship_flag(true),
422            EntityKind::Relationship
423        );
424        for kind in [EntityKind::Node, EntityKind::Relationship] {
425            assert_eq!(
426                EntityKind::from_relationship_flag(kind.is_relationship()),
427                kind
428            );
429        }
430    }
431
432    #[test]
433    fn entity_kind_display_name_round_trips() {
434        assert_eq!(EntityKind::Node.display_name(), "NODE");
435        assert_eq!(EntityKind::Relationship.display_name(), "RELATIONSHIP");
436        assert_eq!(EntityKind::Node.to_string(), "NODE");
437        for kind in [EntityKind::Node, EntityKind::Relationship] {
438            assert_eq!(
439                EntityKind::from_display_name(kind.display_name()),
440                Some(kind)
441            );
442        }
443        assert_eq!(EntityKind::from_display_name("node"), None);
444        assert_eq!(EntityKind::from_display_name("EDGE"), None);
445    }
446}