use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::sync::Arc;
use relate_core::{integer_args, temporal, ArithmeticFailure, Error, ErrorKind, Result, Value};
use relate_ir::{BinaryOp, Expr, UnaryOp};
use relate_names::{NamedToken, SmallName, Token};
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::string::char_range;
use super::{bool_operand, eval};
pub(crate) fn reject_deleted_access(graph: &ExecGraph<'_>, v: &Value) -> Result<()> {
match v {
Value::Node(n) if graph.is_deleted_node(n.id) => Err(Error::execution(
"DeletedEntityAccess: cannot access properties of a deleted node",
)),
Value::Relationship(r) if graph.is_deleted_rel(r.id) => Err(Error::execution(
"DeletedEntityAccess: cannot access properties of a deleted relationship",
)),
_ => Ok(()),
}
}
pub(crate) fn prop(graph: &ExecGraph<'_>, v: &Value, key: &NamedToken) -> Result<Value> {
Ok(match v {
Value::Node(n) => graph
.node_prop_resolved(n.id, key)
.or_else(|| key.0.with_str(|text| n.properties.get(text).cloned()))
.unwrap_or(Value::Null),
Value::Relationship(r) => graph
.rel_prop_resolved(r.id, key)
.or_else(|| key.0.with_str(|text| r.properties.get(text).cloned()))
.unwrap_or(Value::Null),
Value::Map(m) => key
.0
.with_str(|text| m.get(text).cloned())
.unwrap_or(Value::Null),
Value::Temporal(t) => key.0.with_str(|text| t.component(text))?,
Value::Point(p) => key
.0
.with_str(|text| relate_core::point_component(p, text))?,
Value::Null => Value::Null,
_ => {
return Err(Error::invalid_argument_type(
"property access requires a map, node, relationship, temporal, or point value",
))
}
})
}
pub(crate) fn unary(op: UnaryOp, v: Value) -> Result<Value> {
Ok(match op {
UnaryOp::Not => match bool_operand(&v, "NOT")? {
Some(b) => Value::Bool(!b),
None => Value::Null,
},
UnaryOp::Plus => match v {
Value::Int(i) => Value::Int(i),
Value::Float(f) => Value::Float(f),
Value::Temporal(t @ temporal::Temporal::Duration { .. }) => Value::Temporal(t),
Value::Null => Value::Null,
_ => return Err(Error::ty("unary + needs a number")),
},
UnaryOp::Minus => match v {
Value::Int(i) => Value::Int(
i.checked_neg()
.ok_or_else(|| Error::ty("integer out of range"))?,
),
Value::Float(f) => Value::Float(-f),
Value::Temporal(t @ temporal::Temporal::Duration { .. }) => {
Value::Temporal(temporal::negate_duration(&t)?)
}
Value::Null => Value::Null,
_ => return Err(Error::ty("unary - needs a number")),
},
UnaryOp::IsNull => Value::Bool(v.is_null()),
UnaryOp::IsNotNull => Value::Bool(!v.is_null()),
})
}
pub(crate) fn binary(graph: &ExecGraph<'_>, op: BinaryOp, l: Value, r: Value) -> Result<Value> {
binary_inner(Some(graph), op, l, r)
}
pub(crate) fn binary_pure(op: BinaryOp, l: Value, r: Value) -> Result<Value> {
binary_inner(None, op, l, r)
}
fn binary_inner(charge: Option<&ExecGraph<'_>>, op: BinaryOp, l: Value, r: Value) -> Result<Value> {
Ok(match op {
BinaryOp::Eq => l.cypher_eq(&r),
BinaryOp::Neq => match l.cypher_eq(&r) {
Value::Bool(b) => Value::Bool(!b),
other => other,
},
BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Lte | BinaryOp::Gte => {
let (equality_allowed, pred) =
ordering_operator(op).expect("`op` matched one of the four ordering operators");
cmp_bool(&l, &r, equality_allowed, pred)
}
BinaryOp::And => match (
bool_operand(&l, op.as_str())?,
bool_operand(&r, op.as_str())?,
) {
(Some(false), _) | (_, Some(false)) => Value::Bool(false),
(Some(true), Some(true)) => Value::Bool(true),
_ => Value::Null,
},
BinaryOp::Or => match (
bool_operand(&l, op.as_str())?,
bool_operand(&r, op.as_str())?,
) {
(Some(true), _) | (_, Some(true)) => Value::Bool(true),
(Some(false), Some(false)) => Value::Bool(false),
_ => Value::Null,
},
BinaryOp::Xor => match (
bool_operand(&l, op.as_str())?,
bool_operand(&r, op.as_str())?,
) {
(Some(a), Some(b)) => Value::Bool(a ^ b),
_ => Value::Null,
},
BinaryOp::Add => match charge {
Some(graph) => add(graph, l, r)?,
None => {
return Err(Error::internal(
"allocating '+' reached the comparison-only binary path",
))
}
},
BinaryOp::Sub => sub(l, r)?,
BinaryOp::Mul => mul(l, r)?,
BinaryOp::Div => div(l, r)?,
BinaryOp::Mod => mod_op(l, r)?,
BinaryOp::Pow => pow(l, r)?,
BinaryOp::Concat => match charge {
Some(graph) => concat(graph, l, r)?,
None => {
return Err(Error::internal(
"allocating '||' reached the comparison-only binary path",
))
}
},
BinaryOp::In => in_op(l, r)?,
BinaryOp::StartsWith => str_pred(l, r, |a, b| a.starts_with(b)),
BinaryOp::EndsWith => str_pred(l, r, |a, b| a.ends_with(b)),
BinaryOp::Contains => str_pred(l, r, |a, b| a.contains(b)),
BinaryOp::Regex => match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::String(a), Value::String(b)) => match regex_is_match(a, b) {
Ok(m) => Value::Bool(m),
Err(_) => return Err(Error::argument_error("invalid regular expression")),
},
_ => {
return Err(Error::invalid_argument_type(
"the regex operator requires string operands",
))
}
},
})
}
pub(crate) fn regex_is_match(text: &str, pattern: &str) -> std::result::Result<bool, regex::Error> {
regex::Regex::new(&format!("^(?:{pattern})$")).map(|re| re.is_match(text))
}
pub(crate) type OrderingOperator = (bool, fn(Ordering) -> bool);
pub(crate) fn ordering_operator(op: BinaryOp) -> Option<OrderingOperator> {
Some(match op {
BinaryOp::Lt => (false, Ordering::is_lt),
BinaryOp::Gt => (false, Ordering::is_gt),
BinaryOp::Lte => (true, Ordering::is_le),
BinaryOp::Gte => (true, Ordering::is_ge),
_ => return None,
})
}
pub(crate) fn cmp_bool(
l: &Value,
r: &Value,
equality_allowed: bool,
pred: impl Fn(std::cmp::Ordering) -> bool,
) -> Value {
let ln = l.as_number();
let rn = r.as_number();
if ln.is_some_and(|f| f.is_nan()) || rn.is_some_and(|f| f.is_nan()) {
return if ln.is_some() && rn.is_some() {
Value::Bool(false)
} else {
Value::Null
};
}
match l.compare(r) {
Some(o) => Value::Bool(pred(o)),
None if equality_allowed => match l.cypher_eq(r) {
Value::Bool(true) => Value::Bool(true),
_ => Value::Null,
},
None => Value::Null,
}
}
fn concat_scalar_string(
graph: &ExecGraph<'_>,
string: &Arc<str>,
scalar: &Value,
string_first: bool,
) -> Result<Value> {
let rendered = scalar.to_display_string();
graph.charge_expression(relate_core::str_logical_bytes(string) + rendered.len() as u64)?;
Ok(Value::String(
if string_first {
format!("{string}{rendered}")
} else {
format!("{rendered}{string}")
}
.into(),
))
}
fn is_concat_scalar(v: &Value) -> bool {
matches!(
v,
Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Temporal(_) | Value::Point(_)
)
}
pub(crate) fn add(graph: &ExecGraph<'_>, l: Value, r: Value) -> Result<Value> {
Ok(match (l, r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::String(a), Value::String(b)) => {
graph.charge_expression(relate_core::str_logical_bytes(&a) + b.len() as u64)?;
Value::String(format!("{a}{b}").into())
}
(Value::String(a), r) if is_concat_scalar(&r) => concat_scalar_string(graph, &a, &r, true)?,
(l, Value::String(b)) if is_concat_scalar(&l) => {
concat_scalar_string(graph, &b, &l, false)?
}
(Value::List(a), Value::List(b)) => {
graph.charge_value_buffer(a.len() + b.len())?;
let mut o = Arc::unwrap_or_clone(a);
o.extend(Arc::unwrap_or_clone(b));
Value::checked_list(o)?
}
(Value::Map(a), Value::Map(b)) => {
graph.charge_expression(crate::workspace::map_entries_bytes(a.len() + b.len()))?;
let mut o = Arc::unwrap_or_clone(a);
o.extend(Arc::unwrap_or_clone(b));
Value::checked_map(o)?
}
(Value::List(a), r) => {
graph.charge_value_buffer(a.len() + 1)?;
let mut o = Arc::unwrap_or_clone(a);
o.push(r);
Value::checked_list(o)?
}
(l, Value::List(b)) => {
graph.charge_value_buffer(b.len() + 1)?;
let mut o = vec![l];
o.extend(Arc::unwrap_or_clone(b));
Value::checked_list(o)?
}
(Value::Temporal(a), Value::Temporal(b)) => {
if matches!(b, temporal::Temporal::Duration { .. }) {
Value::Temporal(temporal::add_duration(&a, &b)?)
} else if matches!(a, temporal::Temporal::Duration { .. }) {
Value::Temporal(temporal::add_duration(&b, &a)?)
} else {
return Err(Error::ty("+ type mismatch"));
}
}
(Value::Int(a), Value::Int(b)) => Value::Int(
a.checked_add(b)
.ok_or_else(|| Error::ty("integer out of range"))?,
),
(l, r) => {
if let (Some(a), Some(b)) = (l.as_number(), r.as_number()) {
Value::Float(a + b)
} else {
return Err(Error::ty("+ type mismatch"));
}
}
})
}
pub(crate) fn concat(graph: &ExecGraph<'_>, l: Value, r: Value) -> Result<Value> {
match (&l, &r) {
(Value::String(_), Value::String(_)) | (Value::List(_), Value::List(_)) => add(graph, l, r),
(Value::Null, Value::String(_) | Value::List(_))
| (Value::String(_) | Value::List(_), Value::Null)
| (Value::Null, Value::Null) => Ok(Value::Null),
_ => Err(Error::invalid_argument_type(
"|| requires two strings or two lists",
)),
}
}
pub(crate) fn sub(l: Value, r: Value) -> Result<Value> {
match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
(Value::Temporal(a), Value::Temporal(b)) => {
if matches!(b, temporal::Temporal::Duration { .. }) {
Ok(Value::Temporal(temporal::sub_duration(a, b)?))
} else {
Err(Error::ty("- type mismatch"))
}
}
_ => num_op(l, r, i64::checked_sub, |a, b| a - b),
}
}
pub(crate) fn mul(l: Value, r: Value) -> Result<Value> {
Ok(match (&l, &r) {
(Value::Temporal(d @ temporal::Temporal::Duration { .. }), b)
| (b, Value::Temporal(d @ temporal::Temporal::Duration { .. })) => match b.as_number() {
Some(n) => Value::Temporal(temporal::scale_duration(d, n)?),
None => num_op(l, r, i64::checked_mul, |a, b| a * b)?,
},
_ => num_op(l, r, i64::checked_mul, |a, b| a * b)?,
})
}
pub(crate) fn div(l: Value, r: Value) -> Result<Value> {
Ok(match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::Temporal(d @ temporal::Temporal::Duration { .. }), b) => {
let n = b.as_number().ok_or_else(|| Error::ty("/ needs numbers"))?;
if n == 0.0 {
return Err(Error::arithmetic(ArithmeticFailure::DivisionByZero));
}
Value::Temporal(temporal::scale_duration(d, 1.0 / n)?)
}
(Value::Int(a), Value::Int(b)) => {
if *b == 0 {
return Err(Error::arithmetic(ArithmeticFailure::DivisionByZero));
}
Value::Int(
a.checked_div(*b)
.ok_or_else(|| Error::ty("integer out of range"))?,
)
}
_ => {
let a = l.as_number().ok_or_else(|| Error::ty("/ needs numbers"))?;
let b = r.as_number().ok_or_else(|| Error::ty("/ needs numbers"))?;
Value::Float(a / b)
}
})
}
pub(crate) fn mod_op(l: Value, r: Value) -> Result<Value> {
Ok(match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::Int(a), Value::Int(b)) => {
if *b == 0 {
return Err(Error::arithmetic(ArithmeticFailure::ModuloByZero));
}
Value::Int(a.wrapping_rem(*b))
}
_ => {
let a = l.as_number().ok_or_else(|| Error::ty("% needs numbers"))?;
let b = r.as_number().ok_or_else(|| Error::ty("% needs numbers"))?;
Value::Float(a % b)
}
})
}
pub(crate) fn pow(l: Value, r: Value) -> Result<Value> {
Ok(if l.is_null() || r.is_null() {
Value::Null
} else {
let a = l.as_number().ok_or_else(|| Error::ty("^ needs numbers"))?;
let b = r.as_number().ok_or_else(|| Error::ty("^ needs numbers"))?;
if a.abs() == 1.0 && !b.is_finite() {
Value::Float(f64::NAN)
} else {
Value::Float(a.powf(b))
}
})
}
pub(crate) fn num_op(
l: Value,
r: Value,
on_int: impl Fn(i64, i64) -> Option<i64>,
on_float: impl Fn(f64, f64) -> f64,
) -> Result<Value> {
Ok(match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::Int(a), Value::Int(b)) => {
Value::Int(on_int(*a, *b).ok_or_else(|| Error::ty("integer out of range"))?)
}
_ => {
let a = l.as_number().ok_or_else(|| Error::ty("numeric op"))?;
let b = r.as_number().ok_or_else(|| Error::ty("numeric op"))?;
Value::Float(on_float(a, b))
}
})
}
pub(crate) fn in_rhs(value: &Value) -> Result<Option<&[Value]>> {
if value.is_null() {
return Ok(None);
}
match value {
Value::List(xs) => Ok(Some(xs)),
_ => Err(Error::invalid_argument_type(
"IN requires a list on the right-hand side",
)),
}
}
pub(crate) fn in_op(l: Value, r: Value) -> Result<Value> {
Ok(match in_rhs(&r)? {
Some(members) => super::membership(&l, members),
None => Value::Null,
})
}
pub(crate) fn str_pred(l: Value, r: Value, f: impl Fn(&str, &str) -> bool) -> Value {
match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::String(a), Value::String(b)) => Value::Bool(f(a, b)),
_ => Value::Null,
}
}
pub(crate) fn subscript(graph: &ExecGraph<'_>, v: &Value, index: Value) -> Result<Value> {
Ok(match (v, index) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::List(xs), idx) => {
let i = match idx {
Value::Int(i) => i,
_ => {
return Err(Error::invalid_argument_type(
integer_args::LIST_INDEX.type_error,
))
}
};
let n = xs.len() as i64;
let i = if i < 0 { n + i } else { i };
if i < 0 || i >= n {
Value::Null
} else {
xs[i as usize].clone()
}
}
(_, Value::String(k)) => prop(graph, v, &(SmallName::from_name(&k), Token::Unresolved))?,
(Value::Vector { .. }, _) => {
return Err(Error::invalid_argument_type(
"vector indexing is not supported",
))
}
(Value::Map(_), _) | (Value::Node(_), _) | (Value::Relationship(_), _) => {
return Err(Error::ty(
"MapElementAccessByNonString: map index must be a string",
))
}
_ => {
return Err(Error::invalid_argument_type(
"subscript requires a list or map",
))
}
})
}
pub(crate) fn slice(v: &Value, start: Option<Value>, end: Option<Value>) -> Result<Value> {
let (start, end) = (start.as_ref(), end.as_ref());
Ok(match v {
Value::Null => Value::Null,
Value::List(xs) => match slice_bounds(xs.len(), start, end)? {
Some(range) => Value::List(xs[range].to_vec().into()),
None => Value::Null,
},
Value::String(s) => match slice_bounds(s.chars().count(), start, end)? {
Some(range) => Value::String(char_range(s, range).into()),
None => Value::Null,
},
_ => return Err(Error::ty("slice needs a list")),
})
}
fn slice_bounds(
len: usize,
start: Option<&Value>,
end: Option<&Value>,
) -> Result<Option<std::ops::Range<usize>>> {
if matches!(start, Some(Value::Null)) || matches!(end, Some(Value::Null)) {
return Ok(None);
}
let n = len as i64;
let bound = |b: Option<&Value>, missing: i64, what: &str| -> Result<usize> {
let i = match b {
None => missing,
Some(v) => {
let i = super::numeric::int_arg(v).ok_or_else(|| Error::ty(what))?;
if matches!(v, Value::Float(_))
&& !(i64::from(i32::MIN)..=i64::from(i32::MAX)).contains(&i)
{
return Err(Error::argument_value_kind(
ErrorKind::NumberOutOfRange,
what,
));
}
i
}
};
Ok((if i < 0 { i + n } else { i }).clamp(0, n) as usize)
};
let s = bound(start, 0, "slice start")?;
let e = bound(end, n, "slice end")?;
Ok(Some(s..e.max(s)))
}
pub(crate) fn eval_case(
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
when_then: &[(Expr, Expr)],
else_expr: &Option<Box<Expr>>,
cypher_version: Option<u32>,
) -> Result<Value> {
for (when, then) in when_then {
if eval(graph, row, when, params, cypher_version)?.truthy() == Some(true) {
return eval(graph, row, then, params, cypher_version);
}
}
match else_expr {
Some(e) => eval(graph, row, e, params, cypher_version),
None => Ok(Value::Null),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn s(x: &str) -> Value {
Value::String(x.into())
}
fn int(x: i64) -> Value {
Value::Int(x)
}
fn ty_err(msg: &str) -> String {
Error::ty(msg).to_string()
}
#[test]
fn integer_division_overflow_is_rejected_and_modulo_wraps() {
assert_eq!(
div(int(i64::MIN), int(-1)).unwrap_err().to_string(),
ty_err("integer out of range")
);
assert_eq!(mod_op(int(i64::MIN), int(-1)).unwrap(), int(0));
}
const MB: &str = "añ😀bç";
fn mb_slice(start: Option<Value>, end: Option<Value>) -> Value {
slice(&s(MB), start, end).unwrap()
}
#[test]
fn string_slice_indexes_by_character() {
assert_eq!(mb_slice(Some(int(1)), Some(int(3))), s("ñ😀"));
assert_eq!(mb_slice(Some(int(2)), None), s("😀bç"));
assert_eq!(mb_slice(None, Some(int(2))), s("añ"));
assert_eq!(mb_slice(None, None), s(MB));
assert_eq!(mb_slice(Some(int(4)), Some(int(5))), s("ç"));
assert_eq!(
mb_slice(Some(Value::Float(1.0)), Some(Value::Float(2.0))),
s("ñ")
);
}
#[test]
fn string_slice_negative_bounds_count_from_the_end() {
assert_eq!(mb_slice(Some(int(-2)), None), s("bç"));
assert_eq!(mb_slice(Some(int(-4)), Some(int(-1))), s("ñ😀b"));
assert_eq!(mb_slice(None, Some(int(-3))), s("añ"));
}
#[test]
fn string_slice_out_of_range_bounds_clamp() {
assert_eq!(mb_slice(Some(int(-10)), Some(int(10))), s(MB));
assert_eq!(mb_slice(Some(int(3)), Some(int(99))), s("bç"));
assert_eq!(mb_slice(Some(int(-99)), Some(int(2))), s("añ"));
}
#[test]
fn string_slice_empty_range_is_the_empty_string() {
assert_eq!(mb_slice(Some(int(2)), Some(int(2))), s(""));
assert_eq!(mb_slice(Some(int(4)), Some(int(1))), s(""));
assert_eq!(mb_slice(Some(int(7)), None), s(""));
assert_eq!(mb_slice(None, Some(int(-9))), s(""));
assert_eq!(slice(&s(""), Some(int(0)), Some(int(1))).unwrap(), s(""));
}
#[test]
fn string_slice_null_and_non_integer_bounds() {
assert_eq!(mb_slice(Some(Value::Null), Some(int(2))), Value::Null);
assert_eq!(mb_slice(Some(int(1)), Some(Value::Null)), Value::Null);
assert_eq!(mb_slice(Some(Value::Null), None), Value::Null);
assert_eq!(mb_slice(Some(s("x")), Some(Value::Null)), Value::Null);
let err = |start, end| slice(&s(MB), start, end).unwrap_err().to_string();
assert_eq!(err(Some(s("x")), None), ty_err("slice start"));
assert_eq!(err(None, Some(Value::Bool(true))), ty_err("slice end"));
assert_eq!(err(Some(s("x")), Some(s("y"))), ty_err("slice start"));
}
#[test]
fn list_slice_follows_the_same_bounds_rules() {
let list = |xs: &[i64]| Value::List(xs.iter().map(|&x| int(x)).collect::<Vec<_>>().into());
let xs = list(&[0, 1, 2, 3]);
let sl = |start, end| slice(&xs, start, end);
assert_eq!(sl(Some(int(1)), Some(int(3))).unwrap(), list(&[1, 2]));
assert_eq!(sl(Some(int(-3)), Some(int(-1))).unwrap(), list(&[1, 2]));
assert_eq!(
sl(Some(int(-9)), Some(int(9))).unwrap(),
list(&[0, 1, 2, 3])
);
assert_eq!(sl(Some(int(3)), Some(int(1))).unwrap(), list(&[]));
assert_eq!(sl(None, Some(Value::Null)).unwrap(), Value::Null);
assert_eq!(
sl(Some(Value::Bool(true)), None).unwrap_err().to_string(),
ty_err("slice start")
);
assert_eq!(
sl(None, Some(s("x"))).unwrap_err().to_string(),
ty_err("slice end")
);
}
#[test]
fn list_slice_bounds_clamp_at_and_beyond_the_int32_range() {
let list = |xs: &[i64]| Value::List(xs.iter().map(|&x| int(x)).collect::<Vec<_>>().into());
let xs = list(&[1, 2, 3, 4, 5]);
let sl = |start, end| slice(&xs, start, end).unwrap();
let i32_max_plus_1 = i64::from(i32::MAX) + 1;
assert_eq!(sl(None, Some(int(i32_max_plus_1))), xs);
assert_eq!(
sl(Some(int(0)), Some(int(i32_max_plus_1))),
list(&[1, 2, 3, 4, 5])
);
assert_eq!(
sl(Some(int(i32_max_plus_1)), Some(int(i32_max_plus_1 + 1))),
list(&[])
);
assert_eq!(sl(None, Some(int(i64::from(i32::MIN) - 1))), list(&[]));
assert_eq!(sl(Some(int(i64::from(i32::MIN) - 1)), None), xs);
assert_eq!(sl(None, Some(int(i64::MAX))), xs);
assert_eq!(sl(Some(int(i64::MAX)), None), list(&[]));
assert_eq!(sl(None, Some(int(i64::MIN))), list(&[]));
assert_eq!(sl(Some(int(i64::MIN)), None), xs);
}
#[test]
fn add_concatenates_a_string_with_temporal_and_point_scalars() {
let g = crate::graph::Graph::default();
let graph = ExecGraph::read(&g);
let point = Value::Point(relate_core::PointValue::cartesian_2d(1.0, 0.0));
let point_text = "point({x: 1.0, y: 0.0, crs: 'cartesian'})";
let cases: Vec<(Value, Value, String)> = vec![
(s("hi"), duration(0, 1), "hiP1D".into()),
(duration(0, 1), s("hi"), "P1Dhi".into()),
(s("hi"), point.clone(), format!("hi{point_text}")),
(point, s("hi"), format!("{point_text}hi")),
(s("hi"), int(2), "hi2".to_string()),
(int(2), s("hi"), "2hi".to_string()),
];
for (l, r, expected) in cases {
assert_eq!(add(&graph, l, r).unwrap(), s(&expected), "{expected}");
}
}
#[test]
fn slice_of_null_or_a_non_sequence() {
assert_eq!(
slice(&Value::Null, Some(s("x")), None).unwrap(),
Value::Null
);
assert_eq!(
slice(&int(5), Some(s("x")), None).unwrap_err().to_string(),
ty_err("slice needs a list")
);
}
#[test]
fn regex_rejections_carry_the_neo4j_classes() {
let g = crate::graph::Graph::default();
let graph = ExecGraph::read(&g);
let run = |l: Value, r: Value| binary(&graph, BinaryOp::Regex, l, r);
assert!(run(s("a"), int(42)).is_err());
assert_eq!(
run(s("a"), s("[")).unwrap_err(),
Error::argument_error("invalid regular expression")
);
assert_eq!(run(Value::Null, int(42)).unwrap(), Value::Null);
}
#[test]
fn regex_anchors_at_both_ends() {
assert!(!regex_is_match("21_val", "1_.*").unwrap());
assert!(regex_is_match("1_val", "1_.*").unwrap());
assert!(!regex_is_match("ab", "a|b").unwrap());
assert!(regex_is_match("a", "a|b").unwrap());
assert!(regex_is_match("", "x*").unwrap());
assert!(regex_is_match("x1_val", ".*1_.*").unwrap());
assert!(regex_is_match("abc", "abc").unwrap());
assert!(regex_is_match("abc", "b").is_ok_and(|m| !m));
assert!(regex_is_match("abc", "[").is_err());
}
fn duration(months: i64, days: i64) -> Value {
Value::Temporal(relate_core::Temporal::Duration {
months,
days,
nanos: 0,
})
}
#[test]
fn mixed_list_and_string_charges_the_list_buffer() {
let g = crate::graph::Graph::default();
let graph = ExecGraph::read(&g);
let list = Value::List(vec![int(1), int(2), int(3)].into());
let out = add(&graph, list, s("x")).unwrap();
assert!(matches!(out, Value::List(_)), "{out:?}");
assert_eq!(
graph.expression_built_bytes(),
crate::workspace::buffer_bytes(4, std::mem::size_of::<Value>() as u64,)
);
}
#[test]
fn mixed_list_and_string_is_refused_when_the_buffer_exceeds_the_cap() {
let mut g = crate::graph::Graph::default();
g.configure_expression_memory_limit(Some(1));
let graph = ExecGraph::read(&g);
let list = Value::List(vec![int(1), int(2), int(3)].into());
let error = add(&graph, list, s("x")).unwrap_err();
assert!(
matches!(
error,
Error::Capacity {
limit: 1,
kind: relate_core::CapacityKind::Expression,
..
}
),
"{error}"
);
}
fn cmp(op: BinaryOp, l: Value, r: Value) -> Value {
let g = crate::graph::Graph::default();
let graph = ExecGraph::read(&g);
binary(&graph, op, l, r).unwrap()
}
#[test]
fn equal_durations_satisfy_the_equality_tolerant_operators() {
let d = duration(0, 1);
assert_eq!(cmp(BinaryOp::Lt, d.clone(), d.clone()), Value::Null);
assert_eq!(cmp(BinaryOp::Gt, d.clone(), d.clone()), Value::Null);
assert_eq!(cmp(BinaryOp::Lte, d.clone(), d.clone()), Value::Bool(true));
assert_eq!(cmp(BinaryOp::Gte, d.clone(), d.clone()), Value::Bool(true));
let other = duration(0, 2);
for op in [BinaryOp::Lt, BinaryOp::Gt, BinaryOp::Lte, BinaryOp::Gte] {
assert_eq!(cmp(op, d.clone(), other.clone()), Value::Null);
}
}
#[test]
fn subtracting_two_temporals_is_a_type_mismatch() {
let date = Value::Temporal(temporal::parse_iso("date", "2020-01-01").unwrap());
let error = sub(date.clone(), date.clone()).unwrap_err();
assert_eq!(error.to_string(), ty_err("- type mismatch"));
assert_eq!(
sub(date, duration(0, 1)).unwrap(),
Value::Temporal(temporal::parse_iso("date", "2019-12-31").unwrap())
);
}
#[test]
fn equal_uuids_satisfy_the_equality_tolerant_operators() {
let a = Value::Uuid(1);
let b = Value::Uuid(2);
assert_eq!(cmp(BinaryOp::Gt, a.clone(), b.clone()), Value::Null);
assert_eq!(cmp(BinaryOp::Lt, b.clone(), a.clone()), Value::Null);
assert_eq!(cmp(BinaryOp::Gte, a.clone(), a.clone()), Value::Bool(true));
assert_eq!(cmp(BinaryOp::Lte, a.clone(), a.clone()), Value::Bool(true));
}
}