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 = crate::point::srid_dimension(self.srid)? == 3;
152 (canonical_3d == self.is_3d()).then(|| crate::wire::crs_name(self.srid))
153 }
154}
155
156pub fn float_text(f: f64) -> String {
165 if f.is_nan() {
166 return "NaN".into();
167 }
168 if f == f64::INFINITY {
169 return "Infinity".into();
170 }
171 if f == f64::NEG_INFINITY {
172 return "-Infinity".into();
173 }
174 let mut rendered = format!("{f}");
175 if !rendered.contains('.') {
176 rendered.push_str(".0");
177 }
178 rendered
179}
180
181impl fmt::Display for PointValue {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 match self.z {
184 Some(z) => write!(
185 f,
186 "point({{srid: {}, x: {}, y: {}, z: {}}})",
187 self.srid, self.x, self.y, z
188 ),
189 None => write!(
190 f,
191 "point({{srid: {}, x: {}, y: {}}})",
192 self.srid, self.x, self.y
193 ),
194 }
195 }
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
208pub enum VectorCoordKind {
209 Int8,
210 Int16,
211 Int32,
212 Int64,
213 Float16,
215 BFloat16,
218 Float32,
219 Float64,
220}
221
222impl VectorCoordKind {
223 pub fn canonical_name(&self) -> &'static str {
229 match self {
230 VectorCoordKind::Int8 => "INTEGER8",
231 VectorCoordKind::Int16 => "INTEGER16",
232 VectorCoordKind::Int32 => "INTEGER32",
233 VectorCoordKind::Int64 => "INTEGER",
234 VectorCoordKind::Float16 => "FLOAT16",
235 VectorCoordKind::BFloat16 => "BFLOAT16",
236 VectorCoordKind::Float32 => "FLOAT32",
237 VectorCoordKind::Float64 => "FLOAT",
238 }
239 }
240
241 pub fn from_canonical_name(name: &str) -> Option<Self> {
244 Some(match name {
245 "INTEGER8" => VectorCoordKind::Int8,
246 "INTEGER16" => VectorCoordKind::Int16,
247 "INTEGER32" => VectorCoordKind::Int32,
248 "INTEGER" => VectorCoordKind::Int64,
249 "FLOAT16" => VectorCoordKind::Float16,
250 "BFLOAT16" => VectorCoordKind::BFloat16,
251 "FLOAT32" => VectorCoordKind::Float32,
252 "FLOAT" => VectorCoordKind::Float64,
253 _ => return None,
254 })
255 }
256
257 pub fn from_alias(name: &str) -> Option<Self> {
262 Some(match name {
263 "INT8" | "INTEGER8" => VectorCoordKind::Int8,
264 "INT16" | "INTEGER16" => VectorCoordKind::Int16,
265 "INT32" | "INTEGER32" => VectorCoordKind::Int32,
266 "INT" | "INTEGER" | "INT64" | "INTEGER64" | "SIGNED INTEGER" => VectorCoordKind::Int64,
267 "FLOAT16" => VectorCoordKind::Float16,
268 "BFLOAT16" => VectorCoordKind::BFloat16,
269 "FLOAT32" => VectorCoordKind::Float32,
270 "FLOAT" | "FLOAT64" => VectorCoordKind::Float64,
271 _ => return None,
272 })
273 }
274
275 pub fn is_integer(&self) -> bool {
279 !matches!(
280 self,
281 VectorCoordKind::Float16
282 | VectorCoordKind::BFloat16
283 | VectorCoordKind::Float32
284 | VectorCoordKind::Float64
285 )
286 }
287
288 pub fn order_rank(&self) -> u8 {
293 match self {
294 VectorCoordKind::Int8 => 0,
295 VectorCoordKind::Int16 => 1,
296 VectorCoordKind::Int32 => 2,
297 VectorCoordKind::Int64 => 3,
298 VectorCoordKind::BFloat16 => 4,
299 VectorCoordKind::Float16 => 5,
300 VectorCoordKind::Float32 => 6,
301 VectorCoordKind::Float64 => 7,
302 }
303 }
304
305 pub fn narrow_float(self, f: f64) -> Option<f64> {
312 if !f.is_finite() {
313 return None;
314 }
315 let narrowed = match self {
316 VectorCoordKind::Float64 => f,
317 VectorCoordKind::Float32 => f as f32 as f64,
318 VectorCoordKind::Float16 => f16_bits_to_f32(f32_to_f16_bits(f as f32)) as f64,
319 VectorCoordKind::BFloat16 => f32::from_bits(bfloat16_bits(f as f32)) as f64,
320 VectorCoordKind::Int8
321 | VectorCoordKind::Int16
322 | VectorCoordKind::Int32
323 | VectorCoordKind::Int64 => return None,
324 };
325 narrowed.is_finite().then_some(narrowed)
326 }
327
328 pub fn is_exact(self, f: f64) -> bool {
337 f.is_finite() && self.narrow_float(f) == Some(f)
338 }
339
340 pub fn holds_int(self, n: i64) -> bool {
346 match self {
347 VectorCoordKind::Int8 => i8::try_from(n).is_ok(),
348 VectorCoordKind::Int16 => i16::try_from(n).is_ok(),
349 VectorCoordKind::Int32 => i32::try_from(n).is_ok(),
350 VectorCoordKind::Int64 => true,
351 VectorCoordKind::Float16
352 | VectorCoordKind::BFloat16
353 | VectorCoordKind::Float32
354 | VectorCoordKind::Float64 => false,
355 }
356 }
357}
358
359pub type Coord2D = [f64; 2];
361
362#[derive(Debug, Clone, PartialEq)]
364pub enum GeometryValue {
365 LineString {
366 coordinates: Vec<Coord2D>,
367 srid: i32,
368 },
369 Polygon {
370 rings: Vec<Vec<Coord2D>>,
372 srid: i32,
373 },
374 MultiPoint {
375 points: Vec<Coord2D>,
376 srid: i32,
377 },
378 MultiLineString {
379 lines: Vec<Vec<Coord2D>>,
380 srid: i32,
381 },
382 MultiPolygon {
383 polygons: Vec<Vec<Vec<Coord2D>>>,
384 srid: i32,
385 },
386 GeometryCollection {
387 geometries: Vec<GeometryValue>,
388 srid: i32,
389 },
390}
391
392impl GeometryValue {
393 pub fn srid(&self) -> i32 {
395 match self {
396 GeometryValue::LineString { srid, .. }
397 | GeometryValue::Polygon { srid, .. }
398 | GeometryValue::MultiPoint { srid, .. }
399 | GeometryValue::MultiLineString { srid, .. }
400 | GeometryValue::MultiPolygon { srid, .. }
401 | GeometryValue::GeometryCollection { srid, .. } => *srid,
402 }
403 }
404
405 pub fn type_name(&self) -> &'static str {
407 match self {
408 GeometryValue::LineString { .. } => "LineString",
409 GeometryValue::Polygon { .. } => "Polygon",
410 GeometryValue::MultiPoint { .. } => "MultiPoint",
411 GeometryValue::MultiLineString { .. } => "MultiLineString",
412 GeometryValue::MultiPolygon { .. } => "MultiPolygon",
413 GeometryValue::GeometryCollection { .. } => "GeometryCollection",
414 }
415 }
416}
417
418impl fmt::Display for GeometryValue {
419 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420 match self {
421 GeometryValue::LineString { coordinates, srid } => {
422 write!(f, "linestring({{srid: {srid}, coordinates: [")?;
423 for (i, c) in coordinates.iter().enumerate() {
424 if i > 0 {
425 write!(f, ", ")?;
426 }
427 write!(f, "[{}, {}]", c[0], c[1])?;
428 }
429 write!(f, "]}})")
430 }
431 GeometryValue::Polygon { rings, srid } => {
432 write!(f, "polygon({{srid: {srid}, coordinates: [")?;
433 for (i, ring) in rings.iter().enumerate() {
434 if i > 0 {
435 write!(f, ", ")?;
436 }
437 write!(f, "[")?;
438 for (j, c) in ring.iter().enumerate() {
439 if j > 0 {
440 write!(f, ", ")?;
441 }
442 write!(f, "[{}, {}]", c[0], c[1])?;
443 }
444 write!(f, "]")?;
445 }
446 write!(f, "]}})")
447 }
448 GeometryValue::MultiPoint { points, srid } => {
449 write!(f, "multipoint({{srid: {srid}, coordinates: [")?;
450 for (i, c) in points.iter().enumerate() {
451 if i > 0 {
452 write!(f, ", ")?;
453 }
454 write!(f, "[{}, {}]", c[0], c[1])?;
455 }
456 write!(f, "]}})")
457 }
458 GeometryValue::MultiLineString { lines: _, srid } => {
459 write!(f, "multilinestring({{srid: {srid}, ...}})")
460 }
461 GeometryValue::MultiPolygon { polygons: _, srid } => {
462 write!(f, "multipolygon({{srid: {srid}, ...}})")
463 }
464 GeometryValue::GeometryCollection { geometries, srid } => {
465 write!(
466 f,
467 "geometrycollection({{srid: {}, count: {}}})",
468 srid,
469 geometries.len()
470 )
471 }
472 }
473 }
474}
475
476#[derive(Debug, Clone)]
481pub enum CypherValue {
482 Null,
483 Bool(bool),
484 Int(i64),
485 Float(f64),
486 Str(String),
487 List(Vec<CypherValue>),
488 Map(IndexMap<String, CypherValue>),
489 Node {
490 id: i64,
491 labels: Vec<String>,
492 properties: IndexMap<String, CypherValue>,
493 },
494 Relationship {
495 id: i64,
496 start_id: i64,
497 end_id: i64,
498 rel_type: String,
499 properties: IndexMap<String, CypherValue>,
500 },
501 Path {
502 nodes: Vec<CypherValue>,
503 relationships: Vec<CypherValue>,
504 },
505 Date(NaiveDate),
506 Time(NaiveTime, Option<FixedOffset>),
507 DateTime(DateTime<FixedOffset>, Option<String>),
509 LocalDateTime(NaiveDateTime),
510 Duration(IsoDuration),
511 Point(PointValue),
512 Geometry(GeometryValue),
513 Vector {
520 coord: VectorCoordKind,
521 dim: usize,
522 values: Vec<CypherValue>,
523 },
524}
525
526impl CypherValue {
527 pub fn is_null(&self) -> bool {
529 matches!(self, CypherValue::Null)
530 }
531
532 pub fn is_temporal(&self) -> bool {
538 match self {
539 CypherValue::Date(_)
540 | CypherValue::Time(..)
541 | CypherValue::DateTime(..)
542 | CypherValue::LocalDateTime(_)
543 | CypherValue::Duration(_) => true,
544 CypherValue::Null
545 | CypherValue::Bool(_)
546 | CypherValue::Int(_)
547 | CypherValue::Float(_)
548 | CypherValue::Str(_)
549 | CypherValue::List(_)
550 | CypherValue::Map(_)
551 | CypherValue::Node { .. }
552 | CypherValue::Relationship { .. }
553 | CypherValue::Path { .. }
554 | CypherValue::Geometry(_)
555 | CypherValue::Vector { .. }
556 | CypherValue::Point(_) => false,
557 }
558 }
559
560 pub fn type_name(&self) -> &'static str {
562 match self {
563 CypherValue::Null => "NULL",
564 CypherValue::Bool(_) => "BOOLEAN",
565 CypherValue::Int(_) => "INTEGER",
566 CypherValue::Float(_) => "FLOAT",
567 CypherValue::Str(_) => "STRING",
568 CypherValue::List(_) => "LIST",
569 CypherValue::Map(_) => "MAP",
570 CypherValue::Node { .. } => "NODE",
571 CypherValue::Relationship { .. } => "RELATIONSHIP",
572 CypherValue::Path { .. } => "PATH",
573 CypherValue::Date(_) => "DATE",
574 CypherValue::Time(_, _) => "TIME",
575 CypherValue::DateTime(..) => "DATE_TIME",
576 CypherValue::LocalDateTime(_) => "LOCAL_DATE_TIME",
577 CypherValue::Duration(_) => "DURATION",
578 CypherValue::Point(_) => "POINT",
579 CypherValue::Geometry(g) => g.type_name(),
580 CypherValue::Vector { .. } => "VECTOR",
581 }
582 }
583
584 pub fn as_bool(&self) -> Option<bool> {
586 match self {
587 CypherValue::Bool(b) => Some(*b),
588 _ => None,
589 }
590 }
591
592 pub fn as_int(&self) -> Option<i64> {
594 match self {
595 CypherValue::Int(i) => Some(*i),
596 _ => None,
597 }
598 }
599
600 pub fn as_float(&self) -> Option<f64> {
602 match self {
603 CypherValue::Float(f) => Some(*f),
604 CypherValue::Int(i) => Some(*i as f64),
605 _ => None,
606 }
607 }
608
609 pub fn as_str(&self) -> Option<&str> {
611 match self {
612 CypherValue::Str(s) => Some(s),
613 _ => None,
614 }
615 }
616
617 pub fn as_list(&self) -> Option<&[CypherValue]> {
619 match self {
620 CypherValue::List(l) => Some(l),
621 _ => None,
622 }
623 }
624
625 pub fn as_map(&self) -> Option<&IndexMap<String, CypherValue>> {
627 match self {
628 CypherValue::Map(m) => Some(m),
629 _ => None,
630 }
631 }
632
633 pub fn to_bool_3vl(&self) -> Option<bool> {
636 match self {
637 CypherValue::Null => None,
638 CypherValue::Bool(b) => Some(*b),
639 _ => Some(true), }
641 }
642
643 pub fn as_numeric(&self) -> Option<(f64, bool)> {
646 match self {
647 CypherValue::Int(i) => Some((*i as f64, true)),
648 CypherValue::Float(f) => Some((*f, false)),
649 _ => None,
650 }
651 }
652}
653
654impl fmt::Display for CypherValue {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 match self {
657 CypherValue::Null => write!(f, "null"),
658 CypherValue::Bool(b) => write!(f, "{b}"),
659 CypherValue::Int(i) => write!(f, "{i}"),
660 CypherValue::Float(v) => {
661 if v.is_nan() {
662 write!(f, "NaN")
663 } else if v.is_infinite() {
664 write!(f, "{}Inf", if *v < 0.0 { "-" } else { "" })
665 } else if v.fract() == 0.0 {
666 write!(f, "{v}.0")
667 } else {
668 write!(f, "{v}")
669 }
670 }
671 CypherValue::Str(s) => write!(f, "\"{s}\""),
672 CypherValue::List(items) => {
673 write!(f, "[")?;
674 for (i, item) in items.iter().enumerate() {
675 if i > 0 {
676 write!(f, ", ")?;
677 }
678 write!(f, "{item}")?;
679 }
680 write!(f, "]")
681 }
682 CypherValue::Map(map) => {
683 write!(f, "{{")?;
684 for (i, (k, v)) in map.iter().enumerate() {
685 if i > 0 {
686 write!(f, ", ")?;
687 }
688 write!(f, "{k}: {v}")?;
689 }
690 write!(f, "}}")
691 }
692 CypherValue::Node {
693 labels, properties, ..
694 } => {
695 write!(f, "(:{}", labels.join(":"))?;
696 if !properties.is_empty() {
697 write!(f, " {{")?;
698 for (i, (k, v)) in properties.iter().enumerate() {
699 if i > 0 {
700 write!(f, ", ")?;
701 }
702 write!(f, "{k}: {v}")?;
703 }
704 write!(f, "}}")?;
705 }
706 write!(f, ")")
707 }
708 CypherValue::Relationship {
709 rel_type,
710 properties,
711 ..
712 } => {
713 write!(f, "[:{rel_type}")?;
714 if !properties.is_empty() {
715 write!(f, " {{")?;
716 for (i, (k, v)) in properties.iter().enumerate() {
717 if i > 0 {
718 write!(f, ", ")?;
719 }
720 write!(f, "{k}: {v}")?;
721 }
722 write!(f, "}}")?;
723 }
724 write!(f, "]")
725 }
726 CypherValue::Path {
727 nodes,
728 relationships,
729 } => {
730 for (i, node) in nodes.iter().enumerate() {
731 if i > 0 {
732 if let Some(rel) = relationships.get(i - 1) {
733 write!(f, "-{rel}-")?;
734 } else {
735 write!(f, "--")?;
736 }
737 }
738 write!(f, "{node}")?;
739 }
740 Ok(())
741 }
742 CypherValue::Date(d) => write!(f, "{d}"),
743 CypherValue::Time(t, tz) => {
744 use chrono::Timelike;
745 let nanos = t.nanosecond() % 1_000_000_000;
747 if nanos != 0 {
748 let frac = format!("{nanos:09}");
749 let trimmed = frac.trim_end_matches('0');
750 write!(
751 f,
752 "{:02}:{:02}:{:02}.{}",
753 t.hour(),
754 t.minute(),
755 t.second(),
756 trimmed
757 )?;
758 } else if t.second() != 0 {
759 write!(f, "{}", t.format("%H:%M:%S"))?;
760 } else {
761 write!(f, "{}", t.format("%H:%M"))?;
762 }
763 if let Some(offset) = tz {
765 let total_secs = offset.local_minus_utc();
766 if total_secs == 0 {
767 write!(f, "Z")
768 } else {
769 let sign = if total_secs >= 0 { '+' } else { '-' };
770 let abs_secs = total_secs.unsigned_abs();
771 let hours = abs_secs / 3600;
772 let mins = (abs_secs % 3600) / 60;
773 let secs = abs_secs % 60;
774 if secs != 0 {
775 write!(f, "{sign}{hours:02}:{mins:02}:{secs:02}")
776 } else {
777 write!(f, "{sign}{hours:02}:{mins:02}")
778 }
779 }
780 } else {
781 Ok(())
782 }
783 }
784 CypherValue::DateTime(dt, tz_name) => {
785 let nanos = dt.timestamp_subsec_nanos();
787 let date_part = dt.date_naive();
788 let time_part = dt.time();
789 if nanos != 0 {
790 let frac = format!("{nanos:09}");
791 let trimmed = frac.trim_end_matches('0');
792 write!(
793 f,
794 "{}T{}.{}",
795 date_part,
796 time_part.format("%H:%M:%S"),
797 trimmed
798 )?;
799 } else {
800 write!(f, "{}T{}", date_part, time_part.format("%H:%M:%S"))?;
801 }
802 let offset = dt.offset();
804 let total_secs = offset.local_minus_utc();
805 if total_secs == 0 {
806 write!(f, "Z")?;
807 } else {
808 let sign = if total_secs >= 0 { '+' } else { '-' };
809 let abs_secs = total_secs.unsigned_abs();
810 let hours = abs_secs / 3600;
811 let mins = (abs_secs % 3600) / 60;
812 let secs_rem = abs_secs % 60;
813 if secs_rem != 0 {
814 write!(f, "{sign}{hours:02}:{mins:02}:{secs_rem:02}")?;
815 } else {
816 write!(f, "{sign}{hours:02}:{mins:02}")?;
817 }
818 }
819 if let Some(tz) = tz_name {
821 write!(f, "[{tz}]")?;
822 }
823 Ok(())
824 }
825 CypherValue::LocalDateTime(dt) => {
826 let nanos = dt.and_utc().timestamp_subsec_nanos();
828 if nanos != 0 {
829 let frac = format!("{nanos:09}");
830 let trimmed = frac.trim_end_matches('0');
831 write!(
832 f,
833 "{}T{}.{}",
834 dt.date(),
835 dt.time().format("%H:%M:%S"),
836 trimmed
837 )
838 } else {
839 write!(f, "{}T{}", dt.date(), dt.time().format("%H:%M:%S"))
840 }
841 }
842 CypherValue::Duration(d) => write!(f, "{d}"),
843 CypherValue::Point(p) => write!(f, "{p}"),
844 CypherValue::Geometry(g) => write!(f, "{g}"),
845 CypherValue::Vector { coord, dim, values } => {
846 write!(f, "vector([")?;
847 for (i, v) in values.iter().enumerate() {
848 if i > 0 {
849 write!(f, ", ")?;
850 }
851 write!(f, "{v}")?;
852 }
853 write!(f, "], {}, {} NOT NULL)", dim, coord.canonical_name())
854 }
855 }
856 }
857}
858
859impl PartialEq for CypherValue {
860 fn eq(&self, other: &Self) -> bool {
861 match (self, other) {
862 (CypherValue::Null, CypherValue::Null) => true,
863 (CypherValue::Bool(a), CypherValue::Bool(b)) => a == b,
864 (CypherValue::Int(a), CypherValue::Int(b)) => a == b,
865 (CypherValue::Float(a), CypherValue::Float(b)) => a == b,
866 (CypherValue::Int(a), CypherValue::Float(b)) => {
873 crate::canonical_key::eq_i64_f64(*a, *b)
874 }
875 (CypherValue::Float(a), CypherValue::Int(b)) => {
876 crate::canonical_key::eq_i64_f64(*b, *a)
877 }
878 (CypherValue::Str(a), CypherValue::Str(b)) => a == b,
879 (CypherValue::List(a), CypherValue::List(b)) => a == b,
880 (CypherValue::Map(a), CypherValue::Map(b)) => a == b,
881 (CypherValue::Node { id: a, .. }, CypherValue::Node { id: b, .. }) => a == b,
882 (CypherValue::Relationship { id: a, .. }, CypherValue::Relationship { id: b, .. }) => {
883 a == b
884 }
885 (CypherValue::Date(a), CypherValue::Date(b)) => a == b,
886 (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => a == b && ao == bo,
887 (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a == b,
888 (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a == b,
889 (CypherValue::Duration(a), CypherValue::Duration(b)) => a == b,
890 (CypherValue::Point(a), CypherValue::Point(b)) => a == b,
891 (CypherValue::Geometry(a), CypherValue::Geometry(b)) => a == b,
892 (
893 CypherValue::Vector {
894 coord: ca,
895 dim: da,
896 values: va,
897 },
898 CypherValue::Vector {
899 coord: cb,
900 dim: db,
901 values: vb,
902 },
903 ) => ca == cb && da == db && va == vb,
904 (
905 CypherValue::Path {
906 nodes: n1,
907 relationships: r1,
908 },
909 CypherValue::Path {
910 nodes: n2,
911 relationships: r2,
912 },
913 ) => n1 == n2 && r1 == r2,
914 _ => false,
915 }
916 }
917}
918
919impl PartialOrd for CypherValue {
920 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
921 match (self, other) {
922 (CypherValue::Int(a), CypherValue::Int(b)) => a.partial_cmp(b),
923 (CypherValue::Float(a), CypherValue::Float(b)) => a.partial_cmp(b),
924 (CypherValue::Int(a), CypherValue::Float(b)) => {
928 crate::canonical_key::cmp_i64_f64(*a, *b)
929 }
930 (CypherValue::Float(a), CypherValue::Int(b)) => {
931 crate::canonical_key::cmp_i64_f64(*b, *a).map(std::cmp::Ordering::reverse)
932 }
933 (CypherValue::Str(a), CypherValue::Str(b)) => a.partial_cmp(b),
934 (CypherValue::Bool(a), CypherValue::Bool(b)) => a.partial_cmp(b),
935 (CypherValue::Date(a), CypherValue::Date(b)) => a.partial_cmp(b),
936 (CypherValue::List(a), CypherValue::List(b)) => {
937 for (av, bv) in a.iter().zip(b.iter()) {
939 match av.partial_cmp(bv) {
940 Some(std::cmp::Ordering::Equal) => continue,
941 Some(ord) => return Some(ord),
942 None => return None,
943 }
944 }
945 a.len().partial_cmp(&b.len())
946 }
947 (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => {
948 match (ao, bo) {
950 (Some(a_off), Some(b_off)) => {
951 use chrono::Timelike;
952 let a_utc_secs =
953 a.num_seconds_from_midnight() as i64 - a_off.local_minus_utc() as i64;
954 let b_utc_secs =
955 b.num_seconds_from_midnight() as i64 - b_off.local_minus_utc() as i64;
956 match a_utc_secs.partial_cmp(&b_utc_secs) {
957 Some(std::cmp::Ordering::Equal) => {
958 let a_nanos = a.nanosecond() % 1_000_000_000;
960 let b_nanos = b.nanosecond() % 1_000_000_000;
961 a_nanos.partial_cmp(&b_nanos)
962 }
963 other => other,
964 }
965 }
966 (None, None) => a.partial_cmp(b),
967 _ => None,
968 }
969 }
970 (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a.partial_cmp(b),
971 (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a.partial_cmp(b),
972 _ => None,
973 }
974 }
975}
976
977impl From<bool> for CypherValue {
978 fn from(b: bool) -> Self {
979 CypherValue::Bool(b)
980 }
981}
982
983impl From<i64> for CypherValue {
984 fn from(i: i64) -> Self {
985 CypherValue::Int(i)
986 }
987}
988
989impl From<f64> for CypherValue {
990 fn from(f: f64) -> Self {
991 CypherValue::Float(f)
992 }
993}
994
995impl From<String> for CypherValue {
996 fn from(s: String) -> Self {
997 CypherValue::Str(s)
998 }
999}
1000
1001impl From<&str> for CypherValue {
1002 fn from(s: &str) -> Self {
1003 CypherValue::Str(s.to_string())
1004 }
1005}
1006
1007impl<T: Into<CypherValue>> From<Vec<T>> for CypherValue {
1008 fn from(v: Vec<T>) -> Self {
1009 CypherValue::List(v.into_iter().map(|x| x.into()).collect())
1010 }
1011}
1012
1013impl<T: Into<CypherValue>> From<Option<T>> for CypherValue {
1014 fn from(o: Option<T>) -> Self {
1015 match o {
1016 Some(v) => v.into(),
1017 None => CypherValue::Null,
1018 }
1019 }
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024 use super::*;
1025
1026 #[test]
1027 #[allow(clippy::approx_constant)]
1028 fn test_type_names() {
1029 assert_eq!(CypherValue::Null.type_name(), "NULL");
1030 assert_eq!(CypherValue::Bool(true).type_name(), "BOOLEAN");
1031 assert_eq!(CypherValue::Int(42).type_name(), "INTEGER");
1032 assert_eq!(CypherValue::Float(3.14).type_name(), "FLOAT");
1033 assert_eq!(CypherValue::Str("hello".into()).type_name(), "STRING");
1034 assert_eq!(CypherValue::List(vec![]).type_name(), "LIST");
1035 assert_eq!(CypherValue::Map(IndexMap::new()).type_name(), "MAP");
1036 }
1037
1038 #[test]
1039 fn point_crs_name_classifies_the_four_point_codes() {
1040 let cases = [
1041 (PointValue::cartesian_2d(1.0, 2.0), "cartesian", false),
1042 (
1043 PointValue::cartesian_3d(1.0, 2.0, 3.0),
1044 "cartesian-3d",
1045 true,
1046 ),
1047 (PointValue::wgs84_2d(1.0, 2.0), "wgs-84", false),
1048 (PointValue::wgs84_3d(1.0, 2.0, 3.0), "wgs-84-3d", true),
1049 ];
1050 for (point, name, is_3d) in cases {
1051 assert_eq!(point.crs_name(), Some(name), "{point:?}");
1052 assert_eq!(point.is_3d(), is_3d, "{point:?}");
1053 }
1054 let unknown = PointValue {
1057 srid: 1234,
1058 x: 1.0,
1059 y: 2.0,
1060 z: None,
1061 };
1062 assert_eq!(unknown.crs_name(), None);
1063 let wrong_dimension = PointValue {
1064 srid: 7203,
1065 x: 1.0,
1066 y: 2.0,
1067 z: Some(3.0),
1068 };
1069 assert_eq!(wrong_dimension.crs_name(), None);
1070 }
1071
1072 #[test]
1073 fn test_int_float_equality() {
1074 assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1075 assert_eq!(CypherValue::Float(1.0), CypherValue::Int(1));
1076 assert_ne!(CypherValue::Int(1), CypherValue::Float(1.5));
1077 }
1078
1079 #[test]
1080 fn test_partial_ord() {
1081 assert!(CypherValue::Int(1) < CypherValue::Int(2));
1082 assert!(CypherValue::Int(1) < CypherValue::Float(1.5));
1083 assert!(CypherValue::Str("a".into()) < CypherValue::Str("b".into()));
1084 }
1085
1086 #[test]
1087 fn int_float_equality_is_exact_past_2_pow_53() {
1088 let big_int = CypherValue::Int(9_007_199_254_740_993);
1095 let near_float = CypherValue::Float(9_007_199_254_740_992.0);
1096 assert_ne!(big_int, near_float);
1097 assert_ne!(near_float, big_int);
1098
1099 assert_eq!(
1101 CypherValue::Int(9_007_199_254_740_992),
1102 CypherValue::Float(9_007_199_254_740_992.0)
1103 );
1104
1105 assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1107 assert_eq!(CypherValue::Int(0), CypherValue::Float(-0.0));
1108 }
1109
1110 #[test]
1111 fn int_float_ordering_stays_consistent_with_equality() {
1112 let probes = [
1117 (9_007_199_254_740_993_i64, 9_007_199_254_740_992.0_f64),
1118 (9_007_199_254_740_992, 9_007_199_254_740_992.0),
1119 (i64::MAX, 9_223_372_036_854_775_808.0), (i64::MIN, -9_223_372_036_854_775_808.0), (0, -0.0),
1122 (1, 1.0),
1123 (2, 1.5),
1124 (1, 1.5),
1125 ];
1126 for (i, f) in probes {
1127 let iv = CypherValue::Int(i);
1128 let fv = CypherValue::Float(f);
1129 let eq = iv == fv;
1130 let cmp_eq = iv.partial_cmp(&fv) == Some(std::cmp::Ordering::Equal);
1131 assert_eq!(eq, cmp_eq, "eq/ord disagree for Int({i}) vs Float({f})");
1132 let rev = fv.partial_cmp(&iv);
1134 assert_eq!(
1135 iv.partial_cmp(&fv),
1136 rev.map(std::cmp::Ordering::reverse),
1137 "forward/reverse ordering not antisymmetric for {i}/{f}"
1138 );
1139 }
1140 assert!(
1142 CypherValue::Int(9_007_199_254_740_993) > CypherValue::Float(9_007_199_254_740_992.0)
1143 );
1144 }
1145
1146 #[test]
1147 fn test_display() {
1148 assert_eq!(format!("{}", CypherValue::Null), "null");
1149 assert_eq!(format!("{}", CypherValue::Bool(true)), "true");
1150 assert_eq!(format!("{}", CypherValue::Int(42)), "42");
1151 assert_eq!(format!("{}", CypherValue::Float(3.0)), "3.0");
1152 assert_eq!(format!("{}", CypherValue::Str("hi".into())), "\"hi\"");
1153 }
1154
1155 #[test]
1156 #[allow(clippy::approx_constant)]
1157 fn test_as_float_promotion() {
1158 assert_eq!(CypherValue::Int(5).as_float(), Some(5.0));
1159 assert_eq!(CypherValue::Float(3.14).as_float(), Some(3.14));
1160 assert_eq!(CypherValue::Str("x".into()).as_float(), None);
1161 }
1162
1163 #[test]
1164 fn test_three_valued_logic() {
1165 assert_eq!(CypherValue::Null.to_bool_3vl(), None);
1166 assert_eq!(CypherValue::Bool(true).to_bool_3vl(), Some(true));
1167 assert_eq!(CypherValue::Bool(false).to_bool_3vl(), Some(false));
1168 assert_eq!(CypherValue::Int(0).to_bool_3vl(), Some(true));
1169 }
1170
1171 #[test]
1172 fn test_iso_duration_display() {
1173 assert_eq!(format!("{}", IsoDuration::new(0, 0, 0, 0)), "PT0S");
1174 assert_eq!(format!("{}", IsoDuration::new(14, 0, 0, 0)), "P1Y2M");
1175 assert_eq!(format!("{}", IsoDuration::new(0, 5, 3661, 0)), "P5DT1H1M1S");
1176 assert_eq!(
1178 format!("{}", IsoDuration::new(0, 0, -3661, -500_000_000)),
1179 "PT-1H-1M-1.5S"
1180 );
1181 assert_eq!(
1183 format!("{}", IsoDuration::new(0, 0, 1, -1_500_000_000)),
1184 "PT-0.5S"
1185 );
1186 }
1187
1188 #[test]
1189 fn test_iso_duration_display_extreme_magnitudes() {
1190 assert_eq!(
1192 format!("{}", IsoDuration::new(12_000_000, 0, 0, 0)),
1193 "P1000000Y"
1194 );
1195 assert_eq!(
1196 format!("{}", IsoDuration::new(-12_000_000, 0, 0, 0)),
1197 "P-1000000Y"
1198 );
1199 assert_eq!(
1202 format!("{}", IsoDuration::new(0, 0, i64::MAX, 999_999_999)),
1203 "PT2562047788015215H30M7.999999999S"
1204 );
1205 assert_eq!(
1206 format!("{}", IsoDuration::new(0, 0, i64::MIN, -999_999_999)),
1207 "PT-2562047788015215H-30M-8.999999999S"
1208 );
1209 assert_eq!(
1211 format!("{}", IsoDuration::new(12_000_000, 0, i64::MAX, 999_999_999)),
1212 "P1000000YT2562047788015215H30M7.999999999S"
1213 );
1214 assert_eq!(
1215 format!(
1216 "{}",
1217 IsoDuration::new(-12_000_000, 0, i64::MIN, -999_999_999)
1218 ),
1219 "P-1000000YT-2562047788015215H-30M-8.999999999S"
1220 );
1221 }
1222
1223 #[test]
1224 fn test_point_display() {
1225 let p = PointValue::wgs84_2d(-73.9857, 40.7484);
1226 assert_eq!(
1227 format!("{p}"),
1228 "point({srid: 4326, x: -73.9857, y: 40.7484})"
1229 );
1230 }
1231
1232 #[test]
1233 fn test_from_conversions() {
1234 let v: CypherValue = 42i64.into();
1235 assert_eq!(v, CypherValue::Int(42));
1236
1237 let v: CypherValue = "hello".into();
1238 assert_eq!(v, CypherValue::Str("hello".to_string()));
1239
1240 let v: CypherValue = true.into();
1241 assert_eq!(v, CypherValue::Bool(true));
1242
1243 let v: CypherValue = None::<i64>.into();
1244 assert_eq!(v, CypherValue::Null);
1245 }
1246
1247 #[test]
1248 fn test_float_display_infinity_and_nan() {
1249 assert_eq!(format!("{}", CypherValue::Float(f64::INFINITY)), "Inf");
1253 assert_eq!(format!("{}", CypherValue::Float(f64::NEG_INFINITY)), "-Inf");
1254 assert_eq!(format!("{}", CypherValue::Float(f64::NAN)), "NaN");
1255 assert_eq!(format!("{}", CypherValue::Float(2.0)), "2.0");
1257 assert_eq!(format!("{}", CypherValue::Float(1.5)), "1.5");
1258 }
1259
1260 #[test]
1263 fn test_vector_display() {
1264 let v = CypherValue::Vector {
1265 coord: VectorCoordKind::Int64,
1266 dim: 3,
1267 values: vec![
1268 CypherValue::Int(1),
1269 CypherValue::Int(2),
1270 CypherValue::Int(3),
1271 ],
1272 };
1273 assert_eq!(format!("{v}"), "vector([1, 2, 3], 3, INTEGER NOT NULL)");
1274
1275 let float_v = CypherValue::Vector {
1276 coord: VectorCoordKind::Float32,
1277 dim: 2,
1278 values: vec![CypherValue::Float(1.0), CypherValue::Float(2.5)],
1279 };
1280 assert_eq!(
1281 format!("{float_v}"),
1282 "vector([1.0, 2.5], 2, FLOAT32 NOT NULL)"
1283 );
1284 }
1285
1286 #[test]
1287 fn test_vector_equality_compares_coord_dim_and_values() {
1288 let a = CypherValue::Vector {
1289 coord: VectorCoordKind::Int32,
1290 dim: 2,
1291 values: vec![CypherValue::Int(1), CypherValue::Int(2)],
1292 };
1293 let same = a.clone();
1294 assert_eq!(a, same);
1295
1296 let different_coord = CypherValue::Vector {
1297 coord: VectorCoordKind::Int64,
1298 dim: 2,
1299 values: vec![CypherValue::Int(1), CypherValue::Int(2)],
1300 };
1301 assert_ne!(a, different_coord);
1302
1303 let different_values = CypherValue::Vector {
1304 coord: VectorCoordKind::Int32,
1305 dim: 2,
1306 values: vec![CypherValue::Int(2), CypherValue::Int(1)],
1307 };
1308 assert_ne!(a, different_values);
1309
1310 let list = CypherValue::List(vec![CypherValue::Int(1), CypherValue::Int(2)]);
1313 assert_ne!(a, list);
1314 }
1315
1316 #[test]
1317 fn test_vector_type_name_and_ordering_is_unordered() {
1318 let a = CypherValue::Vector {
1319 coord: VectorCoordKind::Int32,
1320 dim: 1,
1321 values: vec![CypherValue::Int(1)],
1322 };
1323 let b = a.clone();
1324 assert_eq!(a.type_name(), "VECTOR");
1325 assert_eq!(a.partial_cmp(&b), None);
1330 }
1331
1332 #[test]
1333 fn test_vector_coord_kind_aliases_and_canonical_names() {
1334 assert_eq!(
1335 VectorCoordKind::from_alias("INT8"),
1336 Some(VectorCoordKind::Int8)
1337 );
1338 assert_eq!(
1339 VectorCoordKind::from_alias("INTEGER8"),
1340 Some(VectorCoordKind::Int8)
1341 );
1342 assert_eq!(
1343 VectorCoordKind::from_alias("SIGNED INTEGER"),
1344 Some(VectorCoordKind::Int64)
1345 );
1346 assert_eq!(
1347 VectorCoordKind::from_alias("FLOAT64"),
1348 Some(VectorCoordKind::Float64)
1349 );
1350 assert_eq!(VectorCoordKind::from_alias("STRING"), None);
1351
1352 assert_eq!(VectorCoordKind::Int64.canonical_name(), "INTEGER");
1353 assert_eq!(VectorCoordKind::Float64.canonical_name(), "FLOAT");
1354 assert_eq!(VectorCoordKind::Float32.canonical_name(), "FLOAT32");
1355
1356 assert!(VectorCoordKind::Int8.order_rank() < VectorCoordKind::Int16.order_rank());
1360 assert!(VectorCoordKind::Int16.order_rank() < VectorCoordKind::Int32.order_rank());
1361 assert!(VectorCoordKind::Int32.order_rank() < VectorCoordKind::Int64.order_rank());
1362 assert!(VectorCoordKind::Int64.order_rank() < VectorCoordKind::BFloat16.order_rank());
1363 assert!(VectorCoordKind::BFloat16.order_rank() < VectorCoordKind::Float16.order_rank());
1364 assert!(VectorCoordKind::Float16.order_rank() < VectorCoordKind::Float32.order_rank());
1365 assert!(VectorCoordKind::Float32.order_rank() < VectorCoordKind::Float64.order_rank());
1366 }
1367
1368 #[test]
1369 fn narrow_float_rounds_to_the_coordinate_precision() {
1370 use VectorCoordKind::*;
1371 assert_eq!(Float16.narrow_float(1.0), Some(1.0));
1373 assert_eq!(Float16.narrow_float(0.1), Some(0.0999755859375));
1374 assert_eq!(Float16.narrow_float(65504.0), Some(65504.0));
1375 assert_eq!(Float16.narrow_float(65520.0), None);
1376 assert_eq!(Float16.narrow_float(2f64.powi(-24)), Some(2f64.powi(-24)));
1377 assert_eq!(Float16.narrow_float(2f64.powi(-25)), Some(0.0));
1378 assert_eq!(BFloat16.narrow_float(1.0), Some(1.0));
1380 assert_eq!(BFloat16.narrow_float(257.0), Some(256.0));
1381 assert_eq!(
1382 BFloat16.narrow_float(3.3895314e38),
1383 Some(3.3895314e38f32 as f64)
1384 );
1385 assert_eq!(BFloat16.narrow_float(1e39), None);
1386 assert_eq!(BFloat16.narrow_float(9.18e-41), Some(9.183549615799121e-41));
1388 assert_eq!(Float32.narrow_float(0.1), Some(0.1f32 as f64));
1390 assert_eq!(Float64.narrow_float(0.1), Some(0.1));
1391 assert_eq!(Int8.narrow_float(1.0), None);
1392 assert_eq!(Float16.narrow_float(f64::NAN), None);
1393 }
1394
1395 #[test]
1396 fn is_exact_holds_only_for_values_the_kind_spells_unchanged() {
1397 use VectorCoordKind::*;
1398 assert!(!Float16.is_exact(0.1));
1401 assert!(!BFloat16.is_exact(0.1));
1402 assert!(!Float32.is_exact(0.1));
1403 assert!(Float64.is_exact(0.1));
1404 assert!(Float16.is_exact(0.0999755859375));
1405 assert!(BFloat16.is_exact(256.0));
1406 assert!(Float32.is_exact(0.1f32 as f64));
1407 for kind in [Float16, BFloat16, Float32, Float64] {
1408 assert!(!kind.is_exact(f64::INFINITY), "{kind:?}");
1409 assert!(!kind.is_exact(f64::NAN), "{kind:?}");
1410 }
1411 assert!(!Int8.is_exact(1.0));
1413 }
1414}