relate-core 1.0.0

Core values, errors, and IDs for Relate
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
//! Relate `Value` <-> CypherValue bridge (relate-model).

use std::collections::BTreeMap;
use std::sync::Arc;

use chrono::{FixedOffset, TimeZone};
use relate_model::value::IsoDuration;
use relate_model::wire::ColumnTypeKind;
use relate_model::{CypherValue, IndexMap};

use crate::temporal::Temporal;
use crate::value::{next_depth, Node, Path, Relationship, Value};

/// Classify an engine `Value` into its canonical ADR-0224 kind — the
/// engine-side spelling of `relate_model::wire::column_type_kind`,
/// classifying into the same single-sourced [`ColumnTypeKind`] set.
///
/// `Value` has no `Geometry` variant (that is a `CypherValue`-only kind,
/// `Point` on this side). `Value::Uuid` has no `CypherValue` counterpart —
/// `value_to_cypher` crosses it as `Str` — so it classifies `String`: the
/// wire taxonomy cannot distinguish it, and the `Uuid` kind stays reserved
/// per ADR-0224. `Value::Bytes` stamps ADR-0224's `BINARY`: the column type
/// names the engine value, which the Bolt surface sends as PackStream Bytes
/// (ADR-0327).
pub fn column_type_kind(value: &Value) -> ColumnTypeKind {
    match value {
        Value::Null => ColumnTypeKind::Any,
        Value::Bool(_) => ColumnTypeKind::Boolean,
        Value::Int(_) => ColumnTypeKind::Integer,
        Value::Float(_) => ColumnTypeKind::Float,
        Value::String(_) | Value::Uuid(_) => ColumnTypeKind::String,
        Value::Bytes(_) => ColumnTypeKind::Binary,
        Value::List(_) => ColumnTypeKind::List,
        Value::Map(_) => ColumnTypeKind::Map,
        Value::Node(_) => ColumnTypeKind::Node,
        Value::Relationship(_) => ColumnTypeKind::Relationship,
        Value::Path(_) => ColumnTypeKind::Path,
        Value::Point(_) => ColumnTypeKind::Point,
        Value::Vector { .. } => ColumnTypeKind::Vector,
        Value::Temporal(t) => match t {
            Temporal::Date(_) | Temporal::CivilDate { .. } => ColumnTypeKind::Date,
            Temporal::LocalTime(_) | Temporal::Time { .. } => ColumnTypeKind::Time,
            Temporal::LocalDateTime(_)
            | Temporal::CivilDateTime { .. }
            | Temporal::DateTime { .. } => ColumnTypeKind::DateTime,
            Temporal::Duration { .. } => ColumnTypeKind::Duration,
        },
    }
}

/// One canonical ADR-0224 type name for an engine `Value` — the name
/// spelling of [`column_type_kind`], for the engine's
/// `QueryResult::column_types` stamp.
pub fn column_type_name(value: &Value) -> &'static str {
    column_type_kind(value).name()
}

pub fn value_to_cypher(v: &Value) -> CypherValue {
    value_to_cypher_at(v, 0)
}

