1use crate::vector::float16::{bfloat16_bits, f16_bits_to_f32, f32_to_f16_bits};
2use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime};
3use indexmap::IndexMap;
4use std::fmt;
5
6#[derive(Debug, Clone, PartialEq)]
9pub struct IsoDuration {
10 pub months: i64,
11 pub days: i64,
12 pub seconds: i64,
13 pub nanoseconds: i64,
14}
15
16impl IsoDuration {
17 pub fn new(months: i64, days: i64, seconds: i64, nanoseconds: i64) -> Self {
18 Self {
19 months,
20 days,
21 seconds,
22 nanoseconds,
23 }
24 }
25
26 pub fn zero() -> Self {
27 Self::new(0, 0, 0, 0)
28 }
29}
30
31impl fmt::Display for IsoDuration {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 write!(f, "P")?;
34 let years = self.months / 12;
35 let months = self.months % 12;
36 if years != 0 {
37 write!(f, "{years}Y")?;
38 }
39 if months != 0 {
40 write!(f, "{months}M")?;
41 }
42 if self.days != 0 {
43 write!(f, "{}D", self.days)?;
44 }
45
46 let total_nanos = i128::from(self.seconds) * 1_000_000_000 + i128::from(self.nanoseconds);
54 let has_time = total_nanos != 0;
55
56 if has_time || (self.months == 0 && self.days == 0) {
57 write!(f, "T")?;
58
59 let negative = total_nanos < 0;
60 let abs_nanos = total_nanos.unsigned_abs();
61 let abs_seconds = abs_nanos / 1_000_000_000;
62 let frac_nanos = abs_nanos % 1_000_000_000;
63
64 let hours = abs_seconds / 3600;
65 let mins = (abs_seconds % 3600) / 60;
66 let secs = abs_seconds % 60;
67
68 let sign = if negative { "-" } else { "" };
69
70 if hours != 0 {
71 write!(f, "{sign}{hours}H")?;
72 }
73 if mins != 0 {
74 write!(f, "{sign}{mins}M")?;
77 }
78 if secs != 0 || frac_nanos != 0 || (!has_time && self.months == 0 && self.days == 0) {
79 if frac_nanos != 0 {
80 let frac = format!("{frac_nanos:09}");
81 let trimmed = frac.trim_end_matches('0');
82 write!(f, "{sign}{secs}.{trimmed}S")?;
83 } else {
84 write!(f, "{sign}{secs}S")?;
85 }
86 }
87 }
88 Ok(())
89 }
90}
91
92#[derive(Debug, Clone, PartialEq)]
94pub struct PointValue {
95 pub srid: i32,
96 pub x: f64,
97 pub y: f64,
98 pub z: Option<f64>,
99}
100
101impl PointValue {
102 pub fn cartesian_2d(x: f64, y: f64) -> Self {
103 Self {
104 srid: 7203,
105 x,
106 y,
107 z: None,
108 }
109 }
110
111 pub fn cartesian_3d(x: f64, y: f64, z: f64) -> Self {
112 Self {
113 srid: 9157,
114 x,
115 y,
116 z: Some(z),
117 }
118 }
119
120 pub fn wgs84_2d(longitude: f64, latitude: f64) -> Self {
121 Self {
122 srid: 4326,
123 x: longitude,
124 y: latitude,
125 z: None,
126 }
127 }
128
129 pub fn wgs84_3d(longitude: f64, latitude: f64, height: f64) -> Self {
130 Self {
131 srid: 4979,
132 x: longitude,
133 y: latitude,
134 z: Some(height),
135 }
136 }
137
138 pub fn is_3d(&self) -> bool {
141 self.z.is_some()
142 }
143
144 pub fn crs_name(&self) -> Option<&'static str> {
151 let canonical_3d = match self.srid {
152 4326 | 7203 => false,
153 4979 | 9157 => true,
154 _ => return None,
155 };
156 (canonical_3d == self.is_3d()).then(|| crate::wire::crs_name(self.srid))
157 }
158}
159
160impl fmt::Display for PointValue {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 match self.z {
163 Some(z) => write!(
164 f,
165 "point({{srid: {}, x: {}, y: {}, z: {}}})",
166 self.srid, self.x, self.y, z
167 ),
168 None => write!(
169 f,
170 "point({{srid: {}, x: {}, y: {}}})",
171 self.srid, self.x, self.y
172 ),
173 }
174 }
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
187pub enum VectorCoordKind {
188 Int8,
189 Int16,
190 Int32,
191 Int64,
192 Float16,
194 BFloat16,
197 Float32,
198 Float64,
199}
200
201impl VectorCoordKind {
202 pub fn canonical_name(&self) -> &'static str {
208 match self {
209 VectorCoordKind::Int8 => "INTEGER8",
210 VectorCoordKind::Int16 => "INTEGER16",
211 VectorCoordKind::Int32 => "INTEGER32",
212 VectorCoordKind::Int64 => "INTEGER",
213 VectorCoordKind::Float16 => "FLOAT16",
214 VectorCoordKind::BFloat16 => "BFLOAT16",
215 VectorCoordKind::Float32 => "FLOAT32",
216 VectorCoordKind::Float64 => "FLOAT",
217 }
218 }
219
220 pub fn from_canonical_name(name: &str) -> Option<Self> {
223 Some(match name {
224 "INTEGER8" => VectorCoordKind::Int8,
225 "INTEGER16" => VectorCoordKind::Int16,
226 "INTEGER32" => VectorCoordKind::Int32,
227 "INTEGER" => VectorCoordKind::Int64,
228 "FLOAT16" => VectorCoordKind::Float16,
229 "BFLOAT16" => VectorCoordKind::BFloat16,
230 "FLOAT32" => VectorCoordKind::Float32,
231 "FLOAT" => VectorCoordKind::Float64,
232 _ => return None,
233 })
234 }
235
236 pub fn from_alias(name: &str) -> Option<Self> {
241 Some(match name {
242 "INT8" | "INTEGER8" => VectorCoordKind::Int8,
243 "INT16" | "INTEGER16" => VectorCoordKind::Int16,
244 "INT32" | "INTEGER32" => VectorCoordKind::Int32,
245 "INT" | "INTEGER" | "INT64" | "INTEGER64" | "SIGNED INTEGER" => VectorCoordKind::Int64,
246 "FLOAT16" => VectorCoordKind::Float16,
247 "BFLOAT16" => VectorCoordKind::BFloat16,
248 "FLOAT32" => VectorCoordKind::Float32,
249 "FLOAT" | "FLOAT64" => VectorCoordKind::Float64,
250 _ => return None,
251 })
252 }
253
254 pub fn is_integer(&self) -> bool {
258 !matches!(
259 self,
260 VectorCoordKind::Float16
261 | VectorCoordKind::BFloat16
262 | VectorCoordKind::Float32
263 | VectorCoordKind::Float64
264 )
265 }
266
267 pub fn order_rank(&self) -> u8 {
272 match self {
273 VectorCoordKind::Int8 => 0,
274 VectorCoordKind::Int16 => 1,
275 VectorCoordKind::Int32 => 2,
276 VectorCoordKind::Int64 => 3,
277 VectorCoordKind::BFloat16 => 4,
278 VectorCoordKind::Float16 => 5,
279 VectorCoordKind::Float32 => 6,
280 VectorCoordKind::Float64 => 7,
281 }
282 }
283
284 pub fn narrow_float(self, f: f64) -> Option<f64> {
291 if !f.is_finite() {
292 return None;
293 }
294 let narrowed = match self {
295 VectorCoordKind::Float64 => f,
296 VectorCoordKind::Float32 => f as f32 as f64,
297 VectorCoordKind::Float16 => f16_bits_to_f32(f32_to_f16_bits(f as f32)) as f64,
298 VectorCoordKind::BFloat16 => f32::from_bits(bfloat16_bits(f as f32)) as f64,
299 VectorCoordKind::Int8
300 | VectorCoordKind::Int16
301 | VectorCoordKind::Int32
302 | VectorCoordKind::Int64 => return None,
303 };
304 narrowed.is_finite().then_some(narrowed)
305 }
306
307 pub fn is_exact(self, f: f64) -> bool {
316 f.is_finite() && self.narrow_float(f) == Some(f)
317 }
318
319 pub fn holds_int(self, n: i64) -> bool {
325 match self {
326 VectorCoordKind::Int8 => i8::try_from(n).is_ok(),
327 VectorCoordKind::Int16 => i16::try_from(n).is_ok(),
328 VectorCoordKind::Int32 => i32::try_from(n).is_ok(),
329 VectorCoordKind::Int64 => true,
330 VectorCoordKind::Float16
331 | VectorCoordKind::BFloat16
332 | VectorCoordKind::Float32
333 | VectorCoordKind::Float64 => false,
334 }
335 }
336}
337
338pub type Coord2D = [f64; 2];
340
341#[derive(Debug, Clone, PartialEq)]
343pub enum GeometryValue {
344 LineString {
345 coordinates: Vec<Coord2D>,
346 srid: i32,
347 },
348 Polygon {
349 rings: Vec<Vec<Coord2D>>,
351 srid: i32,
352 },
353 MultiPoint {
354 points: Vec<Coord2D>,
355 srid: i32,
356 },
357 MultiLineString {
358 lines: Vec<Vec<Coord2D>>,
359 srid: i32,
360 },
361 MultiPolygon {
362 polygons: Vec<Vec<Vec<Coord2D>>>,
363 srid: i32,
364 },
365 GeometryCollection {
366 geometries: Vec<GeometryValue>,
367 srid: i32,
368 },
369}
370
371impl GeometryValue {
372 pub fn srid(&self) -> i32 {
374 match self {
375 GeometryValue::LineString { srid, .. }
376 | GeometryValue::Polygon { srid, .. }
377 | GeometryValue::MultiPoint { srid, .. }
378 | GeometryValue::MultiLineString { srid, .. }
379 | GeometryValue::MultiPolygon { srid, .. }
380 | GeometryValue::GeometryCollection { srid, .. } => *srid,
381 }
382 }
383
384 pub fn type_name(&self) -> &'static str {
386 match self {
387 GeometryValue::LineString { .. } => "LineString",
388 GeometryValue::Polygon { .. } => "Polygon",
389 GeometryValue::MultiPoint { .. } => "MultiPoint",
390 GeometryValue::MultiLineString { .. } => "MultiLineString",
391 GeometryValue::MultiPolygon { .. } => "MultiPolygon",
392 GeometryValue::GeometryCollection { .. } => "GeometryCollection",
393 }
394 }
395}
396
397impl fmt::Display for GeometryValue {
398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
399 match self {
400 GeometryValue::LineString { coordinates, srid } => {
401 write!(f, "linestring({{srid: {srid}, coordinates: [")?;
402 for (i, c) in coordinates.iter().enumerate() {
403 if i > 0 {
404 write!(f, ", ")?;
405 }
406 write!(f, "[{}, {}]", c[0], c[1])?;
407 }
408 write!(f, "]}})")
409 }
410 GeometryValue::Polygon { rings, srid } => {
411 write!(f, "polygon({{srid: {srid}, coordinates: [")?;
412 for (i, ring) in rings.iter().enumerate() {
413 if i > 0 {
414 write!(f, ", ")?;
415 }
416 write!(f, "[")?;
417 for (j, c) in ring.iter().enumerate() {
418 if j > 0 {
419 write!(f, ", ")?;
420 }
421 write!(f, "[{}, {}]", c[0], c[1])?;
422 }
423 write!(f, "]")?;
424 }
425 write!(f, "]}})")
426 }
427 GeometryValue::MultiPoint { points, srid } => {
428 write!(f, "multipoint({{srid: {srid}, coordinates: [")?;
429 for (i, c) in points.iter().enumerate() {
430 if i > 0 {
431 write!(f, ", ")?;
432 }
433 write!(f, "[{}, {}]", c[0], c[1])?;
434 }
435 write!(f, "]}})")
436 }
437 GeometryValue::MultiLineString { lines: _, srid } => {
438 write!(f, "multilinestring({{srid: {srid}, ...}})")
439 }
440 GeometryValue::MultiPolygon { polygons: _, srid } => {
441 write!(f, "multipolygon({{srid: {srid}, ...}})")
442 }
443 GeometryValue::GeometryCollection { geometries, srid } => {
444 write!(
445 f,
446 "geometrycollection({{srid: {}, count: {}}})",
447 srid,
448 geometries.len()
449 )
450 }
451 }
452 }
453}
454
455#[derive(Debug, Clone)]
460pub enum CypherValue {
461 Null,
462 Bool(bool),
463 Int(i64),
464 Float(f64),
465 Str(String),
466 List(Vec<CypherValue>),
467 Map(IndexMap<String, CypherValue>),
468 Node {
469 id: i64,
470 labels: Vec<String>,
471 properties: IndexMap<String, CypherValue>,
472 },
473 Relationship {
474 id: i64,
475 start_id: i64,
476 end_id: i64,
477 rel_type: String,
478 properties: IndexMap<String, CypherValue>,
479 },
480 Path {
481 nodes: Vec<CypherValue>,
482 relationships: Vec<CypherValue>,
483 },
484 Date(NaiveDate),
485 Time(NaiveTime, Option<FixedOffset>),
486 DateTime(DateTime<FixedOffset>, Option<String>),
488 LocalDateTime(NaiveDateTime),
489 Duration(IsoDuration),
490 Point(PointValue),
491 Geometry(GeometryValue),
492 Vector {
499 coord: VectorCoordKind,
500 dim: usize,
501 values: Vec<CypherValue>,
502 },
503}
504
505impl CypherValue {
506 pub fn is_null(&self) -> bool {
508 matches!(self, CypherValue::Null)
509 }
510
511 pub fn is_temporal(&self) -> bool {
517 match self {
518 CypherValue::Date(_)
519 | CypherValue::Time(..)
520 | CypherValue::DateTime(..)
521 | CypherValue::LocalDateTime(_)
522 | CypherValue::Duration(_) => true,
523 CypherValue::Null
524 | CypherValue::Bool(_)
525 | CypherValue::Int(_)
526 | CypherValue::Float(_)
527 | CypherValue::Str(_)
528 | CypherValue::List(_)
529 | CypherValue::Map(_)
530 | CypherValue::Node { .. }
531 | CypherValue::Relationship { .. }
532 | CypherValue::Path { .. }
533 | CypherValue::Geometry(_)
534 | CypherValue::Vector { .. }
535 | CypherValue::Point(_) => false,
536 }
537 }
538
539 pub fn type_name(&self) -> &'static str {
541 match self {
542 CypherValue::Null => "NULL",
543 CypherValue::Bool(_) => "BOOLEAN",
544 CypherValue::Int(_) => "INTEGER",
545 CypherValue::Float(_) => "FLOAT",
546 CypherValue::Str(_) => "STRING",
547 CypherValue::List(_) => "LIST",
548 CypherValue::Map(_) => "MAP",
549 CypherValue::Node { .. } => "NODE",
550 CypherValue::Relationship { .. } => "RELATIONSHIP",
551 CypherValue::Path { .. } => "PATH",
552 CypherValue::Date(_) => "DATE",
553 CypherValue::Time(_, _) => "TIME",
554 CypherValue::DateTime(..) => "DATE_TIME",
555 CypherValue::LocalDateTime(_) => "LOCAL_DATE_TIME",
556 CypherValue::Duration(_) => "DURATION",
557 CypherValue::Point(_) => "POINT",
558 CypherValue::Geometry(g) => g.type_name(),
559 CypherValue::Vector { .. } => "VECTOR",
560 }
561 }
562
563 pub fn as_bool(&self) -> Option<bool> {
565 match self {
566 CypherValue::Bool(b) => Some(*b),
567 _ => None,
568 }
569 }
570
571 pub fn as_int(&self) -> Option<i64> {
573 match self {
574 CypherValue::Int(i) => Some(*i),
575 _ => None,
576 }
577 }
578
579 pub fn as_float(&self) -> Option<f64> {
581 match self {
582 CypherValue::Float(f) => Some(*f),
583 CypherValue::Int(i) => Some(*i as f64),
584 _ => None,
585 }
586 }
587
588 pub fn as_str(&self) -> Option<&str> {
590 match self {
591 CypherValue::Str(s) => Some(s),
592 _ => None,
593 }
594 }
595
596 pub fn as_list(&self) -> Option<&[CypherValue]> {
598 match self {
599 CypherValue::List(l) => Some(l),
600 _ => None,
601 }
602 }
603
604 pub fn as_map(&self) -> Option<&IndexMap<String, CypherValue>> {
606 match self {
607 CypherValue::Map(m) => Some(m),
608 _ => None,
609 }
610 }
611
612 pub fn to_bool_3vl(&self) -> Option<bool> {
615 match self {
616 CypherValue::Null => None,
617 CypherValue::Bool(b) => Some(*b),
618 _ => Some(true), }
620 }
621
622 pub fn as_numeric(&self) -> Option<(f64, bool)> {
625 match self {
626 CypherValue::Int(i) => Some((*i as f64, true)),
627 CypherValue::Float(f) => Some((*f, false)),
628 _ => None,
629 }
630 }
631}
632
633impl fmt::Display for CypherValue {
634 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635 match self {
636 CypherValue::Null => write!(f, "null"),
637 CypherValue::Bool(b) => write!(f, "{b}"),
638 CypherValue::Int(i) => write!(f, "{i}"),
639 CypherValue::Float(v) => {
640 if v.is_nan() {
641 write!(f, "NaN")
642 } else if v.is_infinite() {
643 write!(f, "{}Inf", if *v < 0.0 { "-" } else { "" })
644 } else if v.fract() == 0.0 {
645 write!(f, "{v}.0")
646 } else {
647 write!(f, "{v}")
648 }
649 }
650 CypherValue::Str(s) => write!(f, "\"{s}\""),
651 CypherValue::List(items) => {
652 write!(f, "[")?;
653 for (i, item) in items.iter().enumerate() {
654 if i > 0 {
655 write!(f, ", ")?;
656 }
657 write!(f, "{item}")?;
658 }
659 write!(f, "]")
660 }
661 CypherValue::Map(map) => {
662 write!(f, "{{")?;
663 for (i, (k, v)) in map.iter().enumerate() {
664 if i > 0 {
665 write!(f, ", ")?;
666 }
667 write!(f, "{k}: {v}")?;
668 }
669 write!(f, "}}")
670 }
671 CypherValue::Node {
672 labels, properties, ..
673 } => {
674 write!(f, "(:{}", labels.join(":"))?;
675 if !properties.is_empty() {
676 write!(f, " {{")?;
677 for (i, (k, v)) in properties.iter().enumerate() {
678 if i > 0 {
679 write!(f, ", ")?;
680 }
681 write!(f, "{k}: {v}")?;
682 }
683 write!(f, "}}")?;
684 }
685 write!(f, ")")
686 }
687 CypherValue::Relationship {
688 rel_type,
689 properties,
690 ..
691 } => {
692 write!(f, "[:{rel_type}")?;
693 if !properties.is_empty() {
694 write!(f, " {{")?;
695 for (i, (k, v)) in properties.iter().enumerate() {
696 if i > 0 {
697 write!(f, ", ")?;
698 }
699 write!(f, "{k}: {v}")?;
700 }
701 write!(f, "}}")?;
702 }
703 write!(f, "]")
704 }
705 CypherValue::Path {
706 nodes,
707 relationships,
708 } => {
709 for (i, node) in nodes.iter().enumerate() {
710 if i > 0 {
711 if let Some(rel) = relationships.get(i - 1) {
712 write!(f, "-{rel}-")?;
713 } else {
714 write!(f, "--")?;
715 }
716 }
717 write!(f, "{node}")?;
718 }
719 Ok(())
720 }
721 CypherValue::Date(d) => write!(f, "{d}"),
722 CypherValue::Time(t, tz) => {
723 use chrono::Timelike;
724 let nanos = t.nanosecond() % 1_000_000_000;
726 if nanos != 0 {
727 let frac = format!("{nanos:09}");
728 let trimmed = frac.trim_end_matches('0');
729 write!(
730 f,
731 "{:02}:{:02}:{:02}.{}",
732 t.hour(),
733 t.minute(),
734 t.second(),
735 trimmed
736 )?;
737 } else if t.second() != 0 {
738 write!(f, "{}", t.format("%H:%M:%S"))?;
739 } else {
740 write!(f, "{}", t.format("%H:%M"))?;
741 }
742 if let Some(offset) = tz {
744 let total_secs = offset.local_minus_utc();
745 if total_secs == 0 {
746 write!(f, "Z")
747 } else {
748 let sign = if total_secs >= 0 { '+' } else { '-' };
749 let abs_secs = total_secs.unsigned_abs();
750 let hours = abs_secs / 3600;
751 let mins = (abs_secs % 3600) / 60;
752 let secs = abs_secs % 60;
753 if secs != 0 {
754 write!(f, "{sign}{hours:02}:{mins:02}:{secs:02}")
755 } else {
756 write!(f, "{sign}{hours:02}:{mins:02}")
757 }
758 }
759 } else {
760 Ok(())
761 }
762 }
763 CypherValue::DateTime(dt, tz_name) => {
764 let nanos = dt.timestamp_subsec_nanos();
766 let date_part = dt.date_naive();
767 let time_part = dt.time();
768 if nanos != 0 {
769 let frac = format!("{nanos:09}");
770 let trimmed = frac.trim_end_matches('0');
771 write!(
772 f,
773 "{}T{}.{}",
774 date_part,
775 time_part.format("%H:%M:%S"),
776 trimmed
777 )?;
778 } else {
779 write!(f, "{}T{}", date_part, time_part.format("%H:%M:%S"))?;
780 }
781 let offset = dt.offset();
783 let total_secs = offset.local_minus_utc();
784 if total_secs == 0 {
785 write!(f, "Z")?;
786 } else {
787 let sign = if total_secs >= 0 { '+' } else { '-' };
788 let abs_secs = total_secs.unsigned_abs();
789 let hours = abs_secs / 3600;
790 let mins = (abs_secs % 3600) / 60;
791 let secs_rem = abs_secs % 60;
792 if secs_rem != 0 {
793 write!(f, "{sign}{hours:02}:{mins:02}:{secs_rem:02}")?;
794 } else {
795 write!(f, "{sign}{hours:02}:{mins:02}")?;
796 }
797 }
798 if let Some(tz) = tz_name {
800 write!(f, "[{tz}]")?;
801 }
802 Ok(())
803 }
804 CypherValue::LocalDateTime(dt) => {
805 let nanos = dt.and_utc().timestamp_subsec_nanos();
807 if nanos != 0 {
808 let frac = format!("{nanos:09}");
809 let trimmed = frac.trim_end_matches('0');
810 write!(
811 f,
812 "{}T{}.{}",
813 dt.date(),
814 dt.time().format("%H:%M:%S"),
815 trimmed
816 )
817 } else {
818 write!(f, "{}T{}", dt.date(), dt.time().format("%H:%M:%S"))
819 }
820 }
821 CypherValue::Duration(d) => write!(f, "{d}"),
822 CypherValue::Point(p) => write!(f, "{p}"),
823 CypherValue::Geometry(g) => write!(f, "{g}"),
824 CypherValue::Vector { coord, dim, values } => {
825 write!(f, "vector([")?;
826 for (i, v) in values.iter().enumerate() {
827 if i > 0 {
828 write!(f, ", ")?;
829 }
830 write!(f, "{v}")?;
831 }
832 write!(f, "], {}, {} NOT NULL)", dim, coord.canonical_name())
833 }
834 }
835 }
836}
837
838impl PartialEq for CypherValue {
839 fn eq(&self, other: &Self) -> bool {
840 match (self, other) {
841 (CypherValue::Null, CypherValue::Null) => true,
842 (CypherValue::Bool(a), CypherValue::Bool(b)) => a == b,
843 (CypherValue::Int(a), CypherValue::Int(b)) => a == b,
844 (CypherValue::Float(a), CypherValue::Float(b)) => a == b,
845 (CypherValue::Int(a), CypherValue::Float(b)) => {
852 crate::canonical_key::eq_i64_f64(*a, *b)
853 }
854 (CypherValue::Float(a), CypherValue::Int(b)) => {
855 crate::canonical_key::eq_i64_f64(*b, *a)
856 }
857 (CypherValue::Str(a), CypherValue::Str(b)) => a == b,
858 (CypherValue::List(a), CypherValue::List(b)) => a == b,
859 (CypherValue::Map(a), CypherValue::Map(b)) => a == b,
860 (CypherValue::Node { id: a, .. }, CypherValue::Node { id: b, .. }) => a == b,
861 (CypherValue::Relationship { id: a, .. }, CypherValue::Relationship { id: b, .. }) => {
862 a == b
863 }
864 (CypherValue::Date(a), CypherValue::Date(b)) => a == b,
865 (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => a == b && ao == bo,
866 (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a == b,
867 (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a == b,
868 (CypherValue::Duration(a), CypherValue::Duration(b)) => a == b,
869 (CypherValue::Point(a), CypherValue::Point(b)) => a == b,
870 (CypherValue::Geometry(a), CypherValue::Geometry(b)) => a == b,
871 (
872 CypherValue::Vector {
873 coord: ca,
874 dim: da,
875 values: va,
876 },
877 CypherValue::Vector {
878 coord: cb,
879 dim: db,
880 values: vb,
881 },
882 ) => ca == cb && da == db && va == vb,
883 (
884 CypherValue::Path {
885 nodes: n1,
886 relationships: r1,
887 },
888 CypherValue::Path {
889 nodes: n2,
890 relationships: r2,
891 },
892 ) => n1 == n2 && r1 == r2,
893 _ => false,
894 }
895 }
896}
897
898impl PartialOrd for CypherValue {
899 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
900 match (self, other) {
901 (CypherValue::Int(a), CypherValue::Int(b)) => a.partial_cmp(b),
902 (CypherValue::Float(a), CypherValue::Float(b)) => a.partial_cmp(b),
903 (CypherValue::Int(a), CypherValue::Float(b)) => {
907 crate::canonical_key::cmp_i64_f64(*a, *b)
908 }
909 (CypherValue::Float(a), CypherValue::Int(b)) => {
910 crate::canonical_key::cmp_i64_f64(*b, *a).map(std::cmp::Ordering::reverse)
911 }
912 (CypherValue::Str(a), CypherValue::Str(b)) => a.partial_cmp(b),
913 (CypherValue::Bool(a), CypherValue::Bool(b)) => a.partial_cmp(b),
914 (CypherValue::Date(a), CypherValue::Date(b)) => a.partial_cmp(b),
915 (CypherValue::List(a), CypherValue::List(b)) => {
916 for (av, bv) in a.iter().zip(b.iter()) {
918 match av.partial_cmp(bv) {
919 Some(std::cmp::Ordering::Equal) => continue,
920 Some(ord) => return Some(ord),
921 None => return None,
922 }
923 }
924 a.len().partial_cmp(&b.len())
925 }
926 (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => {
927 match (ao, bo) {
929 (Some(a_off), Some(b_off)) => {
930 use chrono::Timelike;
931 let a_utc_secs =
932 a.num_seconds_from_midnight() as i64 - a_off.local_minus_utc() as i64;
933 let b_utc_secs =
934 b.num_seconds_from_midnight() as i64 - b_off.local_minus_utc() as i64;
935 match a_utc_secs.partial_cmp(&b_utc_secs) {
936 Some(std::cmp::Ordering::Equal) => {
937 let a_nanos = a.nanosecond() % 1_000_000_000;
939 let b_nanos = b.nanosecond() % 1_000_000_000;
940 a_nanos.partial_cmp(&b_nanos)
941 }
942 other => other,
943 }
944 }
945 (None, None) => a.partial_cmp(b),
946 _ => None,
947 }
948 }
949 (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a.partial_cmp(b),
950 (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a.partial_cmp(b),
951 _ => None,
952 }
953 }
954}
955
956impl From<bool> for CypherValue {
957 fn from(b: bool) -> Self {
958 CypherValue::Bool(b)
959 }
960}
961
962impl From<i64> for CypherValue {
963 fn from(i: i64) -> Self {
964 CypherValue::Int(i)
965 }
966}
967
968impl From<f64> for CypherValue {
969 fn from(f: f64) -> Self {
970 CypherValue::Float(f)
971 }
972}
973
974impl From<String> for CypherValue {
975 fn from(s: String) -> Self {
976 CypherValue::Str(s)
977 }
978}
979
980impl From<&str> for CypherValue {
981 fn from(s: &str) -> Self {
982 CypherValue::Str(s.to_string())
983 }
984}
985
986impl<T: Into<CypherValue>> From<Vec<T>> for CypherValue {
987 fn from(v: Vec<T>) -> Self {
988 CypherValue::List(v.into_iter().map(|x| x.into()).collect())
989 }
990}
991
992impl<T: Into<CypherValue>> From<Option<T>> for CypherValue {
993 fn from(o: Option<T>) -> Self {
994 match o {
995 Some(v) => v.into(),
996 None => CypherValue::Null,
997 }
998 }
999}
1000
1001#[cfg(test)]
1002mod tests {
1003 use super::*;
1004
1005 #[test]
1006 #[allow(clippy::approx_constant)]
1007 fn test_type_names() {
1008 assert_eq!(CypherValue::Null.type_name(), "NULL");
1009 assert_eq!(CypherValue::Bool(true).type_name(), "BOOLEAN");
1010 assert_eq!(CypherValue::Int(42).type_name(), "INTEGER");
1011 assert_eq!(CypherValue::Float(3.14).type_name(), "FLOAT");
1012 assert_eq!(CypherValue::Str("hello".into()).type_name(), "STRING");
1013 assert_eq!(CypherValue::List(vec![]).type_name(), "LIST");
1014 assert_eq!(CypherValue::Map(IndexMap::new()).type_name(), "MAP");
1015 }
1016
1017 #[test]
1018 fn point_crs_name_classifies_the_four_point_codes() {
1019 let cases = [
1020 (PointValue::cartesian_2d(1.0, 2.0), "cartesian", false),
1021 (
1022 PointValue::cartesian_3d(1.0, 2.0, 3.0),
1023 "cartesian-3d",
1024 true,
1025 ),
1026 (PointValue::wgs84_2d(1.0, 2.0), "wgs-84", false),
1027 (PointValue::wgs84_3d(1.0, 2.0, 3.0), "wgs-84-3d", true),
1028 ];
1029 for (point, name, is_3d) in cases {
1030 assert_eq!(point.crs_name(), Some(name), "{point:?}");
1031 assert_eq!(point.is_3d(), is_3d, "{point:?}");
1032 }
1033 let unknown = PointValue {
1036 srid: 1234,
1037 x: 1.0,
1038 y: 2.0,
1039 z: None,
1040 };
1041 assert_eq!(unknown.crs_name(), None);
1042 let wrong_dimension = PointValue {
1043 srid: 7203,
1044 x: 1.0,
1045 y: 2.0,
1046 z: Some(3.0),
1047 };
1048 assert_eq!(wrong_dimension.crs_name(), None);
1049 }
1050
1051 #[test]
1052 fn test_int_float_equality() {
1053 assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1054 assert_eq!(CypherValue::Float(1.0), CypherValue::Int(1));
1055 assert_ne!(CypherValue::Int(1), CypherValue::Float(1.5));
1056 }
1057
1058 #[test]
1059 fn test_partial_ord() {
1060 assert!(CypherValue::Int(1) < CypherValue::Int(2));
1061 assert!(CypherValue::Int(1) < CypherValue::Float(1.5));
1062 assert!(CypherValue::Str("a".into()) < CypherValue::Str("b".into()));
1063 }
1064
1065 #[test]
1066 fn int_float_equality_is_exact_past_2_pow_53() {
1067 let big_int = CypherValue::Int(9_007_199_254_740_993);
1074 let near_float = CypherValue::Float(9_007_199_254_740_992.0);
1075 assert_ne!(big_int, near_float);
1076 assert_ne!(near_float, big_int);
1077
1078 assert_eq!(
1080 CypherValue::Int(9_007_199_254_740_992),
1081 CypherValue::Float(9_007_199_254_740_992.0)
1082 );
1083
1084 assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1086 assert_eq!(CypherValue::Int(0), CypherValue::Float(-0.0));
1087 }
1088
1089 #[test]
1090 fn int_float_ordering_stays_consistent_with_equality() {
1091 let probes = [
1096 (9_007_199_254_740_993_i64, 9_007_199_254_740_992.0_f64),
1097 (9_007_199_254_740_992, 9_007_199_254_740_992.0),
1098 (i64::MAX, 9_223_372_036_854_775_808.0), (i64::MIN, -9_223_372_036_854_775_808.0), (0, -0.0),
1101 (1, 1.0),
1102 (2, 1.5),
1103 (1, 1.5),
1104 ];
1105 for (i, f) in probes {
1106 let iv = CypherValue::Int(i);
1107 let fv = CypherValue::Float(f);
1108 let eq = iv == fv;
1109 let cmp_eq = iv.partial_cmp(&fv) == Some(std::cmp::Ordering::Equal);
1110 assert_eq!(eq, cmp_eq, "eq/ord disagree for Int({i}) vs Float({f})");
1111 let rev = fv.partial_cmp(&iv);
1113 assert_eq!(
1114 iv.partial_cmp(&fv),
1115 rev.map(std::cmp::Ordering::reverse),
1116 "forward/reverse ordering not antisymmetric for {i}/{f}"
1117 );
1118 }
1119 assert!(
1121 CypherValue::Int(9_007_199_254_740_993) > CypherValue::Float(9_007_199_254_740_992.0)
1122 );
1123 }
1124
1125 #[test]
1126 fn test_display() {
1127 assert_eq!(format!("{}", CypherValue::Null), "null");
1128 assert_eq!(format!("{}", CypherValue::Bool(true)), "true");
1129 assert_eq!(format!("{}", CypherValue::Int(42)), "42");
1130 assert_eq!(format!("{}", CypherValue::Float(3.0)), "3.0");
1131 assert_eq!(format!("{}", CypherValue::Str("hi".into())), "\"hi\"");
1132 }
1133
1134 #[test]
1135 #[allow(clippy::approx_constant)]
1136 fn test_as_float_promotion() {
1137 assert_eq!(CypherValue::Int(5).as_float(), Some(5.0));
1138 assert_eq!(CypherValue::Float(3.14).as_float(), Some(3.14));
1139 assert_eq!(CypherValue::Str("x".into()).as_float(), None);
1140 }
1141
1142 #[test]
1143 fn test_three_valued_logic() {
1144 assert_eq!(CypherValue::Null.to_bool_3vl(), None);
1145 assert_eq!(CypherValue::Bool(true).to_bool_3vl(), Some(true));
1146 assert_eq!(CypherValue::Bool(false).to_bool_3vl(), Some(false));
1147 assert_eq!(CypherValue::Int(0).to_bool_3vl(), Some(true));
1148 }
1149
1150 #[test]
1151 fn test_iso_duration_display() {
1152 assert_eq!(format!("{}", IsoDuration::new(0, 0, 0, 0)), "PT0S");
1153 assert_eq!(format!("{}", IsoDuration::new(14, 0, 0, 0)), "P1Y2M");
1154 assert_eq!(format!("{}", IsoDuration::new(0, 5, 3661, 0)), "P5DT1H1M1S");
1155 assert_eq!(
1157 format!("{}", IsoDuration::new(0, 0, -3661, -500_000_000)),
1158 "PT-1H-1M-1.5S"
1159 );
1160 assert_eq!(
1162 format!("{}", IsoDuration::new(0, 0, 1, -1_500_000_000)),
1163 "PT-0.5S"
1164 );
1165 }
1166
1167 #[test]
1168 fn test_iso_duration_display_extreme_magnitudes() {
1169 assert_eq!(
1171 format!("{}", IsoDuration::new(12_000_000, 0, 0, 0)),
1172 "P1000000Y"
1173 );
1174 assert_eq!(
1175 format!("{}", IsoDuration::new(-12_000_000, 0, 0, 0)),
1176 "P-1000000Y"
1177 );
1178 assert_eq!(
1181 format!("{}", IsoDuration::new(0, 0, i64::MAX, 999_999_999)),
1182 "PT2562047788015215H30M7.999999999S"
1183 );
1184 assert_eq!(
1185 format!("{}", IsoDuration::new(0, 0, i64::MIN, -999_999_999)),
1186 "PT-2562047788015215H-30M-8.999999999S"
1187 );
1188 assert_eq!(
1190 format!("{}", IsoDuration::new(12_000_000, 0, i64::MAX, 999_999_999)),
1191 "P1000000YT2562047788015215H30M7.999999999S"
1192 );
1193 assert_eq!(
1194 format!(
1195 "{}",
1196 IsoDuration::new(-12_000_000, 0, i64::MIN, -999_999_999)
1197 ),
1198 "P-1000000YT-2562047788015215H-30M-8.999999999S"
1199 );
1200 }
1201
1202 #[test]
1203 fn test_point_display() {
1204 let p = PointValue::wgs84_2d(-73.9857, 40.7484);
1205 assert_eq!(
1206 format!("{p}"),
1207 "point({srid: 4326, x: -73.9857, y: 40.7484})"
1208 );
1209 }
1210
1211 #[test]
1212 fn test_from_conversions() {
1213 let v: CypherValue = 42i64.into();
1214 assert_eq!(v, CypherValue::Int(42));
1215
1216 let v: CypherValue = "hello".into();
1217 assert_eq!(v, CypherValue::Str("hello".to_string()));
1218
1219 let v: CypherValue = true.into();
1220 assert_eq!(v, CypherValue::Bool(true));
1221
1222 let v: CypherValue = None::<i64>.into();
1223 assert_eq!(v, CypherValue::Null);
1224 }
1225
1226 #[test]
1227 fn test_float_display_infinity_and_nan() {
1228 assert_eq!(format!("{}", CypherValue::Float(f64::INFINITY)), "Inf");
1232 assert_eq!(format!("{}", CypherValue::Float(f64::NEG_INFINITY)), "-Inf");
1233 assert_eq!(format!("{}", CypherValue::Float(f64::NAN)), "NaN");
1234 assert_eq!(format!("{}", CypherValue::Float(2.0)), "2.0");
1236 assert_eq!(format!("{}", CypherValue::Float(1.5)), "1.5");
1237 }
1238
1239 #[test]
1242 fn test_vector_display() {
1243 let v = CypherValue::Vector {
1244 coord: VectorCoordKind::Int64,
1245 dim: 3,
1246 values: vec![
1247 CypherValue::Int(1),
1248 CypherValue::Int(2),
1249 CypherValue::Int(3),
1250 ],
1251 };
1252 assert_eq!(format!("{v}"), "vector([1, 2, 3], 3, INTEGER NOT NULL)");
1253
1254 let float_v = CypherValue::Vector {
1255 coord: VectorCoordKind::Float32,
1256 dim: 2,
1257 values: vec![CypherValue::Float(1.0), CypherValue::Float(2.5)],
1258 };
1259 assert_eq!(
1260 format!("{float_v}"),
1261 "vector([1.0, 2.5], 2, FLOAT32 NOT NULL)"
1262 );
1263 }
1264
1265 #[test]
1266 fn test_vector_equality_compares_coord_dim_and_values() {
1267 let a = CypherValue::Vector {
1268 coord: VectorCoordKind::Int32,
1269 dim: 2,
1270 values: vec![CypherValue::Int(1), CypherValue::Int(2)],
1271 };
1272 let same = a.clone();
1273 assert_eq!(a, same);
1274
1275 let different_coord = CypherValue::Vector {
1276 coord: VectorCoordKind::Int64,
1277 dim: 2,
1278 values: vec![CypherValue::Int(1), CypherValue::Int(2)],
1279 };
1280 assert_ne!(a, different_coord);
1281
1282 let different_values = CypherValue::Vector {
1283 coord: VectorCoordKind::Int32,
1284 dim: 2,
1285 values: vec![CypherValue::Int(2), CypherValue::Int(1)],
1286 };
1287 assert_ne!(a, different_values);
1288
1289 let list = CypherValue::List(vec![CypherValue::Int(1), CypherValue::Int(2)]);
1292 assert_ne!(a, list);
1293 }
1294
1295 #[test]
1296 fn test_vector_type_name_and_ordering_is_unordered() {
1297 let a = CypherValue::Vector {
1298 coord: VectorCoordKind::Int32,
1299 dim: 1,
1300 values: vec![CypherValue::Int(1)],
1301 };
1302 let b = a.clone();
1303 assert_eq!(a.type_name(), "VECTOR");
1304 assert_eq!(a.partial_cmp(&b), None);
1309 }
1310
1311 #[test]
1312 fn test_vector_coord_kind_aliases_and_canonical_names() {
1313 assert_eq!(
1314 VectorCoordKind::from_alias("INT8"),
1315 Some(VectorCoordKind::Int8)
1316 );
1317 assert_eq!(
1318 VectorCoordKind::from_alias("INTEGER8"),
1319 Some(VectorCoordKind::Int8)
1320 );
1321 assert_eq!(
1322 VectorCoordKind::from_alias("SIGNED INTEGER"),
1323 Some(VectorCoordKind::Int64)
1324 );
1325 assert_eq!(
1326 VectorCoordKind::from_alias("FLOAT64"),
1327 Some(VectorCoordKind::Float64)
1328 );
1329 assert_eq!(VectorCoordKind::from_alias("STRING"), None);
1330
1331 assert_eq!(VectorCoordKind::Int64.canonical_name(), "INTEGER");
1332 assert_eq!(VectorCoordKind::Float64.canonical_name(), "FLOAT");
1333 assert_eq!(VectorCoordKind::Float32.canonical_name(), "FLOAT32");
1334
1335 assert!(VectorCoordKind::Int8.order_rank() < VectorCoordKind::Int16.order_rank());
1339 assert!(VectorCoordKind::Int16.order_rank() < VectorCoordKind::Int32.order_rank());
1340 assert!(VectorCoordKind::Int32.order_rank() < VectorCoordKind::Int64.order_rank());
1341 assert!(VectorCoordKind::Int64.order_rank() < VectorCoordKind::BFloat16.order_rank());
1342 assert!(VectorCoordKind::BFloat16.order_rank() < VectorCoordKind::Float16.order_rank());
1343 assert!(VectorCoordKind::Float16.order_rank() < VectorCoordKind::Float32.order_rank());
1344 assert!(VectorCoordKind::Float32.order_rank() < VectorCoordKind::Float64.order_rank());
1345 }
1346
1347 #[test]
1348 fn narrow_float_rounds_to_the_coordinate_precision() {
1349 use VectorCoordKind::*;
1350 assert_eq!(Float16.narrow_float(1.0), Some(1.0));
1352 assert_eq!(Float16.narrow_float(0.1), Some(0.0999755859375));
1353 assert_eq!(Float16.narrow_float(65504.0), Some(65504.0));
1354 assert_eq!(Float16.narrow_float(65520.0), None);
1355 assert_eq!(Float16.narrow_float(2f64.powi(-24)), Some(2f64.powi(-24)));
1356 assert_eq!(Float16.narrow_float(2f64.powi(-25)), Some(0.0));
1357 assert_eq!(BFloat16.narrow_float(1.0), Some(1.0));
1359 assert_eq!(BFloat16.narrow_float(257.0), Some(256.0));
1360 assert_eq!(
1361 BFloat16.narrow_float(3.3895314e38),
1362 Some(3.3895314e38f32 as f64)
1363 );
1364 assert_eq!(BFloat16.narrow_float(1e39), None);
1365 assert_eq!(BFloat16.narrow_float(9.18e-41), Some(9.183549615799121e-41));
1367 assert_eq!(Float32.narrow_float(0.1), Some(0.1f32 as f64));
1369 assert_eq!(Float64.narrow_float(0.1), Some(0.1));
1370 assert_eq!(Int8.narrow_float(1.0), None);
1371 assert_eq!(Float16.narrow_float(f64::NAN), None);
1372 }
1373
1374 #[test]
1375 fn is_exact_holds_only_for_values_the_kind_spells_unchanged() {
1376 use VectorCoordKind::*;
1377 assert!(!Float16.is_exact(0.1));
1380 assert!(!BFloat16.is_exact(0.1));
1381 assert!(!Float32.is_exact(0.1));
1382 assert!(Float64.is_exact(0.1));
1383 assert!(Float16.is_exact(0.0999755859375));
1384 assert!(BFloat16.is_exact(256.0));
1385 assert!(Float32.is_exact(0.1f32 as f64));
1386 for kind in [Float16, BFloat16, Float32, Float64] {
1387 assert!(!kind.is_exact(f64::INFINITY), "{kind:?}");
1388 assert!(!kind.is_exact(f64::NAN), "{kind:?}");
1389 }
1390 assert!(!Int8.is_exact(1.0));
1392 }
1393}