use super::*;
use relate_names::SmallName;
const EXCEPTION_IDS: [&str; 34] = [
"ref-aggregate-arg/NOT",
"ref-arithmetic/FALSE",
"ref-arithmetic/TRUE",
"ref-comparison/ALL",
"ref-comparison/DISTINCT",
"ref-comparison/NOT",
"ref-function-arg/ALL",
"ref-function-arg/DISTINCT",
"ref-function-arg/FALSE",
"ref-function-arg/NOT",
"ref-function-arg/TRUE",
"ref-list-element/NOT",
"ref-order-by/NOT",
"ref-property-base/ALL",
"ref-property-base/DISTINCT",
"ref-property-base/FALSE",
"ref-property-base/INF",
"ref-property-base/INFINITY",
"ref-property-base/NAN",
"ref-property-base/NOT",
"ref-property-base/TRUE",
"ref-return-bare/ALL",
"ref-return-bare/DISTINCT",
"ref-return-bare/NOT",
"ref-subscript-base/FALSE",
"ref-subscript-base/INF",
"ref-subscript-base/INFINITY",
"ref-subscript-base/NAN",
"ref-subscript-base/TRUE",
"ref-where/NOT",
"ref-with-after-comma/NOT",
"ref-with-first/ALL",
"ref-with-first/DISTINCT",
"ref-with-first/NOT",
];
fn return_item(s: &Statement) -> &ReturnItem {
match s.clauses.last() {
Some(Clause::Return(r)) if r.items.len() == 1 => &r.items[0],
other => panic!("expected a one-item RETURN, got {other:?}"),
}
}
fn return_clause(s: &Statement) -> &ReturnClause {
match s.clauses.last() {
Some(Clause::Return(r)) => r,
other => panic!("expected RETURN, got {other:?}"),
}
}
fn with_clause(s: &Statement) -> &WithClause {
match &s.clauses[0] {
Clause::With(w) => w,
other => panic!("expected WITH, got {other:?}"),
}
}
type AliasOf = fn(&Statement) -> SmallName;
fn return_alias(s: &Statement) -> SmallName {
return_item(s).alias.clone().expect("RETURN item alias")
}
fn unwind_alias(s: &Statement) -> SmallName {
match &s.clauses[0] {
Clause::Unwind(u) => u.alias.clone(),
other => panic!("expected UNWIND, got {other:?}"),
}
}
fn load_csv_alias(s: &Statement) -> SmallName {
match &s.clauses[0] {
Clause::LoadCSV(l) => l.alias.clone(),
other => panic!("expected LOAD CSV, got {other:?}"),
}
}
fn yield_alias(s: &Statement) -> SmallName {
let yields = match &s.clauses[0] {
Clause::CallProcedure(c) => &c.yields,
Clause::ShowFunctions(f) => &f.yields,
Clause::ShowIndexes(i) => &i.yields,
other => panic!("expected CALL/SHOW YIELD, got {other:?}"),
};
yields
.items
.first()
.and_then(|item| item.alias.clone())
.expect("YIELD alias")
}
#[test]
fn probe_fixture_has_alias_rows() {
super::probe_group_rows("alias");
}
#[test]
fn probe_alias_and_reference_rows_parse_as_decided() {
let mut rows = super::probe_group_rows("alias");
rows.extend(super::probe_group_rows("reference"));
assert_eq!(rows.len(), 1207, "alias + reference rows");
let mut accepted_checked = 0;
let mut exception_checked = 0;
for row in &rows {
let parsed = parse(row.query);
if EXCEPTION_IDS.contains(&row.id) {
exception_checked += 1;
assert_eq!(
parsed.is_ok(),
row.relate == "accepted",
"{}: the recorded relate outcome {:?} must stay ({:?})",
row.id,
row.relate,
parsed.err()
);
} else if row.neo4j == "accepted" {
accepted_checked += 1;
assert!(
parsed.is_ok(),
"{}: {:?} must parse: {:?}",
row.id,
row.query,
parsed.err()
);
}
}
assert_eq!(accepted_checked, 1157, "neo4j-accepted non-exception rows");
assert_eq!(exception_checked, 34, "exception rows");
}
#[test]
fn keyword_alias_sites_keep_the_spelling() {
let cases: [(&str, AliasOf, &str); 8] = [
("WITH 1 AS a RETURN a AS as", return_alias, "as"),
("WITH [1] AS s RETURN s AS union", return_alias, "union"),
("RETURN 1 AS MATCH", return_alias, "MATCH"),
("UNWIND [1] AS MATCH RETURN 1", unwind_alias, "MATCH"),
(
"LOAD CSV FROM 'file:///x.csv' AS MATCH RETURN 1",
load_csv_alias,
"MATCH",
),
(
"CALL db.labels() YIELD label AS MATCH RETURN 1",
yield_alias,
"MATCH",
),
(
"SHOW FUNCTIONS YIELD name AS MATCH RETURN 1",
yield_alias,
"MATCH",
),
(
"SHOW INDEXES YIELD name AS MATCH RETURN 1",
yield_alias,
"MATCH",
),
];
for (query, extract, expected) in cases {
assert_eq!(extract(&parse_ok(query)), expected, "{query}");
}
}
type IsLiteral = fn(&LiteralValue) -> bool;
#[test]
fn keyword_literals_keep_their_literal_meaning() {
let cases: [(&str, IsLiteral, &str); 6] = [
("RETURN null", |v| *v == LiteralValue::Null, "null"),
("RETURN true", |v| *v == LiteralValue::Bool(true), "true"),
("RETURN false", |v| *v == LiteralValue::Bool(false), "false"),
(
"RETURN inf",
|v| matches!(v, LiteralValue::Float(f) if f.is_infinite()),
"inf",
),
(
"RETURN infinity",
|v| matches!(v, LiteralValue::Float(f) if f.is_infinite()),
"infinity",
),
(
"RETURN nan",
|v| matches!(v, LiteralValue::Float(f) if f.is_nan()),
"nan",
),
];
for (query, is_expected, what) in cases {
match return_expr(&parse_ok(query)) {
Expr::Literal(v) => assert!(
is_expected(v),
"{query}: expected the {what} literal, got {v:?}"
),
other => panic!("{query}: expected a literal, got {other:?}"),
}
}
}
#[test]
fn keyword_reference_existing_meanings_keep_priority() {
match return_expr(&parse_ok("RETURN NOT true")) {
Expr::Unary(u) => {
assert_eq!(u.op, "NOT");
assert_eq!(u.expr, Expr::Literal(LiteralValue::Bool(true)));
}
other => panic!("expected NOT negation, got {other:?}"),
}
assert!(return_clause(&parse_ok("RETURN DISTINCT 1")).distinct);
assert!(with_clause(&parse_ok("WITH DISTINCT 1 RETURN 1")).distinct);
let all_stmt = parse_ok("RETURN ALL 1");
let all = return_clause(&all_stmt);
assert!(!all.distinct);
assert_eq!(all.items[0].expr, Expr::Literal(LiteralValue::Integer(1)));
match return_expr(&parse_ok("RETURN count(DISTINCT x)")) {
Expr::FunctionCall(f) => {
assert_eq!(f.name, "count");
assert!(f.distinct);
assert_eq!(f.args, vec![Expr::Variable("x".into())]);
}
other => panic!("expected count(), got {other:?}"),
}
match return_expr(&parse_ok("RETURN count(ALL x)")) {
Expr::FunctionCall(f) => {
assert_eq!(f.name, "count");
assert!(!f.distinct);
assert_eq!(f.args, vec![Expr::Variable("x".into())]);
}
other => panic!("expected count(), got {other:?}"),
}
match return_expr(&parse_ok("RETURN 1 + 2")) {
Expr::Binary(b) => {
assert_eq!(b.op, "+");
assert_eq!(b.left, Expr::Literal(LiteralValue::Integer(1)));
assert_eq!(b.right, Expr::Literal(LiteralValue::Integer(2)));
}
other => panic!("expected 1 + 2, got {other:?}"),
}
for query in [
"RETURN distinct",
"WITH distinct RETURN 1",
"RETURN count(distinct)",
"RETURN not",
"WITH 1 AS `all` RETURN all AS r",
"RETURN ALL",
"WITH ALL RETURN 1",
] {
assert!(parse(query).is_err(), "{query:?} must stay a syntax error");
}
assert!(parse("RETURN NOT + 1").is_err());
for query in ["RETURN abs(DISTINCT)", "RETURN abs(ALL)"] {
assert!(parse(query).is_ok(), "{query:?} stays accepted");
}
}
#[test]
fn keyword_forms_and_variable_fallbacks() {
assert!(matches!(
return_expr(&parse_ok("RETURN CASE WHEN true THEN 1 END AS r")),
Expr::Case(_)
));
for (query, name) in [
("RETURN count(x) AS r", "count"),
("RETURN collect(x) AS r", "collect"),
("RETURN exists(n.p) AS r", "exists"),
] {
match return_expr(&parse_ok(query)) {
Expr::FunctionCall(f) => assert_eq!(f.name, name, "{query}"),
other => panic!("{query}: expected a function call, got {other:?}"),
}
}
assert!(matches!(
return_expr(&parse_ok("RETURN reduce(s = 0, x IN [1] | s + x) AS r")),
Expr::Reduce(_)
));
for (query, name) in [
("RETURN case AS r", "case"),
("RETURN count AS r", "count"),
("RETURN collect AS r", "collect"),
("RETURN exists AS r", "exists"),
("RETURN EXISTS AS r", "EXISTS"),
("RETURN REDUCE AS r", "REDUCE"),
("RETURN reduce AS r", "reduce"),
("RETURN VECTOR AS r", "VECTOR"),
] {
assert_eq!(
return_expr(&parse_ok(query)),
&Expr::Variable(SmallName::from_name(name)),
"{query}"
);
}
}
const CLAUSE_KEYWORD_SPELLINGS: [&str; 22] = [
"match", "optional", "create", "insert", "merge", "delete", "detach", "set", "remove", "with",
"unwind", "where", "order", "by", "limit", "skip", "as", "distinct", "foreach", "union",
"require", "drop",
];
fn search_clause(s: &Statement) -> &SearchClause {
match_clause(s).search.as_ref().expect("SEARCH clause")
}
fn set_clause_of(s: &Statement) -> &SetClause {
s.clauses
.iter()
.find_map(|c| match c {
Clause::Set(sc) => Some(sc),
_ => None,
})
.expect("no SET clause")
}
fn remove_clause_of(s: &Statement) -> &RemoveClause {
s.clauses
.iter()
.find_map(|c| match c {
Clause::Remove(rc) => Some(rc),
_ => None,
})
.expect("no REMOVE clause")
}
fn property_target_variable(item_property: &Option<PropertyAccess>, query: &str) -> SmallName {
match item_property {
Some(pa) => match &pa.expr {
Expr::Variable(v) => v.clone(),
other => panic!("{query}: expected a variable base, got {other:?}"),
},
None => panic!("{query}: expected a property target"),
}
}
#[test]
fn keyword_search_binding_variable() {
for kw in CLAUSE_KEYWORD_SPELLINGS {
let query = format!(
"MATCH (`{kw}`:Doc) SEARCH {kw} IN (VECTOR INDEX docs FOR [1.0] LIMIT 2) RETURN 1"
);
assert_eq!(search_clause(&parse_ok(&query)).binding_var, kw, "{query}");
}
let stmt =
parse_ok("MATCH (n:Doc) SEARCH null IN (VECTOR INDEX docs FOR [1.0] LIMIT 2) RETURN 1");
assert_eq!(search_clause(&stmt).binding_var, "null");
assert!(
parse("MATCH (n:Doc) SEARCH 5 IN (VECTOR INDEX docs FOR [1.0] LIMIT 2) RETURN 1").is_err()
);
assert!(parse(
"MATCH (n:Doc) SEARCH n.title IN (VECTOR INDEX docs FOR [1.0] LIMIT 2) RETURN 1"
)
.is_err());
}
#[test]
fn keyword_score_as_variable() {
for kw in CLAUSE_KEYWORD_SPELLINGS {
let query = format!(
"MATCH (n:Doc) SEARCH n IN (VECTOR INDEX docs FOR [1.0] LIMIT 2) SCORE AS {kw} RETURN 1"
);
assert_eq!(
search_clause(&parse_ok(&query)).score_var.as_ref(),
Some(&SmallName::from_name(kw)),
"{query}"
);
}
}
#[test]
fn keyword_report_status_as_variable() {
for kw in CLAUSE_KEYWORD_SPELLINGS {
let query = format!(
"CALL {{ CREATE (x) }} IN TRANSACTIONS ON ERROR CONTINUE REPORT STATUS AS {kw} RETURN 1"
);
let stmt = parse_ok(&query);
let in_tx = call_subquery_of(&stmt)
.in_transactions
.as_ref()
.expect("IN TRANSACTIONS");
assert_eq!(
in_tx.report_status.as_ref(),
Some(&SmallName::from_name(kw)),
"{query}"
);
}
}
#[test]
fn keyword_set_target_variable() {
for kw in CLAUSE_KEYWORD_SPELLINGS {
let query = format!("MATCH (`{kw}`:Doc) SET {kw}.prop = 1 RETURN 1");
let stmt = parse_ok(&query);
let item = &set_clause_of(&stmt).items[0];
assert_eq!(
property_target_variable(&item.property, &query),
kw,
"{query}"
);
}
let stmt = parse_ok("MATCH (`match`:Doc) SET match:Label RETURN 1");
let item = &set_clause_of(&stmt).items[0];
assert_eq!(item.variable.as_ref(), Some(&SmallName::from_name("match")));
assert_eq!(item.labels.len(), 1);
let stmt = parse_ok("MATCH (`match`:Doc) SET match = 1 RETURN 1");
assert_eq!(
set_clause_of(&stmt).items[0].variable.as_ref(),
Some(&SmallName::from_name("match"))
);
let stmt = parse_ok("MATCH (`match`:Doc) SET match += {p: 1} RETURN 1");
assert_eq!(
set_clause_of(&stmt).items[0].variable.as_ref(),
Some(&SmallName::from_name("match"))
);
assert!(parse("MATCH (n:Doc) SET 5.prop = 1 RETURN 1").is_err());
}
#[test]
fn keyword_remove_target_variable() {
for kw in CLAUSE_KEYWORD_SPELLINGS {
let query = format!("MATCH (`{kw}`:Doc) REMOVE {kw}.prop RETURN 1");
let stmt = parse_ok(&query);
let item = &remove_clause_of(&stmt).items[0];
assert_eq!(
property_target_variable(&item.property, &query),
kw,
"{query}"
);
}
let stmt = parse_ok("MATCH (`match`:Doc) REMOVE match:Label RETURN 1");
assert_eq!(
remove_clause_of(&stmt).items[0].variable.as_ref(),
Some(&SmallName::from_name("match"))
);
assert!(parse("MATCH (n:Doc) REMOVE 5.prop RETURN 1").is_err());
}
#[test]
fn distinct_immediately_before_as_is_a_variable() {
let stmt = parse("WITH 1 AS `DISTINCT` RETURN DISTINCT AS x").expect("parses");
assert!(
!return_clause(&stmt).distinct,
"DISTINCT here is a variable, not the row modifier"
);
assert_eq!(
return_item(&stmt).alias.as_ref(),
Some(&SmallName::from_name("x"))
);
let stmt = parse("WITH 1 AS n RETURN DISTINCT n").expect("parses");
assert!(return_clause(&stmt).distinct, "DISTINCT stays the modifier");
}
#[test]
fn unary_plus_parses_bare_and_parenthesized() {
for query in [
"RETURN (+1) AS x",
"RETURN +1 AS x",
"RETURN DISTINCT + 1",
"WITH 1 AS x RETURN +x AS y",
"WITH 2 AS v RETURN CASE v WHEN 2 CONTAINS (+1) THEN 'A' ELSE 'B' END AS t",
] {
assert!(parse(query).is_ok(), "{query} must parse");
}
for query in ["RETURN NOT + 1 AS x", "RETURN + +1 AS x", "RETURN ++1 AS x"] {
assert!(parse(query).is_err(), "{query} must stay a syntax error");
}
}
#[test]
fn union_head_next_does_not_change_arm_columns() {
assert!(
parse("RETURN EXISTS { RETURN 1 AS b UNION RETURN 2 AS b NEXT RETURN b + 1 AS x } AS x")
.is_ok(),
"the arms agree on `b`; the NEXT stage's `x` is not an arm column"
);
}