/// [`value_to_cypher`] with the ADR-0462 `depth` (the number of containers
/// enclosing `v`): past [`crate::MAX_VALUE_DEPTH`] a container crosses as
/// `CypherValue::Null` instead of recursing. Unreachable behind the checked
/// constructors; the bridge has no error channel of its own.
fn value_to_cypher_at(v: &Value, depth: u32) -> CypherValue {
    match v {
        Value::Null => CypherValue::Null,
        Value::Bool(b) => CypherValue::Bool(*b),
        Value::Int(i) => CypherValue::Int(*i),
        Value::Float(f) => CypherValue::Float(*f),
        Value::String(s) => CypherValue::Str(String::from(&**s)),
        // CIP-246 documented deviation: the model-level CypherValue (FFI /
        // Python surface) has no UUID variant, so UUIDs cross as their
        // canonical STRING form.
        Value::Uuid(u) => CypherValue::Str(crate::value::uuid_hyphenated(*u)),
        // ADR-0327 documented deviation: CypherValue has no byte-array
        // variant, so bytes cross as the LIST<INTEGER> of their byte values
        // 0-255 — the representation ADR-0219 gives Python `bytes`
        // parameters. Only the Bolt surface carries real bytes.
        Value::Bytes(b) => {
            CypherValue::List(b.iter().map(|&x| CypherValue::Int(x.into())).collect())
        }
        Value::List(xs) => {
            let Some(next) = next_depth(depth) else {
                return CypherValue::Null;
            };
            CypherValue::List(xs.iter().map(|v| value_to_cypher_at(v, next)).collect())
        }
        Value::Map(m) => {
            let Some(next) = next_depth(depth) else {
                return CypherValue::Null;
            };
            CypherValue::Map(
                m.iter()
                    .map(|(k, v)| (k.clone(), value_to_cypher_at(v, next)))
                    .collect(),
            )
        }
        Value::Node(n) => node_to_cypher(n, depth),
        Value::Relationship(r) => rel_to_cypher(r, depth),
        Value::Path(p) => {
            if next_depth(depth).is_none() {
                return CypherValue::Null;
            }
            // A path's embedded entities are not an extra container level
            // (ADR-0462 depth accounting); they share the path's.
            CypherValue::Path {
                nodes: p.nodes.iter().map(|n| node_to_cypher(n, depth)).collect(),
                relationships: p.rels.iter().map(|r| rel_to_cypher(r, depth)).collect(),
            }
        }
        Value::Point(p) => CypherValue::Point(p.clone()),
        Value::Vector { coord, values } => {
            let Some(next) = next_depth(depth) else {
                return CypherValue::Null;
            };
            let mapped: Vec<CypherValue> =
                values.iter().map(|v| value_to_cypher_at(v, next)).collect();
            CypherValue::Vector {
                coord: *coord,
                dim: mapped.len(),
                values: mapped,
            }
        }
        Value::Temporal(t) => temporal_to_cypher(t),
    }
}

/// Node -> CypherValue, shared by the [`Value::Node`] arm and the
/// [`Value::Path`] arm, which converts each path element directly instead
/// of cloning it into a [`Value`] and re-entering the generic dispatcher
/// (which cloned labels and properties a second time).
fn node_to_cypher(n: &Node, depth: u32) -> CypherValue {
    // `depth` is the node's ancestor-container count; its property values
    // sit one container deeper. The same guard at the entity boundary keeps
    // all four renderers agreeing (ADR-0462).
    let Some(next) = next_depth(depth) else {
        return CypherValue::Null;
    };
    CypherValue::Node {
        id: n.id,
        labels: (*n.labels).clone(),
        properties: n
            .properties
            .iter()
            .map(|(k, v)| (k.clone(), value_to_cypher_at(v, next)))
            .collect(),
    }
}

/// Relationship -> CypherValue, shared by the [`Value::Relationship`] arm
/// and the [`Value::Path`] arm (see [`node_to_cypher`]).
fn rel_to_cypher(r: &Relationship, depth: u32) -> CypherValue {
    let Some(next) = next_depth(depth) else {
        return CypherValue::Null;
    };
    CypherValue::Relationship {
        id: r.id,
        start_id: r.start,
        end_id: r.end,
        rel_type: r.rel_type.clone(),
        properties: r
            .properties
            .iter()
            .map(|(k, v)| (k.clone(), value_to_cypher_at(v, next)))
            .collect(),
    }
}

