use std::collections::BTreeMap;
use std::sync::Arc;
use chrono::{FixedOffset, TimeZone};
use relate_model::value::IsoDuration;
use relate_model::wire::ColumnTypeKind;
use relate_model::{CypherValue, IndexMap};
use crate::temporal::Temporal;
use crate::value::{next_depth, Node, Path, Relationship, Value};
pub fn column_type_kind(value: &Value) -> ColumnTypeKind {
match value {
Value::Null => ColumnTypeKind::Any,
Value::Bool(_) => ColumnTypeKind::Boolean,
Value::Int(_) => ColumnTypeKind::Integer,
Value::Float(_) => ColumnTypeKind::Float,
Value::String(_) | Value::Uuid(_) => ColumnTypeKind::String,
Value::Bytes(_) => ColumnTypeKind::Binary,
Value::List(_) => ColumnTypeKind::List,
Value::Map(_) => ColumnTypeKind::Map,
Value::Node(_) => ColumnTypeKind::Node,
Value::Relationship(_) => ColumnTypeKind::Relationship,
Value::Path(_) => ColumnTypeKind::Path,
Value::Point(_) => ColumnTypeKind::Point,
Value::Vector { .. } => ColumnTypeKind::Vector,
Value::Temporal(t) => match t {
Temporal::Date(_) | Temporal::CivilDate { .. } => ColumnTypeKind::Date,
Temporal::LocalTime(_) | Temporal::Time { .. } => ColumnTypeKind::Time,
Temporal::LocalDateTime(_)
| Temporal::CivilDateTime { .. }
| Temporal::DateTime { .. } => ColumnTypeKind::DateTime,
Temporal::Duration { .. } => ColumnTypeKind::Duration,
},
}
}
pub fn column_type_name(value: &Value) -> &'static str {
column_type_kind(value).name()
}
pub fn value_to_cypher(v: &Value) -> CypherValue {
value_to_cypher_at(v, 0)
}
fn value_to_cypher_at(v: &Value, depth: u32) -> CypherValue {
match v {
Value::Null => CypherValue::Null,
Value::Bool(b) => CypherValue::Bool(*b),
Value::Int(i) => CypherValue::Int(*i),
Value::Float(f) => CypherValue::Float(*f),
Value::String(s) => CypherValue::Str(String::from(&**s)),
Value::Uuid(u) => CypherValue::Str(crate::value::uuid_hyphenated(*u)),
Value::Bytes(b) => {
CypherValue::List(b.iter().map(|&x| CypherValue::Int(x.into())).collect())
}
Value::List(xs) => {
let Some(next) = next_depth(depth) else {
return CypherValue::Null;
};
CypherValue::List(xs.iter().map(|v| value_to_cypher_at(v, next)).collect())
}
Value::Map(m) => {
let Some(next) = next_depth(depth) else {
return CypherValue::Null;
};
CypherValue::Map(
m.iter()
.map(|(k, v)| (k.clone(), value_to_cypher_at(v, next)))
.collect(),
)
}
Value::Node(n) => node_to_cypher(n, depth),
Value::Relationship(r) => rel_to_cypher(r, depth),
Value::Path(p) => {
if next_depth(depth).is_none() {
return CypherValue::Null;
}
CypherValue::Path {
nodes: p.nodes.iter().map(|n| node_to_cypher(n, depth)).collect(),
relationships: p.rels.iter().map(|r| rel_to_cypher(r, depth)).collect(),
}
}
Value::Point(p) => CypherValue::Point(p.clone()),
Value::Vector { coord, values } => {
let Some(next) = next_depth(depth) else {
return CypherValue::Null;
};
let mapped: Vec<CypherValue> =
values.iter().map(|v| value_to_cypher_at(v, next)).collect();
CypherValue::Vector {
coord: *coord,
dim: mapped.len(),
values: mapped,
}
}
Value::Temporal(t) => temporal_to_cypher(t),
}
}
fn node_to_cypher(n: &Node, depth: u32) -> CypherValue {
let Some(next) = next_depth(depth) else {
return CypherValue::Null;
};
CypherValue::Node {
id: n.id,
labels: (*n.labels).clone(),
properties: n
.properties
.iter()
.map(|(k, v)| (k.clone(), value_to_cypher_at(v, next)))
.collect(),
}
}
fn rel_to_cypher(r: &Relationship, depth: u32) -> CypherValue {
let Some(next) = next_depth(depth) else {
return CypherValue::Null;
};
CypherValue::Relationship {
id: r.id,
start_id: r.start,
end_id: r.end,
rel_type: r.rel_type.clone(),
properties: r
.properties
.iter()
.map(|(k, v)| (k.clone(), value_to_cypher_at(v, next)))
.collect(),
}
}
pub fn cypher_to_value(v: &CypherValue) -> Value {
match v {
CypherValue::Null => Value::Null,
CypherValue::Bool(b) => Value::Bool(*b),
CypherValue::Int(i) => Value::Int(*i),
CypherValue::Float(f) => Value::Float(*f),
CypherValue::Str(s) => Value::String(s.as_str().into()),
CypherValue::List(xs) => {
Value::List(xs.iter().map(cypher_to_value).collect::<Vec<_>>().into())
}
CypherValue::Map(m) => Value::Map(
m.iter()
.map(|(k, v)| (k.clone(), cypher_to_value(v)))
.collect::<BTreeMap<_, _>>()
.into(),
),
CypherValue::Node {
id,
labels,
properties,
} => Value::Node(Arc::new(node_from_fields(*id, labels, properties))),
CypherValue::Relationship {
id,
start_id,
end_id,
rel_type,
properties,
} => Value::Relationship(Arc::new(rel_from_fields(
*id, *start_id, *end_id, rel_type, properties,
))),
CypherValue::Path {
nodes,
relationships,
} => {
let nodes = nodes
.iter()
.map(cypher_to_node)
.collect::<Result<Vec<_>, _>>()
.expect("CypherValue::Path nodes must be CypherValue::Node");
let rels = relationships
.iter()
.map(cypher_to_relationship)
.collect::<Result<Vec<_>, _>>()
.expect("CypherValue::Path relationships must be CypherValue::Relationship");
Value::Path(Arc::new(Path { nodes, rels }))
}
CypherValue::Date(d) => Value::Temporal(Temporal::Date(*d)),
CypherValue::Time(t, tz) => match tz {
None => Value::Temporal(Temporal::LocalTime(*t)),
Some(off) => Value::Temporal(Temporal::Time {
time: *t,
offset: off.local_minus_utc(),
}),
},
CypherValue::LocalDateTime(dt) => Value::Temporal(Temporal::LocalDateTime(*dt)),
CypherValue::DateTime(dt, zone) => {
let offset = dt.offset().local_minus_utc();
let utc = dt.naive_utc();
Value::Temporal(Temporal::DateTime {
utc,
offset,
zone: zone.clone(),
})
}
CypherValue::Duration(d) => Value::Temporal(Temporal::Duration {
months: d.months,
days: d.days,
nanos: d.seconds as i128 * 1_000_000_000 + d.nanoseconds as i128,
}),
CypherValue::Point(p) => Value::Point(p.clone()),
CypherValue::Vector { coord, values, .. } => Value::Vector {
coord: *coord,
values: values
.iter()
.map(cypher_to_value)
.collect::<Vec<_>>()
.into(),
},
CypherValue::Geometry(_) => Value::Null,
}
}
fn node_from_fields(
id: i64,
labels: &[String],
properties: &IndexMap<String, CypherValue>,
) -> Node {
Node {
id,
labels: Arc::new(labels.to_vec()),
properties: crate::PropertyMap::share(
properties
.iter()
.map(|(k, v)| (k.clone(), cypher_to_value(v)))
.collect::<std::collections::BTreeMap<_, _>>(),
),
}
}
fn cypher_to_node(v: &CypherValue) -> Result<Node, String> {
match v {
CypherValue::Node {
id,
labels,
properties,
} => Ok(node_from_fields(*id, labels, properties)),
other => Err(format!(
"path node element must be NODE, got {}",
other.type_name()
)),
}
}
fn rel_from_fields(
id: i64,
start: i64,
end: i64,
rel_type: &str,
properties: &IndexMap<String, CypherValue>,
) -> Relationship {
Relationship {
id,
start,
end,
rel_type: rel_type.to_string(),
properties: crate::PropertyMap::share(
properties
.iter()
.map(|(k, v)| (k.clone(), cypher_to_value(v)))
.collect::<std::collections::BTreeMap<_, _>>(),
),
}
}
fn cypher_to_relationship(v: &CypherValue) -> Result<Relationship, String> {
match v {
CypherValue::Relationship {
id,
start_id,
end_id,
rel_type,
properties,
} => Ok(rel_from_fields(
*id, *start_id, *end_id, rel_type, properties,
)),
other => Err(format!(
"path relationship element must be RELATIONSHIP, got {}",
other.type_name()
)),
}
}
fn temporal_to_cypher(t: &Temporal) -> CypherValue {
match t {
Temporal::Date(d) => CypherValue::Date(*d),
Temporal::CivilDate { year, month, day } => civil_naive_date(*year, *month, *day)
.map(CypherValue::Date)
.unwrap_or_else(|| CypherValue::Str(t.iso_string())),
Temporal::LocalTime(tm) => CypherValue::Time(*tm, None),
Temporal::Time { time, offset } => match FixedOffset::east_opt(*offset) {
Some(off) => CypherValue::Time(*time, Some(off)),
None => CypherValue::Str(t.iso_string()),
},
Temporal::LocalDateTime(dt) => CypherValue::LocalDateTime(*dt),
Temporal::CivilDateTime {
year,
month,
day,
time,
} => match civil_naive_date(*year, *month, *day) {
Some(d) => CypherValue::LocalDateTime(d.and_time(*time)),
None => CypherValue::Str(t.iso_string()),
},
Temporal::DateTime { utc, offset, zone } => {
let Some(off) = FixedOffset::east_opt(*offset) else {
return CypherValue::Str(t.iso_string());
};
let dt = off.from_utc_datetime(utc);
CypherValue::DateTime(
dt,
crate::temporal::zone_region(zone.as_deref()).map(String::from),
)
}
Temporal::Duration {
months,
days,
nanos,
} => {
let Ok(seconds) = i64::try_from(nanos / 1_000_000_000) else {
return CypherValue::Str(t.iso_string());
};
let nanoseconds = i64::try_from(nanos % 1_000_000_000)
.expect("a sub-second remainder is below 10^9 in magnitude");
CypherValue::Duration(IsoDuration::new(*months, *days, seconds, nanoseconds))
}
}
}
fn civil_naive_date(year: i64, month: u32, day: u32) -> Option<chrono::NaiveDate> {
i32::try_from(year)
.ok()
.and_then(|year| chrono::NaiveDate::from_ymd_opt(year, month, day))
}
#[cfg(test)]
mod tests {
use super::*;
fn node(id: i64) -> Node {
Node {
id,
labels: Arc::new(vec!["L".into()]),
properties: crate::PropertyMap::share(BTreeMap::from([(
"name".to_string(),
Value::String("x".into()),
)])),
}
}
fn rel(id: i64, start: i64, end: i64) -> Relationship {
Relationship {
id,
start,
end,
rel_type: "R".into(),
properties: crate::PropertyMap::share(BTreeMap::from([(
"w".to_string(),
Value::Float(0.5),
)])),
}
}
#[test]
fn value_to_cypher_path_matches_direct_conversion() {
let path = Value::from_path(Path {
nodes: vec![node(1), node(2)],
rels: vec![rel(3, 1, 2)],
});
let CypherValue::Path {
nodes,
relationships,
} = value_to_cypher(&path)
else {
panic!("path did not convert to CypherValue::Path");
};
assert_eq!(
nodes,
vec![
value_to_cypher(&Value::from_node(node(1))),
value_to_cypher(&Value::from_node(node(2))),
]
);
assert_eq!(
relationships,
vec![value_to_cypher(&Value::from_relationship(rel(3, 1, 2)))]
);
}
#[test]
fn a_civil_year_past_i32_keeps_its_iso_string() {
let t = crate::temporal::parse_iso("localdatetime", "4294967397-01-01T12:00").unwrap();
match value_to_cypher(&Value::Temporal(t)) {
CypherValue::Str(s) => {
assert!(s.contains("4294967397"), "{s}");
assert!(!s.contains("0101"), "the year wrapped: {s}");
}
other => panic!("expected the ISO-string fallback, got {other:?}"),
}
let small = Temporal::CivilDateTime {
year: 10_000,
month: 1,
day: 1,
time: chrono::NaiveTime::from_hms_opt(12, 0, 0).unwrap(),
};
assert!(
matches!(
value_to_cypher(&Value::Temporal(small)),
CypherValue::LocalDateTime(_)
),
"a representable civil year must keep the typed form"
);
let civil_date = Temporal::CivilDate {
year: 4_294_967_397,
month: 1,
day: 1,
};
assert_eq!(
value_to_cypher(&Value::Temporal(civil_date.clone())),
CypherValue::Str(civil_date.iso_string())
);
}
#[test]
fn a_time_offset_past_fixed_offset_range_keeps_its_iso_string() {
let time = chrono::NaiveTime::from_hms_opt(12, 0, 0).unwrap();
let unrepresentable = Temporal::Time {
time,
offset: 100_000,
};
assert_eq!(
value_to_cypher(&Value::Temporal(unrepresentable.clone())),
CypherValue::Str(unrepresentable.iso_string())
);
let representable = Temporal::Time { time, offset: 3600 };
assert!(
matches!(
value_to_cypher(&Value::Temporal(representable)),
CypherValue::Time(_, Some(_))
),
"an in-range offset must keep the typed Time"
);
}
#[test]
fn a_duration_past_i64_seconds_keeps_its_iso_string() {
let nanos = (i128::from(i64::MAX) + 1) * 1_000_000_000;
let t = Temporal::Duration {
months: 0,
days: 0,
nanos,
};
match value_to_cypher(&Value::Temporal(t)) {
CypherValue::Str(s) => assert!(s.starts_with('P'), "{s}"),
other => panic!("expected the ISO-string fallback, got {other:?}"),
}
let ok = Temporal::Duration {
months: 0,
days: 1,
nanos: 1_000_000_000,
};
assert!(matches!(
value_to_cypher(&Value::Temporal(ok)),
CypherValue::Duration(_)
));
}
#[test]
fn cypher_to_value_path_roundtrip_and_typed_element_errors() {
let path = Value::from_path(Path {
nodes: vec![node(1), node(2)],
rels: vec![rel(3, 1, 2)],
});
let cypher = value_to_cypher(&path);
assert_eq!(cypher_to_value(&cypher), path);
let bad = cypher_to_node(&CypherValue::Int(1)).expect_err("non-node accepted");
assert!(bad.contains("INTEGER"), "unexpected error: {bad}");
let bad = cypher_to_relationship(&cypher).expect_err("path accepted as relationship");
assert!(bad.contains("PATH"), "unexpected error: {bad}");
}
}