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;
8
9use relate_model::identifier::quote_identifier_shaped;
10
11use crate::temporal::Temporal;
12use crate::{Error, NodeId, RelId};
13
14mod depth;
15mod json;
16mod ordering;
17mod props;
18pub(crate) use depth::{descends, DEPTH_LIMIT_MARKER};
19pub use depth::{next_depth, value_depth_exceeded, MAX_VALUE_DEPTH};
20pub use json::{tagged_str, TaggedStr};
21pub use props::PropertyMap;
22
23#[derive(Debug, Clone, PartialEq)]
24pub struct Node {
25 pub id: NodeId,
26 pub labels: Arc<Vec<String>>,
27 pub properties: Arc<PropertyMap>,
28}
29
30#[derive(Debug, Clone, PartialEq)]
31pub struct Relationship {
32 pub id: RelId,
33 pub start: NodeId,
34 pub end: NodeId,
35 pub rel_type: String,
36 pub properties: Arc<PropertyMap>,
37}
38
39#[derive(Debug, Clone, PartialEq)]
40pub struct Path {
41 pub nodes: Vec<Node>,
42 pub rels: Vec<Relationship>,
43}
44
45#[derive(Debug, Clone, PartialEq, Default)]
47pub enum Value {
48 #[default]
49 Null,
50 Bool(bool),
51 Int(i64),
52 Float(f64),
53 String(Arc<str>),
54 List(Arc<Vec<Value>>),
55 Map(Arc<BTreeMap<String, Value>>),
56 Node(Arc<Node>),
57 Relationship(Arc<Relationship>),
58 Path(Arc<Path>),
59 Temporal(Temporal),
60 Point(PointValue),
61 Uuid(u128),
65 Vector {
66 coord: VectorCoordKind,
67 values: Arc<Vec<Value>>,
68 },
69 Bytes(Arc<[u8]>),
74}
75
76const _: () = {
79 const fn assert_send_sync<T: Send + Sync>() {}
80 assert_send_sync::<Value>();
81};
82
83pub fn logical_bytes_within<'a>(
95 values: impl IntoIterator<Item = &'a Value>,
96 limit: u64,
97) -> Option<u64> {
98 let mut total = 0;
99 let over = values
100 .into_iter()
101 .try_for_each(|v| v.add_logical_bytes(&mut total, limit, 0))
102 .is_break();
103 (!over).then_some(total)
104}
105
106fn add_bytes(acc: &mut u64, bytes: u64, budget: u64) -> ControlFlow<()> {
108 *acc = acc.saturating_add(bytes);
109 if *acc > budget {
110 ControlFlow::Break(())
111 } else {
112 ControlFlow::Continue(())
113 }
114}
115
116fn add_str_bytes(s: &str, acc: &mut u64, budget: u64) -> ControlFlow<()> {
119 add_bytes(acc, str_logical_bytes(s), budget)
120}
121
122fn add_payload_bytes(payload: &[u8], acc: &mut u64, budget: u64) -> ControlFlow<()> {
126 add_bytes(acc, bytes_logical_bytes(payload), budget)
127}
128
129fn add_property_bytes<'a>(
130 props: impl IntoIterator<Item = (&'a String, &'a Value)>,
131 acc: &mut u64,
132 budget: u64,
133 depth: u32,
134) -> ControlFlow<()> {
135 props.into_iter().try_for_each(|(k, v)| {
136 add_str_bytes(k, acc, budget)?;
137 v.add_logical_bytes(acc, budget, depth)
138 })
139}
140
141fn add_node_bytes(n: &Node, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
142 n.labels
143 .iter()
144 .try_for_each(|l| add_str_bytes(l, acc, budget))?;
145 add_property_bytes(n.properties.iter(), acc, budget, depth)
146}
147
148fn add_rel_bytes(r: &Relationship, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
149 add_str_bytes(&r.rel_type, acc, budget)?;
150 add_property_bytes(r.properties.iter(), acc, budget, depth)
151}
152
153#[inline]
158pub fn str_logical_bytes(s: &str) -> u64 {
159 16 + s.len() as u64
160}
161
162#[inline]
166pub fn bytes_logical_bytes(payload: &[u8]) -> u64 {
167 16 + payload.len() as u64
168}
169
170impl Value {
171 pub fn from_node(node: Node) -> Self {
173 Value::Node(Arc::new(node))
174 }
175
176 pub fn from_relationship(rel: Relationship) -> Self {
178 Value::Relationship(Arc::new(rel))
179 }
180
181 pub fn from_path(path: Path) -> Self {
183 Value::Path(Arc::new(path))
184 }
185
186 pub fn logical_bytes(&self) -> u64 {
190 let mut total = 0;
191 let flow = self.add_logical_bytes(&mut total, u64::MAX, 0);
192 debug_assert!(
198 flow.is_continue(),
199 "logical_bytes broke on the ADR-0462 depth guard at the cap"
200 );
201 total
202 }
203
204 fn add_logical_bytes(&self, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
214 match self {
215 Value::Null | Value::Bool(_) => add_bytes(acc, 1, budget),
216 Value::Int(_) | Value::Float(_) => add_bytes(acc, 8, budget),
217 Value::String(s) => add_str_bytes(s, acc, budget),
218 Value::Bytes(b) => add_payload_bytes(b, acc, budget),
219 Value::List(xs) | Value::Vector { values: xs, .. } => {
220 let Some(next) = next_depth(depth) else {
221 return ControlFlow::Break(());
222 };
223 add_bytes(acc, 16, budget)?;
224 xs.iter()
225 .try_for_each(|x| x.add_logical_bytes(acc, budget, next))
226 }
227 Value::Map(m) => {
228 let Some(next) = next_depth(depth) else {
229 return ControlFlow::Break(());
230 };
231 add_bytes(acc, 16, budget)?;
232 add_property_bytes(m.iter(), acc, budget, next)
233 }
234 Value::Node(n) => {
235 let Some(next) = next_depth(depth) else {
236 return ControlFlow::Break(());
237 };
238 add_node_bytes(n, acc, budget, next)
239 }
240 Value::Relationship(r) => {
241 let Some(next) = next_depth(depth) else {
242 return ControlFlow::Break(());
243 };
244 add_rel_bytes(r, acc, budget, next)
245 }
246 Value::Path(p) => {
247 let Some(next) = next_depth(depth) else {
248 return ControlFlow::Break(());
249 };
250 p.nodes
251 .iter()
252 .try_for_each(|n| add_node_bytes(n, acc, budget, next))?;
253 p.rels
254 .iter()
255 .try_for_each(|r| add_rel_bytes(r, acc, budget, next))
256 }
257 Value::Temporal(_) => add_bytes(acc, 24, budget),
258 Value::Point(_) => add_bytes(acc, 32, budget),
259 Value::Uuid(_) => add_bytes(acc, 16, budget),
260 }
261 }
262
263 pub fn as_temporal(&self) -> Option<&Temporal> {
264 match self {
265 Value::Temporal(t) => Some(t),
266 _ => None,
267 }
268 }
269
270 pub fn as_string(&self) -> Option<&str> {
271 match self {
272 Value::String(s) => Some(&**s),
273 _ => None,
274 }
275 }
276
277 pub fn is_null(&self) -> bool {
278 matches!(self, Value::Null)
279 }
280
281 pub fn as_bool(&self) -> Option<bool> {
282 match self {
283 Value::Bool(b) => Some(*b),
284 _ => None,
285 }
286 }
287
288 pub fn truthy(&self) -> Option<bool> {
290 match self {
291 Value::Bool(b) => Some(*b),
292 Value::Null => None,
293 _ => None,
294 }
295 }
296
297 pub fn as_number(&self) -> Option<f64> {
298 match self {
299 Value::Int(i) => Some(*i as f64),
300 Value::Float(f) => Some(*f),
301 _ => None,
302 }
303 }
304
305 pub fn as_int(&self) -> Option<i64> {
306 match self {
307 Value::Int(i) => Some(*i),
308 Value::Float(f)
309 if f.fract() == 0.0 && *f >= i64::MIN as f64 && *f <= i64::MAX as f64 =>
310 {
311 Some(*f as i64)
312 }
313 _ => None,
314 }
315 }
316
317 pub fn to_cypher_literal(&self) -> String {
318 self.to_cypher_literal_at(0)
319 }
320
321 fn to_cypher_literal_at(&self, depth: u32) -> String {
326 match self {
327 Value::Null => "null".into(),
328 Value::Bool(true) => "true".into(),
329 Value::Bool(false) => "false".into(),
330 Value::Int(i) => i.to_string(),
331 Value::Float(f) => relate_model::value::float_text(*f),
332 Value::String(s) => format!("'{}'", escape_cypher_string(s)),
333 Value::Bytes(b) => bytes_as_int_list(b),
334 Value::List(xs) => {
335 let Some(next) = next_depth(depth) else {
336 return DEPTH_LIMIT_MARKER.into();
337 };
338 let inner: Vec<_> = xs.iter().map(|v| v.to_cypher_literal_at(next)).collect();
339 format!("[{}]", inner.join(", "))
340 }
341 Value::Map(m) => {
342 let Some(next) = next_depth(depth) else {
343 return DEPTH_LIMIT_MARKER.into();
344 };
345 map_to_cypher_literal(m.iter(), next)
346 }
347 Value::Node(n) => n.to_cypher_literal_at(depth),
348 Value::Relationship(r) => r.to_cypher_literal_at(depth),
349 Value::Path(p) => p.to_cypher_literal_at(depth),
350 Value::Temporal(t) => format!("'{}'", escape_cypher_string(&t.iso_string())),
351 Value::Uuid(u) => format!("uuid('{}')", uuid_hyphenated(*u)),
353 Value::Point(p) => p.to_string(),
354 Value::Vector { coord, values } => {
355 let Some(next) = next_depth(depth) else {
356 return DEPTH_LIMIT_MARKER.into();
357 };
358 let inner = values
359 .iter()
360 .map(|value| value.to_cypher_literal_at(next))
361 .collect::<Vec<_>>();
362 vector_text(&inner, *coord)
363 }
364 }
365 }
366
367 pub fn to_display_string(&self) -> String {
373 self.to_display_string_at(0)
374 }
375
376 fn to_display_string_at(&self, depth: u32) -> String {
380 match self {
381 Value::Null => "null".into(),
382 Value::Bool(b) => b.to_string(),
383 Value::Int(i) => i.to_string(),
384 Value::Float(f) => relate_model::value::float_text(*f),
385 Value::String(s) => String::from(&**s),
388 Value::Bytes(b) => bytes_as_int_list(b),
389 Value::List(xs) => {
390 let Some(next) = next_depth(depth) else {
391 return DEPTH_LIMIT_MARKER.into();
392 };
393 let inner: Vec<_> = xs.iter().map(|v| v.to_display_string_at(next)).collect();
394 format!("[{}]", inner.join(", "))
395 }
396 Value::Map(m) => {
401 let Some(next) = next_depth(depth) else {
402 return DEPTH_LIMIT_MARKER.into();
403 };
404 let inner: Vec<_> = m
405 .iter()
406 .map(|(k, v)| {
407 format!(
408 "{}: {}",
409 quote_identifier_shaped(k),
410 v.to_display_string_at(next)
411 )
412 })
413 .collect();
414 format!("{{{}}}", inner.join(", "))
415 }
416 Value::Node(n) => node_display(n),
417 Value::Relationship(r) => relationship_display(r),
418 Value::Path(p) => p.display_string(),
421 Value::Temporal(t) => t.full_seconds_string(),
422 Value::Uuid(u) => uuid_hyphenated(*u),
424 Value::Point(pt) => point_display(pt),
425 Value::Vector { coord, values } => {
426 let Some(next) = next_depth(depth) else {
427 return DEPTH_LIMIT_MARKER.into();
428 };
429 let inner: Vec<_> = values
430 .iter()
431 .map(|v| v.to_display_string_at(next))
432 .collect();
433 vector_text(&inner, *coord)
434 }
435 }
436 }
437}
438
439pub fn point_component(p: &PointValue, key: &str) -> Result<Value, Error> {
453 let name = key.to_ascii_lowercase();
454 Ok(match name.as_str() {
455 "srid" => Value::Int(i64::from(p.srid)),
456 "crs" => Value::String(
460 p.crs_name()
461 .unwrap_or_else(|| relate_model::wire::crs_name(p.srid))
462 .into(),
463 ),
464 _ => {
465 let Some(axis) = relate_model::point::point_axis(&name) else {
466 return Err(Error::argument_error(format!(
468 "no such component '{key}' on a point value"
469 )));
470 };
471 let cartesian = !relate_model::point::is_geographic(p.srid);
474 let unavailable =
475 (cartesian && axis.key(true) == name) || (axis.index == 2 && p.z.is_none());
476 if unavailable {
477 return Err(Error::argument_error(format!(
478 "Field: {key} is not available on a point value"
479 )));
480 }
481 match axis.index {
482 0 => Value::Float(p.x),
483 1 => Value::Float(p.y),
484 _ => Value::Float(p.z.expect("the 3D check admitted only a present z")),
485 }
486 }
487 })
488}
489
490fn point_display(p: &PointValue) -> String {
499 let coord = |value: f64| Value::Float(value).to_cypher_literal();
500 match (p.crs_name(), p.z) {
501 (Some(crs), Some(z)) => format!(
502 "point({{x: {}, y: {}, z: {}, crs: '{crs}'}})",
503 coord(p.x),
504 coord(p.y),
505 coord(z)
506 ),
507 (Some(crs), None) => format!(
508 "point({{x: {}, y: {}, crs: '{crs}'}})",
509 coord(p.x),
510 coord(p.y)
511 ),
512 (None, Some(z)) => format!(
513 "point({{srid: {}, x: {}, y: {}, z: {}}})",
514 p.srid,
515 coord(p.x),
516 coord(p.y),
517 coord(z)
518 ),
519 (None, None) => format!(
520 "point({{srid: {}, x: {}, y: {}}})",
521 p.srid,
522 coord(p.x),
523 coord(p.y)
524 ),
525 }
526}
527
528fn vector_text(elements: &[String], coord: VectorCoordKind) -> String {
535 format!(
536 "vector([{}], {}, {})",
537 elements.join(", "),
538 elements.len(),
539 coord.canonical_name()
540 )
541}
542
543impl Node {
544 pub fn to_cypher_literal(&self) -> String {
545 self.to_cypher_literal_at(0)
546 }
547
548 fn to_cypher_literal_at(&self, depth: u32) -> String {
551 let Some(next) = next_depth(depth) else {
552 return DEPTH_LIMIT_MARKER.into();
553 };
554 let labels: String = self.labels.iter().map(|l| format!(":{l}")).collect();
555 let props = props_suffix(&self.properties, next);
556 format!("({labels}{props})")
557 }
558}
559
560impl Relationship {
561 pub fn to_cypher_literal(&self) -> String {
562 self.to_cypher_literal_at(0)
563 }
564
565 fn to_cypher_literal_at(&self, depth: u32) -> String {
567 let Some(next) = next_depth(depth) else {
568 return DEPTH_LIMIT_MARKER.into();
569 };
570 let props = props_suffix(&self.properties, next);
571 format!("[:{}{}]", self.rel_type, props)
572 }
573}
574
575impl Path {
576 pub fn to_cypher_literal(&self) -> String {
577 self.to_cypher_literal_at(0)
578 }
579
580 fn to_cypher_literal_at(&self, depth: u32) -> String {
582 if next_depth(depth).is_none() {
585 return DEPTH_LIMIT_MARKER.into();
586 }
587 format!(
588 "<{}>",
589 self.walk(
590 |n| n.to_cypher_literal_at(depth),
591 |r| r.to_cypher_literal_at(depth)
592 )
593 )
594 }
595
596 fn display_string(&self) -> String {
604 self.walk(node_display, relationship_display)
605 }
606
607 fn walk(
612 &self,
613 node: impl Fn(&Node) -> String,
614 rel: impl Fn(&Relationship) -> String,
615 ) -> String {
616 let mut s = String::new();
617 for (i, n) in self.nodes.iter().enumerate() {
618 s.push_str(&node(n));
619 if let Some(r) = self.rels.get(i) {
620 let (left, right) = if r.start == n.id {
624 ("-", "->")
625 } else {
626 ("<-", "-")
627 };
628 s.push_str(&format!("{left}{}{right}", rel(r)));
629 }
630 }
631 s
632 }
633}
634
635fn node_display(n: &Node) -> String {
639 let mut labels: Vec<&str> = n.labels.iter().map(String::as_str).collect();
640 labels.sort_unstable();
641 let labels: String = labels
642 .iter()
643 .map(|l| format!(":{}", quote_identifier_shaped(l)))
644 .collect();
645 format!("({labels})")
646}
647
648fn relationship_display(r: &Relationship) -> String {
651 format!("[:{}]", quote_identifier_shaped(&r.rel_type))
652}
653
654impl fmt::Display for Value {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 write!(f, "{}", self.to_cypher_literal())
657 }
658}
659
660fn bytes_as_int_list(bytes: &[u8]) -> String {
664 let inner: Vec<_> = bytes.iter().map(u8::to_string).collect();
665 format!("[{}]", inner.join(", "))
666}
667
668fn escape_cypher_string(s: &str) -> String {
669 s.replace('\\', "\\\\").replace('\'', "\\'")
670}
671
672fn props_suffix(props: &PropertyMap, depth: u32) -> String {
677 if props.is_empty() {
678 String::new()
679 } else {
680 format!(" {}", map_to_cypher_literal(props.iter(), depth))
681 }
682}
683
684fn map_to_cypher_literal<'a>(
685 m: impl IntoIterator<Item = (&'a String, &'a Value)>,
686 depth: u32,
687) -> String {
688 let inner: Vec<_> = m
689 .into_iter()
690 .map(|(k, v)| format!("{}: {}", k, v.to_cypher_literal_at(depth)))
691 .collect();
692 format!("{{{}}}", inner.join(", "))
693}
694
695pub fn uuid_hyphenated(u: u128) -> String {
698 let hex = format!("{u:032x}");
699 format!(
700 "{}-{}-{}-{}-{}",
701 &hex[0..8],
702 &hex[8..12],
703 &hex[12..16],
704 &hex[16..20],
705 &hex[20..32]
706 )
707}
708
709pub fn uuid_parse(s: &str) -> Option<u128> {
714 const GROUP_LEN: [usize; 5] = [8, 4, 4, 4, 12];
719 let mut chars = s.chars();
720 let mut u: u128 = 0;
721 for (i, &len) in GROUP_LEN.iter().enumerate() {
722 if i > 0 && chars.next()? != '-' {
723 return None;
724 }
725 for _ in 0..len {
726 u = (u << 4) | chars.next()?.to_digit(16)? as u128;
727 }
728 }
729 if chars.next().is_some() {
730 return None;
731 }
732 Some(u)
733}
734
735#[cfg(test)]
736mod depth_tests;
737#[cfg(test)]
738mod point_tests;
739#[cfg(test)]
740mod tests;