pub fn cypher_to_value(v: &CypherValue) -> Value {
    match v {
        CypherValue::Null => Value::Null,
        CypherValue::Bool(b) => Value::Bool(*b),
        CypherValue::Int(i) => Value::Int(*i),
        CypherValue::Float(f) => Value::Float(*f),
        CypherValue::Str(s) => Value::String(s.as_str().into()),
        CypherValue::List(xs) => {
            Value::List(xs.iter().map(cypher_to_value).collect::<Vec<_>>().into())
        }
        CypherValue::Map(m) => Value::Map(
            m.iter()
                .map(|(k, v)| (k.clone(), cypher_to_value(v)))
                .collect::<BTreeMap<_, _>>()
                .into(),
        ),
        CypherValue::Node {
            id,
            labels,
            properties,
        } => Value::Node(Arc::new(node_from_fields(*id, labels, properties))),
        CypherValue::Relationship {
            id,
            start_id,
            end_id,
            rel_type,
            properties,
        } => Value::Relationship(Arc::new(rel_from_fields(
            *id, *start_id, *end_id, rel_type, properties,
        ))),
        CypherValue::Path {
            nodes,
            relationships,
        } => {
            // `CypherValue::Path` erases its element types
            // (`Vec<CypherValue>`), so a non-entity element is
            // representable. Every producer validates the shape -- the
            // engine builds paths from graph entities and the Arrow
            // typed-JSON decoder rejects bad members -- so a mismatch here
            // is an invariant violation: fail loudly instead of silently
            // dropping the element (the old `filter_map` did).
            let nodes = nodes
                .iter()
                .map(cypher_to_node)
                .collect::<Result<Vec<_>, _>>()
                .expect("CypherValue::Path nodes must be CypherValue::Node");
            let rels = relationships
                .iter()
                .map(cypher_to_relationship)
                .collect::<Result<Vec<_>, _>>()
                .expect("CypherValue::Path relationships must be CypherValue::Relationship");
            Value::Path(Arc::new(Path { nodes, rels }))
        }
        CypherValue::Date(d) => Value::Temporal(Temporal::Date(*d)),
        CypherValue::Time(t, tz) => match tz {
            None => Value::Temporal(Temporal::LocalTime(*t)),
            Some(off) => Value::Temporal(Temporal::Time {
                time: *t,
                offset: off.local_minus_utc(),
            }),
        },
        CypherValue::LocalDateTime(dt) => Value::Temporal(Temporal::LocalDateTime(*dt)),
        CypherValue::DateTime(dt, zone) => {
            let offset = dt.offset().local_minus_utc();
            let utc = dt.naive_utc();
            Value::Temporal(Temporal::DateTime {
                utc,
                offset,
                zone: zone.clone(),
            })
        }
        CypherValue::Duration(d) => Value::Temporal(Temporal::Duration {
            months: d.months,
            days: d.days,
            nanos: d.seconds as i128 * 1_000_000_000 + d.nanoseconds as i128,
        }),
        CypherValue::Point(p) => Value::Point(p.clone()),
        CypherValue::Vector { coord, values, .. } => Value::Vector {
            coord: *coord,
            values: values
                .iter()
                .map(cypher_to_value)
                .collect::<Vec<_>>()
                .into(),
        },
        // Documented deviation (mirrors the Uuid arm in `value_to_cypher`):
        // the core `Value` has no Geometry variant, so a Geometry crossing
        // the model -> core bridge degrades to Null. Persisted properties
        // never take this path: the storage codec rejects Geometry before
        // conversion (`reject_geometry` in relate-storage).
        CypherValue::Geometry(_) => Value::Null,
    }
}

/// Node construction from `CypherValue::Node` fields: infallible because
/// the caller's pattern already proved the variant.
fn node_from_fields(
    id: i64,
    labels: &[String],
    properties: &IndexMap<String, CypherValue>,
) -> Node {
    Node {
        id,
        labels: Arc::new(labels.to_vec()),
        properties: crate::PropertyMap::share(
            properties
                .iter()
                .map(|(k, v)| (k.clone(), cypher_to_value(v)))
                .collect::<std::collections::BTreeMap<_, _>>(),
        ),
    }
}

/// Typed conversion of a `CypherValue::Path` node element: errors on any
/// other variant, so a malformed path element cannot be silently dropped.
fn cypher_to_node(v: &CypherValue) -> Result<Node, String> {
    match v {
        CypherValue::Node {
            id,
            labels,
            properties,
        } => Ok(node_from_fields(*id, labels, properties)),
        other => Err(format!(
            "path node element must be NODE, got {}",
            other.type_name()
        )),
    }
}

/// Relationship construction from `CypherValue::Relationship` fields (see
/// [`node_from_fields`]).
fn rel_from_fields(
    id: i64,
    start: i64,
    end: i64,
    rel_type: &str,
    properties: &IndexMap<String, CypherValue>,
) -> Relationship {
    Relationship {
        id,
        start,
        end,
        rel_type: rel_type.to_string(),
        properties: crate::PropertyMap::share(
            properties
                .iter()
                .map(|(k, v)| (k.clone(), cypher_to_value(v)))
                .collect::<std::collections::BTreeMap<_, _>>(),
        ),
    }
}

/// Typed conversion of a `CypherValue::Path` relationship element: errors
/// on any other variant (see [`cypher_to_node`]).
fn cypher_to_relationship(v: &CypherValue) -> Result<Relationship, String> {
    match v {
        CypherValue::Relationship {
            id,
            start_id,
            end_id,
            rel_type,
            properties,
        } => Ok(rel_from_fields(
            *id, *start_id, *end_id, rel_type, properties,
        )),
        other => Err(format!(
            "path relationship element must be RELATIONSHIP, got {}",
            other.type_name()
        )),
    }
}

