graphforge-value 0.6.0-rc.1

GraphForge checked identity and persisted value contracts
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
//! Compiler-independent literal carrier with the existing tagged JSON encoding.

use graphforge_core::SpatialValue;
use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

// ---------------------------------------------------------------------------
// Literal
// ---------------------------------------------------------------------------

/// A scalar constant value in the Graph IR.
///
/// Temporal values are stored as microseconds since the Unix epoch (UTC),
/// consistent with the Arrow `Timestamp(Microsecond, "UTC")` convention used
/// throughout the project.
///
/// ## Float serialisation
///
/// Finite `Float` values serialise as JSON numbers.  Non-finite IEEE-754 values
/// (`NaN`, `+Infinity`, `-Infinity`) that `serde_json` cannot represent as JSON
/// numbers are encoded as a tagged object `{"$float": "<tag>"}` where `<tag>` is
/// `"NaN"`, `"+Infinity"`, or `"-Infinity"`.  This preserves full round-trip
/// fidelity rather than silently collapsing to `null`.
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    /// The Cypher `null` value.
    Null,
    /// A boolean constant.
    Bool(bool),
    /// A 64-bit integer constant.
    Int(i64),
    /// A 64-bit floating-point constant.
    ///
    /// Non-finite values (NaN, ±Infinity) are supported and round-trip through
    /// JSON via a tagged encoding; see the enum-level docs.
    Float(f64),
    /// A UTF-8 string constant.
    Str(String),
    /// A typed UUID query parameter, stored as its canonical 16-byte identity.
    /// This is not Cypher syntax and must not be inferred from strings.
    Uuid([u8; 16]),
    /// A Cypher duration as signed months/days/nanos (ADR 0009): months and days
    /// kept distinct from sub-day time. Persisted as a `Struct{months,days,nanos}`
    /// (Parquet cannot store Arrow `Interval`). (#920)
    Duration {
        /// Signed whole months.
        months: i64,
        /// Signed whole days.
        days: i64,
        /// Signed whole sub-day seconds (split from `nanos` so billion-year spans
        /// fit `i64`). (#1011)
        seconds: i64,
        /// Signed nanoseconds-of-second, `(-1e9, 1e9)`, same sign as `seconds`.
        nanos: i64,
    },
    /// A point-in-time expressed as microseconds since the Unix epoch (UTC).
    DateTime(i64),
    /// A calendar date as **i64 days** since the Unix epoch — the full openCypher
    /// year range −999,999,999..+999,999,999. Persisted as a self-describing
    /// `Struct{epoch_day: Int64}` (a bare Int64 is indistinguishable from an
    /// integer property). (#920/#1011)
    Date(i64),
    /// A Cypher `localdatetime` (ADR 0009): a date (`days` since the Unix epoch)
    /// plus a time-of-day (`nanos` since midnight), with no zone. Persisted as a
    /// `Struct{date: Int64, time: Time64(ns)}`. (#920/#1011)
    LocalDateTime {
        /// Days since the Unix epoch (i64, full year range).
        days: i64,
        /// Nanoseconds since midnight (Arrow `Time64(ns)`).
        nanos: i64,
    },
    /// A Cypher `localtime` (ADR 0009): a time-of-day in nanoseconds since
    /// midnight, no zone. Persisted as a native Arrow `Time64(ns)` column. (#920)
    Time(i64),
    /// A Cypher `time` (ADR 0009): a time-of-day plus its UTC offset in seconds.
    /// Persisted as a `Struct{time: Time64(ns), offset: Int32}`. (#920)
    ZonedTime {
        /// Nanoseconds since midnight (Arrow `Time64(ns)`).
        nanos: i64,
        /// UTC offset in seconds.
        offset: i32,
    },
    /// A Cypher `datetime` (ADR 0009): a date+time, its UTC offset in seconds,
    /// and an optional named IANA zone. Persisted as a
    /// `Struct{date: Date32, time: Time64(ns), offset: Int32, zone: Utf8}`.
    /// Distinct from [`Literal::DateTime`] (a bare UTC micros instant). (#920/#1011)
    ZonedDateTime {
        /// Days since the Unix epoch (i64, full year range).
        days: i64,
        /// Nanoseconds since midnight (Arrow `Time64(ns)`).
        nanos: i64,
        /// UTC offset in seconds.
        offset: i32,
        /// Named IANA zone, or `None` for an offset-only datetime.
        zone: Option<String>,
    },
    /// A canonical typed spatial property value.
    Spatial(SpatialValue),
    /// A homogeneous list of values, persisted as an Arrow `List<inner>` column
    /// (the inner type is inferred from the elements). Stores e.g. a property
    /// whose value is `[date(…), date(…)]`. Heterogeneous lists are out of scope
    /// (#1005). (#1006)
    List(Vec<Literal>),
    /// A query-parameter map value. Map literals in parsed Cypher still lower as
    /// `IrExpr::MapLiteral`; this variant lets callers bind `$param` to a map
    /// through `execute_with_params` and then use Cypher value access on it.
    Map(Vec<(String, Literal)>),
}

