1use crate::vector::coords::VectorCoords;
2use crate::vector::float16::{bfloat16_bits, f16_bits_to_f32, f32_to_f16_bits};
3use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime};
4use indexmap::IndexMap;
5use std::fmt;
6
7#[derive(Debug, Clone, PartialEq)]
10pub struct IsoDuration {
11 pub months: i64,
12 pub days: i64,
13 pub seconds: i64,
14 pub nanoseconds: i64,
15}
16
17impl IsoDuration {
18 pub fn new(months: i64, days: i64, seconds: i64, nanoseconds: i64) -> Self {
19 Self {
20 months,
21 days,
22 seconds,
23 nanoseconds,
24 }
25 }
26
27 pub fn zero() -> Self {
28 Self::new(0, 0, 0, 0)
29 }
30}
31
32impl fmt::Display for IsoDuration {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 write!(f, "P")?;
35 let years = self.months / 12;
36 let months = self.months % 12;
37 if years != 0 {
38 write!(f, "{years}Y")?;
39 }
40 if months != 0 {
41 write!(f, "{months}M")?;
42 }
43 if self.days != 0 {
44 write!(f, "{}D", self.days)?;
45 }
46
47 let total_nanos = i128::from(self.seconds) * 1_000_000_000 + i128::from(self.nanoseconds);
55 let has_time = total_nanos != 0;
56
57 if has_time || (self.months == 0 && self.days == 0) {
58 write!(f, "T")?;
59
60 let negative = total_nanos < 0;
61 let abs_nanos = total_nanos.unsigned_abs();
62 let abs_seconds = abs_nanos / 1_000_000_000;
63 let frac_nanos = abs_nanos % 1_000_000_000;
64
65 let hours = abs_seconds / 3600;
66 let mins = (abs_seconds % 3600) / 60;
67 let secs = abs_seconds % 60;
68
69 let sign = if negative { "-" } else { "" };
70
71 if hours != 0 {
72 write!(f, "{sign}{hours}H")?;
73 }
74 if mins != 0 {
75 write!(f, "{sign}{mins}M")?;
78 }
79 if secs != 0 || frac_nanos != 0 || (!has_time && self.months == 0 && self.days == 0) {
80 if frac_nanos != 0 {
81 let frac = format!("{frac_nanos:09}");
82 let trimmed = frac.trim_end_matches('0');
83 write!(f, "{sign}{secs}.{trimmed}S")?;
84 } else {
85 write!(f, "{sign}{secs}S")?;
86 }
87 }
88 }
89 Ok(())
90 }
91}
92
93#[derive(Debug, Clone, PartialEq)]
95pub struct PointValue {
96 pub srid: i32,
97 pub x: f64,
98 pub y: f64,
99 pub z: Option<f64>,
100}
101
102impl PointValue {
103 pub fn cartesian_2d(x: f64, y: f64) -> Self {
104 Self {
105 srid: 7203,
106 x,
107 y,
108 z: None,
109 }
110 }
111
112 pub fn cartesian_3d(x: f64, y: f64, z: f64) -> Self {
113 Self {
114 srid: 9157,
115 x,
116 y,
117 z: Some(z),
118 }
119 }
120
121 pub fn wgs84_2d(longitude: f64, latitude: f64) -> Self {
122 Self {
123 srid: 4326,
124 x: longitude,
125 y: latitude,
126 z: None,
127 }
128 }
129
130 pub fn wgs84_3d(longitude: f64, latitude: f64, height: f64) -> Self {
131 Self {
132 srid: 4979,
133 x: longitude,
134 y: latitude,
135 z: Some(height),
136 }
137 }
138
139 pub fn is_3d(&self) -> bool {
142 self.z.is_some()
143 }
144
145 pub fn crs_name(&self) -> Option<&'static str> {
152 let canonical_3d = crate::point::srid_dimension(self.srid)? == 3;
153 (canonical_3d == self.is_3d()).then(|| crate::wire::crs_name(self.srid))
154 }
155}
156
157impl fmt::Display for PointValue {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 match self.z {
160 Some(z) => write!(
161 f,
162 "point({{srid: {}, x: {}, y: {}, z: {}}})",
163 self.srid, self.x, self.y, z
164 ),
165 None => write!(
166 f,
167 "point({{srid: {}, x: {}, y: {}}})",
168 self.srid, self.x, self.y
169 ),
170 }
171 }
172}
173
174pub fn float_text(f: f64) -> String {
183 if f.is_nan() {
184 return "NaN".into();
185 }
186 if f == f64::INFINITY {
187 return "Infinity".into();
188 }
189 if f == f64::NEG_INFINITY {
190 return "-Infinity".into();
191 }
192 let mut rendered = format!("{f}");
193 if !rendered.contains('.') {
194 rendered.push_str(".0");
195 }
196 rendered
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum CoordError {
204 NonFinite,
207 Overflow,
209 Inexact,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
223pub enum VectorCoordKind {
224 Int8,
225 Int16,
226 Int32,
227 Int64,
228 Float16,
230 BFloat16,
233 Float32,
234 Float64,
235}
236
237impl VectorCoordKind {
238 pub fn canonical_name(&self) -> &'static str {
244 match self {
245 VectorCoordKind::Int8 => "INTEGER8",
246 VectorCoordKind::Int16 => "INTEGER16",
247 VectorCoordKind::Int32 => "INTEGER32",
248 VectorCoordKind::Int64 => "INTEGER",
249 VectorCoordKind::Float16 => "FLOAT16",
250 VectorCoordKind::BFloat16 => "BFLOAT16",
251 VectorCoordKind::Float32 => "FLOAT32",
252 VectorCoordKind::Float64 => "FLOAT",
253 }
254 }
255
256 pub fn from_canonical_name(name: &str) -> Option<Self> {
259 Some(match name {
260 "INTEGER8" => VectorCoordKind::Int8,
261 "INTEGER16" => VectorCoordKind::Int16,
262 "INTEGER32" => VectorCoordKind::Int32,
263 "INTEGER" => VectorCoordKind::Int64,
264 "FLOAT16" => VectorCoordKind::Float16,
265 "BFLOAT16" => VectorCoordKind::BFloat16,
266 "FLOAT32" => VectorCoordKind::Float32,
267 "FLOAT" => VectorCoordKind::Float64,
268 _ => return None,
269 })
270 }
271
272 pub fn query_api_name(&self) -> Option<&'static str> {
285 match self {
286 VectorCoordKind::Int8 => Some("INT8"),
287 VectorCoordKind::Int16 => Some("INT16"),
288 VectorCoordKind::Int32 => Some("INT32"),
289 VectorCoordKind::Int64 => Some("INT64"),
290 VectorCoordKind::Float32 => Some("FLOAT32"),
291 VectorCoordKind::Float64 => Some("FLOAT64"),
292 VectorCoordKind::Float16 | VectorCoordKind::BFloat16 => None,
293 }
294 }
295
296 pub fn from_alias(name: &str) -> Option<Self> {
301 Some(match name {
302 "INT8" | "INTEGER8" => VectorCoordKind::Int8,
303 "INT16" | "INTEGER16" => VectorCoordKind::Int16,
304 "INT32" | "INTEGER32" => VectorCoordKind::Int32,
305 "INT" | "INTEGER" | "INT64" | "INTEGER64" | "SIGNED INTEGER" => VectorCoordKind::Int64,
306 "FLOAT16" => VectorCoordKind::Float16,
307 "BFLOAT16" => VectorCoordKind::BFloat16,
308 "FLOAT32" => VectorCoordKind::Float32,
309 "FLOAT" | "FLOAT64" => VectorCoordKind::Float64,
310 _ => return None,
311 })
312 }
313
314 pub fn is_integer(&self) -> bool {
318 !matches!(
319 self,
320 VectorCoordKind::Float16
321 | VectorCoordKind::BFloat16
322 | VectorCoordKind::Float32
323 | VectorCoordKind::Float64
324 )
325 }
326
327 pub fn order_rank(&self) -> u8 {
332 match self {
333 VectorCoordKind::Int8 => 0,
334 VectorCoordKind::Int16 => 1,
335 VectorCoordKind::Int32 => 2,
336 VectorCoordKind::Int64 => 3,
337 VectorCoordKind::BFloat16 => 4,
338 VectorCoordKind::Float16 => 5,
339 VectorCoordKind::Float32 => 6,
340 VectorCoordKind::Float64 => 7,
341 }
342 }
343
344 pub fn narrow_float(self, f: f64) -> Option<f64> {
351 if !f.is_finite() {
352 return None;
353 }
354 let narrowed = match self {
355 VectorCoordKind::Float64 => f,
356 VectorCoordKind::Float32 => f as f32 as f64,
357 VectorCoordKind::Float16 => f16_bits_to_f32(f32_to_f16_bits(f as f32)) as f64,
358 VectorCoordKind::BFloat16 => f32::from_bits(bfloat16_bits(f as f32)) as f64,
359 VectorCoordKind::Int8
360 | VectorCoordKind::Int16
361 | VectorCoordKind::Int32
362 | VectorCoordKind::Int64 => return None,
363 };
364 narrowed.is_finite().then_some(narrowed)
365 }
366
367 pub fn is_exact(self, f: f64) -> bool {
376 f.is_finite() && self.narrow_float(f) == Some(f)
377 }
378
379 pub fn coerce(self, n: f64) -> Result<crate::Coord, CoordError> {
385 if self.is_integer() {
386 let n = if n.is_nan() { 0.0 } else { n };
387 if !n.is_finite() {
388 return Err(CoordError::NonFinite);
389 }
390 let truncated = n.trunc();
391 let in_cast_range = truncated >= i64::MIN as f64 && truncated <= i64::MAX as f64;
392 let value = truncated as i64;
393 if !(in_cast_range && self.holds_int(value)) {
394 return Err(CoordError::Overflow);
395 }
396 Ok(crate::Coord::I(value))
397 } else {
398 if !n.is_finite() {
399 return Err(CoordError::NonFinite);
400 }
401 self.narrow_float(n)
402 .map(crate::Coord::F)
403 .ok_or(CoordError::Inexact)
404 }
405 }
406
407 pub fn is_f32_family(self) -> bool {
410 matches!(
411 self,
412 VectorCoordKind::Float16 | VectorCoordKind::BFloat16 | VectorCoordKind::Float32
413 )
414 }
415
416 pub fn holds_int(self, n: i64) -> bool {
422 match self {
423 VectorCoordKind::Int8 => i8::try_from(n).is_ok(),
424 VectorCoordKind::Int16 => i16::try_from(n).is_ok(),
425 VectorCoordKind::Int32 => i32::try_from(n).is_ok(),
426 VectorCoordKind::Int64 => true,
427 VectorCoordKind::Float16
428 | VectorCoordKind::BFloat16
429 | VectorCoordKind::Float32
430 | VectorCoordKind::Float64 => false,
431 }
432 }
433}
434
435pub type Coord2D = [f64; 2];
437
438#[derive(Debug, Clone, PartialEq)]
440pub enum GeometryValue {
441 LineString {
442 coordinates: Vec<Coord2D>,
443 srid: i32,
444 },
445 Polygon {
446 rings: Vec<Vec<Coord2D>>,
448 srid: i32,
449 },
450 MultiPoint {
451 points: Vec<Coord2D>,
452 srid: i32,
453 },
454 MultiLineString {
455 lines: Vec<Vec<Coord2D>>,
456 srid: i32,
457 },
458 MultiPolygon {
459 polygons: Vec<Vec<Vec<Coord2D>>>,
460 srid: i32,
461 },
462 GeometryCollection {
463 geometries: Vec<GeometryValue>,
464 srid: i32,
465 },
466}
467
468impl GeometryValue {
469 pub fn srid(&self) -> i32 {
471 match self {
472 GeometryValue::LineString { srid, .. }
473 | GeometryValue::Polygon { srid, .. }
474 | GeometryValue::MultiPoint { srid, .. }
475 | GeometryValue::MultiLineString { srid, .. }
476 | GeometryValue::MultiPolygon { srid, .. }
477 | GeometryValue::GeometryCollection { srid, .. } => *srid,
478 }
479 }
480
481 pub fn type_name(&self) -> &'static str {
483 match self {
484 GeometryValue::LineString { .. } => "LineString",
485 GeometryValue::Polygon { .. } => "Polygon",
486 GeometryValue::MultiPoint { .. } => "MultiPoint",
487 GeometryValue::MultiLineString { .. } => "MultiLineString",
488 GeometryValue::MultiPolygon { .. } => "MultiPolygon",
489 GeometryValue::GeometryCollection { .. } => "GeometryCollection",
490 }
491 }
492}
493
494impl fmt::Display for GeometryValue {
495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496 match self {
497 GeometryValue::LineString { coordinates, srid } => {
498 write!(f, "linestring({{srid: {srid}, coordinates: [")?;
499 for (i, c) in coordinates.iter().enumerate() {
500 if i > 0 {
501 write!(f, ", ")?;
502 }
503 write!(f, "[{}, {}]", c[0], c[1])?;
504 }
505 write!(f, "]}})")
506 }
507 GeometryValue::Polygon { rings, srid } => {
508 write!(f, "polygon({{srid: {srid}, coordinates: [")?;
509 for (i, ring) in rings.iter().enumerate() {
510 if i > 0 {
511 write!(f, ", ")?;
512 }
513 write!(f, "[")?;
514 for (j, c) in ring.iter().enumerate() {
515 if j > 0 {
516 write!(f, ", ")?;
517 }
518 write!(f, "[{}, {}]", c[0], c[1])?;
519 }
520 write!(f, "]")?;
521 }
522 write!(f, "]}})")
523 }
524 GeometryValue::MultiPoint { points, srid } => {
525 write!(f, "multipoint({{srid: {srid}, coordinates: [")?;
526 for (i, c) in points.iter().enumerate() {
527 if i > 0 {
528 write!(f, ", ")?;
529 }
530 write!(f, "[{}, {}]", c[0], c[1])?;
531 }
532 write!(f, "]}})")
533 }
534 GeometryValue::MultiLineString { lines: _, srid } => {
535 write!(f, "multilinestring({{srid: {srid}, ...}})")
536 }
537 GeometryValue::MultiPolygon { polygons: _, srid } => {
538 write!(f, "multipolygon({{srid: {srid}, ...}})")
539 }
540 GeometryValue::GeometryCollection { geometries, srid } => {
541 write!(
542 f,
543 "geometrycollection({{srid: {}, count: {}}})",
544 srid,
545 geometries.len()
546 )
547 }
548 }
549 }
550}
551
552#[derive(Debug, Clone)]
557pub enum CypherValue {
558 Null,
559 Bool(bool),
560 Int(i64),
561 Float(f64),
562 Str(String),
563 List(Vec<CypherValue>),
564 Map(IndexMap<String, CypherValue>),
565 Node {
566 id: i64,
567 labels: Vec<String>,
568 properties: IndexMap<String, CypherValue>,
569 },
570 Relationship {
571 id: i64,
572 start_id: i64,
573 end_id: i64,
574 rel_type: String,
575 properties: IndexMap<String, CypherValue>,
576 },
577 Path {
578 nodes: Vec<CypherValue>,
579 relationships: Vec<CypherValue>,
580 },
581 Date(NaiveDate),
582 Time(NaiveTime, Option<FixedOffset>),
583 DateTime(DateTime<FixedOffset>, Option<String>),
585 LocalDateTime(NaiveDateTime),
586 Duration(IsoDuration),
587 Point(PointValue),
588 Geometry(GeometryValue),
589 Vector {
596 coord: VectorCoordKind,
597 coords: VectorCoords,
598 },
599}
600
601impl CypherValue {
602 pub fn is_null(&self) -> bool {
604 matches!(self, CypherValue::Null)
605 }
606
607 pub fn vector(coord: VectorCoordKind, coords: VectorCoords) -> CypherValue {
619 coords.assert_conforms(coord);
620 CypherValue::Vector { coord, coords }
621 }
622
623 pub fn is_temporal(&self) -> bool {
629 match self {
630 CypherValue::Date(_)
631 | CypherValue::Time(..)
632 | CypherValue::DateTime(..)
633 | CypherValue::LocalDateTime(_)
634 | CypherValue::Duration(_) => true,
635 CypherValue::Null
636 | CypherValue::Bool(_)
637 | CypherValue::Int(_)
638 | CypherValue::Float(_)
639 | CypherValue::Str(_)
640 | CypherValue::List(_)
641 | CypherValue::Map(_)
642 | CypherValue::Node { .. }
643 | CypherValue::Relationship { .. }
644 | CypherValue::Path { .. }
645 | CypherValue::Geometry(_)
646 | CypherValue::Vector { .. }
647 | CypherValue::Point(_) => false,
648 }
649 }
650
651 pub fn type_name(&self) -> &'static str {
653 match self {
654 CypherValue::Null => "NULL",
655 CypherValue::Bool(_) => "BOOLEAN",
656 CypherValue::Int(_) => "INTEGER",
657 CypherValue::Float(_) => "FLOAT",
658 CypherValue::Str(_) => "STRING",
659 CypherValue::List(_) => "LIST",
660 CypherValue::Map(_) => "MAP",
661 CypherValue::Node { .. } => "NODE",
662 CypherValue::Relationship { .. } => "RELATIONSHIP",
663 CypherValue::Path { .. } => "PATH",
664 CypherValue::Date(_) => "DATE",
665 CypherValue::Time(_, _) => "TIME",
666 CypherValue::DateTime(..) => "DATE_TIME",
667 CypherValue::LocalDateTime(_) => "LOCAL_DATE_TIME",
668 CypherValue::Duration(_) => "DURATION",
669 CypherValue::Point(_) => "POINT",
670 CypherValue::Geometry(g) => g.type_name(),
671 CypherValue::Vector { .. } => "VECTOR",
672 }
673 }
674
675 pub fn as_bool(&self) -> Option<bool> {
677 match self {
678 CypherValue::Bool(b) => Some(*b),
679 _ => None,
680 }
681 }
682
683 pub fn as_int(&self) -> Option<i64> {
685 match self {
686 CypherValue::Int(i) => Some(*i),
687 _ => None,
688 }
689 }
690
691 pub fn as_float(&self) -> Option<f64> {
693 match self {
694 CypherValue::Float(f) => Some(*f),
695 CypherValue::Int(i) => Some(*i as f64),
696 _ => None,
697 }
698 }
699
700 pub fn as_str(&self) -> Option<&str> {
702 match self {
703 CypherValue::Str(s) => Some(s),
704 _ => None,
705 }
706 }
707
708 pub fn as_list(&self) -> Option<&[CypherValue]> {
710 match self {
711 CypherValue::List(l) => Some(l),
712 _ => None,
713 }
714 }
715
716 pub fn as_map(&self) -> Option<&IndexMap<String, CypherValue>> {
718 match self {
719 CypherValue::Map(m) => Some(m),
720 _ => None,
721 }
722 }
723
724 pub fn to_bool_3vl(&self) -> Option<bool> {
727 match self {
728 CypherValue::Null => None,
729 CypherValue::Bool(b) => Some(*b),
730 _ => Some(true), }
732 }
733
734 pub fn as_numeric(&self) -> Option<(f64, bool)> {
737 match self {
738 CypherValue::Int(i) => Some((*i as f64, true)),
739 CypherValue::Float(f) => Some((*f, false)),
740 _ => None,
741 }
742 }
743}
744
745impl fmt::Display for CypherValue {
746 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
747 match self {
748 CypherValue::Null => write!(f, "null"),
749 CypherValue::Bool(b) => write!(f, "{b}"),
750 CypherValue::Int(i) => write!(f, "{i}"),
751 CypherValue::Float(v) => {
752 if v.is_nan() {
753 write!(f, "NaN")
754 } else if v.is_infinite() {
755 write!(f, "{}Inf", if *v < 0.0 { "-" } else { "" })
756 } else if v.fract() == 0.0 {
757 write!(f, "{v}.0")
758 } else {
759 write!(f, "{v}")
760 }
761 }
762 CypherValue::Str(s) => write!(f, "\"{s}\""),
763 CypherValue::List(items) => {
764 write!(f, "[")?;
765 for (i, item) in items.iter().enumerate() {
766 if i > 0 {
767 write!(f, ", ")?;
768 }
769 write!(f, "{item}")?;
770 }
771 write!(f, "]")
772 }
773 CypherValue::Map(map) => {
774 write!(f, "{{")?;
775 for (i, (k, v)) in map.iter().enumerate() {
776 if i > 0 {
777 write!(f, ", ")?;
778 }
779 write!(f, "{k}: {v}")?;
780 }
781 write!(f, "}}")
782 }
783 CypherValue::Node {
784 labels, properties, ..
785 } => {
786 write!(f, "(:{}", labels.join(":"))?;
787 if !properties.is_empty() {
788 write!(f, " {{")?;
789 for (i, (k, v)) in properties.iter().enumerate() {
790 if i > 0 {
791 write!(f, ", ")?;
792 }
793 write!(f, "{k}: {v}")?;
794 }
795 write!(f, "}}")?;
796 }
797 write!(f, ")")
798 }
799 CypherValue::Relationship {
800 rel_type,
801 properties,
802 ..
803 } => {
804 write!(f, "[:{rel_type}")?;
805 if !properties.is_empty() {
806 write!(f, " {{")?;
807 for (i, (k, v)) in properties.iter().enumerate() {
808 if i > 0 {
809 write!(f, ", ")?;
810 }
811 write!(f, "{k}: {v}")?;
812 }
813 write!(f, "}}")?;
814 }
815 write!(f, "]")
816 }
817 CypherValue::Path {
818 nodes,
819 relationships,
820 } => {
821 for (i, node) in nodes.iter().enumerate() {
822 if i > 0 {
823 if let Some(rel) = relationships.get(i - 1) {
824 write!(f, "-{rel}-")?;
825 } else {
826 write!(f, "--")?;
827 }
828 }
829 write!(f, "{node}")?;
830 }
831 Ok(())
832 }
833 CypherValue::Date(d) => write!(f, "{d}"),
834 CypherValue::Time(t, tz) => {
835 use chrono::Timelike;
836 let nanos = t.nanosecond() % 1_000_000_000;
838 if nanos != 0 {
839 let frac = format!("{nanos:09}");
840 let trimmed = frac.trim_end_matches('0');
841 write!(
842 f,
843 "{:02}:{:02}:{:02}.{}",
844 t.hour(),
845 t.minute(),
846 t.second(),
847 trimmed
848 )?;
849 } else if t.second() != 0 {
850 write!(f, "{}", t.format("%H:%M:%S"))?;
851 } else {
852 write!(f, "{}", t.format("%H:%M"))?;
853 }
854 if let Some(offset) = tz {
856 let total_secs = offset.local_minus_utc();
857 if total_secs == 0 {
858 write!(f, "Z")
859 } else {
860 let sign = if total_secs >= 0 { '+' } else { '-' };
861 let abs_secs = total_secs.unsigned_abs();
862 let hours = abs_secs / 3600;
863 let mins = (abs_secs % 3600) / 60;
864 let secs = abs_secs % 60;
865 if secs != 0 {
866 write!(f, "{sign}{hours:02}:{mins:02}:{secs:02}")
867 } else {
868 write!(f, "{sign}{hours:02}:{mins:02}")
869 }
870 }
871 } else {
872 Ok(())
873 }
874 }
875 CypherValue::DateTime(dt, tz_name) => {
876 let nanos = dt.timestamp_subsec_nanos();
878 let date_part = dt.date_naive();
879 let time_part = dt.time();
880 if nanos != 0 {
881 let frac = format!("{nanos:09}");
882 let trimmed = frac.trim_end_matches('0');
883 write!(
884 f,
885 "{}T{}.{}",
886 date_part,
887 time_part.format("%H:%M:%S"),
888 trimmed
889 )?;
890 } else {
891 write!(f, "{}T{}", date_part, time_part.format("%H:%M:%S"))?;
892 }
893 let offset = dt.offset();
895 let total_secs = offset.local_minus_utc();
896 if total_secs == 0 {
897 write!(f, "Z")?;
898 } else {
899 let sign = if total_secs >= 0 { '+' } else { '-' };
900 let abs_secs = total_secs.unsigned_abs();
901 let hours = abs_secs / 3600;
902 let mins = (abs_secs % 3600) / 60;
903 let secs_rem = abs_secs % 60;
904 if secs_rem != 0 {
905 write!(f, "{sign}{hours:02}:{mins:02}:{secs_rem:02}")?;
906 } else {
907 write!(f, "{sign}{hours:02}:{mins:02}")?;
908 }
909 }
910 if let Some(tz) = tz_name {
912 write!(f, "[{tz}]")?;
913 }
914 Ok(())
915 }
916 CypherValue::LocalDateTime(dt) => {
917 let nanos = dt.and_utc().timestamp_subsec_nanos();
919 if nanos != 0 {
920 let frac = format!("{nanos:09}");
921 let trimmed = frac.trim_end_matches('0');
922 write!(
923 f,
924 "{}T{}.{}",
925 dt.date(),
926 dt.time().format("%H:%M:%S"),
927 trimmed
928 )
929 } else {
930 write!(f, "{}T{}", dt.date(), dt.time().format("%H:%M:%S"))
931 }
932 }
933 CypherValue::Duration(d) => write!(f, "{d}"),
934 CypherValue::Point(p) => write!(f, "{p}"),
935 CypherValue::Geometry(g) => write!(f, "{g}"),
936 CypherValue::Vector { coord, coords } => {
937 write!(f, "vector([")?;
938 for (i, c) in coords.iter().enumerate() {
939 if i > 0 {
940 write!(f, ", ")?;
941 }
942 write!(f, "{c}")?;
943 }
944 write!(
945 f,
946 "], {}, {} NOT NULL)",
947 coords.len(),
948 coord.canonical_name()
949 )
950 }
951 }
952 }
953}
954
955impl PartialEq for CypherValue {
956 fn eq(&self, other: &Self) -> bool {
957 match (self, other) {
958 (CypherValue::Null, CypherValue::Null) => true,
959 (CypherValue::Bool(a), CypherValue::Bool(b)) => a == b,
960 (CypherValue::Int(a), CypherValue::Int(b)) => a == b,
961 (CypherValue::Float(a), CypherValue::Float(b)) => a == b,
962 (CypherValue::Int(a), CypherValue::Float(b)) => {
969 crate::canonical_key::eq_i64_f64(*a, *b)
970 }
971 (CypherValue::Float(a), CypherValue::Int(b)) => {
972 crate::canonical_key::eq_i64_f64(*b, *a)
973 }
974 (CypherValue::Str(a), CypherValue::Str(b)) => a == b,
975 (CypherValue::List(a), CypherValue::List(b)) => a == b,
976 (CypherValue::Map(a), CypherValue::Map(b)) => a == b,
977 (CypherValue::Node { id: a, .. }, CypherValue::Node { id: b, .. }) => a == b,
978 (CypherValue::Relationship { id: a, .. }, CypherValue::Relationship { id: b, .. }) => {
979 a == b
980 }
981 (CypherValue::Date(a), CypherValue::Date(b)) => a == b,
982 (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => a == b && ao == bo,
983 (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a == b,
984 (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a == b,
985 (CypherValue::Duration(a), CypherValue::Duration(b)) => a == b,
986 (CypherValue::Point(a), CypherValue::Point(b)) => a == b,
987 (CypherValue::Geometry(a), CypherValue::Geometry(b)) => a == b,
988 (
989 CypherValue::Vector {
990 coord: ca,
991 coords: va,
992 },
993 CypherValue::Vector {
994 coord: cb,
995 coords: vb,
996 },
997 ) => {
998 ca == cb && va.numeric_eq(vb)
1004 }
1005 (
1006 CypherValue::Path {
1007 nodes: n1,
1008 relationships: r1,
1009 },
1010 CypherValue::Path {
1011 nodes: n2,
1012 relationships: r2,
1013 },
1014 ) => n1 == n2 && r1 == r2,
1015 _ => false,
1016 }
1017 }
1018}
1019
1020impl PartialOrd for CypherValue {
1021 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1022 match (self, other) {
1023 (CypherValue::Int(a), CypherValue::Int(b)) => a.partial_cmp(b),
1024 (CypherValue::Float(a), CypherValue::Float(b)) => a.partial_cmp(b),
1025 (CypherValue::Int(a), CypherValue::Float(b)) => {
1029 crate::canonical_key::cmp_i64_f64(*a, *b)
1030 }
1031 (CypherValue::Float(a), CypherValue::Int(b)) => {
1032 crate::canonical_key::cmp_i64_f64(*b, *a).map(std::cmp::Ordering::reverse)
1033 }
1034 (CypherValue::Str(a), CypherValue::Str(b)) => a.partial_cmp(b),
1035 (CypherValue::Bool(a), CypherValue::Bool(b)) => a.partial_cmp(b),
1036 (CypherValue::Date(a), CypherValue::Date(b)) => a.partial_cmp(b),
1037 (CypherValue::List(a), CypherValue::List(b)) => {
1038 for (av, bv) in a.iter().zip(b.iter()) {
1040 match av.partial_cmp(bv) {
1041 Some(std::cmp::Ordering::Equal) => continue,
1042 Some(ord) => return Some(ord),
1043 None => return None,
1044 }
1045 }
1046 a.len().partial_cmp(&b.len())
1047 }
1048 (CypherValue::Time(a, ao), CypherValue::Time(b, bo)) => {
1049 match (ao, bo) {
1051 (Some(a_off), Some(b_off)) => {
1052 use chrono::Timelike;
1053 let a_utc_secs =
1054 a.num_seconds_from_midnight() as i64 - a_off.local_minus_utc() as i64;
1055 let b_utc_secs =
1056 b.num_seconds_from_midnight() as i64 - b_off.local_minus_utc() as i64;
1057 match a_utc_secs.partial_cmp(&b_utc_secs) {
1058 Some(std::cmp::Ordering::Equal) => {
1059 let a_nanos = a.nanosecond() % 1_000_000_000;
1061 let b_nanos = b.nanosecond() % 1_000_000_000;
1062 a_nanos.partial_cmp(&b_nanos)
1063 }
1064 other => other,
1065 }
1066 }
1067 (None, None) => a.partial_cmp(b),
1068 _ => None,
1069 }
1070 }
1071 (CypherValue::DateTime(a, _), CypherValue::DateTime(b, _)) => a.partial_cmp(b),
1072 (CypherValue::LocalDateTime(a), CypherValue::LocalDateTime(b)) => a.partial_cmp(b),
1073 _ => None,
1074 }
1075 }
1076}
1077
1078impl From<bool> for CypherValue {
1079 fn from(b: bool) -> Self {
1080 CypherValue::Bool(b)
1081 }
1082}
1083
1084impl From<i64> for CypherValue {
1085 fn from(i: i64) -> Self {
1086 CypherValue::Int(i)
1087 }
1088}
1089
1090impl From<f64> for CypherValue {
1091 fn from(f: f64) -> Self {
1092 CypherValue::Float(f)
1093 }
1094}
1095
1096impl From<String> for CypherValue {
1097 fn from(s: String) -> Self {
1098 CypherValue::Str(s)
1099 }
1100}
1101
1102impl From<&str> for CypherValue {
1103 fn from(s: &str) -> Self {
1104 CypherValue::Str(s.to_string())
1105 }
1106}
1107
1108impl<T: Into<CypherValue>> From<Vec<T>> for CypherValue {
1109 fn from(v: Vec<T>) -> Self {
1110 CypherValue::List(v.into_iter().map(|x| x.into()).collect())
1111 }
1112}
1113
1114impl<T: Into<CypherValue>> From<Option<T>> for CypherValue {
1115 fn from(o: Option<T>) -> Self {
1116 match o {
1117 Some(v) => v.into(),
1118 None => CypherValue::Null,
1119 }
1120 }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125 use super::*;
1126
1127 #[test]
1128 #[allow(clippy::approx_constant)]
1129 fn test_type_names() {
1130 assert_eq!(CypherValue::Null.type_name(), "NULL");
1131 assert_eq!(CypherValue::Bool(true).type_name(), "BOOLEAN");
1132 assert_eq!(CypherValue::Int(42).type_name(), "INTEGER");
1133 assert_eq!(CypherValue::Float(3.14).type_name(), "FLOAT");
1134 assert_eq!(CypherValue::Str("hello".into()).type_name(), "STRING");
1135 assert_eq!(CypherValue::List(vec![]).type_name(), "LIST");
1136 assert_eq!(CypherValue::Map(IndexMap::new()).type_name(), "MAP");
1137 }
1138
1139 #[test]
1140 fn point_crs_name_classifies_the_four_point_codes() {
1141 let cases = [
1142 (PointValue::cartesian_2d(1.0, 2.0), "cartesian", false),
1143 (
1144 PointValue::cartesian_3d(1.0, 2.0, 3.0),
1145 "cartesian-3d",
1146 true,
1147 ),
1148 (PointValue::wgs84_2d(1.0, 2.0), "wgs-84", false),
1149 (PointValue::wgs84_3d(1.0, 2.0, 3.0), "wgs-84-3d", true),
1150 ];
1151 for (point, name, is_3d) in cases {
1152 assert_eq!(point.crs_name(), Some(name), "{point:?}");
1153 assert_eq!(point.is_3d(), is_3d, "{point:?}");
1154 }
1155 let unknown = PointValue {
1158 srid: 1234,
1159 x: 1.0,
1160 y: 2.0,
1161 z: None,
1162 };
1163 assert_eq!(unknown.crs_name(), None);
1164 let wrong_dimension = PointValue {
1165 srid: 7203,
1166 x: 1.0,
1167 y: 2.0,
1168 z: Some(3.0),
1169 };
1170 assert_eq!(wrong_dimension.crs_name(), None);
1171 }
1172
1173 #[test]
1174 fn test_int_float_equality() {
1175 assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1176 assert_eq!(CypherValue::Float(1.0), CypherValue::Int(1));
1177 assert_ne!(CypherValue::Int(1), CypherValue::Float(1.5));
1178 }
1179
1180 #[test]
1181 fn test_partial_ord() {
1182 assert!(CypherValue::Int(1) < CypherValue::Int(2));
1183 assert!(CypherValue::Int(1) < CypherValue::Float(1.5));
1184 assert!(CypherValue::Str("a".into()) < CypherValue::Str("b".into()));
1185 }
1186
1187 #[test]
1188 fn int_float_equality_is_exact_past_2_pow_53() {
1189 let big_int = CypherValue::Int(9_007_199_254_740_993);
1196 let near_float = CypherValue::Float(9_007_199_254_740_992.0);
1197 assert_ne!(big_int, near_float);
1198 assert_ne!(near_float, big_int);
1199
1200 assert_eq!(
1202 CypherValue::Int(9_007_199_254_740_992),
1203 CypherValue::Float(9_007_199_254_740_992.0)
1204 );
1205
1206 assert_eq!(CypherValue::Int(1), CypherValue::Float(1.0));
1208 assert_eq!(CypherValue::Int(0), CypherValue::Float(-0.0));
1209 }
1210
1211 #[test]
1212 fn int_float_ordering_stays_consistent_with_equality() {
1213 let probes = [
1218 (9_007_199_254_740_993_i64, 9_007_199_254_740_992.0_f64),
1219 (9_007_199_254_740_992, 9_007_199_254_740_992.0),
1220 (i64::MAX, 9_223_372_036_854_775_808.0), (i64::MIN, -9_223_372_036_854_775_808.0), (0, -0.0),
1223 (1, 1.0),
1224 (2, 1.5),
1225 (1, 1.5),
1226 ];
1227 for (i, f) in probes {
1228 let iv = CypherValue::Int(i);
1229 let fv = CypherValue::Float(f);
1230 let eq = iv == fv;
1231 let cmp_eq = iv.partial_cmp(&fv) == Some(std::cmp::Ordering::Equal);
1232 assert_eq!(eq, cmp_eq, "eq/ord disagree for Int({i}) vs Float({f})");
1233 let rev = fv.partial_cmp(&iv);
1235 assert_eq!(
1236 iv.partial_cmp(&fv),
1237 rev.map(std::cmp::Ordering::reverse),
1238 "forward/reverse ordering not antisymmetric for {i}/{f}"
1239 );
1240 }
1241 assert!(
1243 CypherValue::Int(9_007_199_254_740_993) > CypherValue::Float(9_007_199_254_740_992.0)
1244 );
1245 }
1246
1247 #[test]
1248 fn test_display() {
1249 assert_eq!(format!("{}", CypherValue::Null), "null");
1250 assert_eq!(format!("{}", CypherValue::Bool(true)), "true");
1251 assert_eq!(format!("{}", CypherValue::Int(42)), "42");
1252 assert_eq!(format!("{}", CypherValue::Float(3.0)), "3.0");
1253 assert_eq!(format!("{}", CypherValue::Str("hi".into())), "\"hi\"");
1254 }
1255
1256 #[test]
1257 #[allow(clippy::approx_constant)]
1258 fn test_as_float_promotion() {
1259 assert_eq!(CypherValue::Int(5).as_float(), Some(5.0));
1260 assert_eq!(CypherValue::Float(3.14).as_float(), Some(3.14));
1261 assert_eq!(CypherValue::Str("x".into()).as_float(), None);
1262 }
1263
1264 #[test]
1265 fn test_three_valued_logic() {
1266 assert_eq!(CypherValue::Null.to_bool_3vl(), None);
1267 assert_eq!(CypherValue::Bool(true).to_bool_3vl(), Some(true));
1268 assert_eq!(CypherValue::Bool(false).to_bool_3vl(), Some(false));
1269 assert_eq!(CypherValue::Int(0).to_bool_3vl(), Some(true));
1270 }
1271
1272 #[test]
1273 fn test_iso_duration_display() {
1274 assert_eq!(format!("{}", IsoDuration::new(0, 0, 0, 0)), "PT0S");
1275 assert_eq!(format!("{}", IsoDuration::new(14, 0, 0, 0)), "P1Y2M");
1276 assert_eq!(format!("{}", IsoDuration::new(0, 5, 3661, 0)), "P5DT1H1M1S");
1277 assert_eq!(
1279 format!("{}", IsoDuration::new(0, 0, -3661, -500_000_000)),
1280 "PT-1H-1M-1.5S"
1281 );
1282 assert_eq!(
1284 format!("{}", IsoDuration::new(0, 0, 1, -1_500_000_000)),
1285 "PT-0.5S"
1286 );
1287 }
1288
1289 #[test]
1290 fn test_iso_duration_display_extreme_magnitudes() {
1291 assert_eq!(
1293 format!("{}", IsoDuration::new(12_000_000, 0, 0, 0)),
1294 "P1000000Y"
1295 );
1296 assert_eq!(
1297 format!("{}", IsoDuration::new(-12_000_000, 0, 0, 0)),
1298 "P-1000000Y"
1299 );
1300 assert_eq!(
1303 format!("{}", IsoDuration::new(0, 0, i64::MAX, 999_999_999)),
1304 "PT2562047788015215H30M7.999999999S"
1305 );
1306 assert_eq!(
1307 format!("{}", IsoDuration::new(0, 0, i64::MIN, -999_999_999)),
1308 "PT-2562047788015215H-30M-8.999999999S"
1309 );
1310 assert_eq!(
1312 format!("{}", IsoDuration::new(12_000_000, 0, i64::MAX, 999_999_999)),
1313 "P1000000YT2562047788015215H30M7.999999999S"
1314 );
1315 assert_eq!(
1316 format!(
1317 "{}",
1318 IsoDuration::new(-12_000_000, 0, i64::MIN, -999_999_999)
1319 ),
1320 "P-1000000YT-2562047788015215H-30M-8.999999999S"
1321 );
1322 }
1323
1324 #[test]
1325 fn test_point_display() {
1326 let p = PointValue::wgs84_2d(-73.9857, 40.7484);
1327 assert_eq!(
1328 format!("{p}"),
1329 "point({srid: 4326, x: -73.9857, y: 40.7484})"
1330 );
1331 }
1332
1333 #[test]
1334 fn test_from_conversions() {
1335 let v: CypherValue = 42i64.into();
1336 assert_eq!(v, CypherValue::Int(42));
1337
1338 let v: CypherValue = "hello".into();
1339 assert_eq!(v, CypherValue::Str("hello".to_string()));
1340
1341 let v: CypherValue = true.into();
1342 assert_eq!(v, CypherValue::Bool(true));
1343
1344 let v: CypherValue = None::<i64>.into();
1345 assert_eq!(v, CypherValue::Null);
1346 }
1347
1348 #[test]
1349 fn test_float_display_infinity_and_nan() {
1350 assert_eq!(format!("{}", CypherValue::Float(f64::INFINITY)), "Inf");
1354 assert_eq!(format!("{}", CypherValue::Float(f64::NEG_INFINITY)), "-Inf");
1355 assert_eq!(format!("{}", CypherValue::Float(f64::NAN)), "NaN");
1356 assert_eq!(format!("{}", CypherValue::Float(2.0)), "2.0");
1358 assert_eq!(format!("{}", CypherValue::Float(1.5)), "1.5");
1359 }
1360
1361 #[test]
1364 fn test_vector_display() {
1365 let v = CypherValue::vector(
1366 VectorCoordKind::Int64,
1367 VectorCoords::from_int(vec![1i64, 2, 3]),
1368 );
1369 assert_eq!(format!("{v}"), "vector([1, 2, 3], 3, INTEGER NOT NULL)");
1370
1371 let float_v = CypherValue::vector(
1372 VectorCoordKind::Float32,
1373 VectorCoords::from_f32(vec![1.0f32, 2.5]),
1374 );
1375 assert_eq!(
1376 format!("{float_v}"),
1377 "vector([1.0, 2.5], 2, FLOAT32 NOT NULL)"
1378 );
1379 }
1380
1381 #[test]
1382 fn test_vector_equality_compares_coord_dim_and_values() {
1383 let a = CypherValue::vector(
1384 VectorCoordKind::Int32,
1385 VectorCoords::from_int(vec![1i64, 2]),
1386 );
1387 let same = a.clone();
1388 assert_eq!(a, same);
1389
1390 let different_coord = CypherValue::vector(
1391 VectorCoordKind::Int64,
1392 VectorCoords::from_int(vec![1i64, 2]),
1393 );
1394 assert_ne!(a, different_coord);
1395
1396 let different_values = CypherValue::vector(
1397 VectorCoordKind::Int32,
1398 VectorCoords::from_int(vec![2i64, 1]),
1399 );
1400 assert_ne!(a, different_values);
1401
1402 let list = CypherValue::List(vec![CypherValue::Int(1), CypherValue::Int(2)]);
1405 assert_ne!(a, list);
1406 }
1407
1408 #[test]
1409 fn test_vector_type_name_and_ordering_is_unordered() {
1410 let a = CypherValue::vector(VectorCoordKind::Int32, VectorCoords::from_int(vec![1i64]));
1411 let b = a.clone();
1412 assert_eq!(a.type_name(), "VECTOR");
1413 assert_eq!(a.partial_cmp(&b), None);
1418 }
1419
1420 #[test]
1421 fn test_vector_coord_kind_aliases_and_canonical_names() {
1422 assert_eq!(
1423 VectorCoordKind::from_alias("INT8"),
1424 Some(VectorCoordKind::Int8)
1425 );
1426 assert_eq!(
1427 VectorCoordKind::from_alias("INTEGER8"),
1428 Some(VectorCoordKind::Int8)
1429 );
1430 assert_eq!(
1431 VectorCoordKind::from_alias("SIGNED INTEGER"),
1432 Some(VectorCoordKind::Int64)
1433 );
1434 assert_eq!(
1435 VectorCoordKind::from_alias("FLOAT64"),
1436 Some(VectorCoordKind::Float64)
1437 );
1438 assert_eq!(VectorCoordKind::from_alias("STRING"), None);
1439
1440 assert_eq!(VectorCoordKind::Int64.canonical_name(), "INTEGER");
1441 assert_eq!(VectorCoordKind::Float64.canonical_name(), "FLOAT");
1442 assert_eq!(VectorCoordKind::Float32.canonical_name(), "FLOAT32");
1443
1444 for (kind, name) in [
1448 (VectorCoordKind::Int8, "INT8"),
1449 (VectorCoordKind::Int16, "INT16"),
1450 (VectorCoordKind::Int32, "INT32"),
1451 (VectorCoordKind::Int64, "INT64"),
1452 (VectorCoordKind::Float32, "FLOAT32"),
1453 (VectorCoordKind::Float64, "FLOAT64"),
1454 ] {
1455 assert_eq!(kind.query_api_name(), Some(name));
1456 assert_eq!(VectorCoordKind::from_alias(name), Some(kind));
1457 }
1458 assert_eq!(VectorCoordKind::Float16.query_api_name(), None);
1459 assert_eq!(VectorCoordKind::BFloat16.query_api_name(), None);
1460
1461 assert!(VectorCoordKind::Int8.order_rank() < VectorCoordKind::Int16.order_rank());
1465 assert!(VectorCoordKind::Int16.order_rank() < VectorCoordKind::Int32.order_rank());
1466 assert!(VectorCoordKind::Int32.order_rank() < VectorCoordKind::Int64.order_rank());
1467 assert!(VectorCoordKind::Int64.order_rank() < VectorCoordKind::BFloat16.order_rank());
1468 assert!(VectorCoordKind::BFloat16.order_rank() < VectorCoordKind::Float16.order_rank());
1469 assert!(VectorCoordKind::Float16.order_rank() < VectorCoordKind::Float32.order_rank());
1470 assert!(VectorCoordKind::Float32.order_rank() < VectorCoordKind::Float64.order_rank());
1471 }
1472
1473 #[test]
1474 fn narrow_float_rounds_to_the_coordinate_precision() {
1475 use VectorCoordKind::*;
1476 assert_eq!(Float16.narrow_float(1.0), Some(1.0));
1478 assert_eq!(Float16.narrow_float(0.1), Some(0.0999755859375));
1479 assert_eq!(Float16.narrow_float(65504.0), Some(65504.0));
1480 assert_eq!(Float16.narrow_float(65520.0), None);
1481 assert_eq!(Float16.narrow_float(2f64.powi(-24)), Some(2f64.powi(-24)));
1482 assert_eq!(Float16.narrow_float(2f64.powi(-25)), Some(0.0));
1483 assert_eq!(BFloat16.narrow_float(1.0), Some(1.0));
1485 assert_eq!(BFloat16.narrow_float(257.0), Some(256.0));
1486 assert_eq!(
1487 BFloat16.narrow_float(3.3895314e38),
1488 Some(3.3895314e38f32 as f64)
1489 );
1490 assert_eq!(BFloat16.narrow_float(1e39), None);
1491 assert_eq!(BFloat16.narrow_float(9.18e-41), Some(9.183549615799121e-41));
1493 assert_eq!(Float32.narrow_float(0.1), Some(0.1f32 as f64));
1495 assert_eq!(Float64.narrow_float(0.1), Some(0.1));
1496 assert_eq!(Int8.narrow_float(1.0), None);
1497 assert_eq!(Float16.narrow_float(f64::NAN), None);
1498 }
1499
1500 #[test]
1501 fn is_exact_holds_only_for_values_the_kind_spells_unchanged() {
1502 use VectorCoordKind::*;
1503 assert!(!Float16.is_exact(0.1));
1506 assert!(!BFloat16.is_exact(0.1));
1507 assert!(!Float32.is_exact(0.1));
1508 assert!(Float64.is_exact(0.1));
1509 assert!(Float16.is_exact(0.0999755859375));
1510 assert!(BFloat16.is_exact(256.0));
1511 assert!(Float32.is_exact(0.1f32 as f64));
1512 for kind in [Float16, BFloat16, Float32, Float64] {
1513 assert!(!kind.is_exact(f64::INFINITY), "{kind:?}");
1514 assert!(!kind.is_exact(f64::NAN), "{kind:?}");
1515 }
1516 assert!(!Int8.is_exact(1.0));
1518 }
1519}