fn temporal_to_cypher(t: &Temporal) -> CypherValue {
    match t {
        Temporal::Date(d) => CypherValue::Date(*d),
        // Both civil arms cross as the value's own ISO rendering when the
        // year leaves chrono's range — one fallback spelling, the value's,
        // never a bespoke formatter.
        Temporal::CivilDate { year, month, day } => civil_naive_date(*year, *month, *day)
            .map(CypherValue::Date)
            .unwrap_or_else(|| CypherValue::Str(t.iso_string())),
        Temporal::LocalTime(tm) => CypherValue::Time(*tm, None),
        // An offset outside chrono's `FixedOffset` range (any i32 offset is
        // legal in the stored model, and Bolt accepts them) crosses as the
        // value's ISO string — the same stated fallback the `DateTime` arm
        // uses, never a silent loss of the offset.
        Temporal::Time { time, offset } => match FixedOffset::east_opt(*offset) {
            Some(off) => CypherValue::Time(*time, Some(off)),
            None => CypherValue::Str(t.iso_string()),
        },
        Temporal::LocalDateTime(dt) => CypherValue::LocalDateTime(*dt),
        Temporal::CivilDateTime {
            year,
            month,
            day,
            time,
        } => match civil_naive_date(*year, *month, *day) {
            Some(d) => CypherValue::LocalDateTime(d.and_time(*time)),
            None => CypherValue::Str(t.iso_string()),
        },
        Temporal::DateTime { utc, offset, zone } => {
            let Some(off) = FixedOffset::east_opt(*offset) else {
                return CypherValue::Str(t.iso_string());
            };
            let dt = off.from_utc_datetime(utc);
            // The model's second field is the IANA region name it brackets
            // in `Display`; a fixed-offset spelling (`Z`, `+01:00`,
            // `GMT+03:00`) is already carried by the offset and must not
            // render as a second zone suffix.
            CypherValue::DateTime(
                dt,
                crate::temporal::zone_region(zone.as_deref()).map(String::from),
            )
        }
        Temporal::Duration {
            months,
            days,
            nanos,
        } => {
            // The stored sub-day part is an i128 nanosecond count whose second
            // quotient can reach 2^63 (`Temporal::duration_checked` documents
            // and admits that f64-image edge); `as i64` would wrap a positive
            // duration across the sign boundary. The model's `IsoDuration`
            // stores i64 seconds, so a value past that bound crosses as its
            // ISO string — the bridge's stated fallback, like the civil arms'.
            let Ok(seconds) = i64::try_from(nanos / 1_000_000_000) else {
                return CypherValue::Str(t.iso_string());
            };
            let nanoseconds = i64::try_from(nanos % 1_000_000_000)
                .expect("a sub-second remainder is below 10^9 in magnitude");
            CypherValue::Duration(IsoDuration::new(*months, *days, seconds, nanoseconds))
        }
    }
}