// ---------------------------------------------------------------------------
// Literal — custom Serialize
// ---------------------------------------------------------------------------

impl Serialize for Literal {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        // Delegate all variants except Float to the derived representation by
        // using an internal helper that derives Serialize on a mirrored enum.
        match self {
            Self::Null => LiteralSer::Null.serialize(s),
            Self::Bool(b) => LiteralSer::Bool(*b).serialize(s),
            Self::Int(i) => LiteralSer::Int(*i).serialize(s),
            Self::Str(v) => LiteralSer::Str(v).serialize(s),
            Self::Uuid(v) => LiteralSer::Uuid(v).serialize(s),
            Self::Duration {
                months,
                days,
                seconds,
                nanos,
            } => LiteralSer::Duration(*months, *days, *seconds, *nanos).serialize(s),
            Self::DateTime(dt) => LiteralSer::DateTime(*dt).serialize(s),
            Self::Date(d) => LiteralSer::Date(*d).serialize(s),
            Self::LocalDateTime { days, nanos } => {
                LiteralSer::LocalDateTime(*days, *nanos).serialize(s)
            }
            Self::Time(n) => LiteralSer::Time(*n).serialize(s),
            Self::ZonedTime { nanos, offset } => {
                LiteralSer::ZonedTime(*nanos, *offset).serialize(s)
            }
            Self::ZonedDateTime {
                days,
                nanos,
                offset,
                zone,
            } => LiteralSer::ZonedDateTime(*days, *nanos, *offset, zone.clone()).serialize(s),
            Self::Spatial(value) => LiteralSer::Spatial(value).serialize(s),
            // Each element serialises via `Literal`'s own impl (so nested
            // non-finite floats keep their tagged encoding).
            Self::List(items) => LiteralSer::List(items).serialize(s),
            Self::Map(entries) => LiteralSer::Map(entries).serialize(s),
            Self::Float(f) => {
                if f.is_finite() {
                    LiteralSer::Float(*f).serialize(s)
                } else {
                    // Encode non-finite as {"$float": "<tag>"}
                    let tag = if f.is_nan() {
                        "NaN"
                    } else if *f > 0.0 {
                        "+Infinity"
                    } else {
                        "-Infinity"
                    };
                    let mut map = s.serialize_map(Some(1))?;
                    map.serialize_entry("$float", tag)?;
                    map.end()
                }
            }
        }
    }
}

