use relate_core::{Error, Value};
use super::super::test_support::{
assert_expression_cap, exec_autocommit, exec_cypher_on, try_exec_cypher_on,
};
use crate::{ExecGraph, Graph};
#[test]
fn transaction_error_message_keeps_the_pinned_uniqueness_wrapper() {
let error = Error::uniqueness_violation("p_id");
assert_eq!(
super::transaction_error_message(&error),
"A value already exists and violates a uniqueness constraint: \
semantic error: ConstraintValidationFailed: `p_id` uniqueness"
);
let error = Error::type_error("schema name must be STRING");
assert_eq!(
super::transaction_error_message(&error),
"TypeError: schema name must be STRING"
);
let error = Error::argument_value_kind(relate_core::ErrorKind::NumberOutOfRange, "percentile");
assert_eq!(
super::transaction_error_message(&error),
"NumberOutOfRange: percentile"
);
let error = Error::ty("anything");
assert_eq!(super::transaction_error_message(&error), "anything");
}
mod shared_subquery {
use relate_ir::{Clause, Query};
use super::super::shared::{import_invariant_body, shared_execution_plan};
use super::*;
fn call_body(cypher: &str) -> (Query, relate_ir::CallScope) {
let query = relate_front::parse_and_lower(cypher).unwrap();
for part in &query.parts {
for clause in &part.clauses {
if let Clause::CallSubquery { query, scope, .. } = clause {
return ((**query).clone(), scope.clone());
}
}
}
panic!("test query must contain a CALL subquery: {cypher}");
}
fn invariant(cypher: &str) -> bool {
let store = Graph::default();
let graph = ExecGraph::read(&store);
let (body, scope) = call_body(cypher);
let rows = vec![crate::row::Row::from([
("i".to_string(), Value::Int(1)),
("p".to_string(), Value::Int(1)),
])];
let plan = shared_execution_plan(&graph, &body, &scope, &rows)
.expect("the fixture's imports are all in the outer row");
let Some(plan) = plan else {
panic!("fixture must admit the fast path: {cypher}");
};
import_invariant_body(&body, &plan.check())
}
#[test]
fn admits_chained_aggregation_with_pass_through_import() {
assert!(invariant(
"UNWIND range(1,5) AS i \
CALL { WITH i MATCH (n) WITH i, count(*) AS c WITH sum(c) AS s RETURN s } \
RETURN s"
));
assert!(invariant(
"UNWIND range(1,5) AS i CALL (i) { UNWIND [1,2] AS j RETURN j } RETURN j"
));
assert!(invariant(
"UNWIND range(1,5) AS i CALL { WITH i UNWIND [1,2,3] AS j RETURN j LIMIT 2 } RETURN j"
));
assert!(invariant(
"UNWIND range(1,5) AS i CALL (i) { MATCH (a)-[r]->(b) RETURN count(r) AS c } RETURN c"
));
}
#[test]
fn refuses_bodies_computing_from_the_import() {
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i MATCH (n {v: i}) RETURN count(*) AS c } RETURN c"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i MATCH (n) WHERE n.v = i RETURN count(*) AS c } \
RETURN c"
));
assert!(!invariant(
"MATCH (p) CALL (p) { MATCH (p)-[:FRIEND]->(f) RETURN count(f) AS d } RETURN d"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i MATCH (n)-[i]->(m) RETURN count(*) AS c } \
RETURN c"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i MATCH (n) RETURN sum(i) AS s } RETURN s"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL (i) { WITH i AS j RETURN j } RETURN j"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i RETURN rand() AS r } RETURN r"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i RETURN UUID() AS u } RETURN u"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i RETURN datetime.realtime() AS t } RETURN t"
));
assert!(!invariant(
"UNWIND range(1,5) AS i \
CALL { WITH i MATCH (n) WHERE EXISTS { MATCH (m) WHERE rand() < 0.5 } RETURN count(*) AS c } \
RETURN c"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i RETURN COLLECT { MATCH (n) RETURN n } AS ns } \
RETURN ns"
));
assert!(!invariant(
"UNWIND range(1,5) AS i CALL { WITH i CREATE (n:N) RETURN 1 AS one } RETURN one"
));
}
fn rows_of(cypher: &str) -> Vec<Vec<Value>> {
let graph = Graph::default();
let view = ExecGraph::read(&graph);
exec_cypher_on(&view, cypher).rows
}
#[test]
fn shared_execution_matches_per_row_results() {
assert_eq!(
rows_of(
"UNWIND range(1,4) AS i \
CALL { WITH i UNWIND range(1,3) AS j WITH i, count(*) AS c WITH sum(c) AS s RETURN s } \
RETURN i, s ORDER BY i"
),
vec![
vec![Value::Int(1), Value::Int(3)],
vec![Value::Int(2), Value::Int(3)],
vec![Value::Int(3), Value::Int(3)],
vec![Value::Int(4), Value::Int(3)],
]
);
assert_eq!(
rows_of("UNWIND [2,1,2] AS i CALL { WITH i UNWIND [10,20] AS j RETURN j } RETURN i, j"),
vec![
vec![Value::Int(2), Value::Int(10)],
vec![Value::Int(2), Value::Int(20)],
vec![Value::Int(1), Value::Int(10)],
vec![Value::Int(1), Value::Int(20)],
vec![Value::Int(2), Value::Int(10)],
vec![Value::Int(2), Value::Int(20)],
]
);
assert_eq!(
rows_of(
"UNWIND [1,2] AS i OPTIONAL CALL { WITH i UNWIND [] AS z RETURN 1 AS x } RETURN i, x"
),
vec![
vec![Value::Int(1), Value::Null],
vec![Value::Int(2), Value::Null],
]
);
assert_eq!(
rows_of("UNWIND [1,2] AS i CALL { WITH i UNWIND [] AS z RETURN 1 AS x } RETURN i"),
Vec::<Vec<Value>>::new()
);
assert_eq!(
rows_of("UNWIND [1,2] AS i CALL (i) { WITH i AS j RETURN j } RETURN i, j ORDER BY i"),
vec![
vec![Value::Int(1), Value::Int(1)],
vec![Value::Int(2), Value::Int(2)]
]
);
assert_eq!(
rows_of(
"UNWIND [1,2] AS i CALL (i) { UNWIND [10,20] AS j WITH j RETURN i + j AS k } \
RETURN i, k ORDER BY i, k"
),
vec![
vec![Value::Int(1), Value::Int(11)],
vec![Value::Int(1), Value::Int(21)],
vec![Value::Int(2), Value::Int(12)],
vec![Value::Int(2), Value::Int(22)],
]
);
let drawn = rows_of("UNWIND range(1,8) AS i CALL { WITH i RETURN uuid() AS u } RETURN u");
let mut as_text: Vec<String> = drawn.iter().map(|r| format!("{:?}", r[0])).collect();
as_text.sort();
as_text.dedup();
assert_eq!(as_text.len(), drawn.len());
let correlated = rows_of(
"UNWIND [1,2,3] AS i CALL { WITH i UNWIND range(1, i) AS j RETURN count(*) AS c } \
RETURN i, c",
);
assert_eq!(
correlated,
vec![
vec![Value::Int(1), Value::Int(1)],
vec![Value::Int(2), Value::Int(2)],
vec![Value::Int(3), Value::Int(3)],
]
);
}
}
#[test]
fn transaction_error_message_keeps_the_legacy_text_of_adr_0307_variants() {
let cases = [
(
Error::arithmetic(relate_core::ArithmeticFailure::DivisionByZero),
Error::ty("/ by zero"),
),
(
Error::arithmetic(relate_core::ArithmeticFailure::ModuloByZero),
Error::ty("% by zero"),
),
(
Error::arithmetic(relate_core::ArithmeticFailure::RoundingNecessary),
Error::execution("ArithmeticError: rounding necessary"),
),
(
Error::database_not_found("nosuchdb"),
Error::semantic("DatabaseNotFound: Graph not found: nosuchdb"),
),
(Error::cancelled(), Error::execution("query cancelled")),
];
for (typed, legacy) in cases {
assert_eq!(
super::transaction_error_message(&typed),
super::transaction_error_message(&legacy),
"{typed:?}"
);
}
assert_eq!(
super::transaction_error_message(&Error::arithmetic(
relate_core::ArithmeticFailure::DivisionByZero
)),
"/ by zero"
);
}
#[test]
fn subquery_aggregation_over_an_emptied_input_keeps_the_identity_row() {
let graph = Graph::default();
let view = ExecGraph::read(&graph);
let emptied_by_unwind = exec_cypher_on(
&view,
"UNWIND [0, 1] AS x CALL (x) { UNWIND [] AS i WITH count(*) AS c RETURN c } \
RETURN x, c ORDER BY x",
);
assert_eq!(
emptied_by_unwind.columns,
vec!["x".to_string(), "c".to_string()]
);
assert_eq!(
emptied_by_unwind.rows,
vec![
vec![Value::Int(0), Value::Int(0)],
vec![Value::Int(1), Value::Int(0)],
]
);
let emptied_by_filter = exec_cypher_on(
&view,
"UNWIND [0, 1, 2] AS x \
CALL (x) { UNWIND range(1, 3) AS i WITH i WHERE i < 0 WITH count(*) AS c \
RETURN x + c AS result } \
RETURN x, result ORDER BY x",
);
assert_eq!(
emptied_by_filter.rows,
vec![
vec![Value::Int(0), Value::Int(0)],
vec![Value::Int(1), Value::Int(1)],
vec![Value::Int(2), Value::Int(2)],
]
);
}
#[test]
fn scoped_call_union_star_arm_exports_only_the_body_names() {
let graph = Graph::default();
let view = ExecGraph::read(&graph);
let result = exec_cypher_on(
&view,
"WITH 1 AS a \
CALL (a) { LET x = a + 1 RETURN * UNION RETURN 2 AS x } \
RETURN a, x",
);
assert_eq!(result.columns, vec!["a".to_string(), "x".to_string()]);
assert_eq!(result.rows, vec![vec![Value::Int(1), Value::Int(2)]]);
}
#[test]
fn next_stage_over_all_unit_scoped_union_arms_rejects_mismatched_shapes() {
let graph = Graph::default();
let error = exec_autocommit(
&graph,
"UNWIND [1, 2] AS i \
CALL (i) { CREATE (x:T1), (y:T2) UNION ALL CREATE (z:T1) NEXT RETURN 1 AS c } \
RETURN c",
)
.err()
.expect("the arms' row-derived columns differ");
assert!(
error.to_string().contains("UNION requires same columns"),
"expected the typed UNION error, got: {error}"
);
}
#[test]
fn all_unit_scoped_call_union_arms_need_no_column_agreement() {
let graph = Graph::default();
let result = exec_autocommit(
&graph,
"UNWIND [1, 2] AS i \
CALL (i) { CREATE (x:T1) UNION ALL CREATE (y:T2) } \
RETURN count(*) AS c",
)
.unwrap();
assert_eq!(result.rows, vec![vec![Value::Int(2)]]);
}
fn plain_projection_charges_the_product(body: &str, expected_shared_runs: u64) {
let mut graph = Graph::default();
graph.configure_expression_memory_limit(Some(1 << 20));
let view = ExecGraph::read(&graph);
let error = try_exec_cypher_on(
&view,
&format!(
"UNWIND range(1, 5_000) AS i \
CALL (i) {{ {body} }} \
RETURN v"
),
)
.err()
.expect("a materialized subquery product must be refused at the lowered cap");
assert_expression_cap(&error, 1 << 20);
assert_eq!(
super::feed::take_shared_body_runs(),
expected_shared_runs,
"the mode the refusal pins"
);
}
#[test]
fn a_plain_projection_over_the_subquery_product_charges_the_staged_rows() {
plain_projection_charges_the_product("UNWIND range(1, 200) AS j RETURN i * 1000 + j AS v", 0);
}
#[test]
fn a_plain_projection_over_the_shared_product_charges_the_merged_rows() {
plain_projection_charges_the_product("UNWIND range(1, 200) AS j RETURN j AS v", 1);
}
fn folding_consumer_streams_the_product(body: &str, expected_shared_runs: u64) {
let mut graph = Graph::default();
graph.configure_expression_memory_limit(Some(1 << 20));
let view = ExecGraph::read(&graph);
let result = exec_cypher_on(
&view,
&format!(
"UNWIND range(1, 5_000) AS i \
CALL (i) {{ {body} }} \
RETURN count(v) AS c"
),
);
assert_eq!(result.rows, vec![vec![Value::Int(1_000_000)]]);
assert_eq!(
super::feed::take_shared_body_runs(),
expected_shared_runs,
"the mode the fold pinned"
);
}
#[test]
fn a_folding_consumer_streams_the_subquery_product_whatever_its_size() {
folding_consumer_streams_the_product("UNWIND range(1, 200) AS j RETURN i * 1000 + j AS v", 0);
}
#[test]
fn a_folding_consumer_streams_the_shared_execution_product() {
folding_consumer_streams_the_product("UNWIND range(1, 200) AS j RETURN j AS v", 1);
}
#[test]
fn a_writing_body_never_parks_whatever_its_consumer() {
let mut graph = Graph::default();
graph.configure_expression_memory_limit(Some(1 << 20));
let result = exec_autocommit(
&graph,
"UNWIND range(1, 3) AS i \
CALL (i) { WITH i CREATE (:N) } \
WITH i, COUNT { MATCH (m:N) RETURN m } AS c \
RETURN i, c ORDER BY c DESC, i LIMIT 2",
)
.unwrap();
let counts: Vec<i64> = result
.rows
.iter()
.map(|row| row[1].as_int().unwrap_or_default())
.collect();
assert_eq!(counts, vec![3, 3], "{:?}", result.rows);
}
#[test]
fn the_in_transactions_output_is_charged_per_batch() {
const CAP: u64 = 64 * 1024;
const BATCHES: usize = 60;
const PER_BATCH: usize = 20;
let one_batch = crate::workspace::retained_rows_bytes(PER_BATCH, 2);
let whole_product = crate::workspace::retained_rows_bytes(BATCHES * PER_BATCH, 2);
assert!(
one_batch < CAP && CAP < whole_product,
"the cap must admit one batch and refuse the accumulation: \
{one_batch} < {CAP} < {whole_product}"
);
let mut graph = Graph::default();
graph.configure_expression_memory_limit(Some(CAP));
let result = exec_autocommit(
&graph,
&format!(
"UNWIND range(1, {BATCHES}) AS i \
CALL (i) {{ WITH i UNWIND range(1, {PER_BATCH}) AS j \
RETURN i * 1000 + j AS v }} \
IN TRANSACTIONS OF 1 ROWS \
RETURN count(v) AS c"
),
)
.unwrap();
assert_eq!(
result.rows,
vec![vec![Value::Int((BATCHES * PER_BATCH) as i64)]]
);
}