/// The civil date as chrono sees it, or `None` when the year does not fit
/// `i32`. `i32::try_from`, never `as`: an extreme civil year wraps into a
/// plausible-looking one (`4294967397` → 101) and would silently answer a
/// wrong date instead of the ISO-string fallback.
fn civil_naive_date(year: i64, month: u32, day: u32) -> Option<chrono::NaiveDate> {
    i32::try_from(year)
        .ok()
        .and_then(|year| chrono::NaiveDate::from_ymd_opt(year, month, day))
}

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

    fn node(id: i64) -> Node {
        Node {
            id,
            labels: Arc::new(vec!["L".into()]),
            properties: crate::PropertyMap::share(BTreeMap::from([(
                "name".to_string(),
                Value::String("x".into()),
            )])),
        }
    }

    fn rel(id: i64, start: i64, end: i64) -> Relationship {
        Relationship {
            id,
            start,
            end,
            rel_type: "R".into(),
            properties: crate::PropertyMap::share(BTreeMap::from([(
                "w".to_string(),
                Value::Float(0.5),
            )])),
        }
    }

    // The Path arm converts each element directly through the extracted
    // helpers: same output as the generic dispatcher, with no
    // clone-wrap-redispatch.
    #[test]
    fn value_to_cypher_path_matches_direct_conversion() {
        let path = Value::from_path(Path {
            nodes: vec![node(1), node(2)],
            rels: vec![rel(3, 1, 2)],
        });
        let CypherValue::Path {
            nodes,
            relationships,
        } = value_to_cypher(&path)
        else {
            panic!("path did not convert to CypherValue::Path");
        };
        assert_eq!(
            nodes,
            vec![
                value_to_cypher(&Value::from_node(node(1))),
                value_to_cypher(&Value::from_node(node(2))),
            ]
        );
        assert_eq!(
            relationships,
            vec![value_to_cypher(&Value::from_relationship(rel(3, 1, 2)))]
        );
    }

    // B1: an extreme civil year must not wrap into a plausible-looking one —
    // `*year as i32` turned `4294967397` into year 101 and answered a wrong
    // LocalDateTime instead of the ISO-string fallback.
    #[test]
    fn a_civil_year_past_i32_keeps_its_iso_string() {
        let t = crate::temporal::parse_iso("localdatetime", "4294967397-01-01T12:00").unwrap();
        match value_to_cypher(&Value::Temporal(t)) {
            CypherValue::Str(s) => {
                assert!(s.contains("4294967397"), "{s}");
                assert!(!s.contains("0101"), "the year wrapped: {s}");
            }
            other => panic!("expected the ISO-string fallback, got {other:?}"),
        }
        // A civil year that does fit chrono still crosses as a LocalDateTime.
        let small = Temporal::CivilDateTime {
            year: 10_000,
            month: 1,
            day: 1,
            time: chrono::NaiveTime::from_hms_opt(12, 0, 0).unwrap(),
        };
        assert!(
            matches!(
                value_to_cypher(&Value::Temporal(small)),
                CypherValue::LocalDateTime(_)
            ),
            "a representable civil year must keep the typed form"
        );
        // C6: the civil-date twin uses the value's own ISO rendering, never a
        // bespoke spelling (`+4294967397-01-01`, not `4294967397-01-01`).
        let civil_date = Temporal::CivilDate {
            year: 4_294_967_397,
            month: 1,
            day: 1,
        };
        assert_eq!(
            value_to_cypher(&Value::Temporal(civil_date.clone())),
            CypherValue::Str(civil_date.iso_string())
        );
    }

    /// RB6: a stored offset outside chrono's `FixedOffset` range (any i32 is
    /// legal in the stored model, and Bolt accepts them) crosses as the
    /// value's ISO string — the `DateTime` arm's stated fallback, never a
    /// silently offset-less local time.
    #[test]
    fn a_time_offset_past_fixed_offset_range_keeps_its_iso_string() {
        let time = chrono::NaiveTime::from_hms_opt(12, 0, 0).unwrap();
        let unrepresentable = Temporal::Time {
            time,
            offset: 100_000,
        };
        assert_eq!(
            value_to_cypher(&Value::Temporal(unrepresentable.clone())),
            CypherValue::Str(unrepresentable.iso_string())
        );
        // An in-range offset keeps the typed Time carrying it.
        let representable = Temporal::Time { time, offset: 3600 };
        assert!(
            matches!(
                value_to_cypher(&Value::Temporal(representable)),
                CypherValue::Time(_, Some(_))
            ),
            "an in-range offset must keep the typed Time"
        );
    }

    // B2: the sub-day part's second quotient can be 2^63; `as i64` wrapped a
    // positive duration across the sign boundary into i64::MIN.
    #[test]
    fn a_duration_past_i64_seconds_keeps_its_iso_string() {
        let nanos = (i128::from(i64::MAX) + 1) * 1_000_000_000;
        let t = Temporal::Duration {
            months: 0,
            days: 0,
            nanos,
        };
        match value_to_cypher(&Value::Temporal(t)) {
            CypherValue::Str(s) => assert!(s.starts_with('P'), "{s}"),
            other => panic!("expected the ISO-string fallback, got {other:?}"),
        }
        // An in-range duration still crosses as a Duration.
        let ok = Temporal::Duration {
            months: 0,
            days: 1,
            nanos: 1_000_000_000,
        };
        assert!(matches!(
            value_to_cypher(&Value::Temporal(ok)),
            CypherValue::Duration(_)
        ));
    }

    // A well-formed CypherValue::Path round-trips, and the typed element
    // helpers error on a mismatched element instead of silently dropping
    // it (the old `filter_map` behavior).
    #[test]
    fn cypher_to_value_path_roundtrip_and_typed_element_errors() {
        let path = Value::from_path(Path {
            nodes: vec![node(1), node(2)],
            rels: vec![rel(3, 1, 2)],
        });
        let cypher = value_to_cypher(&path);
        assert_eq!(cypher_to_value(&cypher), path);

        let bad = cypher_to_node(&CypherValue::Int(1)).expect_err("non-node accepted");
        assert!(bad.contains("INTEGER"), "unexpected error: {bad}");
        let bad = cypher_to_relationship(&cypher).expect_err("path accepted as relationship");
        assert!(bad.contains("PATH"), "unexpected error: {bad}");
    }
}