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 logical_bytes_within_memo(values, limit, &mut ExpansionMemo::off())
99}
100
101pub fn logical_bytes_within_memo<'a>(
109 values: impl IntoIterator<Item = &'a Value>,
110 limit: u64,
111 memo: &mut ExpansionMemo,
112) -> Option<u64> {
113 let mut total = 0;
114 let over = values
115 .into_iter()
116 .try_for_each(|v| v.add_logical_bytes(&mut total, limit, 0, memo))
117 .is_break();
118 (!over).then_some(total)
119}
120
121pub struct ExpansionMemo {
130 sizes: Option<std::collections::HashMap<depth::PayloadKey, u64>>,
132}
133
134impl Default for ExpansionMemo {
135 fn default() -> Self {
136 Self::new()
137 }
138}
139
140impl ExpansionMemo {
141 pub fn new() -> Self {
143 Self {
144 sizes: Some(Default::default()),
145 }
146 }
147
148 fn off() -> Self {
150 Self { sizes: None }
151 }
152
153 fn open<T>(
159 &mut self,
160 enclosing: u32,
161 payload: &Arc<T>,
162 acc: &mut u64,
163 budget: u64,
164 body: impl FnOnce(&mut Self, &mut u64, u32) -> ControlFlow<()>,
165 ) -> ControlFlow<()> {
166 let Some(next) = next_depth(enclosing) else {
167 return ControlFlow::Break(());
168 };
169 let Some(sizes) = self.sizes.as_mut() else {
170 return body(self, acc, next);
171 };
172 let key = depth::payload_key(payload);
173 if let Some(size) = sizes.get(&key) {
174 return add_bytes(acc, *size, budget);
175 }
176 let before = *acc;
177 body(self, acc, next)?;
178 if let Some(sizes) = self.sizes.as_mut() {
179 sizes.insert(key, *acc - before);
180 }
181 ControlFlow::Continue(())
182 }
183}
184
185fn add_bytes(acc: &mut u64, bytes: u64, budget: u64) -> ControlFlow<()> {
187 *acc = acc.saturating_add(bytes);
188 if *acc > budget {
189 ControlFlow::Break(())
190 } else {
191 ControlFlow::Continue(())
192 }
193}
194
195fn add_str_bytes(s: &str, acc: &mut u64, budget: u64) -> ControlFlow<()> {
198 add_bytes(acc, str_logical_bytes(s), budget)
199}
200
201fn add_payload_bytes(payload: &[u8], acc: &mut u64, budget: u64) -> ControlFlow<()> {
205 add_bytes(acc, bytes_logical_bytes(payload), budget)
206}
207
208fn add_property_bytes<'a>(
209 props: impl IntoIterator<Item = (&'a String, &'a Value)>,
210 acc: &mut u64,
211 budget: u64,
212 depth: u32,
213 memo: &mut ExpansionMemo,
214) -> ControlFlow<()> {
215 props.into_iter().try_for_each(|(k, v)| {
216 add_str_bytes(k, acc, budget)?;
217 v.add_logical_bytes(acc, budget, depth, memo)
218 })
219}
220
221fn add_node_bytes(
222 n: &Node,
223 acc: &mut u64,
224 budget: u64,
225 depth: u32,
226 memo: &mut ExpansionMemo,
227) -> ControlFlow<()> {
228 n.labels
229 .iter()
230 .try_for_each(|l| add_str_bytes(l, acc, budget))?;
231 add_property_bytes(n.properties.iter(), acc, budget, depth, memo)
232}
233
234fn add_rel_bytes(
235 r: &Relationship,
236 acc: &mut u64,
237 budget: u64,
238 depth: u32,
239 memo: &mut ExpansionMemo,
240) -> ControlFlow<()> {
241 add_str_bytes(&r.rel_type, acc, budget)?;
242 add_property_bytes(r.properties.iter(), acc, budget, depth, memo)
243}
244
245#[inline]
250pub fn str_logical_bytes(s: &str) -> u64 {
251 16 + s.len() as u64
252}
253
254#[inline]
258pub fn bytes_logical_bytes(payload: &[u8]) -> u64 {
259 16 + payload.len() as u64
260}
261
262impl Value {
263 pub fn from_node(node: Node) -> Self {
265 Value::Node(Arc::new(node))
266 }
267
268 pub fn from_relationship(rel: Relationship) -> Self {
270 Value::Relationship(Arc::new(rel))
271 }
272
273 pub fn from_path(path: Path) -> Self {
275 Value::Path(Arc::new(path))
276 }
277
278 pub fn logical_bytes(&self) -> u64 {
282 let mut total = 0;
283 let flow = self.add_logical_bytes(&mut total, u64::MAX, 0, &mut ExpansionMemo::off());
284 debug_assert!(
290 flow.is_continue(),
291 "logical_bytes broke on the ADR-0462 depth guard at the cap"
292 );
293 total
294 }
295
296 fn add_logical_bytes(
306 &self,
307 acc: &mut u64,
308 budget: u64,
309 depth: u32,
310 memo: &mut ExpansionMemo,
311 ) -> ControlFlow<()> {
312 match self {
313 Value::Null | Value::Bool(_) => add_bytes(acc, 1, budget),
314 Value::Int(_) | Value::Float(_) => add_bytes(acc, 8, budget),
315 Value::String(s) => add_str_bytes(s, acc, budget),
316 Value::Bytes(b) => add_payload_bytes(b, acc, budget),
317 Value::List(xs) | Value::Vector { values: xs, .. } => {
318 memo.open(depth, xs, acc, budget, |memo, acc, next| {
319 add_bytes(acc, 16, budget)?;
320 xs.iter()
321 .try_for_each(|x| x.add_logical_bytes(acc, budget, next, memo))
322 })
323 }
324 Value::Map(m) => memo.open(depth, m, acc, budget, |memo, acc, next| {
325 add_bytes(acc, 16, budget)?;
326 add_property_bytes(m.iter(), acc, budget, next, memo)
327 }),
328 Value::Node(n) => memo.open(depth, n, acc, budget, |memo, acc, next| {
329 add_node_bytes(n, acc, budget, next, memo)
330 }),
331 Value::Relationship(r) => memo.open(depth, r, acc, budget, |memo, acc, next| {
332 add_rel_bytes(r, acc, budget, next, memo)
333 }),
334 Value::Path(p) => memo.open(depth, p, acc, budget, |memo, acc, next| {
335 p.nodes
336 .iter()
337 .try_for_each(|n| add_node_bytes(n, acc, budget, next, memo))?;
338 p.rels
339 .iter()
340 .try_for_each(|r| add_rel_bytes(r, acc, budget, next, memo))
341 }),
342 Value::Temporal(_) => add_bytes(acc, 24, budget),
343 Value::Point(_) => add_bytes(acc, 32, budget),
344 Value::Uuid(_) => add_bytes(acc, 16, budget),
345 }
346 }
347
348 pub fn as_temporal(&self) -> Option<&Temporal> {
349 match self {
350 Value::Temporal(t) => Some(t),
351 _ => None,
352 }
353 }
354
355 pub fn as_string(&self) -> Option<&str> {
356 match self {
357 Value::String(s) => Some(&**s),
358 _ => None,
359 }
360 }
361
362 pub fn is_null(&self) -> bool {
363 matches!(self, Value::Null)
364 }
365
366 pub fn as_bool(&self) -> Option<bool> {
367 match self {
368 Value::Bool(b) => Some(*b),
369 _ => None,
370 }
371 }
372
373 pub fn truthy(&self) -> Option<bool> {
375 match self {
376 Value::Bool(b) => Some(*b),
377 Value::Null => None,
378 _ => None,
379 }
380 }
381
382 pub fn as_number(&self) -> Option<f64> {
383 match self {
384 Value::Int(i) => Some(*i as f64),
385 Value::Float(f) => Some(*f),
386 _ => None,
387 }
388 }
389
390 pub fn as_int(&self) -> Option<i64> {
391 match self {
392 Value::Int(i) => Some(*i),
393 Value::Float(f)
394 if f.fract() == 0.0 && *f >= i64::MIN as f64 && *f <= i64::MAX as f64 =>
395 {
396 Some(*f as i64)
397 }
398 _ => None,
399 }
400 }
401
402 pub fn to_cypher_literal(&self) -> String {
403 self.to_cypher_literal_at(0)
404 }
405
406 fn to_cypher_literal_at(&self, depth: u32) -> String {
411 match self {
412 Value::Null => "null".into(),
413 Value::Bool(true) => "true".into(),
414 Value::Bool(false) => "false".into(),
415 Value::Int(i) => i.to_string(),
416 Value::Float(f) => relate_model::value::float_text(*f),
417 Value::String(s) => format!("'{}'", escape_cypher_string(s)),
418 Value::Bytes(b) => bytes_as_int_list(b),
419 Value::List(xs) => {
420 let Some(next) = next_depth(depth) else {
421 return DEPTH_LIMIT_MARKER.into();
422 };
423 let inner: Vec<_> = xs.iter().map(|v| v.to_cypher_literal_at(next)).collect();
424 format!("[{}]", inner.join(", "))
425 }
426 Value::Map(m) => {
427 let Some(next) = next_depth(depth) else {
428 return DEPTH_LIMIT_MARKER.into();
429 };
430 map_to_cypher_literal(m.iter(), next)
431 }
432 Value::Node(n) => n.to_cypher_literal_at(depth),
433 Value::Relationship(r) => r.to_cypher_literal_at(depth),
434 Value::Path(p) => p.to_cypher_literal_at(depth),
435 Value::Temporal(t) => format!("'{}'", escape_cypher_string(&t.iso_string())),
436 Value::Uuid(u) => format!("uuid('{}')", uuid_hyphenated(*u)),
438 Value::Point(p) => p.to_string(),
439 Value::Vector { coord, values } => {
440 let Some(next) = next_depth(depth) else {
441 return DEPTH_LIMIT_MARKER.into();
442 };
443 let inner = values
444 .iter()
445 .map(|value| value.to_cypher_literal_at(next))
446 .collect::<Vec<_>>();
447 vector_text(&inner, *coord)
448 }
449 }
450 }
451
452 pub fn to_display_string(&self) -> String {
458 self.to_display_string_at(0)
459 }
460
461 fn to_display_string_at(&self, depth: u32) -> String {
465 match self {
466 Value::Null => "null".into(),
467 Value::Bool(b) => b.to_string(),
468 Value::Int(i) => i.to_string(),
469 Value::Float(f) => relate_model::value::float_text(*f),
470 Value::String(s) => String::from(&**s),
473 Value::Bytes(b) => bytes_as_int_list(b),
474 Value::List(xs) => {
475 let Some(next) = next_depth(depth) else {
476 return DEPTH_LIMIT_MARKER.into();
477 };
478 let inner: Vec<_> = xs.iter().map(|v| v.to_display_string_at(next)).collect();
479 format!("[{}]", inner.join(", "))
480 }
481 Value::Map(m) => {
486 let Some(next) = next_depth(depth) else {
487 return DEPTH_LIMIT_MARKER.into();
488 };
489 let inner: Vec<_> = m
490 .iter()
491 .map(|(k, v)| {
492 format!(
493 "{}: {}",
494 quote_identifier_shaped(k),
495 v.to_display_string_at(next)
496 )
497 })
498 .collect();
499 format!("{{{}}}", inner.join(", "))
500 }
501 Value::Node(n) => node_display(n),
502 Value::Relationship(r) => relationship_display(r),
503 Value::Path(p) => p.display_string(),
506 Value::Temporal(t) => t.full_seconds_string(),
507 Value::Uuid(u) => uuid_hyphenated(*u),
509 Value::Point(pt) => point_display(pt),
510 Value::Vector { coord, values } => {
511 let Some(next) = next_depth(depth) else {
512 return DEPTH_LIMIT_MARKER.into();
513 };
514 let inner: Vec<_> = values
515 .iter()
516 .map(|v| v.to_display_string_at(next))
517 .collect();
518 vector_text(&inner, *coord)
519 }
520 }
521 }
522}
523
524pub fn point_component(p: &PointValue, key: &str) -> Result<Value, Error> {
538 let name = key.to_ascii_lowercase();
539 Ok(match name.as_str() {
540 "srid" => Value::Int(i64::from(p.srid)),
541 "crs" => Value::String(
545 p.crs_name()
546 .unwrap_or_else(|| relate_model::wire::crs_name(p.srid))
547 .into(),
548 ),
549 _ => {
550 let Some(axis) = relate_model::point::point_axis(&name) else {
551 return Err(Error::argument_error(format!(
553 "no such component '{key}' on a point value"
554 )));
555 };
556 let cartesian = !relate_model::point::is_geographic(p.srid);
559 let unavailable =
560 (cartesian && axis.key(true) == name) || (axis.index == 2 && p.z.is_none());
561 if unavailable {
562 return Err(Error::argument_error(format!(
563 "Field: {key} is not available on a point value"
564 )));
565 }
566 match axis.index {
567 0 => Value::Float(p.x),
568 1 => Value::Float(p.y),
569 _ => Value::Float(p.z.expect("the 3D check admitted only a present z")),
570 }
571 }
572 })
573}
574
575fn point_display(p: &PointValue) -> String {
584 let coord = |value: f64| Value::Float(value).to_cypher_literal();
585 match (p.crs_name(), p.z) {
586 (Some(crs), Some(z)) => format!(
587 "point({{x: {}, y: {}, z: {}, crs: '{crs}'}})",
588 coord(p.x),
589 coord(p.y),
590 coord(z)
591 ),
592 (Some(crs), None) => format!(
593 "point({{x: {}, y: {}, crs: '{crs}'}})",
594 coord(p.x),
595 coord(p.y)
596 ),
597 (None, Some(z)) => format!(
598 "point({{srid: {}, x: {}, y: {}, z: {}}})",
599 p.srid,
600 coord(p.x),
601 coord(p.y),
602 coord(z)
603 ),
604 (None, None) => format!(
605 "point({{srid: {}, x: {}, y: {}}})",
606 p.srid,
607 coord(p.x),
608 coord(p.y)
609 ),
610 }
611}
612
613fn vector_text(elements: &[String], coord: VectorCoordKind) -> String {
620 format!(
621 "vector([{}], {}, {})",
622 elements.join(", "),
623 elements.len(),
624 coord.canonical_name()
625 )
626}
627
628impl Node {
629 pub fn to_cypher_literal(&self) -> String {
630 self.to_cypher_literal_at(0)
631 }
632
633 fn to_cypher_literal_at(&self, depth: u32) -> String {
636 let Some(next) = next_depth(depth) else {
637 return DEPTH_LIMIT_MARKER.into();
638 };
639 let labels: String = self.labels.iter().map(|l| format!(":{l}")).collect();
640 let props = props_suffix(&self.properties, next);
641 format!("({labels}{props})")
642 }
643}
644
645impl Relationship {
646 pub fn to_cypher_literal(&self) -> String {
647 self.to_cypher_literal_at(0)
648 }
649
650 fn to_cypher_literal_at(&self, depth: u32) -> String {
652 let Some(next) = next_depth(depth) else {
653 return DEPTH_LIMIT_MARKER.into();
654 };
655 let props = props_suffix(&self.properties, next);
656 format!("[:{}{}]", self.rel_type, props)
657 }
658}
659
660impl Path {
661 pub fn to_cypher_literal(&self) -> String {
662 self.to_cypher_literal_at(0)
663 }
664
665 fn to_cypher_literal_at(&self, depth: u32) -> String {
667 if next_depth(depth).is_none() {
670 return DEPTH_LIMIT_MARKER.into();
671 }
672 format!(
673 "<{}>",
674 self.walk(
675 |n| n.to_cypher_literal_at(depth),
676 |r| r.to_cypher_literal_at(depth)
677 )
678 )
679 }
680
681 fn display_string(&self) -> String {
689 self.walk(node_display, relationship_display)
690 }
691
692 fn walk(
697 &self,
698 node: impl Fn(&Node) -> String,
699 rel: impl Fn(&Relationship) -> String,
700 ) -> String {
701 let mut s = String::new();
702 for (i, n) in self.nodes.iter().enumerate() {
703 s.push_str(&node(n));
704 if let Some(r) = self.rels.get(i) {
705 let (left, right) = if r.start == n.id {
709 ("-", "->")
710 } else {
711 ("<-", "-")
712 };
713 s.push_str(&format!("{left}{}{right}", rel(r)));
714 }
715 }
716 s
717 }
718}
719
720fn node_display(n: &Node) -> String {
724 let mut labels: Vec<&str> = n.labels.iter().map(String::as_str).collect();
725 labels.sort_unstable();
726 let labels: String = labels
727 .iter()
728 .map(|l| format!(":{}", quote_identifier_shaped(l)))
729 .collect();
730 format!("({labels})")
731}
732
733fn relationship_display(r: &Relationship) -> String {
736 format!("[:{}]", quote_identifier_shaped(&r.rel_type))
737}
738
739impl fmt::Display for Value {
740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
741 write!(f, "{}", self.to_cypher_literal())
742 }
743}
744
745fn bytes_as_int_list(bytes: &[u8]) -> String {
749 let inner: Vec<_> = bytes.iter().map(u8::to_string).collect();
750 format!("[{}]", inner.join(", "))
751}
752
753fn escape_cypher_string(s: &str) -> String {
754 s.replace('\\', "\\\\").replace('\'', "\\'")
755}
756
757fn props_suffix(props: &PropertyMap, depth: u32) -> String {
762 if props.is_empty() {
763 String::new()
764 } else {
765 format!(" {}", map_to_cypher_literal(props.iter(), depth))
766 }
767}
768
769fn map_to_cypher_literal<'a>(
770 m: impl IntoIterator<Item = (&'a String, &'a Value)>,
771 depth: u32,
772) -> String {
773 let inner: Vec<_> = m
774 .into_iter()
775 .map(|(k, v)| format!("{}: {}", k, v.to_cypher_literal_at(depth)))
776 .collect();
777 format!("{{{}}}", inner.join(", "))
778}
779
780pub fn uuid_hyphenated(u: u128) -> String {
783 let hex = format!("{u:032x}");
784 format!(
785 "{}-{}-{}-{}-{}",
786 &hex[0..8],
787 &hex[8..12],
788 &hex[12..16],
789 &hex[16..20],
790 &hex[20..32]
791 )
792}
793
794pub fn uuid_parse(s: &str) -> Option<u128> {
799 const GROUP_LEN: [usize; 5] = [8, 4, 4, 4, 12];
804 let mut chars = s.chars();
805 let mut u: u128 = 0;
806 for (i, &len) in GROUP_LEN.iter().enumerate() {
807 if i > 0 && chars.next()? != '-' {
808 return None;
809 }
810 for _ in 0..len {
811 u = (u << 4) | chars.next()?.to_digit(16)? as u128;
812 }
813 }
814 if chars.next().is_some() {
815 return None;
816 }
817 Some(u)
818}
819
820#[cfg(test)]
821mod depth_tests;
822#[cfg(test)]
823mod expansion_tests;
824#[cfg(test)]
825mod point_tests;
826#[cfg(test)]
827mod tests;