relate_core/value/mod.rs
1use std::collections::BTreeMap;
2use std::fmt;
3use std::ops::ControlFlow;
4use std::sync::Arc;
5
6pub use relate_model::value::PointValue;
7pub use relate_model::VectorCoordKind;
8pub use relate_model::{Coord, VectorCoords};
9
10use relate_model::identifier::quote_identifier_shaped;
11
12use crate::temporal::Temporal;
13use crate::{Error, NodeId, RelId};
14
15mod depth;
16mod json;
17mod ordering;
18mod pretty;
19mod props;
20pub(crate) use depth::{descends, DEPTH_LIMIT_MARKER};
21pub use depth::{next_depth, value_depth_exceeded, MAX_VALUE_DEPTH};
22pub use json::{pack_decoded_values, tagged_str, TaggedStr};
23pub use props::PropertyMap;
24
25#[derive(Debug, Clone, PartialEq)]
26pub struct Node {
27 pub id: NodeId,
28 pub labels: Arc<Vec<String>>,
29 pub properties: Arc<PropertyMap>,
30}
31
32#[derive(Debug, Clone, PartialEq)]
33pub struct Relationship {
34 pub id: RelId,
35 pub start: NodeId,
36 pub end: NodeId,
37 pub rel_type: String,
38 pub properties: Arc<PropertyMap>,
39}
40
41#[derive(Debug, Clone, PartialEq)]
42pub struct Path {
43 pub nodes: Vec<Node>,
44 pub rels: Vec<Relationship>,
45}
46
47/// OpenCypher runtime value.
48#[derive(Debug, Clone, PartialEq, Default)]
49pub enum Value {
50 #[default]
51 Null,
52 Bool(bool),
53 Int(i64),
54 Float(f64),
55 String(Arc<str>),
56 List(Arc<Vec<Value>>),
57 Map(Arc<BTreeMap<String, Value>>),
58 Node(Arc<Node>),
59 Relationship(Arc<Relationship>),
60 Path(Arc<Path>),
61 Temporal(Temporal),
62 Point(PointValue),
63 /// CIP-246 UUID: 128-bit value, rendered as the canonical lowercase
64 /// hyphenated string (`to_display_string`/`iso`-style bare form) and
65 /// constructible from a string or two 64-bit halves.
66 Uuid(u128),
67 /// CIP-200 VECTOR runtime value, its coordinates packed per family
68 /// (ADR-0706): one `Arc`-ed slice — `f32` for the reduced float kinds,
69 /// `f64` for FLOAT, `i64` for the integer kinds — 4/8/8 bytes per
70 /// coordinate where `Arc<Vec<Value>>` paid 48. Homogeneous and
71 /// kind-exact by construction: the canonical [`Value::vector`]
72 /// constructor is the only way to produce one. A rewrite swaps the
73 /// `Arc`; the MVCC version chain is the invalidation, so nothing
74 /// scan-side copies or tracks vector coordinates.
75 Vector {
76 coord: VectorCoordKind,
77 coords: VectorCoords,
78 },
79 /// A byte array (ADR-0327). Statement-scoped: it enters only as a query
80 /// parameter (Bolt PackStream Bytes) and flows through expressions,
81 /// lists and maps into results; storing it as a property fails with a
82 /// typed `TypeError`. Shared payload like `String` (ADR-0170).
83 Bytes(Arc<[u8]>),
84}
85
86// Query results cross worker threads, so the shared payloads must keep
87// `Value: Send + Sync` (ADR-0170).
88const _: () = {
89 const fn assert_send_sync<T: Send + Sync>() {}
90 assert_send_sync::<Value>();
91};
92
93/// Whether the summed logical bytes (ADR-0042, as
94/// [`Value::logical_bytes`]) of `values` stay within `limit`, or `None`
95/// once the running total exceeds it. The one early-stopping logical-bytes
96/// walk (ADR-0341): the total stops being computed as soon as it exceeds
97/// `limit` instead of walking every value.
98///
99/// Shared payloads (ADR-0170) still count once per reference: many rows
100/// holding one large list are small in memory but large in logical bytes,
101/// and an unbounded sum over them does work proportional to the product.
102/// The Bolt server sums its open results against one connection-wide cap
103/// with it (ADR-0311).
104pub fn logical_bytes_within<'a>(
105 values: impl IntoIterator<Item = &'a Value>,
106 limit: u64,
107) -> Option<u64> {
108 logical_bytes_within_memo(values, limit, &mut ExpansionMemo::off())
109}
110
111/// [`logical_bytes_within`] with the container payloads it measures
112/// remembered in `memo` (ADR-0691): a payload met again, under another row
113/// or wrapped by a fresh container, costs one lookup instead of a re-walk,
114/// so the work is linear in the *distinct* payloads. The sizes are keyed by
115/// allocation address: every value passed must stay alive while `memo`
116/// does (a freed allocation's address may be reused), so a caller scopes
117/// one memo to values it holds for the call.
118pub fn logical_bytes_within_memo<'a>(
119 values: impl IntoIterator<Item = &'a Value>,
120 limit: u64,
121 memo: &mut ExpansionMemo,
122) -> Option<u64> {
123 let mut total = 0;
124 let over = values
125 .into_iter()
126 .try_for_each(|v| v.add_logical_bytes(&mut total, limit, 0, memo))
127 .is_break();
128 (!over).then_some(total)
129}
130
131/// The logical size of each container payload a [`logical_bytes_within_memo`]
132/// walk finished measuring, keyed by [`depth::payload_key`] (the identity
133/// ADR-0462's depth memo uses). A payload's size is its own contents',
134/// independent of where it sits, so a hit adds the stored size; the depth
135/// guard is unreachable behind the checked constructors, so the memo
136/// ignores the level a payload was first met at. `Default` is the
137/// remembering memo, like [`ExpansionMemo::new`]; the memo-free form is
138/// private.
139pub struct ExpansionMemo {
140 /// `None` is the memo-free walk [`logical_bytes_within`] runs.
141 sizes: Option<std::collections::HashMap<depth::PayloadKey, u64>>,
142}
143
144impl Default for ExpansionMemo {
145 fn default() -> Self {
146 Self::new()
147 }
148}
149
150impl ExpansionMemo {
151 /// A memo that remembers.
152 pub fn new() -> Self {
153 Self {
154 sizes: Some(Default::default()),
155 }
156 }
157
158 /// The memo [`logical_bytes_within`] walks with: remembers nothing.
159 fn off() -> Self {
160 Self { sizes: None }
161 }
162
163 /// Open the container `payload` met `enclosing` levels deep — the one
164 /// place the ADR-0462 depth guard and the memo wrap meet — and add what
165 /// it holds to `acc`: its remembered size when known, otherwise what
166 /// `body` adds at the next level (remembered once `body` completes; a
167 /// walk that broke at the budget measured nothing complete).
168 fn open<T>(
169 &mut self,
170 enclosing: u32,
171 payload: &Arc<T>,
172 acc: &mut u64,
173 budget: u64,
174 body: impl FnOnce(&mut Self, &mut u64, u32) -> ControlFlow<()>,
175 ) -> ControlFlow<()> {
176 let Some(next) = next_depth(enclosing) else {
177 return ControlFlow::Break(());
178 };
179 let Some(sizes) = self.sizes.as_mut() else {
180 return body(self, acc, next);
181 };
182 let key = depth::payload_key(payload);
183 if let Some(size) = sizes.get(&key) {
184 return add_bytes(acc, *size, budget);
185 }
186 let before = *acc;
187 body(self, acc, next)?;
188 if let Some(sizes) = self.sizes.as_mut() {
189 sizes.insert(key, *acc - before);
190 }
191 ControlFlow::Continue(())
192 }
193}
194
195/// Adds `bytes` to `acc` (saturating) and breaks once `acc` exceeds `budget`.
196fn add_bytes(acc: &mut u64, bytes: u64, budget: u64) -> ControlFlow<()> {
197 *acc = acc.saturating_add(bytes);
198 if *acc > budget {
199 ControlFlow::Break(())
200 } else {
201 ControlFlow::Continue(())
202 }
203}
204
205/// Add one string's logical size — [`str_logical_bytes`] is the one
206/// spelling of the size; this is only its budgeted accumulation.
207fn add_str_bytes(s: &str, acc: &mut u64, budget: u64) -> ControlFlow<()> {
208 add_bytes(acc, str_logical_bytes(s), budget)
209}
210
211/// Add one byte payload's logical size (`Value::Bytes`): header 16 plus
212/// its length — the same shape [`str_logical_bytes`] spells for a
213/// string's UTF-8 bytes.
214fn add_payload_bytes(payload: &[u8], acc: &mut u64, budget: u64) -> ControlFlow<()> {
215 add_bytes(acc, bytes_logical_bytes(payload), budget)
216}
217
218fn add_property_bytes<'a>(
219 props: impl IntoIterator<Item = (&'a String, &'a Value)>,
220 acc: &mut u64,
221 budget: u64,
222 depth: u32,
223 memo: &mut ExpansionMemo,
224) -> ControlFlow<()> {
225 props.into_iter().try_for_each(|(k, v)| {
226 add_str_bytes(k, acc, budget)?;
227 v.add_logical_bytes(acc, budget, depth, memo)
228 })
229}
230
231fn add_node_bytes(
232 n: &Node,
233 acc: &mut u64,
234 budget: u64,
235 depth: u32,
236 memo: &mut ExpansionMemo,
237) -> ControlFlow<()> {
238 n.labels
239 .iter()
240 .try_for_each(|l| add_str_bytes(l, acc, budget))?;
241 add_property_bytes(n.properties.iter(), acc, budget, depth, memo)
242}
243
244fn add_rel_bytes(
245 r: &Relationship,
246 acc: &mut u64,
247 budget: u64,
248 depth: u32,
249 memo: &mut ExpansionMemo,
250) -> ControlFlow<()> {
251 add_str_bytes(&r.rel_type, acc, budget)?;
252 add_property_bytes(r.properties.iter(), acc, budget, depth, memo)
253}
254
255/// A string's documented logical size (ADR-0042): the 16-byte header
256/// plus its UTF-8 bytes — the one spelling every string-size sum reads
257/// (row keys, node and relationship property keys), beside
258/// [`Value::logical_bytes`].
259#[inline]
260pub fn str_logical_bytes(s: &str) -> u64 {
261 payload_logical_bytes(s.len() as u64)
262}
263
264/// A byte payload's documented logical size (ADR-0042): the 16-byte header
265/// plus its bytes — the one spelling every payload-size site reads, beside
266/// [`str_logical_bytes`] and [`Value::logical_bytes`].
267#[inline]
268pub fn bytes_logical_bytes(payload: &[u8]) -> u64 {
269 payload_logical_bytes(payload.len() as u64)
270}
271
272/// A length-prefixed payload's documented logical size (ADR-0042): the
273/// 16-byte header plus `len` bytes — the one place the header lives, read
274/// by strings, byte payloads and a vector's packed buffer.
275#[inline]
276pub(crate) fn payload_logical_bytes(len: u64) -> u64 {
277 16 + len
278}
279
280impl Value {
281 /// The one way a `Vector` is built (ADR-0706) — the core twin of
282 /// `CypherValue::vector`, sharing the one invariant spelling
283 /// ([`VectorCoords::assert_conforms`]). No site constructs the
284 /// variant by hand.
285 pub fn vector(coord: VectorCoordKind, coords: VectorCoords) -> Self {
286 coords.assert_conforms(coord);
287 Value::Vector { coord, coords }
288 }
289
290 /// Share one node across every row that clones this value.
291 pub fn from_node(node: Node) -> Self {
292 Value::Node(Arc::new(node))
293 }
294
295 /// Share one relationship across every row that clones this value.
296 pub fn from_relationship(rel: Relationship) -> Self {
297 Value::Relationship(Arc::new(rel))
298 }
299
300 /// Share one path across every row that clones this value.
301 pub fn from_path(path: Path) -> Self {
302 Value::Path(Arc::new(path))
303 }
304
305 /// Documented logical payload size (ADR-0042) — the per-variant
306 /// accumulation of the sizes [`str_logical_bytes`] spells for
307 /// strings.
308 pub fn logical_bytes(&self) -> u64 {
309 let mut total = 0;
310 let flow = self.add_logical_bytes(&mut total, u64::MAX, 0, &mut ExpansionMemo::off());
311 // The byte budget is `u64::MAX`, so the only reachable `Break` is
312 // the ADR-0462 depth guard: were it to fire (unreachable behind the
313 // checked constructors) the result would be the partial sum counted
314 // down to the cap rather than a panic, since this walk has no error
315 // channel.
316 debug_assert!(
317 flow.is_continue(),
318 "logical_bytes broke on the ADR-0462 depth guard at the cap"
319 );
320 total
321 }
322
323 /// The single implementation of the ADR-0042 formula, shared by
324 /// [`Value::logical_bytes`] (budget `u64::MAX`, never breaks) and
325 /// [`logical_bytes_within`]: adds this value's logical bytes to `acc`
326 /// and breaks as soon as `acc` exceeds `budget`.
327 ///
328 /// `depth` is the level of the container whose contents are being
329 /// added; past [`MAX_VALUE_DEPTH`] the walk breaks (ADR-0462). The
330 /// guard is unreachable behind the checked constructors and only keeps
331 /// an over-deep value from recursing without a byte budget to stop it.
332 fn add_logical_bytes(
333 &self,
334 acc: &mut u64,
335 budget: u64,
336 depth: u32,
337 memo: &mut ExpansionMemo,
338 ) -> ControlFlow<()> {
339 match self {
340 Value::Null | Value::Bool(_) => add_bytes(acc, 1, budget),
341 Value::Int(_) | Value::Float(_) => add_bytes(acc, 8, budget),
342 Value::String(s) => add_str_bytes(s, acc, budget),
343 Value::Bytes(b) => add_payload_bytes(b, acc, budget),
344 Value::List(xs) => memo.open(depth, xs, acc, budget, |memo, acc, next| {
345 add_bytes(acc, 16, budget)?;
346 xs.iter()
347 .try_for_each(|x| x.add_logical_bytes(acc, budget, next, memo))
348 }),
349 // The packed coordinates are not child Values (ADR-0706):
350 // nothing descends and the charge is a pure function of the
351 // buffer's length, so it goes straight to `add_bytes` — a memo
352 // entry could not change it. The figure is the buffer's real
353 // footprint (`byte_len`, the one width table), so a FLOAT32
354 // vector charges 4 bytes per coordinate, not the 8 the
355 // `Vec<Value>` walk charged.
356 Value::Vector { coords, .. } => {
357 add_bytes(acc, payload_logical_bytes(coords.byte_len()), budget)
358 }
359 Value::Map(m) => memo.open(depth, m, acc, budget, |memo, acc, next| {
360 add_bytes(acc, 16, budget)?;
361 add_property_bytes(m.iter(), acc, budget, next, memo)
362 }),
363 Value::Node(n) => memo.open(depth, n, acc, budget, |memo, acc, next| {
364 add_node_bytes(n, acc, budget, next, memo)
365 }),
366 Value::Relationship(r) => memo.open(depth, r, acc, budget, |memo, acc, next| {
367 add_rel_bytes(r, acc, budget, next, memo)
368 }),
369 Value::Path(p) => memo.open(depth, p, acc, budget, |memo, acc, next| {
370 p.nodes
371 .iter()
372 .try_for_each(|n| add_node_bytes(n, acc, budget, next, memo))?;
373 p.rels
374 .iter()
375 .try_for_each(|r| add_rel_bytes(r, acc, budget, next, memo))
376 }),
377 Value::Temporal(_) => add_bytes(acc, 24, budget),
378 Value::Point(_) => add_bytes(acc, 32, budget),
379 Value::Uuid(_) => add_bytes(acc, 16, budget),
380 }
381 }
382
383 pub fn as_temporal(&self) -> Option<&Temporal> {
384 match self {
385 Value::Temporal(t) => Some(t),
386 _ => None,
387 }
388 }
389
390 pub fn as_string(&self) -> Option<&str> {
391 match self {
392 Value::String(s) => Some(&**s),
393 _ => None,
394 }
395 }
396
397 pub fn is_null(&self) -> bool {
398 matches!(self, Value::Null)
399 }
400
401 pub fn as_bool(&self) -> Option<bool> {
402 match self {
403 Value::Bool(b) => Some(*b),
404 _ => None,
405 }
406 }
407
408 /// Cypher toBoolean-ish: true/false stay, null stays none.
409 pub fn truthy(&self) -> Option<bool> {
410 match self {
411 Value::Bool(b) => Some(*b),
412 Value::Null => None,
413 _ => None,
414 }
415 }
416
417 pub fn as_number(&self) -> Option<f64> {
418 match self {
419 Value::Int(i) => Some(*i as f64),
420 Value::Float(f) => Some(*f),
421 _ => None,
422 }
423 }
424
425 pub fn as_int(&self) -> Option<i64> {
426 match self {
427 Value::Int(i) => Some(*i),
428 Value::Float(f)
429 if f.fract() == 0.0 && *f >= i64::MIN as f64 && *f <= i64::MAX as f64 =>
430 {
431 Some(*f as i64)
432 }
433 _ => None,
434 }
435 }
436
437 pub fn to_cypher_literal(&self) -> String {
438 self.to_cypher_literal_at(0)
439 }
440
441 /// [`Value::to_cypher_literal`] with the ADR-0462 depth guard: a
442 /// container past [`MAX_VALUE_DEPTH`] renders
443 /// [`DEPTH_LIMIT_MARKER`] instead of recursing. `depth` is the number of
444 /// containers enclosing `self`, so a root is 0 and its children 1.
445 fn to_cypher_literal_at(&self, depth: u32) -> String {
446 match self {
447 Value::Null => "null".into(),
448 Value::Bool(true) => "true".into(),
449 Value::Bool(false) => "false".into(),
450 Value::Int(i) => i.to_string(),
451 Value::Float(f) => relate_model::value::float_text(*f),
452 Value::String(s) => format!("'{}'", escape_cypher_string(s)),
453 Value::Bytes(b) => bytes_as_int_list(b),
454 Value::List(xs) => guarded_container(
455 depth,
456 |joined| format!("[{joined}]"),
457 |d| xs.iter().map(|v| v.to_cypher_literal_at(d)).collect(),
458 ),
459 Value::Map(m) => guarded_container(
460 depth,
461 |joined| format!("{{{joined}}}"),
462 |d| map_to_cypher_literal(m.iter(), d),
463 ),
464 Value::Node(n) => n.to_cypher_literal_at(depth),
465 Value::Relationship(r) => r.to_cypher_literal_at(depth),
466 Value::Path(p) => p.to_cypher_literal_at(depth),
467 Value::Temporal(t) => format!("'{}'", escape_cypher_string(&t.iso_string())),
468 // Round-trippable form like VECTOR: uuid('...') (CIP-246).
469 Value::Uuid(u) => format!("uuid('{}')", uuid_hyphenated(*u)),
470 Value::Point(p) => p.to_string(),
471 Value::Vector { coord, coords } => {
472 // Packed coordinates render through the one vector
473 // rendering (ADR-0706) — identical output, no child walk,
474 // so no depth guard to thread.
475 vector_text(coords, *coord)
476 }
477 }
478 }
479
480 /// The CIP-271 `toString()` rendering: the cypher-shell display form
481 /// rather than the round-trippable literal form — strings are unquoted,
482 /// temporals are bare full-precision ISO strings (ADR-0448), and
483 /// maps/lists render recursively with `, ` separators (verified
484 /// against Neo4j 2026.09.0).
485 pub fn to_display_string(&self) -> String {
486 self.to_display_string_at(0)
487 }
488
489 /// [`Value::to_display_string`] with the ADR-0462 `depth` guard (the
490 /// number of containers enclosing `self`); a container past
491 /// [`MAX_VALUE_DEPTH`] renders [`DEPTH_LIMIT_MARKER`].
492 fn to_display_string_at(&self, depth: u32) -> String {
493 match self {
494 Value::Null => "null".into(),
495 Value::Bool(b) => b.to_string(),
496 Value::Int(i) => i.to_string(),
497 Value::Float(f) => relate_model::value::float_text(*f),
498 // Unquoted: Neo4j 2026.09.0 renders toString({a:'x y'}) as
499 // "{a: x y}".
500 Value::String(s) => String::from(&**s),
501 Value::Bytes(b) => bytes_as_int_list(b),
502 Value::List(xs) => guarded_container(
503 depth,
504 |joined| format!("[{joined}]"),
505 |d| xs.iter().map(|v| v.to_display_string_at(d)).collect(),
506 ),
507 // A key outside the plain identifier shape is backticked
508 // (CIP-271: `{`123`: digit key, `a.b`: dot, `first name`:
509 // Alice}`); the map's own iteration order is already the
510 // sorted one.
511 Value::Map(m) => guarded_container(
512 depth,
513 |joined| format!("{{{joined}}}"),
514 |d| {
515 m.iter()
516 .map(|(k, v)| {
517 format!(
518 "{}: {}",
519 quote_identifier_shaped(k),
520 v.to_display_string_at(d)
521 )
522 })
523 .collect()
524 },
525 ),
526 Value::Node(n) => node_display(n),
527 Value::Relationship(r) => relationship_display(r),
528 // No depth: the display walk renders no properties, so it never
529 // recurses and has no ADR-0462 budget to thread.
530 Value::Path(p) => p.display_string(),
531 Value::Temporal(t) => t.full_seconds_string(),
532 // Bare hyphenated string (verified on 2026.09.0).
533 Value::Uuid(u) => uuid_hyphenated(*u),
534 Value::Point(pt) => point_display(pt),
535 Value::Vector { coord, coords } => {
536 // No depth: like the Path arm above, a packed vector has
537 // no child Values to render — nothing recurses.
538 vector_text(coords, *coord)
539 }
540 }
541 }
542}
543
544/// One component accessor of a point (`p.x`, `p.longitude`, `p.crs`, …) —
545/// the one point-accessor vocabulary, the data-model sibling of the
546/// temporal accessor ([`crate::temporal::Temporal::component`]): a key no
547/// component names is the same typed rejection the temporal reader answers,
548/// never a silently null read. The coordinate aliases (`x` is `longitude`)
549/// are the shared axis vocabulary beside [`PointValue`].
550///
551/// Which axis spellings a point exposes is live Neo4j 2026.10.1's rule
552/// (probed 2026-11-11): a cartesian point has only the cartesian
553/// spellings (`x`/`y`/`z`), a geographic point accepts both (`x` and
554/// `longitude`, …), and the third axis exists only on a 3D point. An
555/// unavailable spelling is `ArgumentError` "Field: <key> is not
556/// available", not a null read.
557pub fn point_component(p: &PointValue, key: &str) -> Result<Value, Error> {
558 let name = key.to_ascii_lowercase();
559 Ok(match name.as_str() {
560 "srid" => Value::Int(i64::from(p.srid)),
561 // The canonical CRS spelling; a decoder-supplied srid/dimensionality
562 // pair outside the four canonical codes keeps the srid table's
563 // spelling rather than claiming no CRS.
564 "crs" => Value::String(
565 p.crs_name()
566 .unwrap_or_else(|| relate_model::wire::crs_name(p.srid))
567 .into(),
568 ),
569 _ => {
570 let Some(axis) = relate_model::point::point_axis(&name) else {
571 // 22G03 invalid argument, not a runtime TypeError.
572 return Err(Error::argument_error(format!(
573 "no such component '{key}' on a point value"
574 )));
575 };
576 // A cartesian point has no geographic spelling; any point has
577 // the third axis only when it is 3D (`p.z` is its presence).
578 let cartesian = !relate_model::point::is_geographic(p.srid);
579 let unavailable =
580 (cartesian && axis.key(true) == name) || (axis.index == 2 && p.z.is_none());
581 if unavailable {
582 return Err(Error::argument_error(format!(
583 "Field: {key} is not available on a point value"
584 )));
585 }
586 match axis.index {
587 0 => Value::Float(p.x),
588 1 => Value::Float(p.y),
589 _ => Value::Float(p.z.expect("the 3D check admitted only a present z")),
590 }
591 }
592 })
593}
594
595/// The Neo4j text form of a point (the CIP-271 display policy `toString()`
596/// and string concatenation use): `point({x: 1.0, y: 2.0, crs:
597/// 'cartesian'})`. Coordinates render through the float-literal policy (so
598/// an integral coordinate keeps its `.0`), a 3D point adds `z`, and the CRS
599/// name comes from [`PointValue::crs_name`]. A srid/dimensionality pair
600/// outside the four `point()` codes — only reachable from a decoder, never
601/// from `point()` — renders the srid spelling rather than claiming a CRS
602/// the value does not have.
603fn point_display(p: &PointValue) -> String {
604 let coord = |value: f64| Value::Float(value).to_cypher_literal();
605 match (p.crs_name(), p.z) {
606 (Some(crs), Some(z)) => format!(
607 "point({{x: {}, y: {}, z: {}, crs: '{crs}'}})",
608 coord(p.x),
609 coord(p.y),
610 coord(z)
611 ),
612 (Some(crs), None) => format!(
613 "point({{x: {}, y: {}, crs: '{crs}'}})",
614 coord(p.x),
615 coord(p.y)
616 ),
617 (None, Some(z)) => format!(
618 "point({{srid: {}, x: {}, y: {}, z: {}}})",
619 p.srid,
620 coord(p.x),
621 coord(p.y),
622 coord(z)
623 ),
624 (None, None) => format!(
625 "point({{srid: {}, x: {}, y: {}}})",
626 p.srid,
627 coord(p.x),
628 coord(p.y)
629 ),
630 }
631}
632
633/// The `vector([…], N, COORD)` text shape shared by the literal and
634/// display renderers; `joined` is the already-rendered, `, `-joined
635/// coordinate list ([`guarded_container`] made the join — this wrap keeps
636/// the whole value-constructor form, CIP-271: a vector VALUE renders as
637/// `vector([1, 2], 2, INTEGER8)` — the coordinate type is the third
638/// argument, not a `NOT NULL`-suffixed type expression (that is the
639/// TYPE rendering's own path, e.g. `valueType()`).
640/// The one vector rendering (ADR-0706): a packed vector's coordinates in
641/// their scalar text, the family's canonical name, and the derived
642/// dimension — the literal and display walks both call this, so the two
643/// cannot drift.
644fn vector_text(coords: &VectorCoords, coord: VectorCoordKind) -> String {
645 let joined = coords
646 .iter()
647 .map(|c| c.text())
648 .collect::<Vec<_>>()
649 .join(", ");
650 format!(
651 "vector([{joined}], {}, {})",
652 coords.len(),
653 coord.canonical_name()
654 )
655}
656
657impl Node {
658 pub fn to_cypher_literal(&self) -> String {
659 self.to_cypher_literal_at(0)
660 }
661
662 /// [`Node::to_cypher_literal`] with the ADR-0462 `depth` (the number of
663 /// containers enclosing this node).
664 fn to_cypher_literal_at(&self, depth: u32) -> String {
665 let Some(next) = next_depth(depth) else {
666 return DEPTH_LIMIT_MARKER.into();
667 };
668 let labels: String = self.labels.iter().map(|l| format!(":{l}")).collect();
669 let props = props_suffix(&self.properties, next);
670 format!("({labels}{props})")
671 }
672}
673
674impl Relationship {
675 pub fn to_cypher_literal(&self) -> String {
676 self.to_cypher_literal_at(0)
677 }
678
679 /// [`Relationship::to_cypher_literal`] with the ADR-0462 `depth`.
680 fn to_cypher_literal_at(&self, depth: u32) -> String {
681 let Some(next) = next_depth(depth) else {
682 return DEPTH_LIMIT_MARKER.into();
683 };
684 let props = props_suffix(&self.properties, next);
685 format!("[:{}{}]", self.rel_type, props)
686 }
687}
688
689impl Path {
690 pub fn to_cypher_literal(&self) -> String {
691 self.to_cypher_literal_at(0)
692 }
693
694 /// [`Path::to_cypher_literal`] with the ADR-0462 `depth`.
695 fn to_cypher_literal_at(&self, depth: u32) -> String {
696 // The path itself is the container (`depth + 1`); its embedded
697 // entities are not an extra level, so they get `depth`.
698 if next_depth(depth).is_none() {
699 return DEPTH_LIMIT_MARKER.into();
700 }
701 format!(
702 "<{}>",
703 self.walk(
704 |n| n.to_cypher_literal_at(depth),
705 |r, current| directed(direction_arrows(r, current), r.to_cypher_literal_at(depth))
706 )
707 )
708 }
709
710 /// The CIP-271 `toString()` form of a path: no enclosing `<…>` and no
711 /// properties — the same label-only / type-only element rendering a
712 /// standalone node or relationship gets (Neo4j 2026.10.1 renders
713 /// `toString(path)` as `(:A)-[:FIRST]->(:B)<-[:SECOND]-(:C)`). The
714 /// display walk renders no properties, so nothing recurses and no
715 /// depth budget applies — the literal twin's guard bounds its own
716 /// property-rendering recursion, not this walk.
717 fn display_string(&self) -> String {
718 self.walk(node_display, |r, current| {
719 directed(direction_arrows(r, current), relationship_display(r))
720 })
721 }
722
723 /// The path's element chain — one node then, if the path continues
724 /// past it, the relationship traversed from it. `node` renders one
725 /// node; `rel` renders one relationship and receives the current
726 /// node's id, the one bit of direction that is always defined: the
727 /// literal and display walks compose their [`direction_arrows`] from
728 /// it, the pretty walk ignores it for its self-dashed form.
729 ///
730 /// The shape — a path is nothing, or a node followed by
731 /// node–relationship–node links — is a **debug** assertion: the
732 /// engine's own constructors always produce it (a violation is an
733 /// engine bug and fails loudly in debug and test builds), while
734 /// `Path`'s public fields let a foreign value (a wire decoder, an
735 /// external binding) carry any shape — and rendering is infallible,
736 /// so a malformed foreign path renders its well-formed prefix
737 /// instead of panicking the library.
738 fn walk(
739 &self,
740 node: impl Fn(&Node) -> String,
741 rel: impl Fn(&Relationship, NodeId) -> String,
742 ) -> String {
743 debug_assert!(
744 self.nodes.len() == self.rels.len() + 1
745 || (self.nodes.is_empty() && self.rels.is_empty()),
746 "a path is a node, then node-relationship-node links - or empty"
747 );
748 let mut s = String::new();
749 if let Some(first) = self.nodes.first() {
750 s.push_str(&node(first));
751 for (i, r) in self.rels.iter().enumerate() {
752 let (Some(current), Some(next)) = (self.nodes.get(i), self.nodes.get(i + 1)) else {
753 // A relationship beyond the nodes it connects — the
754 // malformed shape the debug assertion above names.
755 break;
756 };
757 s.push_str(&rel(r, current.id));
758 s.push_str(&node(next));
759 }
760 }
761 s
762 }
763}
764
765/// The arrows around a traversed relationship — the one bit of the chain
766/// that is always defined: which endpoint is the current node (`rels[i]`
767/// connects `nodes[i]` and `nodes[i+1]`; a self-loop is outgoing). The
768/// literal and display walks' direction policy.
769fn direction_arrows(r: &Relationship, current: NodeId) -> (&'static str, &'static str) {
770 if r.start == current {
771 ("-", "->")
772 } else {
773 ("<-", "-")
774 }
775}
776
777/// Glue a relationship's rendering between its direction arrows — the
778/// composition the literal and display walks pass as `walk`'s `rel` seam.
779fn directed((left, right): (&'static str, &'static str), rendered: String) -> String {
780 format!("{left}{rendered}{right}")
781}
782
783/// Labels only, no properties, alphabetically (CIP-271): Neo4j 2026.09.0
784/// renders `toString(node-with-props)` as `(:X)` and a multi-label node as
785/// `(:A:B:C)` whatever the creation order.
786fn node_display(n: &Node) -> String {
787 let mut labels: Vec<&str> = n.labels.iter().map(String::as_str).collect();
788 labels.sort_unstable();
789 let labels: String = labels
790 .iter()
791 .map(|l| format!(":{}", quote_identifier_shaped(l)))
792 .collect();
793 format!("({labels})")
794}
795
796/// Type only, no properties (CIP-271), the relationship half of
797/// [`node_display`].
798fn relationship_display(r: &Relationship) -> String {
799 format!("[:{}]", quote_identifier_shaped(&r.rel_type))
800}
801
802impl fmt::Display for Value {
803 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804 write!(f, "{}", self.to_cypher_literal())
805 }
806}
807
808/// Cypher has no byte-array literal: a [`Value::Bytes`] renders as the list
809/// of its byte values 0-255 (`[0, 1, 255]`), the same shape it crosses the
810/// `value_to_cypher` bridge in (ADR-0327).
811fn bytes_as_int_list(bytes: &[u8]) -> String {
812 format!("[{}]", bytes_int_list(bytes))
813}
814
815/// The comma-joined decimal byte list — `120, 121` — the one owner of the
816/// byte-list rendering; the display (`[…]`) and pretty (`ByteArray[…]`)
817/// brackets are its two thin wrappers.
818fn bytes_int_list(bytes: &[u8]) -> String {
819 let inner: Vec<_> = bytes.iter().map(u8::to_string).collect();
820 inner.join(", ")
821}
822
823fn escape_cypher_string(s: &str) -> String {
824 s.replace('\\', "\\\\").replace('\'', "\\'")
825}
826
827/// The ` {…}` property suffix shared by the node and relationship literal
828/// renderers (one owner for the policy and the ADR-0462 depth hand-off);
829/// empty when the entity has no properties. `depth` is the property values'
830/// enclosing-container count.
831fn props_suffix(props: &PropertyMap, depth: u32) -> String {
832 if props.is_empty() {
833 String::new()
834 } else {
835 // The entity arms already guarded this depth once for labels and
836 // properties together, so the pairs are joined directly — the one
837 // pre-guarded join, beside the leading space of the props wrap.
838 format!(
839 " {{{}}}",
840 map_to_cypher_literal(props.iter(), depth).join(", ")
841 )
842 }
843}
844
845/// The literal walk's map pairs — `k: v` with the literal-rendered value.
846/// The Map arm collects them inside [`guarded_container`]'s guard;
847/// `props_suffix` joins them under its caller's already-guarded depth.
848fn map_to_cypher_literal<'a>(
849 m: impl IntoIterator<Item = (&'a String, &'a Value)>,
850 depth: u32,
851) -> Vec<String> {
852 m.into_iter()
853 .map(|(k, v)| format!("{}: {}", k, v.to_cypher_literal_at(depth)))
854 .collect()
855}
856
857/// The one guarded-container shape every render walk (the literal,
858/// display and pretty walks' List/Map/Vector arms) routes through: the
859/// ADR-0462 depth guard, the `, `-joined elements, and the walk's own
860/// `wrap`. The item rendering is each walk's own — the thunk receives
861/// the guarded depth; the guard and join are never re-spelled per walk.
862fn guarded_container(
863 depth: u32,
864 wrap: impl FnOnce(String) -> String,
865 items: impl FnOnce(u32) -> Vec<String>,
866) -> String {
867 let Some(next) = next_depth(depth) else {
868 return DEPTH_LIMIT_MARKER.into();
869 };
870 wrap(items(next).join(", "))
871}
872
873/// Render a 128-bit UUID value as the canonical lowercase hyphenated
874/// string (8-4-4-4-12, CIP-246 / RFC 4122).
875pub fn uuid_hyphenated(u: u128) -> String {
876 let hex = format!("{u:032x}");
877 format!(
878 "{}-{}-{}-{}-{}",
879 &hex[0..8],
880 &hex[8..12],
881 &hex[12..16],
882 &hex[16..20],
883 &hex[20..32]
884 )
885}
886
887/// Parse an RFC-4122-shaped UUID string (case-insensitive, hyphens
888/// required, 8-4-4-4-12 groups) into its 128-bit value. `None` on any
889/// non-conforming input, mirroring Java's `UUID.fromString` strictness
890/// (CIP-246).
891pub fn uuid_parse(s: &str) -> Option<u128> {
892 // Allocation-free single pass over the original string: `to_digit(16)`
893 // accepts both hex cases, so no lowercasing or concatenation is needed.
894 // Strictness is unchanged -- exactly five groups of 8-4-4-4-12 hex digits
895 // separated by four hyphens, with nothing before or after.
896 const GROUP_LEN: [usize; 5] = [8, 4, 4, 4, 12];
897 let mut chars = s.chars();
898 let mut u: u128 = 0;
899 for (i, &len) in GROUP_LEN.iter().enumerate() {
900 if i > 0 && chars.next()? != '-' {
901 return None;
902 }
903 for _ in 0..len {
904 u = (u << 4) | chars.next()?.to_digit(16)? as u128;
905 }
906 }
907 if chars.next().is_some() {
908 return None;
909 }
910 Some(u)
911}
912
913#[cfg(test)]
914mod depth_tests;
915#[cfg(test)]
916mod expansion_tests;
917#[cfg(test)]
918mod point_tests;
919#[cfg(test)]
920mod pretty_tests;
921#[cfg(test)]
922mod tests;