Skip to main content

relate_core/
namespace.rs

1//! The fixed namespaces of a Relate store (ADR-0116 §1).
2//!
3//! Every store has exactly three namespaces: [`Namespace::Neo4j`] (the user
4//! data graph), [`Namespace::System`] (CE system database; holds no graph
5//! data) and [`Namespace::SystemOntologies`] (the read-only ontology graph).
6//! None can be created, dropped or renamed, and names match
7//! case-insensitively. A namespace whose visibility tracks a preview
8//! feature (today [`Namespace::SystemOntologies`], ADR-0593) is invisible
9//! while that feature is disabled: listed by no catalog, resolved by no
10//! name — see [`namespace_preview_feature`].
11
12use std::fmt;
13use std::str::FromStr;
14
15use crate::preview::{PreviewFeature, PreviewFeatures};
16use crate::{ce_messages, Error};
17
18/// One of the three fixed namespaces of a store.
19///
20/// Element ids name their namespace through the middle segment of
21/// `<kind>:<segment>:<n|r><id>` (ADR-0116 §7, ADR-0554): the segment is
22/// dash-bearing and names the database — `rl-id` for `neo4j`,
23/// `rl-onto` for `system_ontologies` — and `system` has
24/// no elements and no
25/// segment.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub enum Namespace {
28    /// The user data graph. The only namespace Cypher can write.
29    Neo4j,
30    /// The CE system database: SHOW commands, supported administration
31    /// commands and procedure calls only. Holds no graph data.
32    System,
33    /// The read-only ontology graph, written only through the `db.ontology.*`
34    /// procedures. Its dialect visibility gates behind the `ontology`
35    /// preview feature (ADR-0593): invisible — unlisted, unaddressable —
36    /// while the opt-in is off.
37    SystemOntologies,
38}
39
40impl Namespace {
41    /// Every namespace, in canonical order: `neo4j`, `system`,
42    /// `system_ontologies`.
43    pub const ALL: [Namespace; 3] = [
44        Namespace::Neo4j,
45        Namespace::System,
46        Namespace::SystemOntologies,
47    ];
48
49    /// The canonical (lowercase) namespace name.
50    pub fn as_str(&self) -> &'static str {
51        match self {
52            Namespace::Neo4j => "neo4j",
53            Namespace::System => "system",
54            Namespace::SystemOntologies => "system_ontologies",
55        }
56    }
57
58    /// Parses a namespace name, case-insensitively (ADR-0116 §1). Returns
59    /// `None` for any other name.
60    pub fn parse(name: &str) -> Option<Namespace> {
61        Namespace::ALL
62            .iter()
63            .find(|ns| name.eq_ignore_ascii_case(ns.as_str()))
64            .copied()
65    }
66
67    /// Whether Cypher can write this namespace. Only `neo4j` is writable
68    /// (ADR-0116 §5: read many, write one).
69    pub fn is_writable(&self) -> bool {
70        matches!(self, Namespace::Neo4j)
71    }
72
73    /// Whether this namespace is read-only to Cypher. Only
74    /// `system_ontologies` is (ADR-0116 §1).
75    pub fn is_read_only(&self) -> bool {
76        matches!(self, Namespace::SystemOntologies)
77    }
78
79    /// Whether this namespace is visible under `preview` (ADR-0593): a
80    /// namespace gated by [`namespace_preview_feature`] stays invisible
81    /// until its feature's opt-in is set; the ungated namespaces are
82    /// always visible. The one predicate every visibility consumer
83    /// derives from — the `SHOW DATABASES` listing, `USE` and connect
84    /// resolution, `ALTER DATABASE` targets.
85    pub fn visible_under(self, preview: PreviewFeatures) -> bool {
86        namespace_preview_feature(self).is_none_or(|feature| preview.enabled(feature))
87    }
88
89    /// The visibility gate (ADR-0593): `Ok(())` when
90    /// [`Self::visible_under`] holds, otherwise the ordinary
91    /// unknown-database rejection (42N00, [`ce_messages::graph_not_found`])
92    /// — the name-gate form ADR-0371 prescribes for hidden names: never
93    /// the authored preview error, which would advertise a name the
94    /// catalog must not list.
95    pub fn require_visible(self, preview: PreviewFeatures) -> Result<(), Error> {
96        if self.visible_under(preview) {
97            Ok(())
98        } else {
99            Err(ce_messages::graph_not_found(self.as_str()))
100        }
101    }
102
103    /// The element-id middle segment for this namespace (ADR-0116 §7,
104    /// ADR-0554), or `None` for `system`, which has no elements. The
105    /// segment is dash-bearing and names the database, as Neo4j's UUID
106    /// segment does — clients classify an id as an element id by that
107    /// observable dash (ADR-0554's Context).
108    pub fn element_id_segment(&self) -> Option<&'static str> {
109        match self {
110            Namespace::Neo4j => Some("rl-id"),
111            Namespace::System => None,
112            Namespace::SystemOntologies => Some("rl-onto"),
113        }
114    }
115
116    /// The inverse of [`Namespace::element_id_segment`]: maps an element-id
117    /// middle segment back to its namespace. Returns `None` for any other
118    /// segment (including `system`, which has none).
119    pub fn from_element_id_segment(segment: &str) -> Option<Namespace> {
120        Namespace::ALL
121            .iter()
122            .find(|ns| ns.element_id_segment() == Some(segment))
123            .copied()
124    }
125}
126
127/// The one fixed-namespace → preview-feature mapping (ADR-0593): a
128/// namespace whose dialect visibility tracks a preview feature's opt-in.
129/// Today exactly one row — `system_ontologies` behind the `ontology` row
130/// (ADR-0378's feature; its contract tracks a non-final external spec,
131/// and the namespace exists to host that feature's stored document) —
132/// and the shape is the registry pattern, the namespace twin of the
133/// executor's procedure-to-feature mapping: a future gated namespace
134/// adds its row here, and every consumer — [`Namespace::visible_under`],
135/// [`Namespace::require_visible`] and the resolution sites that consult
136/// them — follows without new machinery.
137fn namespace_preview_feature(namespace: Namespace) -> Option<PreviewFeature> {
138    match namespace {
139        Namespace::SystemOntologies => Some(PreviewFeature::Ontology),
140        Namespace::Neo4j | Namespace::System => None,
141    }
142}
143
144/// The composite-database `graph.*` selector function names, lowercased
145/// (ADR-0116 §3). One shared list: the planner's `use_target` resolves
146/// these calls as `USE` selectors (with element-id resolution for
147/// `graph.byElementId`) and rejects them with CE's 42N72 text in
148/// expression position, while the executor's `SHOW FUNCTIONS` catalog
149/// lists them as catalog-only entries (discoverable but not executable).
150/// Two separate lists would drift.
151pub const GRAPH_SELECTOR_FUNCTIONS: [(&str, usize); 4] = [
152    ("graph.names", 0),
153    ("graph.byname", 1),
154    ("graph.byelementid", 1),
155    ("graph.propertiesbyname", 1),
156];
157
158/// The selector *names*, derived from [`GRAPH_SELECTOR_FUNCTIONS`] — the one
159/// table — for consumers that need a flat `&[&str]` (the executor's
160/// catalog-only `SHOW FUNCTIONS` entries).
161pub const GRAPH_SELECTOR_FUNCTION_NAMES: [&str; GRAPH_SELECTOR_FUNCTIONS.len()] = {
162    let mut names = [""; GRAPH_SELECTOR_FUNCTIONS.len()];
163    let mut i = 0;
164    while i < GRAPH_SELECTOR_FUNCTIONS.len() {
165        names[i] = GRAPH_SELECTOR_FUNCTIONS[i].0;
166        i += 1;
167    }
168    names
169};
170
171/// True for the composite-database `graph.*` selector names
172/// (case-insensitive). The one predicate home — callers never spell the
173/// membership test themselves. Allocation-free: compares with
174/// `eq_ignore_ascii_case` like `Namespace::parse` does.
175pub fn is_graph_selector_function_name(name: &str) -> bool {
176    graph_selector_arity(name).is_some()
177}
178
179/// The one arity table for the `graph.*` selector calls: `graph.names()`
180/// takes no argument, the three element-name lookups take one. Every site
181/// that resolves or rejects these calls checks arity through this table
182/// first, so a wrong argument count reports Neo4j's 42I13 arity failure
183/// rather than the composite-database 42N72 refusal (SemanticErrorPart3
184/// "graph.byElementId with no argument is rejected"). `None` for a name
185/// that is not a selector.
186pub(crate) fn graph_selector_arity(name: &str) -> Option<usize> {
187    GRAPH_SELECTOR_FUNCTIONS
188        .iter()
189        .find(|(selector, _)| name.eq_ignore_ascii_case(selector))
190        .map(|(_, arity)| *arity)
191}
192
193/// The parsed shape of an element id (ADR-0116 §7):
194/// `<kind>:<segment>:<n|r><id>`. This is the one parser for that three-part
195/// structure, shared by `USE graph.byElementId(...)` resolution and
196/// `db.nameFromElementId`; it only splits the shape — callers decide how
197/// much of it to validate (`db.nameFromElementId` checks the kind prefix
198/// and rejects an empty entity segment, but deliberately does not validate
199/// the entity segment's contents).
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub struct ElementIdRef<'a> {
202    /// The first segment: the element kind (`4` node, `5` relationship).
203    pub kind: &'a str,
204    /// The middle segment: names the namespace, dash-bearing
205    /// (ADR-0554): `rl-id` or `rl-onto`.
206    pub segment: &'a str,
207    /// The third segment: the entity reference (`n<id>` / `r<id>`), opaque.
208    pub id: &'a str,
209}
210
211impl<'a> ElementIdRef<'a> {
212    /// Split an element id into its three colon-separated segments, or
213    /// `None` when it does not have exactly that shape.
214    pub fn parse(id: &'a str) -> Option<ElementIdRef<'a>> {
215        let mut parts = id.split(':');
216        let parsed = ElementIdRef {
217            kind: parts.next()?,
218            segment: parts.next()?,
219            id: parts.next()?,
220        };
221        if parts.next().is_some() {
222            return None;
223        }
224        Some(parsed)
225    }
226
227    /// Whether the first segment names an element kind the engine writes —
228    /// the one place the kind digit is resolved against
229    /// [`ElementKind`]'s vocabulary, so a caller never re-spells it.
230    pub fn has_known_kind(&self) -> bool {
231        [ElementKind::Node, ElementKind::Rel]
232            .into_iter()
233            .any(|kind| kind.kind_segment() == self.kind)
234    }
235
236    /// The namespace the middle segment names (ADR-0116 §7), or `None`
237    /// when it names no namespace.
238    pub fn namespace(&self) -> Option<Namespace> {
239        Namespace::from_element_id_segment(self.segment)
240    }
241}
242
243/// The element kind an element id encodes: node (`4`/`n`) or relationship
244/// (`5`/`r`). The digit and the entity prefix travel together, so a
245/// mismatched pair cannot be expressed.
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247enum ElementKind {
248    Node,
249    Rel,
250}
251
252impl ElementKind {
253    /// The first segment of the wire form (`4` node, `5` relationship).
254    fn kind_segment(self) -> &'static str {
255        match self {
256            ElementKind::Node => "4",
257            ElementKind::Rel => "5",
258        }
259    }
260
261    /// The entity prefix of the third segment (`n`/`r`).
262    fn entity_prefix(self) -> char {
263        match self {
264            ElementKind::Node => 'n',
265            ElementKind::Rel => 'r',
266        }
267    }
268}
269
270/// The element id string of a node in `namespace` (`4:<segment>:n<id>`),
271/// built through the same validated namespace the parser accepts — an
272/// ad-hoc segment could emit an id the engine's own parser refuses.
273pub fn node_element_id(id: i64, namespace: Namespace) -> Option<String> {
274    element_id(id, namespace, ElementKind::Node)
275}
276
277/// The element id string of a relationship in `namespace`
278/// (`5:<segment>:r<id>`).
279pub fn rel_element_id(id: i64, namespace: Namespace) -> Option<String> {
280    element_id(id, namespace, ElementKind::Rel)
281}
282
283/// The node id encoded in a relate element id, or `None` for a
284/// relationship id, a foreign namespace, or a malformed value.
285pub fn parse_node_element_id(s: &str) -> Option<i64> {
286    parse_element_id(s, ElementKind::Node)
287}
288
289/// The relationship id encoded in a relate element id, or `None`.
290pub fn parse_rel_element_id(s: &str) -> Option<i64> {
291    parse_element_id(s, ElementKind::Rel)
292}
293
294/// One owner of the element-id wire form: the constructor and the decoder
295/// share the kind digit, the namespace (validated through the canonical
296/// [`Namespace::element_id_segment`] mapping — a bare `starts_with` would
297/// accept `relateXYZ`), and the entity prefix.
298fn element_id(id: i64, namespace: Namespace, kind: ElementKind) -> Option<String> {
299    let segment = namespace.element_id_segment()?;
300    Some(format!(
301        "{}:{}:{}{}",
302        kind.kind_segment(),
303        segment,
304        kind.entity_prefix(),
305        id
306    ))
307}
308
309fn parse_element_id(s: &str, kind: ElementKind) -> Option<i64> {
310    let parsed = ElementIdRef::parse(s)?;
311    if parsed.kind != kind.kind_segment() {
312        return None;
313    }
314    parsed.namespace()?;
315    parsed.id.strip_prefix(kind.entity_prefix())?.parse().ok()
316}
317
318impl fmt::Display for Namespace {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        f.write_str(self.as_str())
321    }
322}
323
324impl FromStr for Namespace {
325    type Err = ();
326
327    fn from_str(s: &str) -> Result<Self, Self::Err> {
328        Namespace::parse(s).ok_or(())
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn parse_is_case_insensitive() {
338        assert_eq!(Namespace::parse("neo4j"), Some(Namespace::Neo4j));
339        assert_eq!(Namespace::parse("Neo4j"), Some(Namespace::Neo4j));
340        assert_eq!(Namespace::parse("NEO4J"), Some(Namespace::Neo4j));
341        assert_eq!(Namespace::parse("SYSTEM"), Some(Namespace::System));
342        assert_eq!(
343            Namespace::parse("System_Ontologies"),
344            Some(Namespace::SystemOntologies)
345        );
346        assert_eq!("neo4j".parse::<Namespace>(), Ok(Namespace::Neo4j));
347        assert_eq!(
348            "SYSTEM_ONTOLOGIES".parse::<Namespace>(),
349            Ok(Namespace::SystemOntologies)
350        );
351    }
352
353    #[test]
354    fn parse_rejects_unknown_names() {
355        assert_eq!(Namespace::parse(""), None);
356        assert_eq!(Namespace::parse("nosuch"), None);
357        assert_eq!(Namespace::parse("systemx"), None);
358        assert_eq!(Namespace::parse("system_ontology"), None);
359        assert!("movies".parse::<Namespace>().is_err());
360    }
361
362    #[test]
363    fn display_and_as_str_are_canonical() {
364        assert_eq!(Namespace::Neo4j.as_str(), "neo4j");
365        assert_eq!(Namespace::System.as_str(), "system");
366        assert_eq!(Namespace::SystemOntologies.as_str(), "system_ontologies");
367        assert_eq!(Namespace::Neo4j.to_string(), "neo4j");
368        assert_eq!(Namespace::System.to_string(), "system");
369        assert_eq!(Namespace::SystemOntologies.to_string(), "system_ontologies");
370    }
371
372    #[test]
373    fn only_neo4j_is_writable() {
374        assert!(Namespace::Neo4j.is_writable());
375        assert!(!Namespace::System.is_writable());
376        assert!(!Namespace::SystemOntologies.is_writable());
377    }
378
379    #[test]
380    fn only_system_ontologies_is_read_only() {
381        assert!(!Namespace::Neo4j.is_read_only());
382        assert!(!Namespace::System.is_read_only());
383        assert!(Namespace::SystemOntologies.is_read_only());
384    }
385
386    #[test]
387    fn system_ontologies_is_the_only_preview_gated_namespace() {
388        // The pinned mapping, mirroring the executor's procedure-gate
389        // test: the gated set is derived over the full vocabulary, so a
390        // namespace added to the enum fails this pin until its gating is
391        // decided here, and one moved in or out of the mapping fails the
392        // equality.
393        assert_eq!(
394            namespace_preview_feature(Namespace::SystemOntologies),
395            Some(PreviewFeature::Ontology)
396        );
397        let gated: Vec<Namespace> = Namespace::ALL
398            .iter()
399            .copied()
400            .filter(|ns| namespace_preview_feature(*ns).is_some())
401            .collect();
402        assert_eq!(gated, [Namespace::SystemOntologies]);
403    }
404
405    #[test]
406    fn visibility_follows_the_mapping_and_hides_with_the_ordinary_rejection() {
407        let off = PreviewFeatures::none();
408        let on = PreviewFeatures::parse("ontology").unwrap();
409        assert!(!Namespace::SystemOntologies.visible_under(off));
410        assert!(Namespace::SystemOntologies.visible_under(on));
411        // The ungated set is the mapping's complement over the full
412        // vocabulary, never a hand-spelled subset: a namespace added to
413        // the enum is pinned always-visible until its gating is decided.
414        for ungated in Namespace::ALL
415            .iter()
416            .copied()
417            .filter(|ns| namespace_preview_feature(*ns).is_none())
418        {
419            assert!(ungated.visible_under(off), "{ungated}");
420            assert!(ungated.visible_under(on), "{ungated}");
421        }
422        // The gate's disabled form is the ordinary unknown-database
423        // rejection — never the authored preview error, which would
424        // advertise the hidden name (ADR-0371's name-gate rule).
425        let err = Namespace::SystemOntologies
426            .require_visible(off)
427            .unwrap_err();
428        assert!(
429            matches!(&err, Error::DatabaseNotFound { name } if name == "system_ontologies"),
430            "{err}"
431        );
432        assert!(Namespace::SystemOntologies.require_visible(on).is_ok());
433    }
434
435    #[test]
436    fn element_id_segments_round_trip() {
437        assert_eq!(Namespace::Neo4j.element_id_segment(), Some("rl-id"));
438        assert_eq!(Namespace::System.element_id_segment(), None);
439        assert_eq!(
440            Namespace::SystemOntologies.element_id_segment(),
441            Some("rl-onto")
442        );
443        for ns in Namespace::ALL {
444            if let Some(segment) = ns.element_id_segment() {
445                assert_eq!(Namespace::from_element_id_segment(segment), Some(ns));
446            }
447        }
448        // `system` has no segment, and unknown segments map to nothing.
449        assert_eq!(Namespace::from_element_id_segment("system"), None);
450        assert_eq!(Namespace::from_element_id_segment("rl-id.system"), None);
451        assert_eq!(Namespace::from_element_id_segment("neo4j"), None);
452        assert_eq!(Namespace::from_element_id_segment(""), None);
453    }
454
455    #[test]
456    fn element_ids_carry_a_dash_so_shape_sniffing_clients_classify_them() {
457        // ADR-0554: real Neo4j ids carry dashes (the database UUID
458        // segment), and clients — Neo4j Browser's neighbour expansion is
459        // the recorded case — pick the element-id code path by exactly
460        // that observable property, parsing the string as a legacy
461        // integer otherwise. Every emitted id must keep a dash.
462        for ns in Namespace::ALL {
463            if ns.element_id_segment().is_some() {
464                assert!(node_element_id(7, ns).unwrap().contains('-'));
465                assert!(rel_element_id(9, ns).unwrap().contains('-'));
466            }
467        }
468    }
469
470    #[test]
471    fn element_id_ref_parses_the_three_part_shape() {
472        let parsed = ElementIdRef::parse("4:rl-onto:r9").unwrap();
473        assert_eq!(parsed.kind, "4");
474        assert_eq!(parsed.segment, "rl-onto");
475        assert_eq!(parsed.id, "r9");
476        assert_eq!(parsed.namespace(), Some(Namespace::SystemOntologies));
477        assert_eq!(
478            ElementIdRef::parse("5:rl-id:n1").unwrap().namespace(),
479            Some(Namespace::Neo4j)
480        );
481        // Only the shape is split: kind and entity segment stay opaque.
482        let parsed = ElementIdRef::parse("4:rl-id:999999").unwrap();
483        assert_eq!(parsed.id, "999999");
484        // Not exactly three segments, or a segment naming no namespace.
485        assert_eq!(ElementIdRef::parse("garbage"), None);
486        assert_eq!(ElementIdRef::parse("4:rl-id"), None);
487        assert_eq!(ElementIdRef::parse("4:rl-id:n1:extra"), None);
488        assert_eq!(ElementIdRef::parse("4::n1").unwrap().namespace(), None);
489        assert_eq!(
490            ElementIdRef::parse("4:00000000-0000-0000-0000-000000000000:n1")
491                .unwrap()
492                .namespace(),
493            None
494        );
495    }
496
497    #[test]
498    fn graph_selector_functions_are_the_four_composite_selectors() {
499        assert_eq!(
500            GRAPH_SELECTOR_FUNCTIONS,
501            [
502                ("graph.names", 0),
503                ("graph.byname", 1),
504                ("graph.byelementid", 1),
505                ("graph.propertiesbyname", 1)
506            ]
507        );
508        assert_eq!(
509            GRAPH_SELECTOR_FUNCTION_NAMES,
510            [
511                "graph.names",
512                "graph.byname",
513                "graph.byelementid",
514                "graph.propertiesbyname"
515            ]
516        );
517        // Already lowercase: `is_graph_selector_function_name` matches
518        // case-insensitively against them (`eq_ignore_ascii_case`).
519        for (name, _) in GRAPH_SELECTOR_FUNCTIONS {
520            assert_eq!(name, name.to_ascii_lowercase());
521        }
522        assert!(is_graph_selector_function_name("Graph.ByName"));
523        assert!(!is_graph_selector_function_name("graph.x"));
524    }
525
526    #[test]
527    fn all_lists_every_namespace_in_order() {
528        assert_eq!(
529            Namespace::ALL,
530            [
531                Namespace::Neo4j,
532                Namespace::System,
533                Namespace::SystemOntologies
534            ]
535        );
536    }
537}