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
170fn float_literal(f: f64) -> String {
181 if f.is_nan() {
182 return "NaN".into();
183 }
184 if f == f64::INFINITY {
185 return "Infinity".into();
186 }
187 if f == f64::NEG_INFINITY {
188 return "-Infinity".into();
189 }
190 let mut rendered = format!("{f}");
191 if !rendered.contains('.') {
192 rendered.push_str(".0");
193 }
194 rendered
195}
196
197impl Value {
198 pub fn from_node(node: Node) -> Self {
200 Value::Node(Arc::new(node))
201 }
202
203 pub fn from_relationship(rel: Relationship) -> Self {
205 Value::Relationship(Arc::new(rel))
206 }
207
208 pub fn from_path(path: Path) -> Self {
210 Value::Path(Arc::new(path))
211 }
212
213 pub fn logical_bytes(&self) -> u64 {
217 let mut total = 0;
218 let flow = self.add_logical_bytes(&mut total, u64::MAX, 0);
219 debug_assert!(
225 flow.is_continue(),
226 "logical_bytes broke on the ADR-0462 depth guard at the cap"
227 );
228 total
229 }
230
231 fn add_logical_bytes(&self, acc: &mut u64, budget: u64, depth: u32) -> ControlFlow<()> {
241 match self {
242 Value::Null | Value::Bool(_) => add_bytes(acc, 1, budget),
243 Value::Int(_) | Value::Float(_) => add_bytes(acc, 8, budget),
244 Value::String(s) => add_str_bytes(s, acc, budget),
245 Value::Bytes(b) => add_payload_bytes(b, acc, budget),
246 Value::List(xs) | Value::Vector { values: xs, .. } => {
247 let Some(next) = next_depth(depth) else {
248 return ControlFlow::Break(());
249 };
250 add_bytes(acc, 16, budget)?;
251 xs.iter()
252 .try_for_each(|x| x.add_logical_bytes(acc, budget, next))
253 }
254 Value::Map(m) => {
255 let Some(next) = next_depth(depth) else {
256 return ControlFlow::Break(());
257 };
258 add_bytes(acc, 16, budget)?;
259 add_property_bytes(m.iter(), acc, budget, next)
260 }
261 Value::Node(n) => {
262 let Some(next) = next_depth(depth) else {
263 return ControlFlow::Break(());
264 };
265 add_node_bytes(n, acc, budget, next)
266 }
267 Value::Relationship(r) => {
268 let Some(next) = next_depth(depth) else {
269 return ControlFlow::Break(());
270 };
271 add_rel_bytes(r, acc, budget, next)
272 }
273 Value::Path(p) => {
274 let Some(next) = next_depth(depth) else {
275 return ControlFlow::Break(());
276 };
277 p.nodes
278 .iter()
279 .try_for_each(|n| add_node_bytes(n, acc, budget, next))?;
280 p.rels
281 .iter()
282 .try_for_each(|r| add_rel_bytes(r, acc, budget, next))
283 }
284 Value::Temporal(_) => add_bytes(acc, 24, budget),
285 Value::Point(_) => add_bytes(acc, 32, budget),
286 Value::Uuid(_) => add_bytes(acc, 16, budget),
287 }
288 }
289
290 pub fn as_temporal(&self) -> Option<&Temporal> {
291 match self {
292 Value::Temporal(t) => Some(t),
293 _ => None,
294 }
295 }
296
297 pub fn as_string(&self) -> Option<&str> {
298 match self {
299 Value::String(s) => Some(&**s),
300 _ => None,
301 }
302 }
303
304 pub fn is_null(&self) -> bool {
305 matches!(self, Value::Null)
306 }
307
308 pub fn as_bool(&self) -> Option<bool> {
309 match self {
310 Value::Bool(b) => Some(*b),
311 _ => None,
312 }
313 }
314
315 pub fn truthy(&self) -> Option<bool> {
317 match self {
318 Value::Bool(b) => Some(*b),
319 Value::Null => None,
320 _ => None,
321 }
322 }
323
324 pub fn as_number(&self) -> Option<f64> {
325 match self {
326 Value::Int(i) => Some(*i as f64),
327 Value::Float(f) => Some(*f),
328 _ => None,
329 }
330 }
331
332 pub fn as_int(&self) -> Option<i64> {
333 match self {
334 Value::Int(i) => Some(*i),
335 Value::Float(f)
336 if f.fract() == 0.0 && *f >= i64::MIN as f64 && *f <= i64::MAX as f64 =>
337 {
338 Some(*f as i64)
339 }
340 _ => None,
341 }
342 }
343
344 pub fn to_cypher_literal(&self) -> String {
345 self.to_cypher_literal_at(0)
346 }
347
348 fn to_cypher_literal_at(&self, depth: u32) -> String {
353 match self {
354 Value::Null => "null".into(),
355 Value::Bool(true) => "true".into(),
356 Value::Bool(false) => "false".into(),
357 Value::Int(i) => i.to_string(),
358 Value::Float(f) => float_literal(*f),
359 Value::String(s) => format!("'{}'", escape_cypher_string(s)),
360 Value::Bytes(b) => bytes_as_int_list(b),
361 Value::List(xs) => {
362 let Some(next) = next_depth(depth) else {
363 return DEPTH_LIMIT_MARKER.into();
364 };
365 let inner: Vec<_> = xs.iter().map(|v| v.to_cypher_literal_at(next)).collect();
366 format!("[{}]", inner.join(", "))
367 }
368 Value::Map(m) => {
369 let Some(next) = next_depth(depth) else {
370 return DEPTH_LIMIT_MARKER.into();
371 };
372 map_to_cypher_literal(m.iter(), next)
373 }
374 Value::Node(n) => n.to_cypher_literal_at(depth),
375 Value::Relationship(r) => r.to_cypher_literal_at(depth),
376 Value::Path(p) => p.to_cypher_literal_at(depth),
377 Value::Temporal(t) => format!("'{}'", escape_cypher_string(&t.iso_string())),
378 Value::Uuid(u) => format!("uuid('{}')", uuid_hyphenated(*u)),
380 Value::Point(p) => p.to_string(),
381 Value::Vector { coord, values } => {
382 let Some(next) = next_depth(depth) else {
383 return DEPTH_LIMIT_MARKER.into();
384 };
385 let inner = values
386 .iter()
387 .map(|value| value.to_cypher_literal_at(next))
388 .collect::<Vec<_>>();
389 vector_text(&inner, *coord)
390 }
391 }
392 }
393
394 pub fn to_display_string(&self) -> String {
400 self.to_display_string_at(0)
401 }
402
403 fn to_display_string_at(&self, depth: u32) -> String {
407 match self {
408 Value::Null => "null".into(),
409 Value::Bool(b) => b.to_string(),
410 Value::Int(i) => i.to_string(),
411 Value::Float(f) => float_literal(*f),
412 Value::String(s) => String::from(&**s),
415 Value::Bytes(b) => bytes_as_int_list(b),
416 Value::List(xs) => {
417 let Some(next) = next_depth(depth) else {
418 return DEPTH_LIMIT_MARKER.into();
419 };
420 let inner: Vec<_> = xs.iter().map(|v| v.to_display_string_at(next)).collect();
421 format!("[{}]", inner.join(", "))
422 }
423 Value::Map(m) => {
428 let Some(next) = next_depth(depth) else {
429 return DEPTH_LIMIT_MARKER.into();
430 };
431 let inner: Vec<_> = m
432 .iter()
433 .map(|(k, v)| {
434 format!(
435 "{}: {}",
436 quote_identifier_shaped(k),
437 v.to_display_string_at(next)
438 )
439 })
440 .collect();
441 format!("{{{}}}", inner.join(", "))
442 }
443 Value::Node(n) => node_display(n),
444 Value::Relationship(r) => relationship_display(r),
445 Value::Path(p) => p.display_string(),
448 Value::Temporal(t) => t.full_seconds_string(),
449 Value::Uuid(u) => uuid_hyphenated(*u),
451 Value::Point(pt) => point_display(pt),
452 Value::Vector { coord, values } => {
453 let Some(next) = next_depth(depth) else {
454 return DEPTH_LIMIT_MARKER.into();
455 };
456 let inner: Vec<_> = values
457 .iter()
458 .map(|v| v.to_display_string_at(next))
459 .collect();
460 vector_text(&inner, *coord)
461 }
462 }
463 }
464}
465
466pub fn point_component(p: &PointValue, key: &str) -> Result<Value, Error> {
480 let name = key.to_ascii_lowercase();
481 Ok(match name.as_str() {
482 "srid" => Value::Int(i64::from(p.srid)),
483 "crs" => Value::String(
487 p.crs_name()
488 .unwrap_or_else(|| relate_model::wire::crs_name(p.srid))
489 .into(),
490 ),
491 _ => {
492 let Some(axis) = relate_model::point::point_axis(&name) else {
493 return Err(Error::argument_error(format!(
495 "no such component '{key}' on a point value"
496 )));
497 };
498 let cartesian = !relate_model::point::is_geographic(p.srid);
501 let unavailable =
502 (cartesian && axis.key(true) == name) || (axis.index == 2 && p.z.is_none());
503 if unavailable {
504 return Err(Error::argument_error(format!(
505 "Field: {key} is not available on a point value"
506 )));
507 }
508 match axis.index {
509 0 => Value::Float(p.x),
510 1 => Value::Float(p.y),
511 _ => Value::Float(p.z.expect("the 3D check admitted only a present z")),
512 }
513 }
514 })
515}
516
517fn point_display(p: &PointValue) -> String {
526 let coord = |value: f64| Value::Float(value).to_cypher_literal();
527 match (p.crs_name(), p.z) {
528 (Some(crs), Some(z)) => format!(
529 "point({{x: {}, y: {}, z: {}, crs: '{crs}'}})",
530 coord(p.x),
531 coord(p.y),
532 coord(z)
533 ),
534 (Some(crs), None) => format!(
535 "point({{x: {}, y: {}, crs: '{crs}'}})",
536 coord(p.x),
537 coord(p.y)
538 ),
539 (None, Some(z)) => format!(
540 "point({{srid: {}, x: {}, y: {}, z: {}}})",
541 p.srid,
542 coord(p.x),
543 coord(p.y),
544 coord(z)
545 ),
546 (None, None) => format!(
547 "point({{srid: {}, x: {}, y: {}}})",
548 p.srid,
549 coord(p.x),
550 coord(p.y)
551 ),
552 }
553}
554
555fn vector_text(elements: &[String], coord: VectorCoordKind) -> String {
562 format!(
563 "vector([{}], {}, {})",
564 elements.join(", "),
565 elements.len(),
566 coord.canonical_name()
567 )
568}
569
570impl Node {
571 pub fn to_cypher_literal(&self) -> String {
572 self.to_cypher_literal_at(0)
573 }
574
575 fn to_cypher_literal_at(&self, depth: u32) -> String {
578 let Some(next) = next_depth(depth) else {
579 return DEPTH_LIMIT_MARKER.into();
580 };
581 let labels: String = self.labels.iter().map(|l| format!(":{l}")).collect();
582 let props = props_suffix(&self.properties, next);
583 format!("({labels}{props})")
584 }
585}
586
587impl Relationship {
588 pub fn to_cypher_literal(&self) -> String {
589 self.to_cypher_literal_at(0)
590 }
591
592 fn to_cypher_literal_at(&self, depth: u32) -> String {
594 let Some(next) = next_depth(depth) else {
595 return DEPTH_LIMIT_MARKER.into();
596 };
597 let props = props_suffix(&self.properties, next);
598 format!("[:{}{}]", self.rel_type, props)
599 }
600}
601
602impl Path {
603 pub fn to_cypher_literal(&self) -> String {
604 self.to_cypher_literal_at(0)
605 }
606
607 fn to_cypher_literal_at(&self, depth: u32) -> String {
609 if next_depth(depth).is_none() {
612 return DEPTH_LIMIT_MARKER.into();
613 }
614 format!(
615 "<{}>",
616 self.walk(
617 |n| n.to_cypher_literal_at(depth),
618 |r| r.to_cypher_literal_at(depth)
619 )
620 )
621 }
622
623 fn display_string(&self) -> String {
631 self.walk(node_display, relationship_display)
632 }
633
634 fn walk(
639 &self,
640 node: impl Fn(&Node) -> String,
641 rel: impl Fn(&Relationship) -> String,
642 ) -> String {
643 let mut s = String::new();
644 for (i, n) in self.nodes.iter().enumerate() {
645 s.push_str(&node(n));
646 if let Some(r) = self.rels.get(i) {
647 let (left, right) = if r.start == n.id {
651 ("-", "->")
652 } else {
653 ("<-", "-")
654 };
655 s.push_str(&format!("{left}{}{right}", rel(r)));
656 }
657 }
658 s
659 }
660}
661
662fn node_display(n: &Node) -> String {
666 let mut labels: Vec<&str> = n.labels.iter().map(String::as_str).collect();
667 labels.sort_unstable();
668 let labels: String = labels
669 .iter()
670 .map(|l| format!(":{}", quote_identifier_shaped(l)))
671 .collect();
672 format!("({labels})")
673}
674
675fn relationship_display(r: &Relationship) -> String {
678 format!("[:{}]", quote_identifier_shaped(&r.rel_type))
679}
680
681impl fmt::Display for Value {
682 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683 write!(f, "{}", self.to_cypher_literal())
684 }
685}
686
687fn bytes_as_int_list(bytes: &[u8]) -> String {
691 let inner: Vec<_> = bytes.iter().map(u8::to_string).collect();
692 format!("[{}]", inner.join(", "))
693}
694
695fn escape_cypher_string(s: &str) -> String {
696 s.replace('\\', "\\\\").replace('\'', "\\'")
697}
698
699fn props_suffix(props: &PropertyMap, depth: u32) -> String {
704 if props.is_empty() {
705 String::new()
706 } else {
707 format!(" {}", map_to_cypher_literal(props.iter(), depth))
708 }
709}
710
711fn map_to_cypher_literal<'a>(
712 m: impl IntoIterator<Item = (&'a String, &'a Value)>,
713 depth: u32,
714) -> String {
715 let inner: Vec<_> = m
716 .into_iter()
717 .map(|(k, v)| format!("{}: {}", k, v.to_cypher_literal_at(depth)))
718 .collect();
719 format!("{{{}}}", inner.join(", "))
720}
721
722pub fn uuid_hyphenated(u: u128) -> String {
725 let hex = format!("{u:032x}");
726 format!(
727 "{}-{}-{}-{}-{}",
728 &hex[0..8],
729 &hex[8..12],
730 &hex[12..16],
731 &hex[16..20],
732 &hex[20..32]
733 )
734}
735
736pub fn uuid_parse(s: &str) -> Option<u128> {
741 const GROUP_LEN: [usize; 5] = [8, 4, 4, 4, 12];
746 let mut chars = s.chars();
747 let mut u: u128 = 0;
748 for (i, &len) in GROUP_LEN.iter().enumerate() {
749 if i > 0 && chars.next()? != '-' {
750 return None;
751 }
752 for _ in 0..len {
753 u = (u << 4) | chars.next()?.to_digit(16)? as u128;
754 }
755 }
756 if chars.next().is_some() {
757 return None;
758 }
759 Some(u)
760}
761
762#[cfg(test)]
763mod depth_tests;
764#[cfg(test)]
765mod point_tests;
766#[cfg(test)]
767mod tests;