Skip to main content

relate_planner/
query_type.rs

1//! The statement query-type classifier: Neo4j Query API v2 `queryType`
2//! values (`r` / `w` / `rw` / `s`) computed from a [`LogicalPlan`].
3//!
4//! The classifier is a projection of the one shared clause fold
5//! ([`crate::access::plan_access`]) — the same traversal and clause
6//! classification the ADR-0116 §4 namespace write gate
7//! ([`crate::namespaces::is_write`]) uses — plus the full-tree
8//! write-procedure sweep ([`crate::namespaces::plan_calls_write_procedure`])
9//! and the statement's returned columns ([`crate::plan_output_names`],
10//! ADR-0319), so it cannot drift from the namespace gate or from the
11//! columns every surface announces. The schema-vs-write clause split
12//! lives in [`crate::clause_kind::clause_class`].
13
14use std::fmt;
15
16use crate::LogicalPlan;
17
18/// Neo4j Query API v2 `queryType` of a statement.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum QueryType {
21    /// Read-only (`r`): no write and no schema clause — MATCH / OPTIONAL
22    /// MATCH / RETURN / WITH / UNWIND / SHOW, CALL of a read procedure,
23    /// USE, FINISH, …
24    Read,
25    /// A write with no returned columns (`w`): CREATE / MERGE / DELETE /
26    /// SET / REMOVE / FOREACH / LOAD CSV without a RETURN, `MATCH … SET`,
27    /// `MATCH … DETACH DELETE`, CALL of a writes-flagged procedure, …
28    Write,
29    /// A write with returned columns (`rw`): `CREATE (n) RETURN n`,
30    /// `MATCH … SET … RETURN …`, a UNION or NEXT chain that writes and
31    /// ends in a RETURN, …
32    ReadWrite,
33    /// Schema commands (`s`): CREATE/DROP INDEX, CREATE/DROP CONSTRAINT.
34    Schema,
35}
36
37impl QueryType {
38    /// The Neo4j Query API v2 `queryType` string: `"r"`, `"w"`, `"rw"` or
39    /// `"s"`.
40    pub fn as_str(self) -> &'static str {
41        match self {
42            QueryType::Read => "r",
43            QueryType::Write => "w",
44            QueryType::ReadWrite => "rw",
45            QueryType::Schema => "s",
46        }
47    }
48}
49
50impl fmt::Display for QueryType {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.write_str(self.as_str())
53    }
54}
55
56/// Classify a planned statement into its Neo4j Query API v2 `queryType`.
57///
58/// `is_write_procedure` classifies `CALL` targets (user-registered
59/// procedures and the built-ins flagged `writes` in the executor's
60/// canonical signature registry, per ADR-0116 §4); the facade supplies it
61/// because the procedure registry lives in the executor, which depends on
62/// this crate (never the reverse) — the same threading
63/// [`crate::namespaces::plan_calls_write_procedure`] uses.
64///
65/// Classification rules (ADR-0332, superseding ADR-0162 item 2's
66/// clause-presence split of `w` vs `rw`):
67///
68/// - No write and no schema clause → [`QueryType::Read`] (`r`).
69/// - Schema clauses with no data clause alongside →
70///   [`QueryType::Schema`] (`s`).
71/// - A write with no returned columns → [`QueryType::Write`] (`w`):
72///   `CREATE (n)`, `MATCH … SET`, `MATCH … DETACH DELETE`, without RETURN.
73/// - A write with returned columns → [`QueryType::ReadWrite`] (`rw`):
74///   `CREATE (n) RETURN n`, `MATCH … SET … RETURN …`.
75///
76/// "Returned columns" is the planned statement's output names
77/// ([`crate::plan_output_names`], ADR-0319) — the same column fact every
78/// surface announces — so a MATCH that only feeds a SET contributes no
79/// columns and the statement classifies `w`, exactly as latest Neo4j
80/// (2026.09.0) does. A planned statement passed the UNION
81/// column-agreement check at validation, so its output names always
82/// derive (`plan_output_names`' `Err` arm is that check's error).
83///
84/// The write/schema flags still come from the shared fold
85/// ([`crate::access::plan_access`]): it accumulates read/write/schema
86/// flags over each part's TOP-LEVEL clauses (UNION arms are parts; NEXT
87/// stages recurse), with `WHEN`/`ELSE` branch bodies recursed into — the
88/// same coverage as the ADR-0116 §4 namespace write gate. Schema clauses
89/// (CREATE/DROP INDEX, CREATE/DROP CONSTRAINT, in either their IR or
90/// `Catalog` form) accumulate the fold's schema flag via
91/// [`crate::clause_kind::clause_class`], never its write flag. A `CALL {
92/// … }` subquery counts as a write outright and `FOREACH` bodies via the
93/// shared clause classification, exactly as the namespace gate classifies
94/// them (conservative; see [`crate::access`]). A `CALL` of a
95/// writes-flagged procedure is a write: the fold's `CALL` arm sets both
96/// bits from one predicate call (read iff NOT writes-flagged), and
97/// [`crate::namespaces::plan_calls_write_procedure`]'s full-tree sweep,
98/// OR'd into the write flag here, covers the nested positions the fold
99/// skips (`CALL { … }` bodies, expression subqueries) — a bare one has no
100/// plan-time output names, so it stays `w`.
101///
102/// Mixed schema+data: a statement whose schema clauses have NO data clause
103/// alongside them is [`QueryType::Schema`]. Plan-time validation forbids
104/// schema clauses sharing a part or a UNION with data clauses, so a mix is
105/// reachable only across NEXT stages; there the schema clause counts as a
106/// WRITE (the statement still mutates the catalog, so it must not report
107/// `r`), and the returned-columns split applies to it like any other
108/// write.
109pub fn query_type(
110    plan: &LogicalPlan,
111    is_write_procedure: &mut impl FnMut(&str) -> bool,
112) -> QueryType {
113    let mut access = crate::access::plan_access(plan, is_write_procedure);
114    access.write |= crate::namespaces::plan_calls_write_procedure(plan, is_write_procedure);
115    if access.schema && !access.read && !access.write {
116        return QueryType::Schema;
117    }
118    // A schema clause mixed with data clauses (NEXT stages only — see
119    // above) counts as a write: the statement mutates the catalog, so it
120    // must not classify as a read.
121    let returns_columns = !crate::plan_output_names_expect(plan).is_empty();
122    match (returns_columns, access.is_write()) {
123        (_, false) => QueryType::Read,
124        (false, true) => QueryType::Write,
125        (true, true) => QueryType::ReadWrite,
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use crate::{plan_of, rejection};
133
134    fn type_of(cypher: &str) -> QueryType {
135        query_type(&plan_of(cypher), &mut |_| false)
136    }
137
138    #[test]
139    fn query_type_strings_match_query_api_v2() {
140        assert_eq!(QueryType::Read.as_str(), "r");
141        assert_eq!(QueryType::Write.as_str(), "w");
142        assert_eq!(QueryType::ReadWrite.as_str(), "rw");
143        assert_eq!(QueryType::Schema.as_str(), "s");
144        assert_eq!(QueryType::ReadWrite.to_string(), "rw");
145    }
146
147    #[test]
148    fn reads_classify_as_r() {
149        for cypher in [
150            "RETURN 1 AS n",
151            "MATCH (n) RETURN n",
152            "MATCH (n) WITH n UNWIND [1, 2] AS x RETURN n, x",
153            "SHOW INDEXES",
154            "SHOW DATABASES",
155            "CALL db.labels()",
156            "USE neo4j MATCH (n) RETURN n",
157            "RETURN 1 AS x UNION RETURN 2 AS x",
158            "WHEN true THEN { RETURN 1 AS x } ELSE { RETURN 2 AS x }",
159        ] {
160            assert_eq!(type_of(cypher), QueryType::Read, "{cypher}");
161        }
162    }
163
164    #[test]
165    fn writes_without_returned_columns_classify_as_w() {
166        // ADR-0332: the write's returned columns — not the read clauses it
167        // consumes — split `w` from `rw`. A MATCH that only feeds a SET,
168        // DELETE or REMOVE returns no columns, exactly like latest Neo4j
169        // (2026.09.0, the LABS-323 driver findings D-53/D-54).
170        for cypher in [
171            "CREATE (n)",
172            "MERGE (n:N {id: 1})",
173            "MATCH (n) SET n.x = 1",
174            "MATCH (n) DETACH DELETE n",
175            "MATCH (n) DELETE n",
176            "MATCH (n) REMOVE n.x",
177            "FOREACH (x IN [1] | CREATE (n))",
178            // The shared write list counts LOAD CSV as a write outright.
179            "LOAD CSV FROM 'file:///f.csv' AS row CREATE (n)",
180            // Conservative, matching the namespace write gate: a top-level
181            // CALL { … } counts as a write outright.
182            "CALL { CREATE (n) }",
183            "WHEN true THEN { CREATE (n) }",
184            // A NEXT chain whose final stage writes and returns nothing.
185            "RETURN 1 AS x NEXT CREATE (n)",
186        ] {
187            assert_eq!(type_of(cypher), QueryType::Write, "{cypher}");
188        }
189    }
190
191    #[test]
192    fn writes_with_returned_columns_classify_as_rw() {
193        for cypher in [
194            "CREATE (n) RETURN n",
195            "MATCH (n) SET n.x = 1 RETURN n",
196            "MATCH (n) DETACH DELETE n RETURN n",
197            "MATCH (n) REMOVE n.x RETURN n",
198            // UNION of a read and a write part, both returning columns.
199            "RETURN 1 AS x UNION CREATE (n) RETURN 1 AS x",
200            // LOAD CSV is on the shared write list; the RETURN exports the
201            // loaded row.
202            "LOAD CSV FROM 'file:///f.csv' AS row RETURN row",
203            // A top-level CALL { … } is a write outright even when its body
204            // only reads; the RETURN tail returns columns.
205            "CALL { RETURN 1 AS x } RETURN x",
206            // A MERGE pattern's variables are returned columns for
207            // `RETURN *`, exactly like CREATE's.
208            "MERGE (n:N {id: 1}) RETURN *",
209        ] {
210            assert_eq!(type_of(cypher), QueryType::ReadWrite, "{cypher}");
211        }
212    }
213
214    #[test]
215    fn schema_commands_classify_as_s() {
216        for cypher in [
217            "CREATE INDEX i FOR (n:N) ON (n.p)",
218            "DROP INDEX i",
219            "CREATE CONSTRAINT c FOR (n:N) REQUIRE n.id IS UNIQUE",
220            "DROP CONSTRAINT c",
221            // Graph-type DDL is catalog schema, not a data write (ADR-0447):
222            // a read tool refuses it, the DDL tool admits it.
223            "CREATE GRAPH TYPE g { (:A => {id :: INTEGER IS KEY}) }",
224            "ALTER CURRENT GRAPH TYPE SET GRAPH TYPE g",
225        ] {
226            assert_eq!(type_of(cypher), QueryType::Schema, "{cypher}");
227        }
228    }
229
230    #[test]
231    fn schema_mixed_with_data_counts_the_schema_clause_as_a_write() {
232        // Reachable only across NEXT stages: plan-time validation forbids
233        // schema clauses sharing a part or a UNION with data clauses. The
234        // returned-columns split then applies to it like any other write.
235        assert_eq!(
236            type_of("CREATE INDEX i FOR (n:N) ON (n.p) NEXT MATCH (n) RETURN n"),
237            QueryType::ReadWrite
238        );
239        assert_eq!(
240            type_of("CREATE INDEX i FOR (n:N) ON (n.p) NEXT CREATE (n)"),
241            QueryType::Write
242        );
243    }
244
245    #[test]
246    fn writes_flagged_procedures_classify_as_writes() {
247        let is_write_proc = &mut |name: &str| name == "db.createLabel";
248        // A writes-flagged procedure is a write wherever it nests; the
249        // built-ins are void, and a bare CALL contributes no plan-time
250        // output names (default yields are runtime knowledge), so a bare
251        // one classifies w (ADR-0332).
252        for cypher in [
253            "CALL db.createLabel('X')",
254            "MATCH (n) RETURN n AS x NEXT CALL db.createLabel('X')",
255        ] {
256            assert_eq!(
257                query_type(&plan_of(cypher), is_write_proc),
258                QueryType::Write,
259                "{cypher}"
260            );
261        }
262        // With returned columns around it, the statement is rw, wherever
263        // in the statement the call nests.
264        for cypher in [
265            "WHEN true THEN { CALL db.createLabel('X') RETURN 1 AS x }",
266            "CALL { CALL db.createLabel('X') RETURN 1 AS x } RETURN x",
267        ] {
268            assert_eq!(
269                query_type(&plan_of(cypher), is_write_proc),
270                QueryType::ReadWrite,
271                "{cypher}"
272            );
273        }
274        // Read procedures stay reads under the same predicate.
275        assert_eq!(
276            query_type(&plan_of("CALL db.labels()"), is_write_proc),
277            QueryType::Read
278        );
279    }
280
281    /// LABS-888: a read statement whose MATCH is followed by an OPTIONAL
282    /// MATCH classifies `r` — OPTIONAL MATCH mutates nothing, so it
283    /// contributes exactly the read its plain MATCH counterpart does, at
284    /// every nesting position the fold walks (top level, a UNION arm, a
285    /// NEXT stage, a WHEN branch). The EXPLAIN-wrapped form is the exact
286    /// input the MCP/extension `read_cypher` gate classifies, so it is
287    /// pinned too. A read with no RETURN is the FINISH-terminated form: a
288    /// MATCH-concluding statement is a composition rejection (below), so
289    /// "no RETURN" reaches the classifier only via FINISH.
290    #[test]
291    fn optional_match_reads_classify_as_r() {
292        for cypher in [
293            // The LABS-888 repro, bare and as the read gate sees it.
294            "MATCH (a:Room) OPTIONAL MATCH (a)-[:NORTH]->(b) RETURN a.name, b.name",
295            "EXPLAIN MATCH (a:Room) OPTIONAL MATCH (a)-[:NORTH]->(b) RETURN a.name, b.name",
296            // The plain-MATCH control: same class, no OPTIONAL.
297            "MATCH (a:Room)-[:NORTH]->(b) RETURN a.name, b.name",
298            "OPTIONAL MATCH (n) RETURN n",
299            "OPTIONAL MATCH (a) RETURN *",
300            // No RETURN: no returned columns, still a read.
301            "MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) FINISH",
302            "OPTIONAL MATCH (n) FINISH",
303            // Every nesting position the fold walks.
304            "MATCH (a) RETURN a AS x UNION MATCH (b) OPTIONAL MATCH (b)-[:R]->(c) RETURN b AS x",
305            "MATCH (a) RETURN a NEXT MATCH (b) OPTIONAL MATCH (b)-[:R]->(c) RETURN b, c",
306            "WHEN true THEN { MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) RETURN a, b }",
307        ] {
308            assert_eq!(type_of(cypher), QueryType::Read, "{cypher}");
309        }
310        // A MATCH-concluding statement is the same composition rejection
311        // with or without the OPTIONAL — the shared rule, so OPTIONAL MATCH
312        // grants no new conclusion rights.
313        assert_eq!(
314            rejection("MATCH (a) OPTIONAL MATCH (a)-[:R]->(b)"),
315            rejection("MATCH (n)")
316        );
317    }
318
319    /// LABS-888 boundary: the write clauses after an OPTIONAL MATCH keep
320    /// their own class — the OPTIONAL flag never downgrades a write.
321    #[test]
322    fn optional_match_neighbors_classify_as_writes() {
323        for cypher in [
324            "MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) SET a.x = 1",
325            "MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) CREATE (c)",
326            "MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) DELETE b",
327            "MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) DETACH DELETE b",
328        ] {
329            assert_eq!(type_of(cypher), QueryType::Write, "{cypher}");
330        }
331        for cypher in [
332            "MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) SET a.x = 1 RETURN a",
333            "MATCH (a) OPTIONAL MATCH (a)-[:R]->(b) CREATE (c) RETURN c",
334        ] {
335            assert_eq!(type_of(cypher), QueryType::ReadWrite, "{cypher}");
336        }
337    }
338
339    /// ADR-0332 acceptance: the one statement of each kind the rule is
340    /// about, at the classifier itself — including an EXPLAIN-wrapped
341    /// write (the front-end lowers the wrapped statement, so the plan the
342    /// classifier sees is the write's, with no returned columns).
343    #[test]
344    fn the_adr0332_rule_table() {
345        assert_eq!(type_of("MATCH (n) RETURN n"), QueryType::Read);
346        assert_eq!(type_of("CREATE (n)"), QueryType::Write);
347        assert_eq!(type_of("CREATE (n) RETURN n"), QueryType::ReadWrite);
348        assert_eq!(type_of("MATCH (n) SET n.x = 1"), QueryType::Write);
349        assert_eq!(
350            type_of("MATCH (n) SET n.x = 1 RETURN n"),
351            QueryType::ReadWrite
352        );
353        assert_eq!(type_of("MATCH (n) DETACH DELETE n"), QueryType::Write);
354        assert_eq!(
355            type_of("MATCH (n) DETACH DELETE n RETURN n"),
356            QueryType::ReadWrite
357        );
358        assert_eq!(
359            type_of("CREATE INDEX i FOR (n:N) ON (n.p)"),
360            QueryType::Schema
361        );
362        assert_eq!(type_of("EXPLAIN CREATE (n)"), QueryType::Write);
363    }
364}