Skip to main content

powdb_query/executor/
prepared.rs

1//! PreparedQuery struct and related Engine methods.
2
3use crate::ast::*;
4use crate::plan::*;
5use crate::planner;
6use crate::result::{QueryError, QueryResult};
7use powdb_storage::catalog::Catalog;
8use powdb_storage::row::{ROW_MAGIC, ROW_PREFIX_SIZE};
9use powdb_storage::types::*;
10
11use super::compiled::*;
12use super::eval::*;
13use super::Engine;
14
15pub struct PreparedQuery {
16    plan_template: PlanNode,
17    /// Total number of `Expr::Literal` slots reachable from the plan.
18    /// Callers must supply exactly this many literals per execution.
19    pub param_count: usize,
20    /// Fast-path metadata for `PlanNode::Insert`. `Some` when:
21    ///   * the template is an Insert, and
22    ///   * every assignment RHS is `Expr::Literal(_)` (no computed exprs),
23    ///     which means param_count == assignments.len() and the caller's
24    ///     literal slice maps 1:1 to schema column indices.
25    ///
26    /// Mission C Phase 15: upgraded from a bare `Vec<usize>` to a
27    /// dedicated [`InsertFast`] struct so the execute path can skip the
28    /// second `catalog.schema(table)` HashMap lookup just to read
29    /// `n_cols`, and can dispatch through `get_table_mut` + `tbl.insert`
30    /// instead of going via the generic `catalog.insert` wrapper.
31    insert_fast: Option<InsertFast>,
32    /// Mission C Phase 14: fast-path metadata for point updates by primary
33    /// key — `T filter .pk = <lit> update { col := <lit> }` where `pk` is
34    /// an indexed column and `col` is fixed-size and not indexed. At
35    /// execute time we skip plan clone, substitute walk, schema re-lookup,
36    /// `resolved_assignments` + `FastPatch` + `matching_rids` Vec allocs,
37    /// and the whole `PlanNode::Update` arm. Just a btree lookup and a
38    /// byte patch.
39    update_pk_fast: Option<UpdatePkFast>,
40}
41
42/// Mission C Phase 15: precomputed insert fast-path metadata. Built once
43/// in [`Engine::prepare`] from a `PlanNode::Insert` template whose every
44/// assignment RHS is a raw literal. The execute path reads `n_cols` and
45/// `col_indices` directly — no catalog schema lookup needed.
46#[derive(Clone)]
47struct InsertFast {
48    /// Mission C Phase 18: cached slot index into `Catalog::tables`.
49    /// Resolved once at `prepare` time and stable for the lifetime of
50    /// the catalog (PowDB has no DROP TABLE). Lets the hot path dispatch
51    /// through `catalog.table_by_slot_mut(slot)` — a pure Vec index,
52    /// no hash, no bucket walk, no string compare.
53    table_slot: usize,
54    /// Schema column index for each positional literal, in the order the
55    /// caller passes them.
56    col_indices: Vec<usize>,
57    /// Total number of schema columns — the size `insert_values_scratch`
58    /// must be resized to before filling positions via `col_indices`.
59    /// Cached here so the hot loop skips `catalog.schema(table)` entirely.
60    n_cols: usize,
61}
62
63/// Mission C Phase 14: precomputed fast-path for `update_by_pk` shaped
64/// prepared queries. Built once in [`Engine::prepare`] and reused on every
65/// `execute_prepared` call.
66#[derive(Clone)]
67struct UpdatePkFast {
68    /// Mission C Phase 18: cached slot index into `Catalog::tables`.
69    /// Resolved once at `prepare` time and stable for the lifetime of
70    /// the catalog. At a 52ns total budget the swap from FxHashMap
71    /// probe to a Vec index is measurable.
72    table_slot: usize,
73    /// Name of the key column (the `.id = ?` side). We look this up in
74    /// the owning table's `indexed_cols` at execute time rather than
75    /// caching a raw `&BTree` — the engine owns the catalog and can't
76    /// hand out long-lived borrows anyway, and the n≤5 linear scan is
77    /// a handful of ns.
78    key_col: String,
79    /// Byte offset of the target fixed column in the row encoding:
80    /// `2 + bitmap_size + layout.fixed_offsets[target_col]`.
81    field_off: usize,
82    /// Byte offset of the bitmap byte containing the target column's null
83    /// bit (`2 + target_col / 8`).
84    bitmap_byte_off: usize,
85    /// Bit mask for the target column's null bit.
86    bit_mask: u8,
87    /// Type of the target fixed column — drives the literal-to-bytes
88    /// encoding at execute time.
89    target_type: TypeId,
90    /// Index into the caller's `literals` slice that holds the filter key.
91    /// Always 0 today (filter literal is visited before the assignment
92    /// RHS), but stored explicitly so the contract is obvious.
93    key_literal_idx: usize,
94    /// Index into the caller's `literals` slice that holds the new value.
95    value_literal_idx: usize,
96}
97
98impl Engine {
99    pub fn prepare(&mut self, query: &str) -> Result<PreparedQuery, QueryError> {
100        let plan = planner::plan(query).map_err(|e| QueryError::Parse(e.to_string()))?;
101        let param_count = crate::plan_cache::count_literal_slots(&plan);
102
103        // Insert fast path: if the template is Insert and every assignment
104        // RHS is a literal, resolve column indices once here and store
105        // them. execute_prepared will skip the plan-clone + substitute
106        // walk on this path.
107        //
108        // Mission C Phase 15: also cache `n_cols` and the target table
109        // name so execute_prepared doesn't need a second HashMap lookup
110        // on `self.catalog.schema(table)` just to size the scratch Vec.
111        let insert_fast = match &plan {
112            // Single-row inserts only: the byte-level fast path patches one
113            // row's worth of scratch. Multi-row `insert T {..},{..}` falls
114            // through to the generic plan path (always correct).
115            PlanNode::Insert {
116                table,
117                rows,
118                returning,
119            } if !returning
120                && rows.len() == 1
121                && rows[0].iter().all(|a| matches!(a.value, Expr::Literal(_)))
122                && param_count == rows[0].len() =>
123            {
124                let assignments = &rows[0];
125                let table_slot = self
126                    .catalog
127                    .table_slot(table)
128                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
129                let schema = &self.catalog.table_by_slot(table_slot).schema;
130                let n_cols = schema.columns.len();
131                let indices: Result<Vec<usize>, QueryError> = assignments
132                    .iter()
133                    .map(|a| {
134                        schema
135                            .column_index(&a.field)
136                            .ok_or_else(|| QueryError::ColumnNotFound {
137                                table: table.clone(),
138                                column: a.field.clone(),
139                            })
140                    })
141                    .collect();
142                Some(InsertFast {
143                    table_slot,
144                    col_indices: indices?,
145                    n_cols,
146                })
147            }
148            _ => None,
149        };
150
151        // Mission C Phase 14: update-by-pk fast path. Match on the shape
152        // planner::plan_update builds for `T filter .pk = ? update
153        // { col := ? }` — `Update { input: IndexScan(pk), assignments:
154        // [{col, Literal}] }` — and only if every precondition holds:
155        //   * `pk` is an indexed column (so the executor would take the
156        //     btree.lookup path at run time regardless)
157        //   * there's exactly one assignment
158        //   * the assigned column is fixed-size and *not* indexed (so we
159        //     don't have to maintain any secondary index on write)
160        //   * both literal slots are already `Expr::Literal` (no computed
161        //     expressions)
162        // If any of these fail we fall through to the standard substitute
163        // + execute path.
164        let update_pk_fast = Self::try_build_update_pk_fast(&self.catalog, &plan);
165
166        Ok(PreparedQuery {
167            plan_template: plan,
168            param_count,
169            insert_fast,
170            update_pk_fast,
171        })
172    }
173
174    /// Mission C Phase 14: inspect a planned tree and, if it matches the
175    /// `update_by_pk` fast-path shape, return the precomputed byte-patch
176    /// metadata. Returns `None` on any mismatch — the caller falls through
177    /// to the substitute-and-execute path, which is always correct.
178    fn try_build_update_pk_fast(catalog: &Catalog, plan: &PlanNode) -> Option<UpdatePkFast> {
179        // Top level must be `Update { input: IndexScan(...), ... }`.
180        let (table, input, assignments) = match plan {
181            // `returning` must materialize the post-update row image, which the
182            // byte-patch fast path can't produce — fall through to the generic
183            // executor arm.
184            PlanNode::Update {
185                table,
186                input,
187                assignments,
188                returning: false,
189            } => (table, input.as_ref(), assignments),
190            _ => return None,
191        };
192        // Exactly one assignment — the bench hot path and the only case
193        // where a single byte-patch covers the whole mutation.
194        if assignments.len() != 1 {
195            return None;
196        }
197        let assn = &assignments[0];
198        // Assignment RHS must be a raw literal, not a computed expr.
199        if !matches!(assn.value, Expr::Literal(_)) {
200            return None;
201        }
202        // Input must be an IndexScan on the same table with a literal key.
203        let (key_col, key_table) = match input {
204            PlanNode::IndexScan {
205                table: t,
206                column,
207                key: Expr::Literal(_),
208            } => (column.clone(), t.clone()),
209            _ => return None,
210        };
211        if &key_table != table {
212            return None;
213        }
214
215        // Look up schema + index state from the live catalog, caching
216        // the slot so the execute path skips the name probe.
217        let table_slot = catalog.table_slot(table)?;
218        let tbl = catalog.table_by_slot(table_slot);
219        let schema = &tbl.schema;
220
221        // Key column must have an index (the btree.lookup path is what
222        // makes the fast path worth building).
223        if !tbl.has_index(&key_col) {
224            return None;
225        }
226
227        // Target column must exist, be fixed-size, and NOT be indexed (so
228        // we don't have to maintain any secondary index here).
229        let target_col_idx = schema.column_index(&assn.field)?;
230        let target_type = schema.columns[target_col_idx].type_id;
231        if !is_fixed_size(target_type) {
232            return None;
233        }
234        if tbl.has_indexed_col(target_col_idx) {
235            return None;
236        }
237
238        // Precompute byte offsets from the cached row layout.
239        let layout = tbl.row_layout();
240        let fixed_off = layout.fixed_offset(target_col_idx)?;
241        let bitmap_size = layout.bitmap_size();
242        let field_off = 2 + bitmap_size + fixed_off;
243        let bitmap_byte_off = 2 + target_col_idx / 8;
244        let bit_mask = 1u8 << (target_col_idx % 8);
245
246        // Literal walk order for `Update { IndexScan(key), [{value}] }`
247        // (see `plan_cache::substitute_plan` — input first, then the
248        // assignments). The filter key is literal 0, the assignment RHS
249        // is literal 1.
250        Some(UpdatePkFast {
251            table_slot,
252            key_col,
253            field_off,
254            bitmap_byte_off,
255            bit_mask,
256            target_type,
257            key_literal_idx: 0,
258            value_literal_idx: 1,
259        })
260    }
261
262    /// Execute a [`PreparedQuery`] with the given literal values.
263    ///
264    /// The literals are substituted into a clone of the template plan in
265    /// the same deterministic walk order that [`crate::canonicalize`]
266    /// produces (filter predicate first, then projection, then assignment
267    /// RHS, and so on). Substitution errors here mean the caller passed
268    /// the wrong number of literals for this query shape.
269    pub fn execute_prepared(
270        &mut self,
271        prep: &PreparedQuery,
272        literals: &[Literal],
273    ) -> Result<QueryResult, QueryError> {
274        if literals.len() != prep.param_count {
275            return Err(QueryError::Execution(format!(
276                "prepared query expects {} literal(s), got {}",
277                prep.param_count,
278                literals.len(),
279            )));
280        }
281
282        // Mission C Phase 14: update-by-pk fast path. Skip plan clone,
283        // substitute walk, resolved_assignments, FastPatch, Vec<RowId>,
284        // RowLayout::new — straight to btree.lookup_int + byte patch.
285        // On rare mismatches (wrong literal type, index dropped after
286        // prepare) the helper returns `Ok(None)` and we fall through to
287        // the generic substitute-and-execute path below.
288        if let Some(fast) = &prep.update_pk_fast {
289            if let Some(result) = self.try_execute_update_pk_fast(fast, literals)? {
290                // Mark dependent views dirty for prepared update fast path.
291                if let PlanNode::Update { table, .. } = &prep.plan_template {
292                    self.view_registry.mark_dependents_dirty(table);
293                }
294                // Mission B (post-review): statement-boundary WAL group
295                // commit. The fast path appended an Update record but did
296                // not flush — flush it now so the executor's contract is
297                // "WAL is on disk before this returns".
298                self.catalog
299                    .commit_autocommit()
300                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
301                return Ok(result);
302            }
303        }
304
305        // Insert fast path: skip plan-clone + substitute walk + PlanNode::Insert
306        // arm's column-index resolution. Build the Row directly from the
307        // caller's literal slice using indices we resolved at prepare time.
308        // Saves ~300-500ns per insert on the bench.
309        //
310        // Mission C Phase 13: the scratch `Vec<Value>` is reused across
311        // calls — no fresh allocation per insert. We split the borrow
312        // between `self.catalog` and `self.insert_values_scratch` by
313        // moving the scratch into a local, filling it, passing to the
314        // catalog, and putting it back.
315        //
316        // Mission C Phase 15: the cached `InsertFast` carries `n_cols`
317        // and the table name, so the hot path makes exactly one catalog
318        // HashMap lookup (`get_table_mut`) and dispatches straight into
319        // `tbl.insert` — no intermediate schema lookup, no generic
320        // `Catalog::insert` wrapper.
321        if let Some(fast) = &prep.insert_fast {
322            let mut values = std::mem::take(&mut self.insert_values_scratch);
323            values.clear();
324            values.resize(fast.n_cols, Value::Empty);
325            for (pos, lit) in literals.iter().enumerate() {
326                values[fast.col_indices[pos]] = literal_value_from(lit);
327            }
328            // Mission C Phase 18: direct O(1) slot index — no
329            // catalog hash probe. Slot was resolved at prepare time.
330            // Durability fix: route through the WAL-logging `insert_by_slot`
331            // (was the raw `Table::insert`, which bypassed the WAL and lost
332            // every prepared insert on a crash).
333            let res = self
334                .catalog
335                .insert_by_slot(fast.table_slot, &values)
336                .map_err(|e| e.to_string());
337            // Clear strings before returning the scratch — don't keep
338            // dangling allocations from the previous row alive across
339            // calls. `clear()` drops the Value::Str entries.
340            values.clear();
341            self.insert_values_scratch = values;
342            res?;
343            // Mark dependent views dirty for prepared insert fast path.
344            if let PlanNode::Insert { table, .. } = &prep.plan_template {
345                self.view_registry.mark_dependents_dirty(table);
346            }
347            // Mission B (post-review): statement-boundary WAL group commit.
348            self.catalog
349                .commit_autocommit()
350                .map_err(|e| QueryError::StorageError(e.to_string()))?;
351            return Ok(QueryResult::Modified(1));
352        }
353
354        let mut plan = prep.plan_template.clone();
355        let mut idx = 0usize;
356        crate::plan_cache::substitute_plan(&mut plan, literals, &mut idx);
357        debug_assert_eq!(idx, literals.len());
358        let result = self.execute_plan(&plan);
359        // Mission B (post-review): statement-boundary WAL group commit.
360        // No-op when nothing was buffered (read-only plans).
361        self.catalog
362            .commit_autocommit()
363            .map_err(|e| QueryError::StorageError(e.to_string()))?;
364        result
365    }
366
367    /// Mission C Phase 14: point-update fast path for prepared
368    /// `T filter .pk = ? update { col := ? }` queries. The caller has
369    /// already verified this is an int-indexed pk with a fixed-size,
370    /// non-indexed target column; all we do here is pluck the two
371    /// literals out of the caller's slice, run one `btree.lookup_int`,
372    /// and patch 1–8 bytes of the row. No plan clone, no allocations.
373    ///
374    /// Returns:
375    ///   * `Ok(Some(result))` — fast path took the mutation.
376    ///   * `Ok(None)` — can't take the fast path this call (wrong
377    ///     literal type, index dropped since prepare, etc.). Caller
378    ///     falls through to the generic substitute-and-execute path.
379    ///   * `Err(_)` — real error (table gone, I/O, etc.).
380    #[inline]
381    fn try_execute_update_pk_fast(
382        &mut self,
383        fast: &UpdatePkFast,
384        literals: &[Literal],
385    ) -> Result<Option<QueryResult>, QueryError> {
386        // 1) Extract the key literal. The fast path is only built for
387        //    int key columns; any other literal type means the caller
388        //    is violating the prepared-query contract or the schema
389        //    changed — either way, fall back.
390        let key_int = match &literals[fast.key_literal_idx] {
391            Literal::Int(v) => *v,
392            _ => return Ok(None),
393        };
394
395        // 2) Encode the new value as little-endian bytes matching the
396        //    target column's fixed encoding.
397        let bytes: FixedBytes = match (fast.target_type, &literals[fast.value_literal_idx]) {
398            (TypeId::Int, Literal::Int(v)) => FixedBytes::I64(v.to_le_bytes()),
399            (TypeId::DateTime, Literal::Int(v)) => FixedBytes::I64(v.to_le_bytes()),
400            (TypeId::Float, Literal::Float(v)) => FixedBytes::F64(v.to_le_bytes()),
401            (TypeId::Bool, Literal::Bool(v)) => FixedBytes::Bool(if *v { 1 } else { 0 }),
402            // Type mismatch — fall back to the generic path for a
403            // consistent error shape.
404            _ => return Ok(None),
405        };
406
407        // 3) Look up the table + btree, do the int lookup, patch the row
408        //    in place. Phase 18: table dispatch is a direct slot index;
409        //    the btree lookup is the linear scan over `indexed_cols`.
410        //    Single btree.lookup_int + one `with_row_bytes_mut` call.
411        //    No Vec allocations at all.
412        //
413        // Mission B2: route the in-place patch through the catalog's
414        // WAL-logged wrapper so crash recovery sees the update. The
415        // extra cost is one WAL append + fsync per query — the hot
416        // loop structure is unchanged.
417        let tbl = self.catalog.table_by_slot_mut(fast.table_slot);
418        let Some(btree) = tbl.index(&fast.key_col) else {
419            // Index dropped since prepare — bail to the generic path.
420            return Ok(None);
421        };
422        let Some(rid) = btree.lookup_int(key_int) else {
423            return Ok(Some(QueryResult::Modified(0)));
424        };
425
426        let fast_table_slot = fast.table_slot;
427        let bitmap_byte_off = fast.bitmap_byte_off;
428        let bit_mask = fast.bit_mask;
429        let field_off = fast.field_off;
430        let ok = self
431            .catalog
432            .update_row_bytes_logged_by_slot(fast_table_slot, rid, |row| {
433                let base = if row.len() >= ROW_PREFIX_SIZE && &row[0..4] == ROW_MAGIC {
434                    ROW_PREFIX_SIZE
435                } else {
436                    0
437                };
438                // Idempotent null-bit clear — safe even when the column was
439                // already non-null (the overwhelmingly common case).
440                row[base + bitmap_byte_off] &= !bit_mask;
441                let field_bytes = bytes.as_slice();
442                row[base + field_off..base + field_off + field_bytes.len()]
443                    .copy_from_slice(field_bytes);
444            })
445            .map_err(|e| QueryError::StorageError(e.to_string()))?;
446
447        Ok(Some(QueryResult::Modified(if ok { 1 } else { 0 })))
448    }
449
450    /// Mission C Phase 13: moving variant of [`Engine::execute_prepared`]
451    /// for the insert fast path. Takes `literals` by mutable reference
452    /// so that each `Literal::String` can be consumed via `mem::take`
453    /// instead of cloned into a `Value::Str`. On `insert_batch_1k` that
454    /// removes three per-row heap allocations (name, status, email),
455    /// bringing the workload over the line vs SQLite's amortized
456    /// prepare+execute loop.
457    ///
458    /// The caller's `Literal::String` entries are replaced with empty
459    /// strings on successful inserts — the `literals` slice is *not*
460    /// left in a valid-for-reuse state except for `Int`/`Float`/`Bool`
461    /// values. Non-insert templates fall through to the standard
462    /// substitute-and-execute path.
463    pub fn execute_prepared_take(
464        &mut self,
465        prep: &PreparedQuery,
466        literals: &mut [Literal],
467    ) -> Result<QueryResult, QueryError> {
468        if literals.len() != prep.param_count {
469            return Err(QueryError::Execution(format!(
470                "prepared query expects {} literal(s), got {}",
471                prep.param_count,
472                literals.len(),
473            )));
474        }
475
476        if let Some(fast) = &prep.insert_fast {
477            let mut values = std::mem::take(&mut self.insert_values_scratch);
478            values.clear();
479            values.resize(fast.n_cols, Value::Empty);
480            for (pos, lit) in literals.iter_mut().enumerate() {
481                values[fast.col_indices[pos]] = literal_value_take(lit);
482            }
483            // Mission C Phase 18: direct O(1) slot index — see
484            // `execute_prepared` for rationale. This is the hot path
485            // for `insert_batch_1k`. Durability fix: WAL-logging
486            // `insert_by_slot` (was the raw `Table::insert`).
487            let res = self
488                .catalog
489                .insert_by_slot(fast.table_slot, &values)
490                .map_err(|e| e.to_string());
491            values.clear();
492            self.insert_values_scratch = values;
493            res?;
494            // Mission B (post-review): statement-boundary WAL group commit.
495            self.catalog
496                .commit_autocommit()
497                .map_err(|e| QueryError::StorageError(e.to_string()))?;
498            return Ok(QueryResult::Modified(1));
499        }
500
501        // Non-insert templates — fall back to the standard path. We
502        // can't usefully move the literals because `substitute_plan`
503        // still expects an immutable slice, and the non-insert hot
504        // paths are dominated by plan walks anyway.
505        self.execute_prepared(prep, literals)
506    }
507
508    /// Walk an expression tree and replace every `InSubquery` node with
509    /// an `InList` by executing the subquery and collecting its first
510    /// column as literal values. This must be called before entering
511    /// the row-by-row scan loop because the scan closure can't call back
512    /// into the engine.
513    pub(super) fn materialize_subqueries(&mut self, expr: &Expr) -> Result<Expr, QueryError> {
514        match expr {
515            Expr::InSubquery {
516                expr: inner,
517                subquery,
518                negated,
519            } => {
520                if is_correlated_subquery(subquery, &self.catalog) {
521                    let inner = self.materialize_subqueries(inner)?;
522                    return Ok(Expr::InSubquery {
523                        expr: Box::new(inner),
524                        subquery: subquery.clone(),
525                        negated: *negated,
526                    });
527                }
528                let inner = self.materialize_subqueries(inner)?;
529                // Plan and execute the subquery.
530                let sub_plan = crate::planner::plan_statement(Statement::Query(*subquery.clone()))
531                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
532                let result = self.execute_plan(&sub_plan)?;
533                let values = match result {
534                    QueryResult::Rows { rows, .. } => rows
535                        .into_iter()
536                        .filter_map(|mut row| {
537                            if row.is_empty() {
538                                None
539                            } else {
540                                Some(value_to_expr(row.swap_remove(0)))
541                            }
542                        })
543                        .collect(),
544                    _ => Vec::new(),
545                };
546                // WS2: byte-budget guard on the materialized IN-list.
547                self.charge_in_list(&values)?;
548                Ok(Expr::InList {
549                    expr: Box::new(inner),
550                    list: values,
551                    negated: *negated,
552                })
553            }
554            Expr::ExistsSubquery { subquery, negated } => {
555                if is_correlated_subquery(subquery, &self.catalog) {
556                    return Ok(expr.clone());
557                }
558                // Uncorrelated EXISTS: run the subquery once and collapse
559                // into a Bool literal.
560                let sub_plan = crate::planner::plan_statement(Statement::Query(*subquery.clone()))
561                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
562                let result = self.execute_plan(&sub_plan)?;
563                let has_rows = match result {
564                    QueryResult::Rows { rows, .. } => !rows.is_empty(),
565                    _ => false,
566                };
567                let truth = if *negated { !has_rows } else { has_rows };
568                Ok(Expr::Literal(Literal::Bool(truth)))
569            }
570            Expr::BinaryOp(l, op, r) => {
571                let l = self.materialize_subqueries(l)?;
572                let r = self.materialize_subqueries(r)?;
573                Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
574            }
575            Expr::UnaryOp(op, inner) => {
576                let inner = self.materialize_subqueries(inner)?;
577                Ok(Expr::UnaryOp(*op, Box::new(inner)))
578            }
579            Expr::Case { whens, else_expr } => {
580                let whens = whens
581                    .iter()
582                    .map(|(c, r)| {
583                        let c = self.materialize_subqueries(c)?;
584                        let r = self.materialize_subqueries(r)?;
585                        Ok((Box::new(c), Box::new(r)))
586                    })
587                    .collect::<Result<Vec<_>, QueryError>>()?;
588                let else_expr = match else_expr {
589                    Some(e) => Some(Box::new(self.materialize_subqueries(e)?)),
590                    None => None,
591                };
592                Ok(Expr::Case { whens, else_expr })
593            }
594            // Leaf nodes: no subqueries possible.
595            other => Ok(other.clone()),
596        }
597    }
598
599    /// Write-path per-row materialisation of correlated subqueries.
600    pub(super) fn materialize_correlated_for_row(
601        &mut self,
602        expr: &Expr,
603        outer_row: &[Value],
604        outer_columns: &[String],
605    ) -> Result<Expr, QueryError> {
606        match expr {
607            Expr::InSubquery {
608                expr: inner,
609                subquery,
610                negated,
611            } => {
612                let inner = self.materialize_correlated_for_row(inner, outer_row, outer_columns)?;
613                let mut sub = *subquery.clone();
614                if let Some(ref filter) = sub.filter {
615                    sub.filter = Some(substitute_outer_refs(
616                        filter,
617                        &sub.source,
618                        &self.catalog,
619                        outer_row,
620                        outer_columns,
621                    ));
622                }
623                let sub_plan = crate::planner::plan_statement(Statement::Query(sub))
624                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
625                let result = self.execute_plan(&sub_plan)?;
626                let values = match result {
627                    QueryResult::Rows { rows, .. } => rows
628                        .into_iter()
629                        .filter_map(|mut row| {
630                            if row.is_empty() {
631                                None
632                            } else {
633                                Some(value_to_expr(row.swap_remove(0)))
634                            }
635                        })
636                        .collect(),
637                    _ => Vec::new(),
638                };
639                Ok(Expr::InList {
640                    expr: Box::new(inner),
641                    list: values,
642                    negated: *negated,
643                })
644            }
645            Expr::ExistsSubquery { subquery, negated } => {
646                let mut sub = *subquery.clone();
647                if let Some(ref filter) = sub.filter {
648                    sub.filter = Some(substitute_outer_refs(
649                        filter,
650                        &sub.source,
651                        &self.catalog,
652                        outer_row,
653                        outer_columns,
654                    ));
655                }
656                let sub_plan = crate::planner::plan_statement(Statement::Query(sub))
657                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
658                let result = self.execute_plan(&sub_plan)?;
659                let has_rows = match result {
660                    QueryResult::Rows { rows, .. } => !rows.is_empty(),
661                    _ => false,
662                };
663                let truth = if *negated { !has_rows } else { has_rows };
664                Ok(Expr::Literal(Literal::Bool(truth)))
665            }
666            Expr::BinaryOp(l, op, r) => {
667                let l = self.materialize_correlated_for_row(l, outer_row, outer_columns)?;
668                let r = self.materialize_correlated_for_row(r, outer_row, outer_columns)?;
669                Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
670            }
671            Expr::UnaryOp(op, inner) => {
672                let inner = self.materialize_correlated_for_row(inner, outer_row, outer_columns)?;
673                Ok(Expr::UnaryOp(*op, Box::new(inner)))
674            }
675            other => Ok(other.clone()),
676        }
677    }
678}