/// Internal mirror enum used purely to drive derived `Serialize` for the
/// finite/non-float variants of [`Literal`].
#[derive(Serialize)]
#[serde(tag = "type", content = "value")]
enum LiteralSer<'a> {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    Str(&'a str),
    Uuid(&'a [u8; 16]),
    Duration(i64, i64, i64, i64),
    DateTime(i64),
    Date(i64),
    LocalDateTime(i64, i64),
    Time(i64),
    ZonedTime(i64, i32),
    ZonedDateTime(i64, i64, i32, Option<String>),
    Spatial(&'a SpatialValue),
    List(&'a [Literal]),
    Map(&'a [(String, Literal)]),
}

// ---------------------------------------------------------------------------
// Literal — custom Deserialize
// ---------------------------------------------------------------------------

impl<'de> Deserialize<'de> for Literal {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        d.deserialize_any(LiteralVisitor)
    }
}

struct LiteralVisitor;

impl<'de> Visitor<'de> for LiteralVisitor {
    type Value = Literal;

    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "an IrLiteral (tagged object with \"type\"/\"value\" fields, \
             or {{\"$float\": \"NaN\"/\"+Infinity\"/\"-Infinity\"}})"
        )
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
        // Two shapes are valid:
        //   {"$float": "<tag>"}  — non-finite float
        //   {"type": "<Variant>", "value": <data>}  — everything else

        let first_key: String = map
            .next_key()?
            .ok_or_else(|| de::Error::custom("expected at least one map key"))?;

        if first_key == "$float" {
            let tag: String = map.next_value()?;
            let f = match tag.as_str() {
                "NaN" => f64::NAN,
                "+Infinity" => f64::INFINITY,
                "-Infinity" => f64::NEG_INFINITY,
                other => {
                    return Err(de::Error::unknown_variant(
                        other,
                        &["NaN", "+Infinity", "-Infinity"],
                    ));
                }
            };
            return Ok(Literal::Float(f));
        }

        if first_key != "type" {
            return Err(de::Error::unknown_field(&first_key, &["type", "$float"]));
        }

        let variant: String = map.next_value()?;
        // Scan forward through remaining map entries for "value", ignoring
        // any unknown fields along the way so field-order is irrelevant.
        match variant.as_str() {
            "Null" => Ok(Literal::Null),
            "Bool" => Ok(Literal::Bool(read_value_field(&mut map)?)),
            "Int" => Ok(Literal::Int(read_value_field(&mut map)?)),
            "Float" => Ok(Literal::Float(read_value_field(&mut map)?)),
            "Str" => Ok(Literal::Str(read_value_field(&mut map)?)),
            "Uuid" => Ok(Literal::Uuid(read_value_field(&mut map)?)),
            "Duration" => {
                let (months, days, seconds, nanos) = read_value_field(&mut map)?;
                Ok(Literal::Duration {
                    months,
                    days,
                    seconds,
                    nanos,
                })
            }
            "DateTime" => Ok(Literal::DateTime(read_value_field(&mut map)?)),
            "Date" => Ok(Literal::Date(read_value_field(&mut map)?)),
            "LocalDateTime" => {
                let (days, nanos) = read_value_field(&mut map)?;
                Ok(Literal::LocalDateTime { days, nanos })
            }
            "Time" => Ok(Literal::Time(read_value_field(&mut map)?)),
            "ZonedTime" => {
                let (nanos, offset) = read_value_field(&mut map)?;
                Ok(Literal::ZonedTime { nanos, offset })
            }
            "ZonedDateTime" => {
                let (days, nanos, offset, zone) = read_value_field(&mut map)?;
                Ok(Literal::ZonedDateTime {
                    days,
                    nanos,
                    offset,
                    zone,
                })
            }
            "Spatial" => Ok(Literal::Spatial(read_value_field(&mut map)?)),
            "List" => Ok(Literal::List(read_value_field(&mut map)?)),
            "Map" => Ok(Literal::Map(read_value_field(&mut map)?)),
            other => Err(de::Error::unknown_variant(
                other,
                &[
                    "Null",
                    "Bool",
                    "Int",
                    "Float",
                    "Str",
                    "Uuid",
                    "Duration",
                    "DateTime",
                    "Date",
                    "LocalDateTime",
                    "Time",
                    "ZonedTime",
                    "ZonedDateTime",
                    "Spatial",
                    "List",
                    "Map",
                ],
            )),
        }
    }
}

/// Scan `map` for a key named `"value"`, skipping any unrecognised keys, and
/// deserialise its value as `T`.  Returns `de::Error::missing_field("value")`
/// if the key is not found.
fn read_value_field<'de, T, A>(map: &mut A) -> Result<T, A::Error>
where
    T: Deserialize<'de>,
    A: MapAccess<'de>,
{
    while let Some(key) = map.next_key::<String>()? {
        if key == "value" {
            return map.next_value();
        }
        let _: de::IgnoredAny = map.next_value()?;
    }
    Err(de::Error::missing_field("value"))
}

#[cfg(test)]
mod tests {
    use super::Literal;
    use graphforge_core::{
        SpatialCoordinates, SpatialCrs, SpatialGeometryType, SpatialType, SpatialValue,
    };

