use std::collections::BTreeMap;
use relate_core::{Error, Result, Value};
use relate_names::NamedToken;
const BYTES_PROPERTY_DETAIL: &str = "byte array values cannot be stored as node or \
relationship properties; they live only inside a statement (parameter to result)";
pub(crate) enum PropertyInvalidity {
HoldsBytes,
Other,
}
pub(crate) fn check_property_value(v: &Value) -> Result<()> {
match property_value_invalidity(v) {
None => Ok(()),
Some(PropertyInvalidity::HoldsBytes) => Err(Error::type_error(BYTES_PROPERTY_DETAIL)),
Some(PropertyInvalidity::Other) => Err(Error::ty("InvalidPropertyType")),
}
}
pub(crate) fn prepare_property_value(v: Value) -> Result<Value> {
check_property_value(&v)?;
Ok(coerce_mixed_numeric_list(v))
}
fn coerce_mixed_numeric_list(v: Value) -> Value {
let Value::List(xs) = v else {
return v;
};
let has_int = xs.iter().any(|x| matches!(x, Value::Int(_)));
let has_float = xs.iter().any(|x| matches!(x, Value::Float(_)));
if !(has_int && has_float) {
return Value::List(xs);
}
Value::List(
xs.iter()
.map(|x| match x {
Value::Int(i) => Value::Float(*i as f64),
other => other.clone(),
})
.collect::<Vec<_>>()
.into(),
)
}
pub(crate) fn property_value_invalidity(v: &Value) -> Option<PropertyInvalidity> {
match v {
Value::Null | Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::String(_) => None,
Value::Temporal(_) | Value::Point(_) | Value::Uuid(_) => None,
Value::Bytes(_) => Some(PropertyInvalidity::HoldsBytes),
Value::Vector { .. } => None,
Value::List(xs) => {
let mut kind = None;
for item in xs.iter() {
if item.is_null() {
return Some(PropertyInvalidity::Other);
}
if bytes_within(item) {
return Some(PropertyInvalidity::HoldsBytes);
}
let Some(item_kind) = list_item_kind(item) else {
return Some(PropertyInvalidity::Other);
};
if kind.is_some_and(|expected| expected != item_kind) {
return Some(PropertyInvalidity::Other);
}
kind = Some(item_kind);
}
None
}
_ => Some(PropertyInvalidity::Other),
}
}
fn bytes_within(v: &Value) -> bool {
bytes_within_at(v, 0)
}
fn bytes_within_at(v: &Value, depth: u32) -> bool {
match v {
Value::Bytes(_) => true,
Value::List(xs) => relate_core::next_depth(depth)
.is_some_and(|next| xs.iter().any(|x| bytes_within_at(x, next))),
_ => false,
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ListItemKind {
Numeric,
Scalar(std::mem::Discriminant<Value>),
}
fn list_item_kind(v: &Value) -> Option<ListItemKind> {
match v {
Value::Null => None,
Value::Int(_) | Value::Float(_) => Some(ListItemKind::Numeric),
Value::Bool(_)
| Value::String(_)
| Value::Temporal(_)
| Value::Point(_)
| Value::Uuid(_) => Some(ListItemKind::Scalar(std::mem::discriminant(v))),
_ => None,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NullPolicy {
Drop,
Keep,
}
pub(crate) fn admit_props(
map: BTreeMap<String, Value>,
nulls: NullPolicy,
) -> Result<BTreeMap<String, Value>> {
let drop_nulls = nulls == NullPolicy::Drop;
let mut out = BTreeMap::new();
for (k, v) in map {
if drop_nulls && v.is_null() {
continue;
}
out.insert(k, prepare_property_value(v)?);
}
Ok(out)
}
pub(crate) fn props_all_match(
want: &[(NamedToken, Value)],
mut read: impl FnMut(&NamedToken) -> Option<Value>,
) -> bool {
want.iter()
.all(|(key, v)| read(key).is_some_and(|stored| stored.eq_non_null(v)))
}
#[cfg(test)]
mod tests {
use super::*;
use relate_core::{PointValue, Temporal, VectorCoordKind};
use relate_model::VectorCoords;
fn bytes() -> Value {
Value::Bytes(vec![0, 1, 255].into())
}
#[test]
fn property_value_invalidity_classifies_nested_bytes() {
let scalar = Value::Int(1);
assert!(check_property_value(&scalar).is_ok());
assert!(check_property_value(&Value::Null).is_ok());
assert!(check_property_value(&Value::Temporal(Temporal::Duration {
months: 1,
days: 0,
nanos: 0
}))
.is_ok());
assert!(check_property_value(&Value::Point(PointValue::cartesian_2d(1.0, 2.0))).is_ok());
assert!(check_property_value(&Value::vector(
VectorCoordKind::Int8,
VectorCoords::from_int(vec![1]),
))
.is_ok());
assert!(
check_property_value(&Value::List(vec![Value::Int(1), Value::Int(2)].into())).is_ok()
);
assert!(
check_property_value(&Value::List(vec![Value::Int(1), Value::Float(2.5)].into()))
.is_ok()
);
assert_eq!(
check_property_value(&Value::List(vec![Value::Null, Value::Int(1)].into()))
.unwrap_err(),
Error::ty("InvalidPropertyType")
);
assert_eq!(
check_property_value(&Value::List(
vec![Value::Int(1), Value::String("a".into())].into()
))
.unwrap_err(),
Error::ty("InvalidPropertyType")
);
assert_eq!(
check_property_value(&Value::List(
vec![Value::List(vec![Value::Int(1)].into())].into()
))
.unwrap_err(),
Error::ty("InvalidPropertyType")
);
let bytes_detail = Error::type_error(BYTES_PROPERTY_DETAIL);
assert_eq!(check_property_value(&bytes()).unwrap_err(), bytes_detail);
assert_eq!(
check_property_value(&Value::List(vec![bytes()].into())).unwrap_err(),
bytes_detail
);
assert_eq!(
check_property_value(&Value::List(
vec![Value::List(vec![Value::Int(1), bytes()].into())].into()
))
.unwrap_err(),
bytes_detail
);
assert_eq!(
check_property_value(&Value::Map(BTreeMap::new().into())).unwrap_err(),
Error::ty("InvalidPropertyType")
);
}
#[test]
fn prepare_property_value_coerces_mixed_numeric_lists_to_floats() {
let prepared =
prepare_property_value(Value::List(vec![Value::Float(1.0), Value::Int(2)].into()))
.unwrap();
assert_eq!(
prepared,
Value::List(vec![Value::Float(1.0), Value::Float(2.0)].into())
);
let ints = Value::List(vec![Value::Int(1), Value::Int(2)].into());
assert_eq!(prepare_property_value(ints.clone()).unwrap(), ints);
assert_eq!(
prepare_property_value(Value::List(
vec![Value::Int(1), Value::String("a".into())].into()
))
.unwrap_err(),
Error::ty("InvalidPropertyType")
);
}
#[test]
fn admit_props_null_policy_is_the_only_difference() {
let map = || {
BTreeMap::from([
("a".to_string(), Value::Int(1)),
("b".to_string(), Value::Null),
])
};
assert_eq!(
admit_props(map(), NullPolicy::Drop).unwrap(),
BTreeMap::from([("a".into(), Value::Int(1))])
);
assert_eq!(
admit_props(map(), NullPolicy::Keep).unwrap(),
BTreeMap::from([("a".into(), Value::Int(1)), ("b".into(), Value::Null)])
);
let bad = BTreeMap::from([("a".to_string(), Value::Null), ("b".to_string(), bytes())]);
for nulls in [NullPolicy::Drop, NullPolicy::Keep] {
assert_eq!(
admit_props(bad.clone(), nulls).unwrap_err(),
Error::type_error(BYTES_PROPERTY_DETAIL)
);
}
}
}