Skip to main content

marsdb_graph/
model.rs

1use std::collections::BTreeMap;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4pub struct NodeId(pub u64);
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub struct EdgeId(pub u64);
8
9/// A node/edge property, as persisted to redb (via `postcard`, see
10/// `encode.rs`) and used directly as MarsDB's runtime scalar type -- there
11/// is no separate "wire" representation. New variants append at the end
12/// (postcard's derive encodes an enum discriminant by declaration order),
13/// never reorder/remove an existing one, or every already-stored property
14/// silently decodes as the wrong variant.
15///
16/// `Date`/`Duration` are Cypher's `DATE`/`DURATION` temporal types, added
17/// as first-class variants rather than reusing `Int`/`String` -- e.g.
18/// stashing a date as `Int(epoch_day)` would round-trip through storage
19/// fine, but a plain `Int` and a `Date` would then be indistinguishable
20/// once read back (Temporal4's "store a date, read it back, it must
21/// still print/compare/access-components as a date" scenarios need that
22/// distinction to survive the storage boundary). `LocalTime`/`Time`/
23/// `LocalDateTime`/`DateTime` (Cypher's other four temporal types) follow
24/// the same reasoning below. `Time` only accepts a *fixed* UTC offset --
25/// it carries no calendar date, so a named zone's DST-dependent offset
26/// has nothing to resolve against; `DateTime` accepts either a fixed
27/// offset or a named zone (`TzId`).
28///
29/// `Map` exists here for exactly one reason: a `$parameter`'s value can be
30/// map-shaped (`{name: 'Apa'}`, TCK's Map2/Map3), and query-time
31/// parameters flow in as `PropertyValue` (this is the one place a
32/// non-storable shape has to travel through). A node/edge *property*
33/// value is never actually a `Map` though -- real Cypher forbids storing
34/// one (`marsdb-query::executor::value_to_storable_property` rejects it
35/// outright before anything reaches `GraphStore`), so this variant is
36/// only ever constructed on the parameter-passing path, never persisted.
37#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
38pub enum PropertyValue {
39    Null,
40    Bool(bool),
41    Int(i64),
42    Float(f64),
43    String(String),
44    /// A calendar date with no time-of-day or timezone, stored as the
45    /// number of days since the Unix epoch (1970-01-01), proleptic
46    /// Gregorian. Plain `i32` (not a `chrono` type) -- keeps this crate's
47    /// storage format independent of any date library's own internal
48    /// representation (which is free to change across `chrono` versions),
49    /// and keeps comparison a plain integer compare. Conversion to/from
50    /// calendar year/month/day and ISO-8601 text lives in `marsdb-query`
51    /// (`temporal.rs`), not here -- this crate only stores the value, it
52    /// doesn't know Cypher's date grammar/semantics. `i64`, not `i32`:
53    /// Cypher's full year range (±999_999_999, ISO 8601 expanded years)
54    /// reaches ±365 billion epoch days, past `i32`. Wire-compatible with
55    /// values written as `i32`: postcard varints don't encode the width,
56    /// and the index key encoding was already 8-byte (see `index.rs`).
57    Date(i64),
58    /// An ISO-8601 duration (Cypher's `DURATION` type), kept in Neo4j's
59    /// own four-component normalized form rather than as a single scalar
60    /// -- months and days are *not* fungible with each other or with
61    /// seconds (a month is 28-31 days depending which month; without a
62    /// reference date, "3 months" has no fixed length in days at all), so
63    /// collapsing `duration({months: 1})` and `duration({days: 30})` into
64    /// one comparable number would silently be wrong once added to some
65    /// starting date. `nanos` always has the same sign as `seconds` (or is
66    /// `0`) -- i.e. `seconds*1_000_000_000 + nanos` is `total_nanoseconds`
67    /// truncated-towards-zero the same way Rust's integer division/`%`
68    /// already works, never a separately-signed remainder -- so
69    /// "-1.999 seconds" is `seconds: -1, nanos: -999_000_000`, not
70    /// `seconds: -2, nanos: 1_000_000`, which would make the same
71    /// duration representable two different ways.
72    Duration {
73        months: i64,
74        days: i64,
75        seconds: i64,
76        nanos: i32,
77    },
78    /// A time-of-day with no date or timezone, stored as nanoseconds since
79    /// midnight (`0..86_400_000_000_000`, always non-negative -- there's no
80    /// sign to carry the way `Date`'s epoch-day has). Cypher's `LOCAL TIME`.
81    LocalTime(i64),
82    /// A time-of-day with a *fixed* UTC offset (Cypher's `TIME`) -- named
83    /// timezones (`Europe/Stockholm`) aren't supported, only literal
84    /// `+HH:MM`-style offsets (see `marsdb-query::temporal`'s module docs
85    /// for the exact scope). `nanos_of_day` is the wall-clock reading (same
86    /// representation as `LocalTime`); `offset_seconds` is seconds *east*
87    /// of UTC. Comparison/equality use the UTC-equivalent instant-of-day
88    /// (`nanos_of_day - offset_seconds`), not the raw wall-clock reading --
89    /// two `Time`s at different offsets can represent the same instant.
90    Time {
91        nanos_of_day: i64,
92        offset_seconds: i32,
93    },
94    /// A calendar date + time-of-day with no timezone (Cypher's `LOCAL
95    /// DATETIME`), stored as a naive (zone-less) instant: whole seconds
96    /// since the Unix epoch (`epoch_seconds`, signed -- a pre-1970 value is
97    /// negative) plus a `0..999_999_999` nanosecond remainder that always
98    /// stays non-negative (the sign lives entirely in `epoch_seconds`,
99    /// mirroring `Duration`'s "no separately-signed remainder" invariant).
100    LocalDateTime {
101        epoch_seconds: i64,
102        nanos: i32,
103    },
104    /// A calendar date + time-of-day with a timezone (Cypher's
105    /// `DATETIME`) -- either a *fixed* UTC offset or a named IANA zone
106    /// (`Europe/Stockholm`). `epoch_seconds`/`nanos` are the *UTC
107    /// instant* (same convention as `LocalDateTime`); `zone` is kept
108    /// only for display/round-tripping the original wall-clock reading
109    /// -- comparison/equality use the instant alone, matching real
110    /// Cypher (two `DateTime`s at the same instant but different zones
111    /// are equal, even though they print differently). A `Named` zone's
112    /// real offset at this instant is *not* cached here (the same zone
113    /// has different offsets across a DST transition) -- it's re-derived
114    /// on demand via `chrono-tz` (`marsdb-query::temporal::resolve_
115    /// offset`), this crate only stores the value, it doesn't know
116    /// Cypher's timezone-resolution semantics.
117    DateTime {
118        epoch_seconds: i64,
119        nanos: i32,
120        zone: TzId,
121    },
122    /// A homogeneous array of scalars (real Cypher/Neo4j's own property
123    /// restriction: a stored list property can hold any of the scalar
124    /// variants above, all the same variant, never `Null`-mixed-with-a-
125    /// type, another `List`, or a map -- enforced where a `Value::List`
126    /// is converted to a storable `PropertyValue`, in `marsdb-query`, not
127    /// here; this crate just stores whatever `Vec<PropertyValue>` it's
128    /// given). Appended last (see this enum's own doc comment on why
129    /// variant order is a real, one-way storage-compat constraint).
130    List(Vec<PropertyValue>),
131    /// See this enum's own doc comment -- parameter-passing only, never a
132    /// real stored property value.
133    Map(BTreeMap<String, PropertyValue>),
134}
135
136/// A `DateTime`'s zone: a fixed UTC offset, or a named IANA timezone
137/// (`Europe/Stockholm`) whose real offset varies by instant (DST) and is
138/// resolved on demand, not stored -- see `PropertyValue::DateTime`'s doc
139/// comment.
140#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
141pub enum TzId {
142    Offset(i32),
143    Named(String),
144}
145
146#[derive(Debug, Clone, PartialEq)]
147pub struct Node {
148    pub id: NodeId,
149    pub labels: Vec<String>,
150    pub props: BTreeMap<String, PropertyValue>,
151}
152
153#[derive(Debug, Clone, PartialEq)]
154pub struct Edge {
155    pub id: EdgeId,
156    pub label: String,
157    pub src: NodeId,
158    pub dst: NodeId,
159    pub props: BTreeMap<String, PropertyValue>,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum Direction {
164    Out,
165    In,
166}
167
168/// A traversal-hop candidate read directly from an adjacency multimap entry,
169/// without touching the `edges`/`nodes` tables.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub struct AdjEntry {
172    pub edge_id: EdgeId,
173    pub other: NodeId,
174    pub label_id: u32,
175}
176
177/// Composite-key layout for `ADJ_OUT`/`ADJ_IN` (v2 step 2):
178/// `(owner_node, label_id, edge_id)` tuple key -> other node id as the
179/// value. A redb tuple of fixed-width integers stays fixed-width (a
180/// byte-packed `[u8; 20]` key here measured a 2x database file — the
181/// mars-am7 erasure tax; see `tables::ADJ_OUT`'s docs) and orders
182/// component-wise, so one node's edges are contiguous and label-typed
183/// expansion is a sub-prefix range within them. `AdjEntry` stays the
184/// in-memory traversal-candidate type; only its storage layout moved
185/// from a 20-byte multimap *value* into this key shape.
186pub(crate) type AdjKey = (u64, u32, u64);
187
188pub(crate) fn adj_key(owner: u64, label_id: u32, edge_id: u64) -> AdjKey {
189    (owner, label_id, edge_id)
190}
191
192/// Inclusive key bounds covering every adjacency entry a node owns,
193/// any label — the untyped-expansion prefix.
194pub(crate) fn adj_node_bounds(owner: u64) -> (AdjKey, AdjKey) {
195    ((owner, 0, 0), (owner, u32::MAX, u64::MAX))
196}
197
198/// Inclusive key bounds covering one node's entries under one label —
199/// the typed-expansion prefix (`O(matching degree)`).
200pub(crate) fn adj_label_bounds(owner: u64, label_id: u32) -> (AdjKey, AdjKey) {
201    ((owner, label_id, 0), (owner, label_id, u64::MAX))
202}