1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//! The EXISTS/COUNT/COLLECT expression-subquery evaluators (the eval
//! layer's `crate::exec::eval_*_query` entry points, re-exported there):
//! the nested statement context, the LABS-193 existence probes, and the
//! three subquery engines.
use std::collections::BTreeMap;
use relate_core::{Error, Result, Value};
use relate_error::{ErrorKind, COUNT_UNION_MIX_MESSAGE, COUNT_UNION_OMITTED_MESSAGE};
use relate_ir::{Clause, Query};
use super::call::execute_query_seeded;
use super::dispatch::run_nested_clauses;
use super::exists_probe;
use super::mutates_store;
use super::scope::nested_seed_row;
use super::QueryResult;
use crate::ctx::QueryCtx;
use crate::overlay::ExecGraph;
use crate::row::Row;
/// The one fold over a nested pass's `(rows, result)` pair: the rows the
/// pass produced — the concluding result's rows when the body ended in a
/// RETURN, the driving rows otherwise. Both expression-subquery consumers
/// of [`run_nested_clauses`] (the EXISTS existence test and the
/// COUNT-omitted-RETURN count) ask exactly this, so the fold is spelled
/// once here instead of per site.
fn nested_row_count(rows: &[Row], last: &Option<QueryResult>) -> usize {
last.as_ref()
.map(|result| result.rows.len())
.unwrap_or(rows.len())
}
/// The one nested-body preparation the three expression-subquery engines
/// share: strip the enclosing clause engine's internal columns off the
/// seed row (the body's importing scope), rewrite the body so those
/// imports persist through its `WITH`s, and build the nested statement
/// context — a fresh context
/// per ADR-0344 phase 2 (no statement text: a `SHOW TRANSACTIONS` buried
/// in an expression subquery reports an empty `currentQuery`; the
/// version inherited from the enclosing statement per CIP-150 unless
/// the body carries its own preamble; the PROFILE facts never cross the
/// boundary, the clause engine running at the explicit `None` site).
/// The budget never rode the context (ADR-0395): every nested entry
/// ticks the view-owned counter at the engine entries, so a fresh
/// context cannot reset it.
///
/// The seed row is returned because the body must run on the stripped
/// row, not the caller's: a `__`-prefixed column left on it would be
/// imported as a persistent binding and read by the body's projection as
/// its own state (`nested_seed_row`).
///
/// An expression subquery imports the enclosing scope implicitly, and the
/// persistent-import rewrite is what keeps an imported name a grouping key
/// of an aggregating `WITH` (`Collect/Count/ExistsExpression` "Should not
/// use outer scope variables as grouping variables in aggregations
/// dependency": an emptied input must yield no rows, not the identity
/// row). A `CALL` subquery's explicit import is a different contract —
/// `call` carries it as a live scope, not as `WITH` items — so this
/// rewrite stays on the expression-subquery path only.
fn nested_body(
graph: &ExecGraph<'_>,
query: &Query,
outer: &Row,
) -> (Query, QueryCtx<'static>, Row) {
let seed = nested_seed_row(graph, outer);
let imported: Vec<String> = seed.keys().cloned().collect();
let query = relate_planner::query_with_persistent_imports(query, &imported);
let qctx = QueryCtx::new("");
(query, qctx, seed)
}
/// Existence fast path for [`eval_exists_query`]: the query-shape gate of
/// the LABS-193 probe family — one part, no UNION, no NEXT. The
/// clause-level ladder (the endpoint probe for a sole single-pattern
/// WHERE-less plain MATCH, then the depth-first walk) is owned by
/// `exists_probe::probe_multi_pattern_exists`; a body the ladder declines
/// returns `Ok(None)` and runs the engine.
fn exists_pattern_probe(
graph: &ExecGraph<'_>,
row: &Row,
query: &Query,
params: &BTreeMap<String, Value>,
) -> Result<Option<bool>> {
if !query.is_single_flat_part() {
return Ok(None);
}
exists_probe::probe_multi_pattern_exists(graph, row, &query.parts[0].clauses, params)
}
pub(crate) fn eval_exists_query(
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
query: &Query,
) -> Result<Value> {
let (query, qctx, seed) = nested_body(graph, query, row);
// LABS-193: a pattern-only body between row-bound nodes answers
// existence without running the subquery engine — and never ticks
// the budget (ADR-0395).
// The body gate asks the mutation question the composition rule is
// about — a catalog DDL command and a writes-flagged procedure count
// here even though the read dispatcher admits their clause shapes.
// One static admission check for the whole body, before the probe and
// the per-part loop: the rule is a composition fact of the statement,
// not a per-part decision the loop's short-circuits can skip. The
// canonical query walk covers every `NEXT` stage too.
if relate_planner::query_any_clause(&query, &mut mutates_store) {
return Err(Error::syntax(
"InvalidClauseComposition: writes are not allowed in EXISTS { }",
));
}
if let Some(hit) = exists_pattern_probe(graph, &seed, &query, params)? {
return Ok(Value::Bool(hit));
}
// A `NEXT` chain is one pipeline: existence is decided on its final
// stage's rows, so hand the whole query to the seeded statement engine
// (the COUNT path's entry) instead of testing the first stage's parts
// (REL8-2028).
if query.next.is_some() {
let result = execute_query_seeded(graph, &query, params, vec![seed], qctx)?;
return Ok(Value::Bool(!result.rows.is_empty()));
}
for part in &query.parts {
// The subquery's ctx (subquery_qctx) is the canonical nested
// context: nested clauses are not the statement's operators.
// ADR-0395: the clause-engine pass — one per part per outer row.
let (rows, last) =
run_nested_clauses(graph, &part.clauses, params, vec![seed.clone()], qctx)?;
if nested_row_count(&rows, &last) > 0 {
return Ok(Value::Bool(true));
}
}
Ok(Value::Bool(false))
}
/// Whether a UNION part explicitly projects a result: a direct trailing
/// `RETURN`, or a sole CIP-135 conditional part whose branch bodies do (a
/// conditional's own clause list carries no `Return`). The parser's
/// `branch_shape` owns the same classification for parsed text; this
/// is the executor's defense-in-depth spelling for callers that bypass it.
fn part_explicitly_returns(clauses: &[Clause]) -> bool {
if let [Clause::Conditional {
branches,
else_query,
}] = clauses
{
let inner = branches
.first()
.map(|(_, query)| query)
.or(else_query.as_deref());
return inner.is_some_and(|query| {
query
.parts
.first()
.is_some_and(|part| part_explicitly_returns(&part.clauses))
});
}
matches!(clauses.last(), Some(Clause::Return { .. }))
}
pub(crate) fn eval_count_query(
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
query: &Query,
) -> Result<Value> {
let (query, qctx, seed) = nested_body(graph, query, row);
// The parts' explicit-vs-omitted RETURN classification as one count:
// some-but-not-all is the mix error, zero is the omitted-RETURN path,
// and every other count takes the seeded statement engine below. Both
// compositions are rejected before this per-row scan ever runs for
// parsed text — the parser's COUNT-site check
// (`check_subquery_union_consistency`) first, then the front's
// validate battery (`validate_count_subquery_union_shapes`, the
// statically decidable home of the rules, raising these identical
// messages); these scans are defense-in-depth for callers that bypass
// validation (a hand-built query, a future front gap).
let explicit = query
.parts
.iter()
.filter(|part| part_explicitly_returns(&part.clauses))
.count();
if explicit > 0 && explicit < query.parts.len() {
return Err(Error::syntax(format!(
"{}: {COUNT_UNION_MIX_MESSAGE}",
ErrorKind::DifferentColumnsInUnion.as_str()
)));
}
if explicit == 0 {
if query.union_all.iter().any(|all| !*all) {
return Err(Error::syntax(format!(
"{}: {COUNT_UNION_OMITTED_MESSAGE}",
ErrorKind::DifferentColumnsInUnion.as_str()
)));
}
// A `NEXT` chain (REL8-2028): the omitted-RETURN count is the FINAL
// stage's row count, so a chained body takes the seeded engine
// below instead of the first stage's per-part pass.
if query.next.is_none() {
let mut count = 0i64;
for part in &query.parts {
// ADR-0395: the omitted-RETURN path runs the clause engine
// directly — one pass per part per outer row (the RETURN path
// below ticks inside its seeded statement entry).
let (rows, last) =
run_nested_clauses(graph, &part.clauses, params, vec![seed.clone()], qctx)?;
count += nested_row_count(&rows, &last) as i64;
}
return Ok(Value::Int(count));
}
}
let result = execute_query_seeded(graph, &query, params, vec![seed], qctx)?;
Ok(Value::Int(result.rows.len() as i64))
}
pub(crate) fn eval_collect_query(
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
query: &Query,
) -> Result<Value> {
let (query, qctx, seed) = nested_body(graph, query, row);
let result = execute_query_seeded(graph, &query, params, vec![seed], qctx)?;
if result.columns.len() != 1 {
return Err(Error::syntax(
"CollectExpressionMustReturnSingleColumn: COLLECT { } requires one column",
));
}
// ADR-0462: `COLLECT { … }` is a dynamic container construction — a
// chained `WITH COLLECT { … } AS a` adds one level per clause and must
// hit the checked seam like every other constructor.
Value::checked_list(
result
.rows
.into_iter()
// The single-column guard above makes every row exactly one
// value (the result columns' invariant) — a miss is internal
// corruption, not a null to smuggle into the list.
.map(|row| {
row.into_iter()
.next()
.expect("QueryResult rows carry one value per column")
})
.collect::<Vec<_>>(),
)
}