relate_planner/plan.rs
1//! Plan types and the `plan` entry point: consume a lowered `Query`,
2//! validate it, and build the `LogicalPlan` the executor interprets
3//! (ADR-0009), with MATCH rewrites applied after bind (ADR-0024).
4
5use std::collections::BTreeMap;
6
7use relate_core::Result;
8use relate_ir::{Clause, Expr, Query};
9use relate_names::TokenResolver;
10
11use crate::names::stage_output_names;
12use crate::order::{plan_match_strategies, MatchStrategy};
13use crate::pattern::{label_expr_contains_dynamic, pattern_contains_dynamic_operands};
14use crate::rewrite;
15use crate::stats::{NoPatternStats, PatternStats, StatsMemo};
16use crate::validate::chain::{validate_query_with_env, StageSeed};
17
18/// Logical plan is a pipeline of clauses (plus UNION).
19///
20/// Built by `plan`, which consumes the lowered `Query`: the plan owns the
21/// clause vectors moved out of it (no deep clone), so the rewrite pass
22/// mutates them in place.
23#[derive(Debug, Clone)]
24pub struct LogicalPlan {
25 pub parts: Vec<Vec<Clause>>,
26 pub union_all: Vec<bool>,
27 pub next: Option<Box<LogicalPlan>>,
28 /// The statement's resolved `USE` target (ADR-0116 §3), lifted into the
29 /// plan by [`plan`]: `Some(namespace)` when any `USE` clause is present
30 /// (all `USE` clauses in one statement must agree), `None` when the
31 /// statement carries none and the session namespace applies. Resolution
32 /// failures (unknown name 42N00, composite-only selector 42N72, distinct
33 /// targets 42NA5, unresolvable element id 42NA7) are `plan` errors.
34 /// Always `None` on nested `NEXT`-stage plans; the top-level plan's
35 /// resolution walks the whole statement.
36 pub use_target: Option<relate_core::Namespace>,
37 /// Planner-selected physical `MatchStrategy` per `(part_idx, clause_idx)`
38 /// for `MATCH` clauses in this stage (ADR-0737).
39 pub match_strategies: BTreeMap<(usize, usize), MatchStrategy>,
40}
41
42impl LogicalPlan {
43 /// Look up the planned [`MatchStrategy`] for `clause_idx` in `part_idx` of
44 /// this stage, if one was selected.
45 pub fn match_strategy(&self, part_idx: usize, clause_idx: usize) -> Option<MatchStrategy> {
46 self.match_strategies.get(&(part_idx, clause_idx)).copied()
47 }
48 /// Every stage of this plan, top-level first: the plan itself, then each
49 /// `NEXT` stage. The one place the stage-level recursion lives — the
50 /// stage-level walk ([`plan_output_names`]) rides it; part-level walks
51 /// ride [`Self::parts`].
52 pub(crate) fn stages(&self) -> impl Iterator<Item = &LogicalPlan> {
53 std::iter::successors(Some(self), |stage| stage.next.as_deref())
54 }
55
56 /// Every part of every stage, top-level first: the one place the
57 /// stage→parts flatten lives. The part-level walks ([`walk_plan`],
58 /// [`walk_plan_parts`]) and the namespaces classifiers
59 /// ([`crate::namespaces::is_show_databases_with_next`]) ride it.
60 pub(crate) fn parts(&self) -> impl Iterator<Item = &[Clause]> {
61 self.stages()
62 .flat_map(|stage| stage.parts.iter().map(Vec::as_slice))
63 }
64
65 /// The plan's one part, when it has exactly one with no `UNION` and no
66 /// `NEXT` — the whole-statement shape a fast path requires (a bulk write,
67 /// an EXISTS probe, the create-only batch gate). The one home of the
68 /// parts/`union_all`/`next` test: a `UNION` arm is a second part and a
69 /// `NEXT` stage is a second plan, so either disqualifies it. Returning
70 /// the part keeps the shape test and the right to index `parts[0]` one
71 /// value, so a caller cannot pass the guard and then reach in.
72 pub fn single_part(&self) -> Option<&[Clause]> {
73 (self.union_all.is_empty() && self.next.is_none())
74 .then(|| self.parts.first().map(Vec::as_slice))
75 .flatten()
76 }
77
78 /// Whether the statement has the standalone call shape: the
79 /// [`single_part`](Self::single_part) whole-statement shape holding one
80 /// substantive clause (a leading `USE` routes and does not count:
81 /// `USE system CALL db.info()` is standalone). Any other part — a
82 /// `UNION` arm, a `NEXT` part, a longer clause list — is in-query. The
83 /// plan side's spelling of the front end's `CallSite::of_statement`.
84 pub fn is_standalone_call_shape(&self) -> bool {
85 self.single_part()
86 .is_some_and(|part| crate::clause_kind::query_clause_count(part) == 1)
87 }
88}
89
90/// The output column names of a planned statement (ADR-0319): the names the
91/// final stage's `RETURN`/`YIELD`/`SHOW` exports, through the same
92/// output-name analysis semantic validation uses. The engine reports them
93/// for a statement whose execution failed, so a surface can still announce
94/// its columns. A planned statement already passed the UNION
95/// column-agreement check, so the `Err` arm is that check's error; callers
96/// that hold a `plan`-produced statement share the one expect policy
97/// ([`plan_output_names_expect`]).
98pub fn plan_output_names(plan: &LogicalPlan) -> Result<Vec<String>> {
99 plan.stages().try_fold(Vec::new(), |names, stage| {
100 stage_output_names(
101 stage.parts.iter().map(Vec::as_slice),
102 names,
103 &crate::names::no_excluded_imports(),
104 )
105 })
106}
107
108/// [`plan_output_names`] for a caller that holds a planned statement: the
109/// `Err` arm is the UNION column-agreement check, which `plan` already ran,
110/// so a planned statement's output names always derive. The one expect for
111/// that invariant, shared with the facade's `ExecutionFailure::staged`
112/// (ADR-0319, ADR-0332).
113pub fn plan_output_names_expect(plan: &LogicalPlan) -> Vec<String> {
114 plan_output_names(plan).expect("a planned statement's UNION columns agree")
115}
116
117/// The canonical way to visit every clause of a [`LogicalPlan`]: each
118/// part's clause tree via [`relate_ir::walk_clauses`] — UNION arms are
119/// parts, and `CALL { … }` subqueries, `WHEN`/`ELSE` branches, `FOREACH`
120/// bodies and expression subqueries are all descended into — recursing
121/// into `NEXT` stages. Hand-rolling a `plan.parts` + `plan.next` recursion
122/// instead of calling this is how coverage of a nesting position gets
123/// dropped.
124pub fn walk_plan_clauses<'a>(plan: &'a LogicalPlan, on_clause: &mut impl FnMut(&'a Clause)) {
125 walk_plan(plan, on_clause, &mut |_| {});
126}
127
128/// [`walk_plan_clauses`]' full-descent walk, seeing every expression of
129/// the plan (the expression half of the private [`walk_plan`]): the same
130/// coverage — UNION arms, `NEXT` stages, subqueries, branches, `FOREACH`
131/// bodies and pattern payloads — one expression at a time. The
132/// connection-thread fast path's predicate (ADR-0504, `crate::inline`)
133/// reads it; clause-granular analyses keep [`walk_plan_clauses`].
134pub(crate) fn walk_plan_exprs<'a>(plan: &'a LogicalPlan, on_expr: &mut impl FnMut(&'a Expr)) {
135 walk_plan(plan, &mut |_| {}, on_expr);
136}
137
138/// [`walk_plan_clauses`]' full-descent walk, seeing every expression of
139/// the plan as well as every clause. Rides [`LogicalPlan::parts`], the one
140/// stage→parts flatten.
141fn walk_plan<'a>(
142 plan: &'a LogicalPlan,
143 on_clause: &mut impl FnMut(&'a Clause),
144 on_expr: &mut impl FnMut(&'a Expr),
145) {
146 for part in plan.parts() {
147 relate_ir::walk_clauses(part, on_clause, on_expr);
148 }
149}
150
151/// Whether executing `plan` with these parameters would accept a float
152/// where the original literal is rejected at plan time (a slice bound or
153/// a list index). The plan-cache hit path uses this to fall back to the
154/// original statement, which reports the compile error.
155pub fn plan_has_bound_float_integer_site(
156 plan: &LogicalPlan,
157 params: &std::collections::BTreeMap<String, relate_core::Value>,
158) -> bool {
159 let _auto = relate_core::AutoLiteralGuard::install(params);
160 plan_any_expr(plan, &mut |expr| {
161 crate::literal::float_integer_site(expr).is_some()
162 })
163}
164
165/// The parameter names `plan` references (`$name`), each once, in the
166/// order of first appearance in the full-descent walk ([`walk_plan_clauses`]'
167/// coverage: UNION arms, `NEXT` stages, subqueries, branches, `FOREACH`
168/// bodies and pattern payloads). The facade checks them against the
169/// supplied parameters before dispatch (ADR-0308).
170pub fn plan_parameter_names(plan: &LogicalPlan) -> Vec<&str> {
171 let mut names: Vec<&str> = Vec::new();
172 walk_plan(plan, &mut |_| {}, &mut |expr| {
173 if let Expr::Parameter(name) = expr {
174 if !names.contains(&name.as_str()) {
175 names.push(name);
176 }
177 }
178 });
179 names
180}
181
182/// The parameters `plan` references but `params` does not supply — the
183/// ADR-0308 predicate, in one place. Two consumers read it: the facade's
184/// admission gate, which refuses the statement (`connection::dispatch::
185/// post_explain_gates`), and the `01N60` notice the notification derivation
186/// raises under `EXPLAIN` (ADR-0363), so the refusal and the notice can
187/// never disagree about which names are unbound.
188///
189/// The order is [`plan_parameter_names`]' — first appearance, each once.
190pub fn plan_missing_parameters<'a>(
191 plan: &'a LogicalPlan,
192 params: &std::collections::BTreeMap<String, relate_core::Value>,
193) -> Vec<&'a str> {
194 plan_parameter_names(plan)
195 .into_iter()
196 .filter(|name| !params.contains_key(*name))
197 .collect()
198}
199
200/// The canonical way to visit a [`LogicalPlan`] PART BY PART: each part's
201/// TOP-LEVEL clause slice (UNION arms are parts), recursing into `NEXT`
202/// stages — with no descent into `CALL { … }` bodies, `WHEN`/`ELSE`
203/// branches, `FOREACH` bodies or expression subqueries.
204///
205/// This is deliberately NOT [`walk_plan_clauses`]'s coverage: analyses that
206/// reason per part over top-level clauses only (e.g. the `system`-namespace
207/// 42N17 offender collection, where a read MATCH nested in an expression
208/// subquery attached to a standalone CALL stays allowed) must use this walk
209/// so the part-vs-`NEXT` recursion lives in exactly one place. If your
210/// analysis needs the nested positions, use [`walk_plan_clauses`] instead.
211pub fn walk_plan_parts<'a>(plan: &'a LogicalPlan, on_part: &mut impl FnMut(&'a [Clause])) {
212 for part in plan.parts() {
213 on_part(part);
214 }
215}
216
217/// The canonical way to visit a not-yet-planned [`Query`] PART BY PART —
218/// the `ir::Query` analog of [`walk_plan_parts`]: each part's TOP-LEVEL
219/// clause slice (UNION arms are parts), recursing into `NEXT` stages —
220/// with no descent into `CALL { … }` bodies, `WHEN`/`ELSE` branches,
221/// `FOREACH` bodies or expression subqueries.
222///
223/// Analyses that reason per part over the pre-plan IR (the access fold in
224/// [`crate::access`], the validate.rs write / IN TRANSACTIONS sweeps) must
225/// use this walk so the part-vs-`NEXT` recursion lives in exactly one
226/// place. Queries nested inside a clause (`WHEN`/`ELSE` branch bodies,
227/// `CALL { … }`, `FOREACH`) are the CALLER's recursion: the walk yields
228/// the clause slices, and the clause handler decides which nested
229/// [`Query`]s to descend into (as [`crate::access`]'s `WHEN`/`ELSE`
230/// handling does).
231pub fn walk_query_parts<'a>(query: &'a Query, on_part: &mut impl FnMut(&'a [Clause])) {
232 for part in &query.parts {
233 on_part(&part.clauses);
234 }
235 if let Some(next) = query.next.as_deref() {
236 walk_query_parts(next, on_part);
237 }
238}
239
240/// Whether any clause of `plan` (via [`walk_plan_clauses`]) satisfies
241/// `pred` — the one walk-and-accumulate boolean over plan clauses, so
242/// classifiers stay one-line predicates instead of hand-rolling
243/// `let mut found = false; … found |= …; found`.
244pub fn plan_any_clause(plan: &LogicalPlan, pred: &mut impl FnMut(&Clause) -> bool) -> bool {
245 let mut found = false;
246 walk_plan_clauses(plan, &mut |clause| found |= pred(clause));
247 found
248}
249
250/// [`plan_any_clause`]' expression half — the one walk-and-accumulate
251/// boolean over plan expressions (the full-descent coverage of
252/// [`walk_plan_exprs`]), so expression classifiers stay one-line
253/// predicates the same way clause classifiers do.
254pub(crate) fn plan_any_expr(plan: &LogicalPlan, pred: &mut impl FnMut(&Expr) -> bool) -> bool {
255 let mut found = false;
256 walk_plan_exprs(plan, &mut |expr| found |= pred(expr));
257 found
258}
259
260/// The not-yet-planned [`Query`] analog of [`plan_any_clause`], riding
261/// [`walk_query_parts`] (top-level clauses per part, `NEXT` stages; the
262/// caller's predicate decides which nested queries to descend into).
263pub fn query_any_clause(query: &Query, pred: &mut impl FnMut(&Clause) -> bool) -> bool {
264 let mut found = false;
265 walk_query_parts(query, &mut |part| found |= part.iter().any(&mut *pred));
266 found
267}
268
269/// The not-yet-planned [`Query`] analog of [`plan_any_expr`]: whether any
270/// expression of the query satisfies `pred`, riding
271/// [`relate_ir::walk_query`]'s full descent (subquery bodies included).
272pub(crate) fn query_any_expr(query: &Query, pred: &mut impl FnMut(&Expr) -> bool) -> bool {
273 let mut found = false;
274 relate_ir::walk_query(query, &mut |_| {}, &mut |expr| found |= pred(expr));
275 found
276}
277
278/// ADR-0210: whether the plan carries `CALL { … } IN TRANSACTIONS`
279/// anywhere (top level or nested in a `CALL { }` body — the nested form
280/// is rejected by [`crate::validate`], so in practice this is the
281/// top-level batched subquery). The facade's auto-commit write path uses
282/// this to attach the per-batch commit sink.
283pub fn plan_contains_in_transactions(plan: &LogicalPlan) -> bool {
284 plan_any_clause(plan, &mut crate::clause_kind::clause_is_in_transactions)
285}
286
287/// Whether `plan` may join a pipelined write batch (ADR-0642): the
288/// statement's only mutating clause is `CREATE`, it produces no rows, and it
289/// is a single part with no `UNION` and no `NEXT`. The Bolt session opens one
290/// commit for a framed message batch's run of these, so the statement shape
291/// is the conservative gate, not a performance hint.
292///
293/// Deny by default: a clause outside the allowed read set — a second write
294/// flavor (`MERGE`, `SET`, `REMOVE`, `DELETE`, `FOREACH`, `LOAD CSV`), a
295/// `CALL` (a write procedure is a mutation this fold cannot see), a
296/// `CALL { … }` subquery, a `WHEN`/`ELSE` branch, schema DDL — refuses the
297/// plan, as does a `RETURN` (a batched statement's result rows would be held
298/// past its statement boundary). The walk is the full descent
299/// ([`walk_plan_clauses`]), so a write nested in any position counts.
300pub fn plan_is_create_only(plan: &LogicalPlan) -> bool {
301 if plan.single_part().is_none() {
302 return false;
303 }
304 let mut has_create = false;
305 let mut eligible = true;
306 walk_plan_clauses(
307 plan,
308 &mut |clause| match crate::clause_kind::clause_create_only_role(clause) {
309 crate::clause_kind::CreateOnlyRole::Create => has_create = true,
310 crate::clause_kind::CreateOnlyRole::Neutral => {}
311 crate::clause_kind::CreateOnlyRole::Refuse => eligible = false,
312 },
313 );
314 eligible && has_create
315}
316
317/// Whether a plan references any **dynamic name operand** — a dynamic
318/// label (`LabelExpr::Dynamic`, in a pattern's label expressions or a
319/// label predicate) or a dynamic property key (`Expr::DynamicProperty`).
320/// ADR-0503's insert gate reads this: the front validates such operands
321/// against bound *values* at lowering time (LABS-709 — the check has a
322/// content half, an empty or null-byte name, beyond its type half), and a
323/// cache hit skips lowering, so a plan carrying one must not be cached —
324/// the statement stays uncached, never silently unvalidated.
325pub fn plan_contains_dynamic_operands(plan: &LogicalPlan) -> bool {
326 // The clause half: MATCH patterns in both representations, one
327 // predicate over the canonical clause walk. The expression half: the
328 // canonical expression walk — `DynamicProperty`, label predicates,
329 // and the pattern-carrying expression positions (`PatternPred`,
330 // `ShortestPath`) whose inner paths are pattern
331 // payloads too.
332 plan_any_clause(plan, &mut |clause| {
333 matches!(
334 clause,
335 Clause::Match { patterns, .. }
336 if patterns.iter().any(pattern_contains_dynamic_operands)
337 )
338 }) || plan_any_expr(plan, &mut |expr| match expr {
339 Expr::DynamicProperty { .. } => true,
340 Expr::LabelPredicate { label_expr, .. } => label_expr_contains_dynamic(label_expr),
341 // A pattern payload is a dynamic-operand surface the same way a
342 // MATCH pattern is; the variant set lives in the accessor, which
343 // answers once here — no payload, no dynamic operands.
344 other => other
345 .pattern_path()
346 .is_some_and(pattern_contains_dynamic_operands),
347 })
348}
349
350/// Bind AST to a logical plan (ADR-0009), then rewrite MATCH (ADR-0024).
351///
352/// Takes ownership of the query: the clauses are moved into the plan, not
353/// cloned.
354/// `is_write_procedure` classifies `CALL` targets for the write rules
355/// (IN TRANSACTIONS composition, writes in subquery expressions): the
356/// procedure registry lives in the executor, so the facade injects the
357/// canonical predicate rather than the planner hardcoding names.
358pub fn plan(
359 query: Query,
360 is_write_procedure: &mut impl FnMut(&str) -> bool,
361) -> Result<LogicalPlan> {
362 plan_with_stats(query, is_write_procedure, &NoPatternStats)
363}
364
365/// [`plan`] with cardinality hints for MATCH ordering (ADR-0218).
366///
367/// `stats` is consulted while rewriting each MATCH, through ADR-0508's
368/// per-statement consult memo: the one wrapper built here de-duplicates
369/// the greedy order loop's repeated consults for the whole plan call and
370/// is dropped at return, which is the memo's entire invalidation story.
371/// Missing counts fall back to the fixed endpoint ranks. `NoPatternStats`
372/// is what [`plan`] passes, so callers that have no graph keep the
373/// rank-only order.
374pub fn plan_with_stats(
375 query: Query,
376 is_write_procedure: &mut impl FnMut(&str) -> bool,
377 stats: &dyn PatternStats,
378) -> Result<LogicalPlan> {
379 let memo = StatsMemo::new(stats);
380 let mut plan = plan_checked(query, is_write_procedure, &memo)?;
381 // ADR-0116 §3/§10: lift the statement's `USE` target into the plan.
382 // Resolution walks the whole statement (UNION arms, CALL subqueries,
383 // WHEN branches, expression subqueries, NEXT stages), so it runs once,
384 // on the top-level plan.
385 plan.use_target = crate::use_target::resolve_use_target(&plan)?;
386 Ok(plan)
387}
388
389/// [`plan_with_stats`] after resolving the statement's labels, relationship
390/// types and property keys to token ids against `resolver` (ADR-0541), once,
391/// before any planning step reads them. The ids ride the compiled plan; the
392/// caller's statement tree (cloned into `query`) stays id-free.
393pub fn plan_with_tokens(
394 mut query: Query,
395 is_write_procedure: &mut impl FnMut(&str) -> bool,
396 stats: &dyn PatternStats,
397 resolver: &dyn TokenResolver,
398) -> Result<LogicalPlan> {
399 crate::resolve::resolve_query(&mut query, resolver);
400 plan_with_stats(query, is_write_procedure, stats)
401}
402
403/// Validate one statement, then bind it to a plan (ADR-0009) and rewrite
404/// its MATCH parts (ADR-0024). `stats` is whatever the caller holds; the
405/// one production caller ([`plan_with_stats`]) passes its per-statement
406/// [`StatsMemo`] (ADR-0508), which the assembly recursion below threads
407/// unchanged — the memo's lifetime is the whole statement's plan call,
408/// never re-wrapped per stage.
409///
410/// Validation is the validate layer's whole-chain walk, run once here
411/// through the same driver a `CALL { … }` body uses — so the one
412/// chain-advance policy (which names flow into each `NEXT` stage, which
413/// exclusion set carries, which 42I25 fact threads) stays the validate
414/// layer's, and the planner's assembly recursion never re-enters it: the
415/// assembly reads no scope, and each stage validates exactly once, as
416/// before.
417pub(crate) fn plan_checked(
418 query: Query,
419 is_write_procedure: &mut impl FnMut(&str) -> bool,
420 stats: &dyn PatternStats,
421) -> Result<LogicalPlan> {
422 validate_query_with_env(&query, StageSeed::statement(), is_write_procedure)?;
423 // The scan-order rewrite reads no scope, so it runs on the statement's
424 // first stage only: a `NEXT` stage can import a bound variable, which
425 // turns its `MATCH (n)` from a scan into a lookup.
426 let mut query = query;
427 for part in &mut query.parts {
428 crate::scan_order::drop_id_order_over_node_scan(&mut part.clauses);
429 }
430 Ok(plan_stages(query, stats))
431}
432
433/// The planner's stage recursion: rewrite each stage's MATCH parts
434/// (ADR-0024) and assemble the `NEXT` chain into the `LogicalPlan`
435/// (ADR-0009). Infallible by construction — the whole-chain validation in
436/// [`plan_checked`] has already accepted every stage, and the rewrite is
437/// total — so the recursion carries no scope and returns no `Result`.
438fn plan_stages(query: Query, stats: &dyn PatternStats) -> LogicalPlan {
439 let Query {
440 parts,
441 union_all,
442 next,
443 } = query;
444 let mut parts: Vec<Vec<Clause>> = parts.into_iter().map(|part| part.clauses).collect();
445 for part in &mut parts {
446 rewrite::rewrite_part(part, stats);
447 }
448 let match_strategies = plan_match_strategies(&parts, stats);
449 let next = next.map(|next| Box::new(plan_stages(*next, stats)));
450 LogicalPlan {
451 parts,
452 union_all,
453 next,
454 use_target: None,
455 match_strategies,
456 }
457}
458
459#[cfg(test)]
460mod next_seed_tests {
461 /// A NEXT stage sees the chain's inherited names — a `CALL (a) { … }`
462 /// body's imports, or a `WHEN` branch's outer variables — as well as
463 /// the previous stage's columns: the chained statement keeps the
464 /// imported names visible in every one of its parts.
465 #[test]
466 fn next_stage_carries_inherited_names() {
467 crate::plan_of(
468 "LET a = 1 \
469 CALL (a) { WHEN true THEN LET b = 2 RETURN b NEXT RETURN a + b AS x } \
470 RETURN a, x",
471 );
472 }
473
474 /// An explicit `GROUP BY` moves ORDER BY and WHERE after grouping, so
475 /// they may aggregate (Neo4j `GroupByAcceptance` [15] and [19]).
476 #[test]
477 fn explicit_group_by_allows_order_by_and_where_aggregation() {
478 for query in [
479 "UNWIND [1, 2] AS a RETURN a, count(*) AS c GROUP BY a ORDER BY sum(a)",
480 "UNWIND [1, 2] AS a WITH a, count(*) AS c GROUP BY a WHERE sum(a) > 1 RETURN c",
481 ] {
482 crate::plan_of(query);
483 }
484 }
485
486 /// A mid-chain NEXT stage must not re-project an imported name: that
487 /// shadows the enclosing binding the chain keeps visible (the
488 /// redeclaration the chain rejects, 42N07).
489 #[test]
490 fn next_stage_reprojecting_an_import_is_rejected() {
491 let text = crate::rejection(
492 "LET a = 1 \
493 CALL (a) { LET b = 2 RETURN a, b NEXT RETURN a + b AS x } \
494 RETURN a, x",
495 );
496 assert!(
497 text.contains("VariableShadowing") || text.contains("already declared in outer scope"),
498 "{text}"
499 );
500 }
501}
502
503#[cfg(test)]
504mod create_only_tests {
505 use super::*;
506 use crate::plan_of;
507
508 fn create_only(cypher: &str) -> bool {
509 plan_is_create_only(&plan_of(cypher))
510 }
511
512 #[test]
513 fn creates_of_every_matched_shape_are_eligible() {
514 for cypher in [
515 "CREATE (n)",
516 "CREATE (:A)-[:R]->(:B)",
517 "UNWIND $rows AS r CREATE (:N {id: r.id})",
518 "MATCH (a:A {id: 1}) MATCH (b:B {id: 2}) CREATE (a)-[:R]->(b)",
519 "UNWIND $rows AS r MATCH (u:User {id: r.u}) CREATE (u)-[:R]->(:N)",
520 "UNWIND $rows AS x WITH x MATCH (n {id: x}) CREATE (:N {v: x})",
521 "MATCH (n) WITH n CREATE (m)",
522 ] {
523 assert!(create_only(cypher), "{cypher}");
524 }
525 }
526
527 #[test]
528 fn every_other_write_flavor_is_refused() {
529 for cypher in [
530 "MATCH (n) SET n.x = 1",
531 "MERGE (n:N {id: 1})",
532 "MATCH (n) DELETE n",
533 "MATCH (n) REMOVE n.x",
534 "FOREACH (x IN [1] | CREATE (n))",
535 "CREATE INDEX i FOR (n:N) ON (n.p)",
536 "CREATE CONSTRAINT c FOR (n:N) REQUIRE n.id IS UNIQUE",
537 "CALL { CREATE (n) } IN TRANSACTIONS",
538 "CALL db.labels()",
539 ] {
540 assert!(!create_only(cypher), "{cypher}");
541 }
542 }
543
544 #[test]
545 fn a_statement_without_a_create_is_refused() {
546 for cypher in ["RETURN 1 AS n", "MATCH (n) RETURN n"] {
547 assert!(!create_only(cypher), "{cypher}");
548 }
549 }
550
551 #[test]
552 fn a_result_returning_create_and_a_multi_part_plan_are_refused() {
553 for cypher in [
554 "CREATE (n) RETURN n",
555 "CREATE (n) UNION CREATE (m)",
556 "CREATE (n) NEXT RETURN 1",
557 ] {
558 assert!(!create_only(cypher), "{cypher}");
559 }
560 }
561}