    #[test]
    fn literal_json_golden_vectors_preserve_existing_wire_encoding() {
        // These bytes pin the pre-extraction IrLiteral serializer: adjacent
        // type/value tags, tuple temporal payloads, and ordered map entries.
        let vectors = [
            (Literal::Null, r#"{"type":"Null"}"#),
            (Literal::Bool(true), r#"{"type":"Bool","value":true}"#),
            (Literal::Int(-7), r#"{"type":"Int","value":-7}"#),
            (Literal::Float(2.5), r#"{"type":"Float","value":2.5}"#),
            (
                Literal::Str("line\n\"quoted\"".into()),
                r#"{"type":"Str","value":"line\n\"quoted\""}"#,
            ),
            (
                Literal::Uuid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
                r#"{"type":"Uuid","value":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]}"#,
            ),
            (
                Literal::Duration {
                    months: 1,
                    days: -2,
                    seconds: 3,
                    nanos: 4,
                },
                r#"{"type":"Duration","value":[1,-2,3,4]}"#,
            ),
            (Literal::DateTime(-1), r#"{"type":"DateTime","value":-1}"#),
            (
                Literal::Date(3_000_000_000),
                r#"{"type":"Date","value":3000000000}"#,
            ),
            (
                Literal::LocalDateTime {
                    days: 3_000_000_000,
                    nanos: 42,
                },
                r#"{"type":"LocalDateTime","value":[3000000000,42]}"#,
            ),
            (Literal::Time(42), r#"{"type":"Time","value":42}"#),
            (
                Literal::ZonedTime {
                    nanos: 42,
                    offset: -3600,
                },
                r#"{"type":"ZonedTime","value":[42,-3600]}"#,
            ),
            (
                Literal::ZonedDateTime {
                    days: 1,
                    nanos: 42,
                    offset: 3600,
                    zone: Some("Europe/Paris".into()),
                },
                r#"{"type":"ZonedDateTime","value":[1,42,3600,"Europe/Paris"]}"#,
            ),
            (
                Literal::ZonedDateTime {
                    days: 1,
                    nanos: 42,
                    offset: 0,
                    zone: None,
                },
                r#"{"type":"ZonedDateTime","value":[1,42,0,null]}"#,
            ),
            (
                Literal::Spatial(SpatialValue {
                    spatial_type: SpatialType {
                        geometry: SpatialGeometryType::Point,
                        crs: SpatialCrs::Epsg4326,
                    },
                    coordinates: SpatialCoordinates::Point([1.0, 2.0]),
                    extension_name: None,
                    extension_metadata: None,
                }),
                r#"{"type":"Spatial","value":{"spatial_type":{"geometry":"point","crs":"EPSG:4326"},"coordinates":{"Point":[1.0,2.0]}}}"#,
            ),
            (
                Literal::List(vec![Literal::Int(1), Literal::Null]),
                r#"{"type":"List","value":[{"type":"Int","value":1},{"type":"Null"}]}"#,
            ),
            (
                Literal::Map(vec![
                    ("z".into(), Literal::Bool(false)),
                    ("a".into(), Literal::List(vec![])),
                ]),
                r#"{"type":"Map","value":[["z",{"type":"Bool","value":false}],["a",{"type":"List","value":[]}]]}"#,
            ),
        ];
        for (value, expected) in vectors {
            assert_eq!(serde_json::to_string(&value).unwrap(), expected);
            assert_eq!(serde_json::from_str::<Literal>(expected).unwrap(), value);
        }
    }

    #[test]
    fn nonfinite_literal_json_golden_vectors_preserve_nested_tags() {
        for (number, expected) in [
            (f64::NAN, r#"{"$float":"NaN"}"#),
            (f64::INFINITY, r#"{"$float":"+Infinity"}"#),
            (f64::NEG_INFINITY, r#"{"$float":"-Infinity"}"#),
        ] {
            assert_eq!(
                serde_json::to_string(&Literal::Float(number)).unwrap(),
                expected
            );
            let Literal::Float(decoded) = serde_json::from_str::<Literal>(expected).unwrap() else {
                panic!("nonfinite tag must remain a float");
            };
            if number.is_nan() {
                assert!(decoded.is_nan());
            } else {
                assert_eq!(decoded, number);
            }
        }
        let nested = Literal::List(vec![Literal::Map(vec![
            ("nan".into(), Literal::Float(f64::NAN)),
            (
                "infinities".into(),
                Literal::List(vec![
                    Literal::Float(f64::INFINITY),
                    Literal::Float(f64::NEG_INFINITY),
                ]),
            ),
        ])]);
        let expected = r#"{"type":"List","value":[{"type":"Map","value":[["nan",{"$float":"NaN"}],["infinities",{"type":"List","value":[{"$float":"+Infinity"},{"$float":"-Infinity"}]}]]}]}"#;
        assert_eq!(serde_json::to_string(&nested).unwrap(), expected);
        let decoded: Literal = serde_json::from_str(expected).unwrap();
        assert_eq!(serde_json::to_string(&decoded).unwrap(), expected);
    }
}