use super::*;
use crate::auto_parameter::{authored_spellings, substitute_auto_parameters, AuthoredSpellings};
use NormalizedValue::Int;
fn norm(src: &str) -> NormalizeOutcome {
normalize_statement(src, ParseOptions::default())
}
fn normalized_with(src: &str, options: ParseOptions) -> Normalized {
match normalize_statement(src, options) {
NormalizeOutcome::Normalized(n) => n,
NormalizeOutcome::NotCacheable => panic!("expected {src:?} to normalize"),
}
}
fn normalized(src: &str) -> Normalized {
normalized_with(src, ParseOptions::default())
}
fn template(src: &str) -> String {
normalized(src).template
}
fn values(src: &str) -> Vec<(String, NormalizedValue)> {
normalized(src).values
}
#[test]
fn keyword_case_stays_as_written() {
assert_ne!(
template("MATCH (n:order) RETURN n"),
template("MATCH (n:Order) RETURN n")
);
assert_ne!(template("RETURN n.match"), template("RETURN n.MATCH"));
assert_ne!(template("RETURN {match: 1}"), template("RETURN {MATCH: 1}"));
assert_ne!(
template("match (a:Person) where a.age > 21 with a limit 5"),
template("MATCH (a:Person) WHERE a.age > 21 WITH a LIMIT 5")
);
assert_ne!(
template("MATCH (a:Person) RETURN a"),
template("MATCH (b:Person) RETURN b")
);
assert_ne!(template("RETURN count"), template("RETURN COUNT"));
assert_ne!(template("RETURN n.true"), template("RETURN n.TRUE"));
}
#[test]
fn typed_literal_placeholders() {
assert_eq!(
template("MATCH (n:User {id: 42}) RETURN n"),
"MATCH ( n : User { id : $__AUTO_INT_0__ } ) RETURN n"
);
assert_eq!(
template("MATCH (n:User {id: 43}) RETURN n"),
template("MATCH (n:User {id: 42}) RETURN n")
);
let int = template("RETURN 42");
let float = template("RETURN 4.2");
let string = template("RETURN '42'");
assert_ne!(int, float);
assert_ne!(int, string);
assert_ne!(float, string);
assert_eq!(
values("RETURN 'hello'"),
vec![(
"__AUTO_STR_0__".into(),
NormalizedValue::Str("hello".into())
)]
);
}
#[test]
fn lists_collapse_to_one_param() {
assert_eq!(template("RETURN [1, 'a', 2.5]"), "RETURN $__AUTO_LIST_0__");
assert_eq!(
values("RETURN [1, 'a', 2.5]"),
vec![(
"__AUTO_LIST_0__".into(),
NormalizedValue::List(vec![
NormalizedValue::Int(1),
NormalizedValue::Str("a".into()),
NormalizedValue::Float(2.5),
])
)]
);
assert_eq!(template("RETURN []"), "RETURN $__AUTO_LIST_0__");
assert_eq!(template("RETURN [[1, 2], [3]]"), "RETURN $__AUTO_LIST_0__");
assert_eq!(
values("RETURN [[1, 2], [3]]"),
vec![(
"__AUTO_LIST_0__".into(),
NormalizedValue::List(vec![
NormalizedValue::List(vec![Int(1), Int(2)]),
NormalizedValue::List(vec![Int(3)]),
])
)]
);
assert_eq!(
template("RETURN [1, 2 + 3]"),
"RETURN [ $__AUTO_INT_0__ , $__AUTO_INT_1__ + $__AUTO_INT_2__ ]"
);
}
#[test]
fn subscripts_keep_their_brackets() {
let n = normalized("MATCH (n) RETURN labels(n)[0] AS kind");
assert_eq!(
n.template,
"MATCH ( n ) RETURN labels ( n ) [ $__AUTO_INT_0__ ] AS kind"
);
assert_eq!(
n.rewritten,
"MATCH (n) RETURN labels(n)[$__AUTO_INT_0__] AS kind"
);
assert_eq!(n.values, vec![("__AUTO_INT_0__".into(), Int(0))]);
assert_eq!(n.spellings, vec!["0".to_string()]);
assert_eq!(template("RETURN xs[0]"), "RETURN xs [ $__AUTO_INT_0__ ]");
assert_eq!(
template("MATCH (n) RETURN n.tags[1] AS t"),
"MATCH ( n ) RETURN n . tags [ $__AUTO_INT_0__ ] AS t"
);
assert_eq!(
template("RETURN [1, 2, 3][0] AS first"),
"RETURN $__AUTO_LIST_0__ [ $__AUTO_INT_1__ ] AS first"
);
assert_eq!(
values("RETURN [1, 2, 3][0] AS first"),
vec![
(
"__AUTO_LIST_0__".into(),
NormalizedValue::List(vec![Int(1), Int(2), Int(3)])
),
("__AUTO_INT_1__".into(), Int(0)),
]
);
assert_eq!(
template("RETURN xs[1..3] AS s"),
"RETURN xs [ $__AUTO_INT_0__ .. 3 ] AS s"
);
assert_eq!(
template("RETURN {'a': 1}['a'] AS v"),
"RETURN { 'a' : $__AUTO_INT_0__ } [ $__AUTO_STR_1__ ] AS v"
);
assert_eq!(
template("RETURN [[1, 2][0], 3] AS xs"),
"RETURN [ $__AUTO_LIST_0__ [ $__AUTO_INT_1__ ] , $__AUTO_INT_2__ ] AS xs"
);
}
#[test]
fn keyword_operands_keep_their_brackets() {
assert_eq!(
template("RETURN true[0]"),
"RETURN true [ $__AUTO_INT_0__ ]"
);
assert_eq!(
template("RETURN Infinity[0]"),
"RETURN Infinity [ $__AUTO_INT_0__ ]"
);
assert_eq!(template("RETURN NaN[0]"), "RETURN NaN [ $__AUTO_INT_0__ ]");
assert_eq!(
template("RETURN CASE WHEN true THEN [1] ELSE [2] END[0] AS x"),
"RETURN CASE WHEN true THEN $__AUTO_LIST_0__ ELSE $__AUTO_LIST_1__ END [ $__AUTO_INT_2__ ] AS x"
);
assert_eq!(
template("MATCH (n) RETURN n.order[0] AS o"),
"MATCH ( n ) RETURN n . order [ $__AUTO_INT_0__ ] AS o"
);
assert_eq!(
template("RETURN n.end[0] AS e"),
"RETURN n . end [ $__AUTO_INT_0__ ] AS e"
);
assert_eq!(
normalized_with(
"RETURN ******[0]",
ParseOptions {
obfuscated_literals: true,
..ParseOptions::default()
}
)
.template,
"RETURN ****** [ $__AUTO_INT_0__ ]"
);
}
#[test]
fn keyword_variables_in_operand_position_keep_their_brackets() {
assert_eq!(
template("WITH [1, 2] AS count RETURN count[0] AS c"),
"WITH $__AUTO_LIST_0__ AS count RETURN count [ $__AUTO_INT_1__ ] AS c"
);
assert_eq!(
template("RETURN RETURN[0] AS r"),
"RETURN RETURN [ $__AUTO_INT_0__ ] AS r"
);
assert_eq!(
template("RETURN 1 + count[0] AS c"),
"RETURN $__AUTO_INT_0__ + count [ $__AUTO_INT_1__ ] AS c"
);
assert_eq!(
template("MATCH (n) WHERE n.x > 1 AND count[0] < 2 RETURN n"),
"MATCH ( n ) WHERE n . x > $__AUTO_INT_0__ AND count [ $__AUTO_INT_1__ ] < $__AUTO_INT_2__ RETURN n"
);
assert_eq!(
template("RETURN 1 < count[0] AS c"),
"RETURN $__AUTO_INT_0__ < count [ $__AUTO_INT_1__ ] AS c"
);
assert_eq!(
template("RETURN [count[0], 2] AS xs"),
"RETURN [ count [ $__AUTO_INT_0__ ] , $__AUTO_INT_1__ ] AS xs"
);
}
#[test]
fn list_literals_still_collapse_in_clause_position() {
assert_eq!(template("RETURN [1, 2]"), "RETURN $__AUTO_LIST_0__");
assert_eq!(
template("MATCH (n) WHERE n.x IN [1, 2] RETURN n"),
"MATCH ( n ) WHERE n . x IN $__AUTO_LIST_0__ RETURN n"
);
}
#[test]
fn brackets_after_a_dash_render_as_written() {
assert_eq!(
template("MATCH (a)-[r:KNOWS]->(b) RETURN b"),
"MATCH ( a ) - [ r : KNOWS ] -> ( b ) RETURN b"
);
assert_eq!(
template("MATCH (a)-[]->(b) RETURN b"),
"MATCH ( a ) - [ ] -> ( b ) RETURN b"
);
assert_eq!(
template("MATCH (a)<-[]-(b) RETURN b"),
"MATCH ( a ) <- [ ] - ( b ) RETURN b"
);
assert_eq!(
template("RETURN 1 - [1, 2] AS d"),
"RETURN $__AUTO_INT_0__ - [ $__AUTO_INT_1__ , $__AUTO_INT_2__ ] AS d"
);
}
#[test]
fn map_key_strings_stay() {
assert_eq!(
template("RETURN {'a': 1}"),
"RETURN { 'a' : $__AUTO_INT_0__ }"
);
assert_ne!(template("RETURN {'a': 1}"), template("RETURN {'b': 1}"));
assert_ne!(template("RETURN {'a': 1}"), template("RETURN {a: 1}"));
}
#[test]
fn load_csv_field_terminator_stays() {
let t = template("LOAD CSV WITH HEADERS FROM 'data.csv' AS row FIELDTERMINATOR ';' RETURN row");
assert!(t.contains("$__AUTO_STR_0__"), "the URL normalizes: {t}");
assert!(t.contains("';'"), "the terminator stays: {t}");
assert_ne!(
template("LOAD CSV FROM 'a.csv' AS r FIELDTERMINATOR ';' RETURN r"),
template("LOAD CSV FROM 'a.csv' AS r FIELDTERMINATOR ',' RETURN r")
);
}
#[test]
fn quantifier_bounds_stay() {
let t = template("MATCH p = (a)-[:KNOWS*1..3]->(b) RETURN p");
assert!(t.contains("* 1 .. 3"), "the bounds stay: {t}");
assert_ne!(
template("MATCH p = (a)-[:KNOWS*1..3]->(b) RETURN p"),
template("MATCH p = (a)-[:KNOWS*2..3]->(b) RETURN p")
);
assert_ne!(template("RETURN 2 * 3"), template("RETURN 2 * 4"));
}
#[test]
fn function_first_arguments_stay() {
let t = template("WHERE date(p.birthday) > date(\"1990-01-01\")");
assert!(
t.contains("'1990-01-01'"),
"the constructor argument stays: {t}"
);
assert!(!t.contains("$__AUTO_STR"), "no placeholder for it: {t}");
assert_ne!(
template("RETURN date(\"1990-01-01\") AS d"),
template("RETURN date(\"1991-01-01\") AS d")
);
assert!(template("RETURN foo(\"x\") AS y").contains("'x'"));
let dt = template("RETURN datetime({year: 2021}) AS d");
assert!(
dt.contains("2021"),
"the map-form argument stays literal: {dt}"
);
assert!(!dt.contains("$__AUTO_INT"), "no placeholder for it: {dt}");
assert!(template("RETURN left('abc', 2) AS s").contains("'abc'"));
assert_eq!(
template("WHERE n.name = 'alice'"),
"WHERE n . name = $__AUTO_STR_0__"
);
assert_eq!(template("RETURN [1, 2]"), "RETURN $__AUTO_LIST_0__");
let list_arg = template("RETURN f([1, 2]) AS x");
assert!(
list_arg.contains("[ 1 , 2 ]"),
"the list argument stays literal, element-wise: {list_arg}"
);
assert!(
!list_arg.contains("$__AUTO_LIST"),
"no whole-group placeholder inside a call: {list_arg}"
);
}
#[test]
fn parameters_render_with_dollar() {
assert_eq!(
template("MATCH (n {id: $uid}) RETURN n"),
"MATCH ( n { id : $uid } ) RETURN n"
);
assert_ne!(
template("MATCH (n {id: $uid}) RETURN n"),
template("MATCH (n {id: uid}) RETURN n")
);
assert_ne!(
template("MATCH (n {id: $uid}) RETURN n"),
template("MATCH (n {id: $other}) RETURN n")
);
}
#[test]
fn parameter_names_render_through_the_canonical_shaped_form() {
assert_eq!(
template("MATCH (n {id: $`p 1`}) RETURN n"),
"MATCH ( n { id : $`p 1` } ) RETURN n"
);
assert_eq!(
template("MATCH (n {id: $`a``b`}) RETURN n"),
"MATCH ( n { id : $`a``b` } ) RETURN n"
);
assert_ne!(
template("MATCH (n {id: $`p 1`}) RETURN n"),
template("MATCH (n {id: $p1}) RETURN n")
);
assert_eq!(
template("MATCH (n {id: $`p1`}) RETURN n"),
template("MATCH (n {id: $p1}) RETURN n")
);
}
#[test]
fn quoted_identifiers_render_quoted() {
let t = template("MATCH (`a b`) RETURN `a b`");
assert!(t.contains("`a b`"), "the quoted name stays quoted: {t}");
assert_ne!(t, template("MATCH (a) RETURN a"));
assert_ne!(template("RETURN `MATCH`"), template("RETURN MATCH"));
}
#[test]
fn interpolated_strings_bail_the_statement() {
assert!(matches!(
norm("RETURN s'a{x}' AS s"),
NormalizeOutcome::NotCacheable
));
}
#[test]
fn obfuscated_literal_renders_as_written() {
let gated = ParseOptions {
obfuscated_literals: true,
..ParseOptions::default()
};
assert_eq!(
normalized_with("RETURN ******", gated).template,
"RETURN ******"
);
}
#[test]
fn auto_param_prefix_in_statement_bails() {
assert!(matches!(
norm("RETURN $__AUTO_INT_0__"),
NormalizeOutcome::NotCacheable
));
assert!(matches!(
norm("RETURN $__AUTO_LIST_9__"),
NormalizeOutcome::NotCacheable
));
assert!(matches!(
norm("RETURN $__auto_x__"),
NormalizeOutcome::Normalized(_)
));
}
#[test]
fn error_tokens_and_oversize_bail() {
assert!(matches!(
norm("RETURN 1B2c3e67"),
NormalizeOutcome::NotCacheable
));
let oversized = format!("RETURN {}", "1".repeat(MAX_QUERY_BYTES));
assert!(matches!(norm(&oversized), NormalizeOutcome::NotCacheable));
}
#[test]
fn rewritten_statement_parses() {
for src in [
"MATCH (n:User {id: 42}) RETURN n",
"MATCH (n:User {id: 'alice'}) RETURN n.name",
"MATCH (n) WHERE n.age > 21 AND n.name STARTS WITH 'a' RETURN n ORDER BY n.age LIMIT 5",
"MATCH (n) WHERE n.t IN [1, 2, 3] RETURN n",
"RETURN { 'name': 'x', age: 5 } AS m",
"UNWIND [1, 2] AS x RETURN x",
"MATCH (n {id: $uid}) RETURN n",
"match (n:person) return n limit 10",
"MATCH (n) RETURN labels(n)[0] AS kind",
"RETURN [1, 2, 3][0] AS first",
"MATCH (n) RETURN n.tags[1] AS t",
"RETURN xs[1..3] AS s",
"RETURN {'a': 1}['a'] AS v",
"RETURN [[1, 2][0], 3] AS xs",
"RETURN true[0]",
"RETURN Infinity[0]",
"RETURN NaN[0]",
"RETURN CASE WHEN true THEN [1] ELSE [2] END[0] AS x",
"MATCH (n) RETURN n.order[0] AS o",
"RETURN n.end[0] AS e",
"WITH [1, 2] AS count RETURN count[0] AS c",
"MATCH (n) WITH collect(n) AS nodes RETURN nodes[0] AS n0",
"RETURN RETURN[0] AS r",
"MATCH (a)-[]->(b) WHERE a.x = 1 RETURN b",
"RETURN 1 - [1, 2] AS d",
] {
crate::parser::parse(src).expect("the original parses");
let n = normalized(src);
crate::parser::parse(&n.rewritten)
.unwrap_or_else(|e| panic!("rewritten of {src:?} parses: {e}\n{}", n.rewritten));
}
}
#[test]
fn cypher_preamble_integer_fails_closed() {
let n = normalized("CYPHER 25 MATCH (n) RETURN n");
assert!(
n.rewritten.contains("$__AUTO_INT_0__"),
"the version became a placeholder: {}",
n.rewritten
);
assert!(crate::parser::parse(&n.rewritten).is_err());
}
#[test]
fn whitespace_and_comments_do_not_affect_the_template() {
assert_eq!(
template("MATCH (n:User {id: 42}) RETURN n"),
template("MATCH\n ( n : User { id: 42 } )\n// find\n RETURN n")
);
let n = normalized("MATCH (n:User {id: 42}) RETURN n LIMIT 3");
crate::parser::parse(&n.rewritten)
.unwrap_or_else(|e| panic!("the spliced form parses: {e}\n{}", n.rewritten));
let limited = normalized("RETURN 1 LIMIT 2");
assert!(
limited.rewritten.contains("$__AUTO_INT_0__ LIMIT"),
"keyword stays a separate token: {}",
limited.rewritten
);
let added = normalized("RETURN 1+2");
assert!(
added.rewritten.contains("$__AUTO_INT_0__+$__AUTO_INT_1__"),
"operator stays glued: {}",
added.rewritten
);
}
#[test]
fn escaped_strings_share_by_value() {
assert_eq!(template("RETURN 'a\\nb'"), template("RETURN \"a\nb\""));
assert_eq!(
values("RETURN 'a\\nb'"),
vec![("__AUTO_STR_0__".into(), NormalizedValue::Str("a\nb".into()))]
);
}
#[test]
fn deeply_nested_lists_decline_instead_of_recursing() {
let depth = 100_000;
let deep = format!("RETURN {}{}", "[".repeat(depth), "]".repeat(depth));
assert_eq!(norm(&deep), NormalizeOutcome::NotCacheable);
let parsed = relate_test_support::run_with_big_stack(move || crate::parser::parse(&deep));
assert!(parsed.is_err(), "the parser's depth guard rejects it");
let inside = format!("RETURN {}1{}", "[".repeat(8), "]".repeat(8));
let NormalizeOutcome::Normalized(inner) = norm(&inside) else {
panic!("the inside-cap payload normalizes");
};
assert_eq!(inner.template, "RETURN $__AUTO_LIST_0__");
}
mod substitute {
use super::*;
fn spellings_of(src: &str) -> AuthoredSpellings {
let NormalizeOutcome::Normalized(normalized) = norm(src) else {
panic!("expected {src:?} to normalize");
};
authored_spellings(&normalized.values, &normalized.spellings)
}
#[test]
fn a_placeholder_substitutes_to_its_authored_spelling() {
assert_eq!(
substitute_auto_parameters("$__AUTO_INT_0__", &spellings_of("RETURN 1")),
"1"
);
assert_eq!(
substitute_auto_parameters(
"$__AUTO_INT_0__ + $__AUTO_INT_1__",
&spellings_of("RETURN 1 + 2")
),
"1 + 2"
);
assert_eq!(
substitute_auto_parameters("$__AUTO_STR_0__", &spellings_of("RETURN 'x'")),
"'x'"
);
assert_eq!(
substitute_auto_parameters("$__AUTO_LIST_0__", &spellings_of("RETURN [1, 2]")),
"[1, 2]"
);
assert_eq!(
substitute_auto_parameters(
"n.x + $myParam",
&spellings_of("MATCH (n) RETURN n.x + $myParam")
),
"n.x + $myParam"
);
}
#[test]
fn a_lookalike_that_is_not_carried_stays_verbatim() {
let spellings = spellings_of("RETURN startsWith(n.x, '$__AUTO_INT_9__') + 1");
assert_eq!(
spellings
.iter()
.map(|spelling| spelling.placeholder.as_str())
.collect::<Vec<_>>(),
vec!["__AUTO_INT_0__"]
);
assert_eq!(
substitute_auto_parameters(
"startsWith(n.x, '$__AUTO_INT_9__') + $__AUTO_INT_0__",
&spellings
),
"startsWith(n.x, '$__AUTO_INT_9__') + 1"
);
}
#[test]
fn a_carried_name_inside_a_string_literal_stays_verbatim() {
let spellings = spellings_of("RETURN startsWith(n.x, '$__AUTO_INT_0__') + 1");
assert_eq!(
substitute_auto_parameters(
"startsWith(n.x, '$__AUTO_INT_0__') + $__AUTO_INT_0__",
&spellings
),
"startsWith(n.x, '$__AUTO_INT_0__') + 1"
);
let spellings = spellings_of(r#"RETURN startsWith(n.x, 'a\'b') + 1"#);
assert_eq!(
spellings[0].placeholder, "__AUTO_INT_0__",
"the call-argument string is not extracted; only the 1 is"
);
assert_eq!(
substitute_auto_parameters(
r#"startsWith(n.x, 'a\'$__AUTO_INT_0__') + $__AUTO_INT_0__"#,
&spellings
),
r#"startsWith(n.x, 'a\'$__AUTO_INT_0__') + 1"#
);
}
#[test]
fn a_spelling_containing_lookalike_text_lands_once() {
let spellings = spellings_of("RETURN '$__AUTO_INT_0__'");
assert_eq!(spellings[0].placeholder, "__AUTO_STR_0__");
assert_eq!(
substitute_auto_parameters("$__AUTO_STR_0__", &spellings),
"'$__AUTO_INT_0__'"
);
}
#[test]
fn multi_space_spacing_survives_the_substituted_name() {
let spellings = spellings_of("RETURN 1 + 2");
assert_eq!(
substitute_auto_parameters("$__AUTO_INT_0__ + $__AUTO_INT_1__", &spellings),
"1 + 2"
);
}
#[test]
fn malformed_name_shapes_copy_verbatim() {
let spellings = spellings_of("RETURN 1");
for text in [
"$__AUTO_INT_",
"$__AUTO_INT_x__",
"$__AUTO_",
"$__AUTO_INT_0_",
"$myParam",
"$",
] {
assert_eq!(
substitute_auto_parameters(text, &spellings),
text,
"{text:?} copies verbatim"
);
}
}
}