powdb_query/executor/prepared.rs
1//! PreparedQuery struct and related Engine methods.
2
3use crate::ast::*;
4use crate::plan::*;
5use crate::result::{QueryError, QueryResult};
6use powdb_storage::catalog::Catalog;
7use powdb_storage::row::{ROW_MAGIC, ROW_PREFIX_SIZE};
8use powdb_storage::types::*;
9
10use super::compiled::*;
11use super::eval::*;
12use super::Engine;
13
14pub struct PreparedQuery {
15 plan_template: PlanNode,
16 /// Total number of `Expr::Literal` slots reachable from the plan.
17 /// Callers must supply exactly this many literals per execution.
18 pub param_count: usize,
19 /// Fast-path metadata for `PlanNode::Insert`. `Some` when:
20 /// * the template is an Insert, and
21 /// * every assignment RHS is `Expr::Literal(_)` (no computed exprs),
22 /// which means param_count == assignments.len() and the caller's
23 /// literal slice maps 1:1 to schema column indices.
24 ///
25 /// Mission C Phase 15: upgraded from a bare `Vec<usize>` to a
26 /// dedicated [`InsertFast`] struct so the execute path can skip the
27 /// second `catalog.schema(table)` HashMap lookup just to read
28 /// `n_cols`, and can dispatch through `get_table_mut` + `tbl.insert`
29 /// instead of going via the generic `catalog.insert` wrapper.
30 insert_fast: Option<InsertFast>,
31 /// Mission C Phase 14: fast-path metadata for point updates by primary
32 /// key — `T filter .pk = <lit> update { col := <lit> }` where `pk` is
33 /// an indexed column and `col` is fixed-size and not indexed. At
34 /// execute time we skip plan clone, substitute walk, schema re-lookup,
35 /// `resolved_assignments` + `FastPatch` + `matching_rids` Vec allocs,
36 /// and the whole `PlanNode::Update` arm. Just a btree lookup and a
37 /// byte patch.
38 update_pk_fast: Option<UpdatePkFast>,
39}
40
41/// Mission C Phase 15: precomputed insert fast-path metadata. Built once
42/// in [`Engine::prepare`] from a `PlanNode::Insert` template whose every
43/// assignment RHS is a raw literal. The execute path reads `n_cols` and
44/// `col_indices` directly — no catalog schema lookup needed.
45#[derive(Clone)]
46struct InsertFast {
47 /// Mission C Phase 18: cached slot index into `Catalog::tables`.
48 /// DROP/ALTER/index DDL can invalidate the slot or row contract, so every
49 /// execution compares the O(1) catalog structure generation below.
50 table_slot: usize,
51 structure_generation: u64,
52 /// Schema column index for each positional literal, in the order the
53 /// caller passes them.
54 col_indices: Vec<usize>,
55 /// Total number of schema columns — the size `insert_values_scratch`
56 /// must be resized to before filling positions via `col_indices`.
57 /// Cached here so the hot loop skips `catalog.schema(table)` entirely.
58 n_cols: usize,
59 /// Schema slots omitted by this prepared INSERT. The scratch row is shared
60 /// by all prepared inserts on an engine, so these positions must be reset
61 /// to NULL before each execution. Precomputing the complement avoids an
62 /// O(columns × assignments) membership scan on the write hot path.
63 omitted_col_indices: Vec<usize>,
64 /// Assigned column definitions in parameter order. Runtime literals still
65 /// pass through the same coercion rules as the generic INSERT executor;
66 /// preparing with an integer placeholder must not permit a later string to
67 /// be stored in an integer column.
68 assigned_columns: Vec<ColumnDef>,
69 /// Required slots are checked after coercion so a bound NULL cannot bypass
70 /// the generic INSERT required-column contract.
71 required_col_indices: Vec<usize>,
72 /// Needed to mark dependent materialized views dirty in both prepared
73 /// execution variants.
74 table_name: String,
75 /// Prepare-time schema names used only to preserve canonical required-field
76 /// errors. Structural validity is the O(1) generation check above.
77 schema_columns: Vec<ColumnDef>,
78}
79
80/// Mission C Phase 14: precomputed fast-path for `update_by_pk` shaped
81/// prepared queries. Built once in [`Engine::prepare`] and reused on every
82/// `execute_prepared` call.
83#[derive(Clone)]
84struct UpdatePkFast {
85 /// Mission C Phase 18: cached slot index into `Catalog::tables`, guarded
86 /// by the O(1) catalog structure generation on every execution.
87 table_slot: usize,
88 structure_generation: u64,
89 /// Name of the key column (the `.id = ?` side). We look this up in
90 /// the owning table's `indexed_cols` at execute time rather than
91 /// caching a raw `&BTree` — the engine owns the catalog and can't
92 /// hand out long-lived borrows anyway, and the n≤5 linear scan is
93 /// a handful of ns.
94 key_col: String,
95 /// Target column position. A later ALTER ADD INDEX on this column must
96 /// disable the raw byte-patch path so live secondary indexes and unique
97 /// constraints are maintained by the generic update executor.
98 target_col_idx: usize,
99 /// Byte offset of the target fixed column in the row encoding:
100 /// `2 + bitmap_size + layout.fixed_offsets[target_col]`.
101 field_off: usize,
102 /// Byte offset of the bitmap byte containing the target column's null
103 /// bit (`2 + target_col / 8`).
104 bitmap_byte_off: usize,
105 /// Bit mask for the target column's null bit.
106 bit_mask: u8,
107 /// Type of the target fixed column — drives the literal-to-bytes
108 /// encoding at execute time.
109 target_type: TypeId,
110 /// Index into the caller's `literals` slice that holds the filter key.
111 /// Always 0 today (filter literal is visited before the assignment
112 /// RHS), but stored explicitly so the contract is obvious.
113 key_literal_idx: usize,
114 /// Index into the caller's `literals` slice that holds the new value.
115 value_literal_idx: usize,
116}
117
118fn cached_table_matches(catalog: &Catalog, structure_generation: u64) -> bool {
119 catalog.structure_generation() == structure_generation
120}
121
122fn literal_can_take_without_error(literal: &Literal, column: &ColumnDef) -> bool {
123 matches!(
124 (literal, column.type_id),
125 (
126 Literal::Int(_),
127 TypeId::Int | TypeId::Float | TypeId::DateTime
128 ) | (Literal::Float(_), TypeId::Float | TypeId::Int)
129 | (Literal::String(_), TypeId::Str)
130 | (Literal::Bool(_), TypeId::Bool)
131 )
132}
133
134fn restore_taken_strings(fast: &InsertFast, literals: &mut [Literal], values: &mut [Value]) {
135 for (position, literal) in literals.iter_mut().enumerate() {
136 if let Literal::String(destination) = literal {
137 if let Value::Str(source) = &mut values[fast.col_indices[position]] {
138 *destination = std::mem::take(source);
139 }
140 }
141 }
142}
143
144impl Engine {
145 pub fn prepare(&mut self, query: &str) -> Result<PreparedQuery, QueryError> {
146 // The stored template is the RAW plan, exactly like the plan cache's
147 // entries: lowering is a function of catalog state, and a prepared
148 // statement outlives the DDL that changes it. Lowering therefore
149 // happens per execution, below.
150 let (plan, _) = self.plan_text_and_lower(query)?;
151 // Same walk-order restriction as the plan cache: a nested block that
152 // wrote `offset` before `limit` cannot have its slots rebound in
153 // source order.
154 if crate::plan_cache::nested_projection_defeats_cache(&plan) {
155 return Err(QueryError::Execution(
156 "cannot prepare a nested projection that writes `offset` before \
157 `limit`; write `limit` before `offset` in the nested block"
158 .into(),
159 ));
160 }
161 let param_count = crate::plan_cache::count_literal_slots(&plan);
162
163 // Insert fast path: if the template is Insert and every assignment
164 // RHS is a literal, resolve column indices once here and store
165 // them. execute_prepared will skip the plan-clone + substitute
166 // walk on this path.
167 //
168 // Mission C Phase 15: also cache `n_cols` and the target table
169 // name so execute_prepared doesn't need a second HashMap lookup
170 // on `self.catalog.schema(table)` just to size the scratch Vec.
171 let insert_fast = match &plan {
172 // Single-row inserts only: the byte-level fast path patches one
173 // row's worth of scratch. Multi-row `insert T {..},{..}` falls
174 // through to the generic plan path (always correct).
175 PlanNode::Insert {
176 table,
177 rows,
178 returning,
179 } if !returning
180 && rows.len() == 1
181 && rows[0].iter().all(|a| matches!(a.value, Expr::Literal(_)))
182 && param_count == rows[0].len() =>
183 {
184 let assignments = &rows[0];
185 let table_slot = self
186 .catalog
187 .table_slot(table)
188 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
189 let schema = self.catalog.table_by_slot(table_slot).schema();
190 let n_cols = schema.columns.len();
191 let indices: Result<Vec<usize>, QueryError> = assignments
192 .iter()
193 .map(|a| {
194 schema
195 .column_index(&a.field)
196 .ok_or_else(|| QueryError::ColumnNotFound {
197 table: table.clone(),
198 column: a.field.clone(),
199 })
200 })
201 .collect();
202 let indices = indices?;
203 let defaults = self.catalog.column_defaults(table).unwrap_or(&[]);
204 let auto = self.catalog.auto_columns(table).unwrap_or(&[]);
205 let omitted_required = schema
206 .columns
207 .iter()
208 .enumerate()
209 .any(|(index, column)| column.required && !indices.contains(&index));
210 // Defaults and auto columns require table-owned state updates.
211 // Keep those shapes on the generic executor, which applies the
212 // full schema contract. An omitted required column must also
213 // take the generic path so it returns the canonical error.
214 if defaults.iter().any(Option::is_some)
215 || auto.iter().any(|is_auto| *is_auto)
216 || omitted_required
217 {
218 None
219 } else {
220 let omitted_col_indices = (0..n_cols)
221 .filter(|index| !indices.contains(index))
222 .collect();
223 let assigned_columns = indices
224 .iter()
225 .map(|&index| schema.columns[index].clone())
226 .collect();
227 let required_col_indices = schema
228 .columns
229 .iter()
230 .enumerate()
231 .filter_map(|(index, column)| column.required.then_some(index))
232 .collect();
233 Some(InsertFast {
234 table_slot,
235 structure_generation: self.catalog.structure_generation(),
236 col_indices: indices,
237 n_cols,
238 omitted_col_indices,
239 assigned_columns,
240 required_col_indices,
241 table_name: table.clone(),
242 schema_columns: schema.columns.clone(),
243 })
244 }
245 }
246 _ => None,
247 };
248
249 // Mission C Phase 14: update-by-pk fast path. Match on the shape
250 // planner::plan_update builds for `T filter .pk = ? update
251 // { col := ? }` — `Update { input: IndexScan(pk), assignments:
252 // [{col, Literal}] }` — and only if every precondition holds:
253 // * `pk` is an indexed column (so the executor would take the
254 // btree.lookup path at run time regardless)
255 // * there's exactly one assignment
256 // * the assigned column is fixed-size and *not* indexed (so we
257 // don't have to maintain any secondary index on write)
258 // * both literal slots are already `Expr::Literal` (no computed
259 // expressions)
260 // If any of these fail we fall through to the standard substitute
261 // + execute path.
262 let update_pk_fast = Self::try_build_update_pk_fast(&self.catalog, &plan);
263
264 Ok(PreparedQuery {
265 plan_template: plan,
266 param_count,
267 insert_fast,
268 update_pk_fast,
269 })
270 }
271
272 /// Mission C Phase 14: inspect a planned tree and, if it matches the
273 /// `update_by_pk` fast-path shape, return the precomputed byte-patch
274 /// metadata. Returns `None` on any mismatch — the caller falls through
275 /// to the substitute-and-execute path, which is always correct.
276 fn try_build_update_pk_fast(catalog: &Catalog, plan: &PlanNode) -> Option<UpdatePkFast> {
277 // Top level must be `Update { input: IndexScan(...), ... }`.
278 let (table, input, assignments) = match plan {
279 // `returning` must materialize the post-update row image, which the
280 // byte-patch fast path can't produce — fall through to the generic
281 // executor arm.
282 PlanNode::Update {
283 table,
284 input,
285 assignments,
286 returning: false,
287 } => (table, input.as_ref(), assignments),
288 _ => return None,
289 };
290 // Exactly one assignment — the bench hot path and the only case
291 // where a single byte-patch covers the whole mutation.
292 if assignments.len() != 1 {
293 return None;
294 }
295 let assn = &assignments[0];
296 // Assignment RHS must be a raw literal, not a computed expr.
297 if !matches!(assn.value, Expr::Literal(_)) {
298 return None;
299 }
300 // Input must be an IndexScan on the same table with a literal key.
301 let (key_col, key_table) = match input {
302 PlanNode::IndexScan {
303 table: t,
304 column,
305 key: Expr::Literal(_),
306 } => (column.clone(), t.clone()),
307 _ => return None,
308 };
309 if &key_table != table {
310 return None;
311 }
312
313 // Look up schema + index state from the live catalog, caching
314 // the slot so the execute path skips the name probe.
315 let table_slot = catalog.table_slot(table)?;
316 let tbl = catalog.table_by_slot(table_slot);
317 let schema = tbl.schema();
318
319 // Key column must be a UNIQUE INT index, because the execute path
320 // probes it with `BTree::lookup_int`, which binary-searches assuming
321 // every key is a `Value::Int` and treats any other variant as `Less`.
322 //
323 // That probe is only equivalent to the lowered plan's probe under both
324 // conditions at once:
325 //
326 // * `TypeId::Int` — a float / datetime / str / bool column stores its
327 // keys in a different lane, so `lookup_int` addresses nothing and
328 // the mutation silently reported `Modified(0)` while the same text
329 // reported `Modified(1)` (or a typed error, for str and bool);
330 // * unique — a non-unique index does not store one bare `Value::Int`
331 // per key, so the same probe missed there too.
332 //
333 // Both are also what `plan_exec::lowering::coerce_column_index_key`
334 // decides for the text path, which is the definition this fast path has
335 // to match. Anything else falls through to the substitute-and-lower
336 // path below, which is always correct.
337 let key_col_idx = schema.column_index(&key_col)?;
338 if schema.columns[key_col_idx].type_id != TypeId::Int {
339 return None;
340 }
341 if tbl.is_index_unique(&key_col) != Some(true) {
342 return None;
343 }
344
345 // Target column must exist, be fixed-size, and NOT be indexed (so
346 // we don't have to maintain any secondary index here).
347 let target_col_idx = schema.column_index(&assn.field)?;
348 let target_type = schema.columns[target_col_idx].type_id;
349 if !is_fixed_size(target_type) {
350 return None;
351 }
352 if tbl.has_indexed_col(target_col_idx) {
353 return None;
354 }
355
356 // Precompute byte offsets from the cached row layout.
357 let layout = tbl.row_layout();
358 let fixed_off = layout.fixed_offset(target_col_idx)?;
359 let bitmap_size = layout.bitmap_size();
360 let field_off = 2 + bitmap_size + fixed_off;
361 let bitmap_byte_off = 2 + target_col_idx / 8;
362 let bit_mask = 1u8 << (target_col_idx % 8);
363
364 // Literal walk order for `Update { IndexScan(key), [{value}] }`
365 // (see `plan_cache::substitute_plan` — input first, then the
366 // assignments). The filter key is literal 0, the assignment RHS
367 // is literal 1.
368 Some(UpdatePkFast {
369 table_slot,
370 structure_generation: catalog.structure_generation(),
371 key_col,
372 target_col_idx,
373 field_off,
374 bitmap_byte_off,
375 bit_mask,
376 target_type,
377 key_literal_idx: 0,
378 value_literal_idx: 1,
379 })
380 }
381
382 /// Execute a [`PreparedQuery`] with the given literal values.
383 ///
384 /// The literals are substituted into a clone of the template plan in
385 /// the same deterministic walk order that [`crate::canonicalize`]
386 /// produces (filter predicate first, then projection, then assignment
387 /// RHS, and so on). Substitution errors here mean the caller passed
388 /// the wrong number of literals for this query shape.
389 pub fn execute_prepared(
390 &mut self,
391 prep: &PreparedQuery,
392 literals: &[Literal],
393 ) -> Result<QueryResult, QueryError> {
394 if literals.len() != prep.param_count {
395 return Err(QueryError::Execution(format!(
396 "prepared query expects {} literal(s), got {}",
397 prep.param_count,
398 literals.len(),
399 )));
400 }
401
402 // Mission C Phase 14: update-by-pk fast path. Skip plan clone,
403 // substitute walk, resolved_assignments, FastPatch, Vec<RowId>,
404 // RowLayout::new — straight to btree.lookup_int + byte patch.
405 // On rare mismatches (wrong literal type, index dropped after
406 // prepare) the helper returns `Ok(None)` and we fall through to
407 // the generic substitute-and-execute path below.
408 if let Some(fast) = prep
409 .update_pk_fast
410 .as_ref()
411 .filter(|_| !self.generic_path_forced("prepared-update-pk"))
412 {
413 if let Some(result) = self.try_execute_update_pk_fast(fast, literals)? {
414 // Mark dependent views dirty for prepared update fast path.
415 if let PlanNode::Update { table, .. } = &prep.plan_template {
416 self.view_registry.mark_dependents_dirty(table);
417 }
418 // Mission B (post-review): statement-boundary WAL group
419 // commit. The fast path appended an Update record but did
420 // not flush — flush it now so the executor's contract is
421 // "WAL is on disk before this returns".
422 self.catalog
423 .commit_autocommit()
424 .map_err(|e| QueryError::StorageError(e.to_string()))?;
425 return Ok(result);
426 }
427 }
428
429 // Insert fast path: skip plan-clone + substitute walk + PlanNode::Insert
430 // arm's column-index resolution. Build the Row directly from the
431 // caller's literal slice using indices we resolved at prepare time.
432 // Saves ~300-500ns per insert on the bench.
433 //
434 // Mission C Phase 13: the scratch `Vec<Value>` is reused across
435 // calls — no fresh allocation per insert. We split the borrow
436 // between `self.catalog` and `self.insert_values_scratch` by
437 // moving the scratch into a local, filling it, passing to the
438 // catalog, and putting it back.
439 //
440 // Mission C Phase 15: the cached `InsertFast` carries `n_cols`
441 // and the table name, so the hot path makes exactly one catalog
442 // HashMap lookup (`get_table_mut`) and dispatches straight into
443 // `tbl.insert` — no intermediate schema lookup, no generic
444 // `Catalog::insert` wrapper.
445 if let Some(fast) = prep.insert_fast.as_ref().filter(|fast| {
446 !self.generic_path_forced("prepared-insert")
447 && cached_table_matches(&self.catalog, fast.structure_generation)
448 }) {
449 let mut values = std::mem::take(&mut self.insert_values_scratch);
450 values.resize(fast.n_cols, Value::Empty);
451 // Columns omitted by the prepared INSERT must return to NULL on
452 // every execution. Assigned string slots keep their allocation so
453 // repeated prepared inserts copy into stable buffers instead of
454 // allocating one String per field per row.
455 for &index in &fast.omitted_col_indices {
456 values[index] = Value::Empty;
457 }
458 for (pos, lit) in literals.iter().enumerate() {
459 let value = &mut values[fast.col_indices[pos]];
460 let column = &fast.assigned_columns[pos];
461 match (value, lit, column.type_id) {
462 (Value::Str(buffer), Literal::String(text), TypeId::Str) => {
463 buffer.clear();
464 buffer.push_str(text);
465 }
466 (value, literal, _) => {
467 let raw = literal_value_from(literal);
468 match coerce_value(raw, column) {
469 Ok(coerced) => *value = coerced,
470 Err(error) => {
471 self.insert_values_scratch = values;
472 return Err(QueryError::Execution(error));
473 }
474 }
475 }
476 }
477 }
478 for &index in &fast.required_col_indices {
479 if matches!(values[index], Value::Empty) {
480 let column = &fast.schema_columns[index];
481 self.insert_values_scratch = values;
482 return Err(QueryError::Execution(format!(
483 "column '{}' is required but no value was provided",
484 column.name
485 )));
486 }
487 }
488 // Mission C Phase 18: direct O(1) slot index — no
489 // catalog hash probe. Slot was resolved at prepare time.
490 // Durability fix: route through the WAL-logging `insert_by_slot`
491 // (was the raw `Table::insert`, which bypassed the WAL and lost
492 // every prepared insert on a crash).
493 let res = self
494 .catalog
495 .insert_by_slot(fast.table_slot, &values)
496 .map_err(|e| e.to_string());
497 // Retain ordinary row buffers, but do not pin an overflow-sized
498 // client string in the engine forever after one prepared insert.
499 for value in &mut values {
500 if matches!(value, Value::Str(buffer) if buffer.capacity() > powdb_storage::page::MAX_ROW_DATA_SIZE)
501 {
502 *value = Value::Empty;
503 }
504 }
505 // Keep one row's string buffers for the next prepared execution.
506 // This is bounded by the prepared row width and never escapes the
507 // engine; the catalog has already encoded/copied the values.
508 self.insert_values_scratch = values;
509 res?;
510 // Mark dependent views dirty for prepared insert fast path.
511 self.view_registry.mark_dependents_dirty(&fast.table_name);
512 // Mission B (post-review): statement-boundary WAL group commit.
513 self.catalog
514 .commit_autocommit()
515 .map_err(|e| QueryError::StorageError(e.to_string()))?;
516 return Ok(QueryResult::Modified(1));
517 }
518
519 let mut plan = prep.plan_template.clone();
520 let mut idx = 0usize;
521 crate::plan_cache::substitute_plan(&mut plan, literals, &mut idx);
522 debug_assert_eq!(idx, literals.len());
523 // The template is raw planner output and the substituted literals are
524 // new, so this is the first and only chance to lower. Executing the
525 // template directly is what made a prepared `.price < $1` answer
526 // differently from the same query executed as text.
527 let plan = self.lower(&plan);
528 let result = self.execute_lowered(&plan);
529 // Mission B (post-review): statement-boundary WAL group commit.
530 // No-op when nothing was buffered (read-only plans).
531 self.catalog
532 .commit_autocommit()
533 .map_err(|e| QueryError::StorageError(e.to_string()))?;
534 result
535 }
536
537 /// Mission C Phase 14: point-update fast path for prepared
538 /// `T filter .pk = ? update { col := ? }` queries. The caller has
539 /// already verified this is a UNIQUE INT-indexed pk with a fixed-size,
540 /// non-indexed target column; all we do here is pluck the two
541 /// literals out of the caller's slice, run one `btree.lookup_int`,
542 /// and patch 1–8 bytes of the row. No plan clone, no allocations.
543 ///
544 /// Returns:
545 /// * `Ok(Some(result))` — fast path took the mutation.
546 /// * `Ok(None)` — can't take the fast path this call (wrong
547 /// literal type, index dropped since prepare, etc.). Caller
548 /// falls through to the generic substitute-and-execute path.
549 /// * `Err(_)` — real error (table gone, I/O, etc.).
550 #[inline]
551 fn try_execute_update_pk_fast(
552 &mut self,
553 fast: &UpdatePkFast,
554 literals: &[Literal],
555 ) -> Result<Option<QueryResult>, QueryError> {
556 if !cached_table_matches(&self.catalog, fast.structure_generation) {
557 return Ok(None);
558 }
559 let current_table = self.catalog.table_by_slot(fast.table_slot);
560 // Re-check the two properties `lookup_int` depends on rather than
561 // trusting the prepare-time decision. The structure generation above
562 // already catches index DDL, so this is defence in depth against a
563 // future mutation of the index set that forgets to bump it: losing the
564 // fast path costs speed, taking it on a non-unique or non-Int index
565 // loses writes.
566 if current_table.has_indexed_col(fast.target_col_idx)
567 || current_table.is_index_unique(&fast.key_col) != Some(true)
568 {
569 return Ok(None);
570 }
571 // 1) Extract the key literal. The fast path is only built for
572 // int key columns; any other literal type means the caller
573 // is violating the prepared-query contract or the schema
574 // changed — either way, fall back.
575 let key_int = match &literals[fast.key_literal_idx] {
576 Literal::Int(v) => *v,
577 _ => return Ok(None),
578 };
579
580 // 2) Encode the new value as little-endian bytes matching the
581 // target column's fixed encoding.
582 let bytes: FixedBytes = match (fast.target_type, &literals[fast.value_literal_idx]) {
583 (TypeId::Int, Literal::Int(v)) => FixedBytes::I64(v.to_le_bytes()),
584 (TypeId::DateTime, Literal::Int(v)) => FixedBytes::I64(v.to_le_bytes()),
585 (TypeId::Float, Literal::Float(v)) => FixedBytes::F64(v.to_le_bytes()),
586 (TypeId::Bool, Literal::Bool(v)) => FixedBytes::Bool(if *v { 1 } else { 0 }),
587 // Type mismatch — fall back to the generic path for a
588 // consistent error shape.
589 _ => return Ok(None),
590 };
591
592 // 3) Look up the table + btree, do the int lookup, patch the row
593 // in place. Phase 18: table dispatch is a direct slot index;
594 // the btree lookup is the linear scan over `indexed_cols`.
595 // Single btree.lookup_int + one `with_row_bytes_mut` call.
596 // No Vec allocations at all.
597 //
598 // Mission B2: route the in-place patch through the catalog's
599 // WAL-logged wrapper so crash recovery sees the update. The
600 // extra cost is one WAL append + fsync per query — the hot
601 // loop structure is unchanged.
602 let tbl = self.catalog.table_by_slot_mut(fast.table_slot);
603 let btree = tbl
604 .index(&fast.key_col)
605 .expect("prepared update index was revalidated above");
606 let Some(rid) = btree.lookup_int(key_int) else {
607 return Ok(Some(QueryResult::Modified(0)));
608 };
609
610 let fast_table_slot = fast.table_slot;
611 let bitmap_byte_off = fast.bitmap_byte_off;
612 let bit_mask = fast.bit_mask;
613 let field_off = fast.field_off;
614 let ok = self
615 .catalog
616 .update_row_bytes_logged_by_slot(fast_table_slot, rid, |row| {
617 let base = if row.len() >= ROW_PREFIX_SIZE && &row[0..4] == ROW_MAGIC {
618 ROW_PREFIX_SIZE
619 } else {
620 0
621 };
622 // Idempotent null-bit clear — safe even when the column was
623 // already non-null (the overwhelmingly common case).
624 row[base + bitmap_byte_off] &= !bit_mask;
625 let field_bytes = bytes.as_slice();
626 row[base + field_off..base + field_off + field_bytes.len()]
627 .copy_from_slice(field_bytes);
628 })
629 .map_err(|e| QueryError::StorageError(e.to_string()))?;
630
631 Ok(Some(QueryResult::Modified(if ok { 1 } else { 0 })))
632 }
633
634 /// Mission C Phase 13: moving variant of [`Engine::execute_prepared`]
635 /// for the insert fast path. Takes `literals` by mutable reference
636 /// so that each `Literal::String` can be consumed via `mem::take`
637 /// instead of cloned into a `Value::Str`. On `insert_batch_1k` that
638 /// removes three per-row heap allocations (name, status, email),
639 /// bringing the workload over the line vs SQLite's amortized
640 /// prepare+execute loop.
641 ///
642 /// The caller's `Literal::String` entries are replaced with empty
643 /// strings on successful inserts — the `literals` slice is *not*
644 /// left in a valid-for-reuse state except for `Int`/`Float`/`Bool`
645 /// values. Non-insert templates fall through to the standard
646 /// substitute-and-execute path.
647 pub fn execute_prepared_take(
648 &mut self,
649 prep: &PreparedQuery,
650 literals: &mut [Literal],
651 ) -> Result<QueryResult, QueryError> {
652 if literals.len() != prep.param_count {
653 return Err(QueryError::Execution(format!(
654 "prepared query expects {} literal(s), got {}",
655 prep.param_count,
656 literals.len(),
657 )));
658 }
659
660 if let Some(fast) = prep
661 .insert_fast
662 .as_ref()
663 .filter(|fast| cached_table_matches(&self.catalog, fast.structure_generation))
664 {
665 // Moving strings is only safe when coercion cannot fail or replace
666 // the string with another representation. Complex/coercing shapes
667 // use the borrowed path; on success we still honor this method's
668 // consume-on-success contract.
669 if !literals
670 .iter()
671 .zip(&fast.assigned_columns)
672 .all(|(literal, column)| literal_can_take_without_error(literal, column))
673 {
674 let result = self.execute_prepared(prep, literals);
675 if result.is_ok() {
676 for literal in literals {
677 if let Literal::String(value) = literal {
678 value.clear();
679 }
680 }
681 }
682 return result;
683 }
684 let mut values = std::mem::take(&mut self.insert_values_scratch);
685 values.clear();
686 values.resize(fast.n_cols, Value::Empty);
687 for (pos, lit) in literals.iter_mut().enumerate() {
688 let raw = literal_value_take(lit);
689 match coerce_value(raw, &fast.assigned_columns[pos]) {
690 Ok(coerced) => values[fast.col_indices[pos]] = coerced,
691 Err(error) => {
692 restore_taken_strings(fast, literals, &mut values);
693 values.clear();
694 self.insert_values_scratch = values;
695 return Err(QueryError::Execution(error));
696 }
697 }
698 }
699 for &index in &fast.required_col_indices {
700 if matches!(values[index], Value::Empty) {
701 let column = &fast.schema_columns[index];
702 let error = format!(
703 "column '{}' is required but no value was provided",
704 column.name
705 );
706 restore_taken_strings(fast, literals, &mut values);
707 values.clear();
708 self.insert_values_scratch = values;
709 return Err(QueryError::Execution(error));
710 }
711 }
712 // Mission C Phase 18: direct O(1) slot index — see
713 // `execute_prepared` for rationale. This is the hot path
714 // for `insert_batch_1k`. Durability fix: WAL-logging
715 // `insert_by_slot` (was the raw `Table::insert`).
716 if let Err(error) = self.catalog.insert_by_slot(fast.table_slot, &values) {
717 restore_taken_strings(fast, literals, &mut values);
718 values.clear();
719 self.insert_values_scratch = values;
720 return Err(QueryError::StorageError(error.to_string()));
721 }
722 self.view_registry.mark_dependents_dirty(&fast.table_name);
723 // Mission B (post-review): statement-boundary WAL group commit.
724 if let Err(error) = self.catalog.commit_autocommit() {
725 restore_taken_strings(fast, literals, &mut values);
726 values.clear();
727 self.insert_values_scratch = values;
728 return Err(QueryError::StorageError(error.to_string()));
729 }
730 values.clear();
731 self.insert_values_scratch = values;
732 return Ok(QueryResult::Modified(1));
733 }
734
735 // Non-insert templates — fall back to the standard path. We
736 // can't usefully move the literals because `substitute_plan`
737 // still expects an immutable slice, and the non-insert hot
738 // paths are dominated by plan walks anyway.
739 let result = self.execute_prepared(prep, literals);
740 if result.is_ok() && matches!(prep.plan_template, PlanNode::Insert { .. }) {
741 for literal in literals {
742 if let Literal::String(value) = literal {
743 value.clear();
744 }
745 }
746 }
747 result
748 }
749
750 /// Walk an expression tree and replace every `InSubquery` node with
751 /// an `InList` by executing the subquery and collecting its first
752 /// column as literal values. This must be called before entering
753 /// the row-by-row scan loop because the scan closure can't call back
754 /// into the engine.
755 pub(super) fn materialize_subqueries(&mut self, expr: &Expr) -> Result<Expr, QueryError> {
756 match expr {
757 Expr::InSubquery {
758 expr: inner,
759 subquery,
760 negated,
761 } => {
762 if is_correlated_subquery(subquery, &self.catalog) {
763 let inner = self.materialize_subqueries(inner)?;
764 return Ok(Expr::InSubquery {
765 expr: Box::new(inner),
766 subquery: subquery.clone(),
767 negated: *negated,
768 });
769 }
770 let inner = self.materialize_subqueries(inner)?;
771 // Plan and execute the subquery.
772 let sub_plan = self.plan_and_lower(Statement::Query(*subquery.clone()))?;
773 let result = self.execute_lowered(&sub_plan)?;
774 let values = match result {
775 QueryResult::Rows { rows, .. } => {
776 let mut values = Vec::with_capacity(rows.len());
777 let mut cancel = crate::cancel::CancelCheck::new();
778 for mut row in rows {
779 cancel.tick()?;
780 if !row.is_empty() {
781 values.push(value_to_expr(row.swap_remove(0)));
782 }
783 }
784 values
785 }
786 _ => Vec::new(),
787 };
788 // WS2: byte-budget guard on the materialized IN-list.
789 self.charge_in_list(&values)?;
790 Ok(Expr::InList {
791 expr: Box::new(inner),
792 list: values,
793 negated: *negated,
794 })
795 }
796 Expr::ExistsSubquery { subquery, negated } => {
797 if is_correlated_subquery(subquery, &self.catalog) {
798 return Ok(expr.clone());
799 }
800 // Uncorrelated EXISTS: run the subquery once and collapse
801 // into a Bool literal.
802 let sub_plan = self.plan_and_lower(Statement::Query(*subquery.clone()))?;
803 let result = self.execute_lowered(&sub_plan)?;
804 let has_rows = match result {
805 QueryResult::Rows { rows, .. } => !rows.is_empty(),
806 _ => false,
807 };
808 let truth = if *negated { !has_rows } else { has_rows };
809 Ok(Expr::Literal(Literal::Bool(truth)))
810 }
811 Expr::BinaryOp(l, op, r) => {
812 let l = self.materialize_subqueries(l)?;
813 let r = self.materialize_subqueries(r)?;
814 Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
815 }
816 Expr::UnaryOp(op, inner) => {
817 let inner = self.materialize_subqueries(inner)?;
818 Ok(Expr::UnaryOp(*op, Box::new(inner)))
819 }
820 Expr::Case { whens, else_expr } => {
821 let whens = whens
822 .iter()
823 .map(|(c, r)| {
824 let c = self.materialize_subqueries(c)?;
825 let r = self.materialize_subqueries(r)?;
826 Ok((Box::new(c), Box::new(r)))
827 })
828 .collect::<Result<Vec<_>, QueryError>>()?;
829 let else_expr = match else_expr {
830 Some(e) => Some(Box::new(self.materialize_subqueries(e)?)),
831 None => None,
832 };
833 Ok(Expr::Case { whens, else_expr })
834 }
835 // Leaf nodes: no subqueries possible.
836 other => Ok(other.clone()),
837 }
838 }
839
840 /// Write-path per-row materialisation of correlated subqueries.
841 pub(super) fn materialize_correlated_for_row(
842 &mut self,
843 expr: &Expr,
844 outer_row: &[Value],
845 outer_columns: &[String],
846 ) -> Result<Expr, QueryError> {
847 match expr {
848 Expr::InSubquery {
849 expr: inner,
850 subquery,
851 negated,
852 } => {
853 let inner = self.materialize_correlated_for_row(inner, outer_row, outer_columns)?;
854 let mut sub = *subquery.clone();
855 if let Some(ref filter) = sub.filter {
856 sub.filter = Some(substitute_outer_refs(
857 filter,
858 &sub.source,
859 &self.catalog,
860 outer_row,
861 outer_columns,
862 ));
863 }
864 let sub_plan = self.plan_and_lower(Statement::Query(sub))?;
865 let result = self.execute_lowered(&sub_plan)?;
866 let values = match result {
867 QueryResult::Rows { rows, .. } => {
868 let mut values = Vec::with_capacity(rows.len());
869 let mut cancel = crate::cancel::CancelCheck::new();
870 for mut row in rows {
871 cancel.tick()?;
872 if !row.is_empty() {
873 values.push(value_to_expr(row.swap_remove(0)));
874 }
875 }
876 values
877 }
878 _ => Vec::new(),
879 };
880 Ok(Expr::InList {
881 expr: Box::new(inner),
882 list: values,
883 negated: *negated,
884 })
885 }
886 Expr::ExistsSubquery { subquery, negated } => {
887 let mut sub = *subquery.clone();
888 if let Some(ref filter) = sub.filter {
889 sub.filter = Some(substitute_outer_refs(
890 filter,
891 &sub.source,
892 &self.catalog,
893 outer_row,
894 outer_columns,
895 ));
896 }
897 let sub_plan = self.plan_and_lower(Statement::Query(sub))?;
898 let result = self.execute_lowered(&sub_plan)?;
899 let has_rows = match result {
900 QueryResult::Rows { rows, .. } => !rows.is_empty(),
901 _ => false,
902 };
903 let truth = if *negated { !has_rows } else { has_rows };
904 Ok(Expr::Literal(Literal::Bool(truth)))
905 }
906 Expr::BinaryOp(l, op, r) => {
907 let l = self.materialize_correlated_for_row(l, outer_row, outer_columns)?;
908 let r = self.materialize_correlated_for_row(r, outer_row, outer_columns)?;
909 Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
910 }
911 Expr::UnaryOp(op, inner) => {
912 let inner = self.materialize_correlated_for_row(inner, outer_row, outer_columns)?;
913 Ok(Expr::UnaryOp(*op, Box::new(inner)))
914 }
915 other => Ok(other.clone()),
916 }
917 }
918}