Skip to main content

relate_planner/
namespaces.rs

1//! ADR-0116 namespace classifiers: the §2 database-administration
2//! classifiers (the admin-command classifier and the `SHOW DATABASES` +
3//! `NEXT` rule), the §4 `system` gate and the statement read/write
4//! classification they build on. This module is the one home for the
5//! namespace rules — the sibling §3 `USE` rules live in
6//! [`crate::use_target`]; the facade (`relate::connection`) calls here
7//! and keeps only `CALL`-shape validation. The `system_ontologies` gate is
8//! ADR-0229's — every non-administration statement routed there fails with
9//! one fixed text, so it needs no classifier here (the facade raises it in
10//! `Connection::namespace_gate_error`).
11//!
12//! The procedure-aware check ([`plan_calls_write_procedure`]) takes the
13//! write-procedure predicate as an argument: the canonical procedure
14//! signature registry lives in the executor, which depends on this crate
15//! (never the reverse).
16
17use relate_ir::Clause;
18use relate_parser::DatabaseFilter;
19
20use crate::clause_kind::ir_clause_keyword;
21use crate::LogicalPlan;
22
23/// The write classifier is a projection of the one shared clause fold
24/// ([`crate::access::plan_access`]): each part's TOP-LEVEL clauses (plus
25/// `NEXT` stages and `WHEN`/`ELSE` branch bodies) only — it deliberately
26/// does NOT descend into `CALL { … }` bodies or expression subqueries,
27/// because the fold already classifies a top-level `CALL { … }` as a
28/// write outright and a read-only `CALL { … }` nested in an
29/// `EXISTS`/`COUNT`/`COLLECT` expression must not reclassify the statement
30/// as a write. Schema (index/constraint DDL) counts as a write here; see
31/// [`crate::access::Access::is_write`].
32pub fn is_write(plan: &LogicalPlan) -> bool {
33    crate::access::plan_access(plan, &mut |_| false).is_write()
34}
35
36/// Whether any `CALL` of a write procedure appears anywhere in the plan.
37/// [`crate::walk_plan_clauses`] descends into `CALL { … }` subqueries,
38/// `WHEN`/`ELSE` branches, `FOREACH` bodies, expression subqueries and
39/// `NEXT` stages, so a write procedure nested in any of those positions
40/// still counts — the query-type classification reads it
41/// ([`crate::query_type`]).
42pub fn plan_calls_write_procedure(
43    plan: &LogicalPlan,
44    is_write_procedure: &mut impl FnMut(&str) -> bool,
45) -> bool {
46    let mut calls_write = false;
47    crate::walk_plan_clauses(plan, &mut |clause| {
48        if let Clause::Call { name, .. } = clause {
49            calls_write |= name.with_str(|text| is_write_procedure(text));
50        }
51    });
52    calls_write
53}
54
55/// ADR-0116 §2: the database-administration `Catalog` vocabulary, matched
56/// once. [`is_database_admin_command`] asks whether a clause is one of the
57/// commands; the `SHOW DATABASES` + `NEXT` rule
58/// ([`is_show_databases_with_next`]) and ADR-0590's composition rule
59/// ([`composed_show_databases`]) ask for a `SHOW DATABASES` spelling
60/// specifically.
61#[derive(Clone, Copy, PartialEq, Eq)]
62enum DatabaseAdminCommand {
63    ShowDatabases(ShowDatabasesSpelling),
64    AlterDatabase,
65    /// `SHOW SETTINGS` (ADR-0719): the read-only settings report joins
66    /// the any-namespace family — it names store-level resolved state,
67    /// never a namespace's graph.
68    ShowSettings,
69}
70
71/// The `SHOW DATABASE[S]` spelling a clause is — the four CE refuses
72/// composed, each named as written. The parser's clause-keyword table names
73/// the clause *kind* (always the plural), so the spelling has to come from
74/// the clause's own filter.
75#[derive(Clone, Copy, PartialEq, Eq)]
76enum ShowDatabasesSpelling {
77    /// Bare `SHOW DATABASE[S]` — every database.
78    All,
79    /// `SHOW DATABASE <name>` — the singular form.
80    Named,
81    /// `SHOW DEFAULT DATABASE`.
82    Default,
83    /// `SHOW HOME DATABASE`.
84    Home,
85}
86
87impl ShowDatabasesSpelling {
88    /// The spelling as CE's rejection carries it (live 2026.10.1).
89    fn label(self) -> &'static str {
90        match self {
91            ShowDatabasesSpelling::All => "SHOW DATABASES",
92            ShowDatabasesSpelling::Named => "SHOW DATABASE",
93            ShowDatabasesSpelling::Default => "SHOW DEFAULT DATABASE",
94            ShowDatabasesSpelling::Home => "SHOW HOME DATABASE",
95        }
96    }
97}
98
99/// ADR-0116 §2: classify a parser `Catalog` command as one of the
100/// database-administration commands, or `None` for every other `Catalog`
101/// clause. Matched once here, lowered once per clause by
102/// [`admin_command_clause`] — every §2 classifier reads the one match.
103fn database_admin_command(command: &relate_parser::Clause) -> Option<DatabaseAdminCommand> {
104    use relate_parser::Clause as C;
105    match command {
106        C::ShowDatabases(show) => Some(DatabaseAdminCommand::ShowDatabases(match show.filter {
107            DatabaseFilter::All => ShowDatabasesSpelling::All,
108            DatabaseFilter::Named(_) => ShowDatabasesSpelling::Named,
109            DatabaseFilter::Default => ShowDatabasesSpelling::Default,
110            DatabaseFilter::Home => ShowDatabasesSpelling::Home,
111        })),
112        C::AlterDatabase(_) => Some(DatabaseAdminCommand::AlterDatabase),
113        // ADR-0719 decision 6: the settings report is administration —
114        // read-only, store-level, runnable from any namespace.
115        C::ShowSettings(_) => Some(DatabaseAdminCommand::ShowSettings),
116        _ => None,
117    }
118}
119
120/// ADR-0116 §2: the §2 command a top-level IR clause is, or `None` for
121/// every other clause — the one clause-level lowering every §2 classifier
122/// reads: [`is_database_admin_command`]'s all-quantifier,
123/// [`is_show_databases_with_next`]'s and [`composed_show_databases`]'s
124/// `SHOW DATABASES` refinement, [`admin_command_heads_statement`]'s head
125/// probe and the §4 composability walk's containment test all go through
126/// it, so the vocabulary is matched once.
127fn admin_command_clause(clause: &Clause) -> Option<DatabaseAdminCommand> {
128    match clause {
129        Clause::Catalog(command) => database_admin_command(command.as_ref()),
130        _ => None,
131    }
132}
133
134/// ADR-0116 §2: database-administration commands run from any namespace and
135/// execute against the store's catalog (the `neo4j` graph). A plan qualifies
136/// when every clause is a database-administration `Catalog` command.
137pub fn is_database_admin_command(plan: &LogicalPlan) -> bool {
138    !plan.parts.is_empty()
139        && plan.next.is_none()
140        && plan
141            .parts
142            .iter()
143            .flatten()
144            .all(|clause| admin_command_clause(clause).is_some())
145}
146
147/// ADR-0590: the command spelling for a plan that *composes* `SHOW
148/// DATABASES` with other clauses, or `None` when every occurrence stands in
149/// the canonical shape (the command alone, or with a trailing `RETURN` over
150/// its yielded columns, as the statement's whole body). Off the `system`
151/// namespace such a plan is CE's 51N28 `NotSystemDatabaseError`; on `system`
152/// the command is where it belongs and §4's clause whitelist governs
153/// instead.
154///
155/// `SHOW DATABASES` is the whole subject: the other §2 command, `ALTER
156/// DATABASE`, cannot be composed at all — the front end rejects every
157/// composed form of it (`WITH … ALTER …` and `MATCH … ALTER …` as an
158/// invalid composition, the trailing-`RETURN`/`NEXT` forms as 51N27), and
159/// live's grammar does not parse them either. The spelling returned is the
160/// one live refuses — see [`show_databases_label`].
161///
162/// Part-granular over each part's TOP-LEVEL clauses, the granularity the §4
163/// whitelist and the `NEXT` backstop already use. A part's command is
164/// composed when anything substantive precedes it (a leading routing `USE`
165/// run is not composition), when its part is not the statement's only one (a
166/// `UNION` arm is never the standalone shape), when a `NEXT` stage follows,
167/// or when a clause other than a trailing `RETURN` follows it. Live
168/// 2026.10.1 raises the same rejection for the head and the mid-body
169/// position alike.
170pub fn composed_show_databases(plan: &LogicalPlan) -> Option<&'static str> {
171    composed_command(plan, show_databases_label)
172}
173
174/// The composition rule for `SHOW CURRENT USER`, the second command live
175/// refuses composed off `system` (51N28, verified 2026.10.1: `SHOW CURRENT
176/// USER YIELD user MATCH (n) RETURN n`). Same shape rule as
177/// [`composed_show_databases`], but a *composition-only* classifier: the
178/// ADR-0116 §2 vocabulary ([`DatabaseAdminCommand`]) is untouched, so the
179/// bare command's behaviour and the `system_ontologies` exemption
180/// ([`is_database_admin_command`]) do not move. `SHOW USERS`/`ROLES`/
181/// `SERVERS` are not covered: they were not probed (`SHOW USERS` does not
182/// compose on live at all — a parse error).
183pub fn composed_show_current_user(plan: &LogicalPlan) -> Option<&'static str> {
184    composed_command(plan, show_current_user_label)
185}
186
187/// The command spelling for `SHOW CURRENT USER`, or `None` for every other
188/// clause (the plural/`SHOW USER[S]` forms are not a composition subject).
189fn show_current_user_label(clause: &Clause) -> Option<&'static str> {
190    match clause {
191        Clause::Catalog(command) => match command.as_ref() {
192            relate_parser::Clause::ShowUsers(show) if show.current_only => {
193                Some("SHOW CURRENT USER")
194            }
195            _ => None,
196        },
197        _ => None,
198    }
199}
200
201/// The shared composition walk of [`composed_show_databases`] and
202/// [`composed_show_current_user`]: `label` names the command a clause is.
203fn composed_command(
204    plan: &LogicalPlan,
205    label: fn(&Clause) -> Option<&'static str>,
206) -> Option<&'static str> {
207    // A standalone plan (one part, no `UNION`, no `NEXT`) judges its command
208    // by position and followers; any other shape is composed the moment any
209    // part carries the command.
210    let standalone = plan.single_part().is_some();
211    plan.parts().find_map(|part| {
212        let mut clauses = part
213            .iter()
214            .skip_while(|clause| crate::clause_kind::clause_is_routing(clause));
215        let (index, label) = clauses
216            .by_ref()
217            .enumerate()
218            .find_map(|(index, clause)| label(clause).map(|label| (index, label)))?;
219        let composed = !standalone
220            || index != 0
221            || clauses.any(|clause| !matches!(clause, Clause::Return { .. }));
222        composed.then_some(label)
223    })
224}
225
226/// The `SHOW DATABASE[S]` spelling a clause is, or `None` for every other
227/// clause — the one `SHOW DATABASES` test the §2 classifiers share, and the
228/// command name CE's rejection carries. A projection of the vocabulary
229/// match, never a second reading of the clause.
230fn show_databases_label(clause: &Clause) -> Option<&'static str> {
231    match admin_command_clause(clause)? {
232        DatabaseAdminCommand::ShowDatabases(spelling) => Some(spelling.label()),
233        DatabaseAdminCommand::AlterDatabase | DatabaseAdminCommand::ShowSettings => None,
234    }
235}
236
237/// ADR-0116 §2: whether the plan combines `SHOW DATABASES`
238/// with a `NEXT` stage. The front-end's NEXT-chain validation rejects the
239/// combination before planning; this classifier is the execution-phase
240/// backstop the facade checks after its EXPLAIN early return (EXPLAIN plans
241/// without executing, so the rule does not apply there). Part-granular over
242/// every stage's TOP-LEVEL clauses, matching the front-end's per-body scan:
243/// a `SHOW DATABASES` nested in an expression subquery does not participate
244/// in a `NEXT` chain.
245pub fn is_show_databases_with_next(plan: &LogicalPlan) -> bool {
246    plan.next.is_some()
247        && plan.parts().any(|part| {
248            part.iter()
249                .any(|clause| show_databases_label(clause).is_some())
250        })
251}
252
253/// ADR-0116 §2, amended 2026-11-04: whether the statement's body is
254/// *headed* by a database-administration command — the first top-level
255/// clause after any leading `USE` clauses is one of the §2 commands. This
256/// is the shape the 42N79 auto-routing gate is scoped to: every headed
257/// spelling under a non-system `USE` (bare, `YIELD … RETURN …`, `UNION`
258/// arm, `ALTER DATABASE`) is 42N79. A command later in the body (after
259/// e.g. a `MATCH`, or behind a leading `WITH`) is not headed, so that gate
260/// passes it through to the namespace gates — where, off `system`, it is
261/// the composed-form rejection instead (ADR-0590). Part-granular on the
262/// head part only: a command headed in a `NEXT` stage is already refused
263/// by the NEXT-chain rule ([`is_show_databases_with_next`]), and `USE`
264/// clauses never split parts.
265pub fn admin_command_heads_statement(plan: &LogicalPlan) -> bool {
266    plan.parts.first().is_some_and(|head| {
267        head.iter()
268            .find(|clause| !matches!(clause, Clause::Use { .. }))
269            .and_then(admin_command_clause)
270            .is_some()
271    })
272}
273
274/// ADR-0116 §4: on a `system` session only SHOW commands, supported
275/// administration commands and standalone procedure calls
276/// (`CALL … [YIELD …] [RETURN …]`) run. Returns the offending clause kinds
277/// (deduplicated, in order of appearance) for CE's 42N17 text, or `None`
278/// when the statement is allowed.
279pub fn unsupported_system_clause_names(plan: &LogicalPlan) -> Option<String> {
280    let mut offending: Vec<&'static str> = Vec::new();
281    // Part-granular coverage is deliberate: only each part's TOP-LEVEL
282    // clauses (plus `NEXT` stages, via `walk_plan_parts`) are judged — a
283    // read MATCH nested in an expression subquery attached to a standalone
284    // CALL is allowed on `system`. `walk_plan_clauses` would descend into
285    // those nested positions and is the wrong walk here.
286    //
287    // Deliberate contrast with the facade's `validate_calls`, which walks
288    // the FULL clause tree (`walk_plan_clauses`) so a `CALL` nested in a
289    // `CALL { … }` subquery is still validated against the procedure
290    // registry: 42N17 judges the statement's top-level shape, while CALL
291    // validation must cover every call site. Do not "unify" the two walks.
292    crate::walk_plan_parts(plan, &mut |clauses| {
293        collect_system_offenders(clauses, &mut offending);
294    });
295    if offending.is_empty() {
296        None
297    } else {
298        Some(offending.join(", "))
299    }
300}
301
302/// ADR-0116 §4: the tail-clause keywords CE suppresses from the 42N17
303/// offender list when a non-tail offender is present. Encoded ONCE — both
304/// the offender collection (`is_tail` below) and the suppression
305/// (`partition` below) read this list, so the two can never drift apart.
306const SYSTEM_TAIL_KEYWORDS: &[&str] = &["RETURN", "WITH", "FINISH"];
307
308fn collect_system_offenders(clauses: &[Clause], out: &mut Vec<&'static str>) {
309    // A RETURN/WITH/FINISH is only allowed as the tail of a SHOW or a
310    // standalone procedure call in the same query part. The anchor set is
311    // encoded ONCE: both `has_show_or_call` and `allowed` read
312    // `is_system_head`, so the two can never drift apart. `Use` is
313    // deliberately absent — it is allowed on `system` but does not anchor
314    // a tail.
315    let has_show_or_call = clauses.iter().any(is_system_head);
316    let is_tail = |clause: &Clause| SYSTEM_TAIL_KEYWORDS.contains(&ir_clause_keyword(clause));
317    let allowed = |clause: &Clause| {
318        is_system_head(clause)
319            || matches!(clause, Clause::Use { .. })
320            || (is_tail(clause) && has_show_or_call)
321    };
322    // CE lists only the clause kinds outside its supported
323    // CALL/YIELD/RETURN structure: `MATCH (n) RETURN count(n)` reports
324    // `MATCH`, not `MATCH, RETURN` (testdata/ce-errors/neo4j-ce.json
325    // `system_data_clause`). A lone tail offender (`RETURN 1`) still
326    // reports itself.
327    let (non_tail, tail): (Vec<&'static str>, Vec<&'static str>) = clauses
328        .iter()
329        .filter(|clause| !allowed(clause))
330        .map(ir_clause_keyword)
331        .partition(|name| !SYSTEM_TAIL_KEYWORDS.contains(name));
332    let part_offenders = if non_tail.is_empty() { tail } else { non_tail };
333    for name in part_offenders {
334        if !out.contains(&name) {
335            out.push(name);
336        }
337    }
338}
339
340/// ADR-0116 §4's whitelist for a `system` query part: every catalog command —
341/// the SHOW family and `TERMINATE TRANSACTIONS`, whose statement result is
342/// their projected catalog rows — plus `ALTER DATABASE`, the one §2 command
343/// that is not a catalog clause. (The §2 set proper is `ShowDatabases |
344/// AlterDatabase`; `TERMINATE TRANSACTIONS` is admitted here, not there.)
345///
346/// Derived from the one [`is_catalog_clause`] classification rather than
347/// re-listed: the hand-written enumeration this replaces had drifted from
348/// it, which is why `TERMINATE TRANSACTIONS` was missing and the command was
349/// rejected on `system` while its `SHOW` sibling ran.
350///
351/// [`is_catalog_clause`]: relate_front::show_columns::is_catalog_clause
352fn catalog_allowed_on_system(command: &relate_parser::Clause) -> bool {
353    relate_front::show_columns::is_catalog_clause(command)
354        || matches!(command, relate_parser::Clause::AlterDatabase(_))
355}
356
357/// The clauses a `system` query part treats as its SHOW head: every catalog
358/// command the namespace admits, plus `SHOW INDEXES` (its own IR variant).
359/// The one predicate both the §4 valid-head set (`collect_system_offenders`,
360/// which ORs in `Call`) and `composed_system_offence`'s composition
361/// test read.
362fn is_system_show(clause: &Clause) -> bool {
363    match clause {
364        Clause::Catalog(command) => catalog_allowed_on_system(command.as_ref()),
365        Clause::ShowIndexes => true,
366        _ => false,
367    }
368}
369
370/// The clauses that anchor a `system` query part: every SHOW head
371/// ([`is_system_show`]) plus a standalone procedure `CALL`. The one anchor
372/// predicate the §4 whitelist (`collect_system_offenders`) and the
373/// composition count ([`part_offence`]) both read, so the two can never
374/// drift apart.
375fn is_system_head(clause: &Clause) -> bool {
376    is_system_show(clause) || matches!(clause, Clause::Call { .. })
377}
378
379/// ADR-0116 §4: the clause kind CE forbids in a query part that composes a
380/// SHOW command on the `system` namespace — `WITH`, the one tail clause the
381/// §4 whitelist (`collect_system_offenders`) still allows after a SHOW's
382/// `YIELD`. The composition test is [`is_system_show`], the same predicate
383/// the whitelist's head set reads. Live CE 2026.09/2026.10 rejects the
384/// composed command with
385/// `The following clauses are not allowed on a system database: WITH.`
386/// (GQLSTATUS 42NA9) for both the `… YIELD … WITH …` and the
387/// `WITH … <command> …` spelling (position within the part is not part of
388/// the rule); the other §4 offenders keep CE's 42N17 text. Scope is every
389/// catalog command the `system` namespace admits (`SHOW PROCEDURES`,
390/// `SHOW FUNCTIONS`, `SHOW SETTINGS`, `SHOW CURRENT GRAPH TYPE`,
391/// `SHOW TRANSACTIONS`, …), not only the §2 administration commands.
392/// `SHOW CURRENT GRAPH TYPE` beside another command, and a `CALL` beside a
393/// per-database schema catalog (`SHOW INDEXES`, `SHOW CONSTRAINTS`), are
394/// the further offenders ([`part_offence`] orders the rules). Returns the
395/// first offending part's [`SystemComposition`], or `None` when no part
396/// offends.
397///
398/// The caller applies this only under `Namespace::System`; off-system
399/// namespaces compose `SHOW … WITH … RETURN` freely.
400///
401/// The engine's 42N17 text still lists an `UNWIND`/`MATCH` tail after a
402/// SHOW's `YIELD` (the whitelist above rejects it); live CE words those
403/// with this family's text instead — same outcome, different message,
404/// recorded in ADR-0116 §4's Later references.
405pub fn composed_system_offence(plan: &LogicalPlan) -> Option<SystemComposition> {
406    plan.parts().find_map(part_offence)
407}
408
409/// What a `system` query part is rejected for. The gate's ordering
410/// ([`part_offence`] orders the first three): a `WITH` around a SHOW takes
411/// the 42NA9 text, then `SHOW CURRENT GRAPH TYPE` beside another command
412/// takes its 42001 `NotAllowedOnSystemDatabase` text, then a `CALL` beside a
413/// schema catalog takes 42NA9 again, and only a part with none of these
414/// falls through to the 42N17 whitelist.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum SystemComposition {
417    /// CE's 42NA9 clauses-not-allowed rejection, naming the offending
418    /// clause's keyword.
419    ClausesNotAllowed(&'static str),
420    /// `SHOW CURRENT GRAPH TYPE` beside another command: the
421    /// `NotAllowedOnSystemDatabase` clause composition (42001, the syntax
422    /// class the live corpus pins).
423    GraphTypeNotAlone,
424}
425
426/// The offence one `system` query part is rejected for, by explicit rule
427/// priority (the first rule that finds an offender wins): a `WITH` around a
428/// SHOW; `SHOW CURRENT GRAPH TYPE` beside any other command or `CALL` (it
429/// describes one graph's type, which the `system` database has none of, so
430/// it runs there alone — live corpus `CombineMultipleCommands`, 42001); a
431/// `CALL` beside a per-database schema catalog (`SHOW INDEXES`/`SHOW
432/// CONSTRAINTS`: the `system` database has no graph to list, and CE's
433/// planner splits the call from the schema command with the same 42NA9
434/// family), the offender being the catalog command. A part that composes no
435/// SHOW has no offence. The SHOW-only schema-catalog composition is the
436/// front end's own rule and never reaches here.
437fn part_offence(clauses: &[Clause]) -> Option<SystemComposition> {
438    if !clauses.iter().any(is_system_show) {
439        return None;
440    }
441    let is_call = |clause: &Clause| matches!(clause, Clause::Call { .. });
442    let commands = clauses
443        .iter()
444        .filter(|clause| is_system_head(clause))
445        .count();
446    let clauses_not_allowed =
447        |clause: &Clause| SystemComposition::ClausesNotAllowed(ir_clause_keyword(clause));
448    clauses
449        .iter()
450        .find(|clause| matches!(clause, Clause::With { .. }))
451        .map(clauses_not_allowed)
452        .or_else(|| {
453            (commands > 1 && clauses.iter().any(is_show_current_graph_type))
454                .then_some(SystemComposition::GraphTypeNotAlone)
455        })
456        .or_else(|| {
457            clauses
458                .iter()
459                .any(is_call)
460                .then(|| clauses.iter().find(|clause| is_graph_schema_show(clause)))
461                .flatten()
462                .map(clauses_not_allowed)
463        })
464}
465
466/// Whether a clause is `SHOW CURRENT GRAPH TYPE` — the one graph-type
467/// spelling the live corpus pins as running alone on `system` (plain `SHOW
468/// GRAPH TYPE` takes no `YIELD`, so it cannot be composed at all).
469fn is_show_current_graph_type(clause: &Clause) -> bool {
470    matches!(
471        clause,
472        Clause::Catalog(command)
473            if matches!(command.as_ref(), relate_parser::Clause::ShowCurrentGraphType(_))
474    )
475}
476
477/// Whether a clause is one of the two per-database schema catalogs
478/// (`SHOW INDEXES`, `SHOW CONSTRAINTS`): the IR's own `ShowIndexes` arm plus
479/// the front end's one classification
480/// (`relate_front::show_columns::is_graph_schema_catalog`) for the
481/// passed-through parser clauses — the row answer is not re-listed here.
482fn is_graph_schema_show(clause: &Clause) -> bool {
483    match clause {
484        Clause::ShowIndexes => true,
485        Clause::Catalog(command) => {
486            relate_front::show_columns::is_graph_schema_catalog(command.as_ref())
487        }
488        _ => false,
489    }
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495    use crate::plan_of;
496
497    #[test]
498    fn writes_classify_as_writes() {
499        for cypher in [
500            "CREATE (n)",
501            "MERGE (n:N {id: 1})",
502            "MATCH (n) SET n.x = 1",
503            "MATCH (n) DELETE n",
504            "MATCH (n) REMOVE n.x",
505            "CREATE INDEX i FOR (n:N) ON (n.p)",
506            "CREATE CONSTRAINT c FOR (n:N) REQUIRE n.id IS UNIQUE",
507            "FOREACH (x IN [1] | CREATE (n))",
508        ] {
509            assert!(is_write(&plan_of(cypher)), "{cypher}");
510        }
511    }
512
513    #[test]
514    fn reads_classify_as_reads() {
515        for cypher in [
516            "RETURN 1 AS n",
517            "MATCH (n) RETURN n",
518            "SHOW INDEXES",
519            "CALL db.labels()",
520        ] {
521            assert!(!is_write(&plan_of(cypher)), "{cypher}");
522        }
523    }
524
525    #[test]
526    fn read_only_call_in_expression_subqueries_classifies_as_read() {
527        // Regression: `is_write` must not descend into expression
528        // subqueries — a read-only `CALL { … }` there is legal (plan-time
529        // validation only rejects actual writes), and classifying the
530        // statement as a write would reject a pure read on the read-only
531        // `system_ontologies` namespace and misroute it on `neo4j`.
532        for cypher in [
533            "RETURN EXISTS { CALL { RETURN 1 AS x } } AS x",
534            "RETURN COUNT { CALL { RETURN 1 AS x } } AS x",
535            "RETURN COLLECT { CALL { RETURN 1 AS x } RETURN x } AS x",
536        ] {
537            assert!(!is_write(&plan_of(cypher)), "{cypher}");
538        }
539    }
540
541    #[test]
542    fn nested_queries_recurse_through_one_predicate() {
543        // WHEN branches, ELSE bodies and NEXT tails are all recursed into
544        // by `is_write`'s shared fold (`access::plan_access`), so the one
545        // clause classification classifies them.
546        assert!(is_write(&plan_of("WHEN true THEN { CREATE (n) }")));
547        assert!(!is_write(&plan_of(
548            "WHEN true THEN { RETURN 1 AS x } ELSE { RETURN 2 AS x }"
549        )));
550        assert!(is_write(&plan_of(
551            "WHEN false THEN { MATCH (n) RETURN count(n) AS x } \
552             ELSE { CREATE (m) RETURN 0 AS x }"
553        )));
554        assert!(is_write(&plan_of("RETURN 1 AS x NEXT CREATE (n)")));
555        assert!(!is_write(&plan_of("RETURN 1 AS x UNION RETURN 2 AS x")));
556    }
557
558    #[test]
559    fn write_procedure_calls_are_found_anywhere_in_the_clause_tree() {
560        // The facade's predicate classifies `db.createLabel` as a write
561        // (it is flagged `writes` in the canonical registry); the tests
562        // here stand in with a name predicate.
563        let is_write_proc = &mut |name: &str| name == "db.createLabel";
564        for cypher in [
565            "CALL db.createLabel('X')",
566            "WHEN true THEN { CALL db.createLabel('X') }",
567            "WHEN false THEN { RETURN 1 AS x } ELSE { CALL db.createLabel('X') RETURN 1 AS x }",
568            "CALL { CALL db.createLabel('X') }",
569            // A FOREACH body admits only updating clauses, so a procedure
570            // call cannot appear there (42I01, live Neo4j).
571            "RETURN 1 AS x NEXT CALL db.createLabel('X')",
572        ] {
573            assert!(
574                plan_calls_write_procedure(&plan_of(cypher), is_write_proc),
575                "{cypher}"
576            );
577        }
578        // Read procedures and write-free statements still classify as reads.
579        for cypher in [
580            "CALL db.labels()",
581            "WHEN true THEN { CALL db.labels() YIELD label RETURN label }",
582            "RETURN 1 AS x",
583        ] {
584            assert!(
585                !plan_calls_write_procedure(&plan_of(cypher), is_write_proc),
586                "{cypher}"
587            );
588        }
589    }
590
591    #[test]
592    fn database_admin_commands_classify() {
593        assert!(is_database_admin_command(&plan_of("SHOW DATABASES")));
594        assert!(is_database_admin_command(&plan_of(
595            "ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25"
596        )));
597        assert!(!is_database_admin_command(&plan_of("MATCH (n) RETURN n")));
598        assert!(!is_database_admin_command(&plan_of("SHOW INDEXES")));
599        // A non-administrative clause disqualifies the statement.
600        assert!(!is_database_admin_command(&plan_of(
601            "SHOW DATABASES YIELD name RETURN name"
602        )));
603    }
604
605    /// A lowered `SHOW DATABASES` catalog clause. The front-end's
606    /// NEXT-chain validation rejects the command in a chain before
607    /// planning, so the classifier's chain inputs are assembled directly
608    /// here — this is exactly the shape the execution-phase backstop sees.
609    fn show_databases_clause() -> Clause {
610        Clause::Catalog(Box::new(relate_parser::Clause::ShowDatabases(
611            relate_parser::ShowDatabasesClause {
612                filter: relate_parser::DatabaseFilter::All,
613                yields: Default::default(),
614                where_expr: None,
615                stages: Vec::new(),
616            },
617        )))
618    }
619
620    #[test]
621    fn composed_show_databases_follows_ce() {
622        // The canonical shapes: the command alone, with a trailing RETURN
623        // over its own yielded columns, and under a leading routing `USE`
624        // run — which routes the statement but is not composition.
625        for cypher in [
626            "SHOW DATABASES",
627            "SHOW DATABASES YIELD name RETURN name",
628            "USE neo4j SHOW DATABASES",
629            "USE system SHOW DATABASES YIELD name RETURN name",
630            // The other §2 command cannot be composed at all (the front end
631            // rejects every composed form), so it never classifies here.
632            "ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25",
633            "MATCH (n) RETURN n",
634        ] {
635            assert_eq!(composed_show_databases(&plan_of(cypher)), None, "{cypher}");
636        }
637        // Composed: an intervening clause after the YIELD, a clause before
638        // the command, another catalog command ahead of it (the harness's
639        // `SHOW FUNCTIONS … SHOW DATABASES …` scenario), a UNION arm, and a
640        // NEXT stage — live 2026.10.1 rejects each with the command named.
641        for cypher in [
642            "SHOW DATABASES YIELD name WITH 1 AS n RETURN n",
643            "SHOW DATABASES YIELD name MATCH (n) RETURN n",
644            "MATCH (n) SHOW DATABASES YIELD name RETURN name",
645            "SHOW FUNCTIONS YIELD name AS function SHOW DATABASES YIELD name AS database RETURN *",
646            "UNWIND ['a'] AS name RETURN name AS x \
647             UNION SHOW DATABASES YIELD name RETURN name AS x",
648        ] {
649            assert_eq!(
650                composed_show_databases(&plan_of(cypher)),
651                Some("SHOW DATABASES"),
652                "{cypher}"
653            );
654        }
655        // Every `SHOW DATABASE[S]` spelling is refused composed, and the
656        // message carries the spelling live refuses (verified 2026.10.1).
657        for (cypher, label) in [
658            (
659                "SHOW DEFAULT DATABASE YIELD name WITH 1 AS n RETURN n",
660                "SHOW DEFAULT DATABASE",
661            ),
662            (
663                "SHOW HOME DATABASE YIELD name WITH 1 AS n RETURN n",
664                "SHOW HOME DATABASE",
665            ),
666            (
667                "SHOW DATABASE neo4j YIELD name WITH 1 AS n RETURN n",
668                "SHOW DATABASE",
669            ),
670        ] {
671            assert_eq!(
672                composed_show_databases(&plan_of(cypher)),
673                Some(label),
674                "{cypher}"
675            );
676        }
677        // The `NEXT` condition is defensive — the front-end NEXT-chain rule
678        // rejects that combination before planning — so it is pinned on a
679        // spliced plan, the way the sibling `NEXT` classifier's test does.
680        let mut chained = plan_of("RETURN 1 AS x NEXT RETURN x");
681        chained.parts[0] = vec![show_databases_clause()];
682        assert_eq!(composed_show_databases(&chained), Some("SHOW DATABASES"));
683    }
684
685    #[test]
686    fn show_databases_with_next_classifies_the_chain() {
687        // The command in the head stage.
688        let mut head = plan_of("RETURN 1 AS x NEXT RETURN x");
689        head.parts[0] = vec![show_databases_clause()];
690        assert!(is_show_databases_with_next(&head));
691
692        // The command in a NEXT stage: `parts()` spans every stage.
693        let mut tail = plan_of("RETURN 1 AS x NEXT RETURN x");
694        tail.next.as_mut().unwrap().parts[0] = vec![show_databases_clause()];
695        assert!(is_show_databases_with_next(&tail));
696
697        // SHOW DATABASES without a NEXT stage is the plain §2 command.
698        let mut plain = plan_of("RETURN 1 AS x");
699        plain.parts[0] = vec![show_databases_clause()];
700        assert!(!is_show_databases_with_next(&plain));
701
702        // ALTER DATABASE is §2 but not a SHOW DATABASES chain participant.
703        let mut alter = plan_of("ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25");
704        alter.next = Some(Box::new(plan_of("RETURN 1 AS x")));
705        assert!(!is_show_databases_with_next(&alter));
706
707        // An ordinary NEXT chain does not classify.
708        assert!(!is_show_databases_with_next(&plan_of(
709            "RETURN 1 AS x NEXT RETURN x + 1 AS y"
710        )));
711    }
712
713    #[test]
714    fn system_offender_names_follow_ce() {
715        // Data clauses offend; CE suppresses the tail when a non-tail
716        // offender is present.
717        assert_eq!(
718            unsupported_system_clause_names(&plan_of("MATCH (n) RETURN count(n) AS c")),
719            Some("MATCH".to_string())
720        );
721        // A lone tail offender still reports itself.
722        assert_eq!(
723            unsupported_system_clause_names(&plan_of("RETURN 1 AS x")),
724            Some("RETURN".to_string())
725        );
726        // Standalone procedure calls, SHOW commands and administration
727        // commands are allowed.
728        for cypher in [
729            "CALL db.labels()",
730            "CALL db.labels() YIELD label RETURN label",
731            "SHOW INDEXES",
732            "SHOW DATABASES",
733        ] {
734            assert_eq!(
735                unsupported_system_clause_names(&plan_of(cypher)),
736                None,
737                "{cypher}"
738            );
739        }
740    }
741
742    /// ADR-0116 §4: a `WITH` in a part that composes any SHOW command — the
743    /// classifier is namespace-blind (the facade gate applies it to
744    /// `system` only), and position within the part is not part of the rule
745    /// (live CE rejects the `WITH … <command> …` spelling with the same
746    /// text).
747    #[test]
748    fn composed_system_offence_flags_with_around_show_commands() {
749        for cypher in [
750            "SHOW DATABASES YIELD name AS d1 WITH 1 AS n RETURN n",
751            "USE system SHOW DATABASES YIELD name AS d1 WITH 1 AS n RETURN n",
752            "WITH 1 AS n SHOW DATABASES YIELD name RETURN name",
753            "SHOW DEFAULT DATABASE YIELD name WITH 1 AS n RETURN n",
754            "SHOW HOME DATABASE YIELD name WITH 1 AS n RETURN n",
755            "SHOW DATABASE neo4j YIELD name WITH 1 AS n RETURN n",
756            "SHOW PROCEDURES YIELD name AS p1 WITH 1 AS n RETURN n",
757            "SHOW FUNCTIONS YIELD name AS f1 WITH 1 AS n RETURN n",
758            "SHOW SETTINGS YIELD name AS s1 WITH 1 AS n RETURN n",
759            "SHOW CURRENT GRAPH TYPE YIELD specification AS spec1 WITH 1 AS n RETURN n",
760        ] {
761            assert_eq!(
762                composed_system_offence(&plan_of(cypher)),
763                Some(SystemComposition::ClausesNotAllowed("WITH")),
764                "{cypher}"
765            );
766        }
767        // No SHOW composed: the tail keeps its `WITH` composability.
768        for cypher in [
769            "CALL db.labels() YIELD label WITH 1 AS n RETURN n",
770            "WITH 1 AS n RETURN n",
771        ] {
772            assert_eq!(composed_system_offence(&plan_of(cypher)), None, "{cypher}");
773        }
774        // Administration commands without a `WITH` stay composable with
775        // their CE tails (WHERE/RETURN live in or after the command).
776        for cypher in [
777            "SHOW DATABASES",
778            "SHOW DATABASES YIELD name RETURN name",
779            "USE system SHOW DEFAULT DATABASE YIELD name AS defaultDb SHOW DATABASES YIELD name AS db, access WHERE defaultDb = db RETURN *",
780            "ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25",
781        ] {
782            assert_eq!(
783                composed_system_offence(&plan_of(cypher)),
784                None,
785                "{cypher}"
786            );
787        }
788    }
789
790    /// A procedure call composed with a per-database schema catalog is the
791    /// `system` database's 42NA9 rejection, naming the catalog command; a
792    /// call composed with a catalog the `system` database owns, and a call
793    /// alone, stay composable.
794    #[test]
795    fn composed_system_offence_flags_a_call_beside_a_schema_catalog() {
796        for (cypher, keyword) in [
797            (
798                "CALL db.labels() YIELD label SHOW CONSTRAINTS YIELD name RETURN label, name",
799                "SHOW CONSTRAINTS",
800            ),
801            (
802                "SHOW INDEXES YIELD name AS i CALL db.labels() YIELD label RETURN i, label",
803                "SHOW INDEXES",
804            ),
805        ] {
806            assert_eq!(
807                composed_system_offence(&plan_of(cypher)),
808                Some(SystemComposition::ClausesNotAllowed(keyword)),
809                "{cypher}"
810            );
811        }
812        for cypher in [
813            "CALL db.labels() YIELD label SHOW PROCEDURES YIELD name RETURN label, name",
814            "CALL db.labels() YIELD label RETURN label",
815            "SHOW CONSTRAINTS YIELD name RETURN name",
816        ] {
817            assert_eq!(composed_system_offence(&plan_of(cypher)), None, "{cypher}");
818        }
819    }
820
821    /// `SHOW CURRENT GRAPH TYPE` runs on `system` only alone: beside another
822    /// command or a `CALL` it is the graph-type offence, while a `WITH`
823    /// around it keeps the `WITH` rule's priority.
824    #[test]
825    fn composed_system_offence_keeps_a_current_graph_type_alone() {
826        for cypher in [
827            "SHOW CURRENT GRAPH TYPE YIELD specification AS s \
828             SHOW PROCEDURES YIELD name RETURN *",
829            "SHOW FUNCTIONS YIELD name AS f \
830             SHOW CURRENT GRAPH TYPE YIELD specification AS s RETURN *",
831            "SHOW CURRENT GRAPH TYPE YIELD specification AS s \
832             CALL db.labels() YIELD label RETURN *",
833        ] {
834            assert_eq!(
835                composed_system_offence(&plan_of(cypher)),
836                Some(SystemComposition::GraphTypeNotAlone),
837                "{cypher}"
838            );
839        }
840        assert_eq!(
841            composed_system_offence(&plan_of(
842                "SHOW CURRENT GRAPH TYPE YIELD specification AS s WITH 1 AS n RETURN n"
843            )),
844            Some(SystemComposition::ClausesNotAllowed("WITH")),
845        );
846        for cypher in [
847            "SHOW CURRENT GRAPH TYPE",
848            "SHOW CURRENT GRAPH TYPE YIELD specification RETURN specification",
849        ] {
850            assert_eq!(composed_system_offence(&plan_of(cypher)), None, "{cypher}");
851        }
852    }
853
854    /// ADR-0116 §2 amendment (2026-11-04): the statement-body head shape
855    /// CE's 42N79 rule guards — first clause after any leading `USE` is a
856    /// database-administration command.
857    #[test]
858    fn admin_command_heads_statement_classifies_the_head() {
859        for cypher in [
860            "SHOW DATABASES",
861            "USE system SHOW DATABASES",
862            "USE neo4j SHOW DATABASES",
863            "USE neo4j SHOW DEFAULT DATABASE",
864            "USE neo4j SHOW HOME DATABASE",
865            "USE neo4j SHOW DATABASE neo4j",
866            "USE neo4j ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 5",
867            "USE neo4j SHOW DATABASES YIELD name RETURN name",
868            // A UNION arm's head counts through the statement's own head
869            // part (live CE 2026.09: 42N79 for this shape).
870            "USE neo4j SHOW DATABASES YIELD name AS a RETURN a UNION SHOW DATABASES YIELD name AS a RETURN a",
871        ] {
872            assert!(
873                admin_command_heads_statement(&plan_of(cypher)),
874                "{cypher}"
875            );
876        }
877        for cypher in [
878            "MATCH (n) RETURN n",
879            // A command later in the body is not headed: the 42N79 gate
880            // passes it to the namespace gates, where off-system it is the
881            // composed-form rejection (ADR-0590, live 2026.10.1).
882            "USE neo4j MATCH (n) SHOW DATABASES YIELD name RETURN name",
883            // A leading WITH heads the body instead — same outcome, the
884            // other rule.
885            "USE neo4j WITH 1 AS n SHOW DATABASES YIELD name RETURN name",
886            "SHOW INDEXES",
887        ] {
888            assert!(!admin_command_heads_statement(&plan_of(cypher)), "{cypher}");
889        }
890    }
891}