powdb_query/executor/mod.rs
1//! PowDB query executor.
2
3// Submodules that don't use macros defined in this file.
4mod compiled;
5mod eval;
6pub mod mem_budget;
7
8use crate::ast::*;
9use crate::canonicalize::canonicalize;
10use crate::plan::*;
11use crate::plan_cache::PlanCache;
12use crate::planner;
13use crate::result::{QueryError, QueryResult};
14use powdb_storage::catalog::Catalog;
15use powdb_storage::row::{decode_row, RowLayout, ROW_MAGIC, ROW_PREFIX_SIZE};
16use powdb_storage::types::*;
17use powdb_storage::view::ViewRegistry;
18pub use powdb_storage::wal::{WalDurabilityTicket, WalSyncMode};
19
20use std::io;
21use std::path::Path;
22use std::sync::{Arc, Mutex};
23use std::time::Instant;
24use tracing::{error, info, Level};
25
26use self::compiled::*;
27use self::eval::*;
28
29/// Legacy sentinel string constant — kept for backward compatibility with
30/// any external code matching on the string representation. New code should
31/// match on `QueryError::ReadonlyNeedsWrite` directly.
32pub const READONLY_NEEDS_WRITE: &str = "__POWDB_READONLY_NEEDS_WRITE__";
33
34/// Return the byte offset where the row body starts.
35///
36/// v0.5 rows begin with the `PROW` magic/version prefix. Legacy rows start
37/// directly with the row body. Raw executor fast paths must add this base
38/// before reading body-relative bitmap/data offsets.
39#[inline]
40pub(crate) fn row_body_base(row: &[u8]) -> usize {
41 if row.len() >= ROW_PREFIX_SIZE && &row[0..4] == ROW_MAGIC {
42 ROW_PREFIX_SIZE
43 } else {
44 0
45 }
46}
47
48/// Query frontend dialect. PowQL remains the default/native dialect; SQL is
49/// an explicit frontend that lowers to the same AST before planning.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum QueryDialect {
52 PowQL,
53 Sql,
54}
55
56/// Plan cache capacity. Bench workloads fill ~15 slots; real apps will sit
57/// comfortably in 256. Lookup is O(1), collisions clear the cache (see
58/// `plan_cache::PlanCache::insert`).
59const PLAN_CACHE_CAPACITY: usize = 256;
60const SQL_RAW_CACHE_SALT: u64 = 0x7261_772d_7371_6c01;
61
62#[inline]
63fn sql_raw_cache_hash(hash: u64) -> u64 {
64 hash ^ SQL_RAW_CACHE_SALT
65}
66type WalArchiveHook =
67 Arc<dyn Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync>;
68
69/// Maximum number of rows a join may produce before the executor aborts.
70/// Prevents Cartesian-product blowups (e.g. `T cross join T` on 10K rows
71/// would produce 100M rows in memory without this cap).
72pub(super) const MAX_JOIN_ROWS: usize = 1_000_000;
73
74/// Maximum candidate pairs allowed for a fallback nested-loop join. This is
75/// grounded in the release benchmark's conservative 250 ms evaluation budget.
76pub(super) const MAX_NESTED_LOOP_PAIRS: usize = 6_400_000;
77
78/// Maximum number of rows that may be materialized for sorting.
79/// Queries that exceed this should add a LIMIT clause to narrow the input
80/// before sorting.
81pub(super) const MAX_SORT_ROWS: usize = 10_000_000;
82
83#[inline]
84pub(super) fn check_join_limit(row_count: usize) -> Result<(), QueryError> {
85 if row_count > MAX_JOIN_ROWS {
86 return Err(QueryError::JoinLimitExceeded);
87 }
88 Ok(())
89}
90
91// ─── Mission D11 Phase 1: scalar hot-loop helpers ─────────────────────────
92//
93// These macros expand into the scan body of `agg_single_col_fast` and sit
94// inside the `for_each_row_raw` closure. They exist to:
95//
96// 1. Split the loop on presence of a predicate *outside* the hot body,
97// so the no-predicate path (agg_sum/agg_min/agg_max bench workloads)
98// never pays the `Option<CompiledPredicate>` branch per row.
99// 2. Drop two bounds checks per row by reading the null bitmap byte
100// and the 8-byte value via raw pointer casts.
101//
102// SAFETY (shared across every call site below):
103//
104// - `$bmp_byte` is `col_idx / 8` where `col_idx < n_cols`, and the row body
105// encoding stores `bitmap_size = n_cols.div_ceil(8)` bytes of bitmap
106// starting at body offset 2. So `bmp_off = row_body_base(row) + 2 +
107// $bmp_byte < row_len`, and `get_unchecked(bmp_off)` is inside the
108// row slice.
109// - `$off = 2 + bitmap_size + fixed_offsets[col_idx]` is body-relative for a fixed-size
110// column. Every fixed-size column contributes `fixed_size(type_id)`
111// bytes to the fixed region, so the row always has
112// `[data_off .. data_off + 8]` available for any i64/f64 column, where
113// `data_off = row_body_base(row) + $off` — enforced by the row encoder
114// (`storage/src/row.rs`) and the schema invariant that a row with a
115// given schema has enough body bytes for `2 + bitmap_size + fixed_region_size`.
116// - Both macros are only invoked from `agg_single_col_fast`, which
117// early-returns if the column isn't Int/Float (8-byte fixed) and
118// early-returns if `fast.fixed_offsets[col_idx]` is `None`.
119macro_rules! agg_int_loop {
120 (
121 $self:expr, $table:expr, $pred:expr,
122 $bmp_byte:expr, $bmp_bit:expr, $off:expr,
123 |$v:ident : i64| $body:block
124 ) => {{
125 let bmp_byte = $bmp_byte;
126 let bmp_bit = $bmp_bit;
127 let off = $off;
128 if let Some(pred) = &$pred {
129 for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
130 if !pred(data) {
131 return;
132 }
133 let base = row_body_base(data);
134 let bmp_off = base + 2 + bmp_byte;
135 let data_off = base + off;
136 // Bounds guard: skip corrupt/truncated rows that are too
137 // short to contain the bitmap byte or the 8-byte value.
138 if bmp_off >= data.len() || data_off + 8 > data.len() {
139 return;
140 }
141 // SAFETY: `bmp_off < data.len()` is checked above.
142 // The bitmap byte lives at body offset 2..2+bitmap_size in
143 // the row encoding, and bmp_byte = col_idx / 8 < bitmap_size.
144 // Corrupt rows are rejected by the bounds guard.
145 let bmp = unsafe { *data.get_unchecked(bmp_off) };
146 if (bmp >> bmp_bit) & 1 == 1 {
147 return;
148 }
149 // SAFETY: `data_off + 8 <= data.len()` is checked above.
150 // `data_off = base + 2 + bitmap_size + fixed_offsets[col_idx]`
151 // points to an 8-byte i64 in the fixed-size region of the row.
152 // The pointer cast is valid because we read exactly 8
153 // bytes via from_le_bytes. Corrupt rows are rejected by
154 // the bounds guard.
155 let $v: i64 =
156 unsafe { i64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
157 $body
158 })?;
159 } else {
160 for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
161 let base = row_body_base(data);
162 let bmp_off = base + 2 + bmp_byte;
163 let data_off = base + off;
164 // Bounds guard: skip corrupt/truncated rows.
165 if bmp_off >= data.len() || data_off + 8 > data.len() {
166 return;
167 }
168 // SAFETY: `bmp_off < data.len()` is checked above.
169 // See the predicate branch for the full invariant.
170 let bmp = unsafe { *data.get_unchecked(bmp_off) };
171 if (bmp >> bmp_bit) & 1 == 1 {
172 return;
173 }
174 // SAFETY: `data_off + 8 <= data.len()` is checked above.
175 // See the predicate branch for the full invariant.
176 let $v: i64 =
177 unsafe { i64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
178 $body
179 })?;
180 }
181 }};
182}
183
184macro_rules! agg_float_loop {
185 (
186 $self:expr, $table:expr, $pred:expr,
187 $bmp_byte:expr, $bmp_bit:expr, $off:expr,
188 |$v:ident : f64| $body:block
189 ) => {{
190 let bmp_byte = $bmp_byte;
191 let bmp_bit = $bmp_bit;
192 let off = $off;
193 if let Some(pred) = &$pred {
194 for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
195 if !pred(data) {
196 return;
197 }
198 let base = row_body_base(data);
199 let bmp_off = base + 2 + bmp_byte;
200 let data_off = base + off;
201 // Bounds guard: skip corrupt/truncated rows that are too
202 // short to contain the bitmap byte or the 8-byte value.
203 if bmp_off >= data.len() || data_off + 8 > data.len() {
204 return;
205 }
206 // SAFETY: `bmp_off < data.len()` is checked above.
207 // The bitmap byte lives at body offset 2..2+bitmap_size in
208 // the row encoding, and bmp_byte = col_idx / 8 < bitmap_size.
209 // Corrupt rows are rejected by the bounds guard.
210 let bmp = unsafe { *data.get_unchecked(bmp_off) };
211 if (bmp >> bmp_bit) & 1 == 1 {
212 return;
213 }
214 // SAFETY: `data_off + 8 <= data.len()` is checked above.
215 // `data_off = base + 2 + bitmap_size + fixed_offsets[col_idx]`
216 // points to an 8-byte f64 in the fixed-size region of the row.
217 // The pointer cast is valid because we read exactly 8
218 // bytes via from_le_bytes. Corrupt rows are rejected by
219 // the bounds guard.
220 let $v: f64 =
221 unsafe { f64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
222 $body
223 })?;
224 } else {
225 for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
226 let base = row_body_base(data);
227 let bmp_off = base + 2 + bmp_byte;
228 let data_off = base + off;
229 // Bounds guard: skip corrupt/truncated rows.
230 if bmp_off >= data.len() || data_off + 8 > data.len() {
231 return;
232 }
233 // SAFETY: `bmp_off < data.len()` is checked above.
234 // See the predicate branch for the full invariant.
235 let bmp = unsafe { *data.get_unchecked(bmp_off) };
236 if (bmp >> bmp_bit) & 1 == 1 {
237 return;
238 }
239 // SAFETY: `data_off + 8 <= data.len()` is checked above.
240 // See the predicate branch for the full invariant.
241 let $v: f64 =
242 unsafe { f64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
243 $body
244 })?;
245 }
246 }};
247}
248
249// Submodules that use the macros above — must be declared after macro_rules!.
250mod plan_exec;
251mod prepared;
252
253#[cfg(test)]
254mod tests;
255
256// Re-exports for the public API
257pub use self::prepared::PreparedQuery;
258
259use self::plan_exec::{
260 aggregate_rows, aggregate_rows_with_provenance, compare_order_values,
261 cooperative_stable_sort_by, exec_group_by, exec_group_by_with_provenance,
262 execute_materialized_join, execute_window, for_each_row_raw_cancellable, format_plan_tree,
263 lower_unindexed_scans, predicate_column_indices_json, range_matches,
264 synthesize_range_predicate, validate_json_path_types, validate_no_stray_aggregates,
265};
266
267/// Mission infra-1: classify a parsed statement as read-only vs. mutating.
268/// Used by [`Engine::execute_powql_readonly`] and by the server handler
269/// to decide between the RwLock reader and writer sides. `Union` recurses
270/// because each side can independently be read/write (though in practice
271/// both sides are reads — the parser only builds Union from query shapes).
272pub fn is_read_only_statement(stmt: &Statement) -> bool {
273 match stmt {
274 Statement::Query(_) => true,
275 Statement::ListTypes | Statement::Describe(_) => true,
276 Statement::Union(u) => is_read_only_statement(&u.left) && is_read_only_statement(&u.right),
277 Statement::Insert(_)
278 | Statement::Upsert(_)
279 | Statement::UpdateQuery(_)
280 | Statement::DeleteQuery(_)
281 | Statement::CreateType(_)
282 | Statement::CreateLink(_)
283 | Statement::AlterTable(_)
284 | Statement::DropTable(_)
285 | Statement::CreateView(_)
286 | Statement::RefreshView(_)
287 | Statement::DropView(_) => false,
288 Statement::Begin | Statement::Commit | Statement::Rollback => false,
289 Statement::Explain(inner) => is_read_only_statement(inner),
290 }
291}
292
293/// Map a read-only executor result into the read-only-engine surface: the
294/// internal "this statement writes" sentinel ([`QueryError::ReadonlyNeedsWrite`])
295/// becomes the terminal, operator-facing [`QueryError::ReadonlyMode`]. There is
296/// no writer to escalate to in read-only mode, so the sentinel never leaves the
297/// engine.
298fn to_readonly_terminal(
299 result: Result<QueryResult, QueryError>,
300) -> Result<QueryResult, QueryError> {
301 match result {
302 Err(QueryError::ReadonlyNeedsWrite) => Err(QueryError::ReadonlyMode),
303 other => other,
304 }
305}
306
307/// Return whether executing this read plan would have to refresh a dirty
308/// materialized view. This is intentionally a whole-plan preflight: the server
309/// may retry only this typed condition under exclusive admission, so it must be
310/// raised before any input branch performs row work.
311fn plan_reads_dirty_view(plan: &PlanNode, views: &ViewRegistry) -> bool {
312 match plan {
313 PlanNode::SeqScan { table }
314 | PlanNode::AliasScan { table, .. }
315 | PlanNode::IndexScan { table, .. }
316 | PlanNode::RangeScan { table, .. }
317 | PlanNode::ExprIndexScan { table, .. }
318 | PlanNode::ExprRangeScan { table, .. }
319 | PlanNode::OrderedExprIndexScan { table, .. } => views.is_dirty(table),
320
321 PlanNode::Filter { input, .. }
322 | PlanNode::Project { input, .. }
323 | PlanNode::Sort { input, .. }
324 | PlanNode::Limit { input, .. }
325 | PlanNode::Offset { input, .. }
326 | PlanNode::Aggregate { input, .. }
327 | PlanNode::Distinct { input }
328 | PlanNode::GroupBy { input, .. }
329 | PlanNode::Window { input, .. } => plan_reads_dirty_view(input, views),
330
331 PlanNode::NestedLoopJoin { left, right, .. } | PlanNode::Union { left, right, .. } => {
332 plan_reads_dirty_view(left, views) || plan_reads_dirty_view(right, views)
333 }
334
335 // Nested sub-query fields scan their child tables directly, so a
336 // dirty child view needs the same escalation as the parent input.
337 PlanNode::NestedProject { input, fields } => {
338 plan_reads_dirty_view(input, views)
339 || fields.iter().any(|field| match field {
340 crate::plan::NestedProjectField::Nested(nested) => {
341 let mut dirty = false;
342 nested.visit_tables(&mut |table| dirty |= views.is_dirty(table));
343 // A block link traversal's child table is a placeholder
344 // until execution-time catalog resolution, so
345 // visit_tables cannot see it; escalate conservatively
346 // whenever any view is dirty.
347 dirty
348 || (plan_exec::nested_fields_have_via_link(std::slice::from_ref(field))
349 && any_view_dirty(views))
350 }
351 crate::plan::NestedProjectField::Plain(_) => false,
352 // Scalar link hop tables are likewise unknown here.
353 crate::plan::NestedProjectField::Link(link) => {
354 link.resolved.is_none() && any_view_dirty(views)
355 }
356 })
357 }
358
359 // EXPLAIN formats its input without executing it, so inspecting a plan
360 // that names a dirty view never requires a refresh.
361 PlanNode::Explain { .. }
362 | PlanNode::AlterTable { .. }
363 | PlanNode::DropTable { .. }
364 | PlanNode::Insert { .. }
365 | PlanNode::Upsert { .. }
366 | PlanNode::Update { .. }
367 | PlanNode::Delete { .. }
368 | PlanNode::CreateTable { .. }
369 | PlanNode::CreateLink { .. }
370 | PlanNode::ListTypes
371 | PlanNode::Describe { .. }
372 | PlanNode::CreateView { .. }
373 | PlanNode::RefreshView { .. }
374 | PlanNode::DropView { .. }
375 | PlanNode::Begin
376 | PlanNode::Commit
377 | PlanNode::Rollback => false,
378 }
379}
380
381/// True when any registered materialized view is currently dirty. Conservative
382/// escalation test for plans whose scanned tables are not knowable before
383/// execution-time catalog resolution (link traversals resolve their child
384/// tables from the persistent catalog at query time).
385fn any_view_dirty(views: &ViewRegistry) -> bool {
386 views.list_views().iter().any(|v| views.is_dirty(v))
387}
388
389pub struct Engine {
390 catalog: Catalog,
391 /// Exclusive PID-based lock on the data directory, held for the engine's
392 /// lifetime so two separate processes can't open the same dir and corrupt
393 /// the heap/WAL. Released on clean drop; a `mem::forget` crash leaves a
394 /// stale lock the next open takes over. Leading `_`: it does its work
395 /// through `Drop`, never read directly.
396 _dir_lock: powdb_storage::dir_lock::DirLock,
397 /// Mission D9 — cached parsed+planned query trees keyed by canonical
398 /// hash. Saves the ~3μs parse+plan cost on repeat queries that differ
399 /// only in literal values.
400 ///
401 /// Mission infra-1: wrapped in `Mutex` so the read path can be driven
402 /// by `&self`. The critical section is extremely short — a single
403 /// hashmap lookup + plan clone on a hit, or a single insert on a miss.
404 /// A full `RwLock` would be over-engineered here; the contention window
405 /// is smaller than the read-path scan work it gates.
406 plan_cache: Mutex<PlanCache>,
407 /// Mission C Phase 13: reusable `Vec<Value>` scratch buffer for the
408 /// prepared-insert fast path. `execute_prepared` used to allocate a
409 /// fresh `vec![Value::Empty; n_cols]` on every insert; recycling this
410 /// buffer shaves one heap alloc per row on `insert_batch_1k`.
411 insert_values_scratch: Vec<Value>,
412 /// Materialized view registry: tracks view definitions, dependencies,
413 /// and dirty state. Views are backed by regular catalog tables; this
414 /// registry adds the lifecycle metadata.
415 view_registry: ViewRegistry,
416 in_transaction: bool,
417 /// WS2 — per-query memory budget ceiling (bytes). The running total lives
418 /// in a thread-local (see [`mem_budget`]) and is reset at every top-level
419 /// query entry, so sort/join/GROUP BY/IN-list materialization can be capped
420 /// without OOM-killing the process. This field holds only the *limit* (a
421 /// plain `usize`, so `Engine` stays `Sync` for the concurrent read path).
422 /// Default [`mem_budget::DEFAULT_QUERY_MEMORY_LIMIT`] (256 MB); overridable
423 /// via `Engine::with_memory_limit` (server reads `POWDB_QUERY_MEMORY_LIMIT`).
424 query_memory_limit: usize,
425 /// Maximum candidate pairs a fallback nested-loop join may evaluate before
426 /// it is rejected. Default [`MAX_NESTED_LOOP_PAIRS`], overridable via
427 /// [`Engine::set_nested_loop_pair_limit`] (server reads
428 /// `POWDB_MAX_NESTED_LOOP_PAIRS`). A plain `usize` so `Engine` stays `Sync`.
429 nested_loop_pair_limit: usize,
430 wal_archive_hook: Option<WalArchiveHook>,
431 /// True when opened via [`Engine::open_read_only`] for snapshot serving. In
432 /// this mode the catalog and its files are read-only, the `DirLock` is a
433 /// shared reader lock, and every mutating execute path returns the terminal
434 /// [`QueryError::ReadonlyMode`] instead of ever touching disk.
435 read_only: bool,
436}
437
438impl Engine {
439 /// Open or create a PowDB engine rooted at `data_dir`.
440 ///
441 /// If the directory already contains a catalog, it is reopened.
442 /// Otherwise a fresh empty database is created.
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// use powdb_query::executor::Engine;
448 ///
449 /// let dir = tempfile::tempdir().unwrap();
450 /// let engine = Engine::new(dir.path()).unwrap();
451 /// // Engine is ready — the directory now contains a catalog.
452 /// ```
453 pub fn new(data_dir: &Path) -> io::Result<Self> {
454 Self::new_inner(data_dir, None)
455 }
456
457 /// Open or create an engine that archives WAL records before any recovery,
458 /// rollback, or drop checkpoint truncates them. This keeps the query crate
459 /// independent of replication metadata while giving sync-aware callers one
460 /// lifecycle boundary for retained-history preservation.
461 pub fn new_with_wal_archive<F>(data_dir: &Path, archive: F) -> io::Result<Self>
462 where
463 F: Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync + 'static,
464 {
465 Self::new_inner(data_dir, Some(Arc::new(archive)))
466 }
467
468 fn new_inner(data_dir: &Path, wal_archive_hook: Option<WalArchiveHook>) -> io::Result<Self> {
469 powdb_storage::create_data_dir_secure(data_dir)?;
470 // Refuse to open a directory another live process already holds, before
471 // touching any on-disk state (concurrent writers corrupt the heap/WAL).
472 let dir_lock = powdb_storage::dir_lock::DirLock::acquire(data_dir)?;
473 // Try to reopen an existing database first; only create a fresh
474 // catalog when there isn't one already on disk.
475 let catalog_result = match &wal_archive_hook {
476 Some(hook) => {
477 let hook = Arc::clone(hook);
478 Catalog::open_with_wal_archive(data_dir, move |dir, records| hook(dir, records))
479 }
480 None => Catalog::open(data_dir),
481 };
482 let catalog = match catalog_result {
483 Ok(c) => {
484 info!(data_dir = %data_dir.display(), "engine reopened existing database");
485 c
486 }
487 Err(e) if e.kind() == io::ErrorKind::NotFound => {
488 info!(data_dir = %data_dir.display(), "engine initialized fresh database");
489 Catalog::create(data_dir)?
490 }
491 Err(e) => return Err(e),
492 };
493 let view_registry =
494 ViewRegistry::open(data_dir).unwrap_or_else(|_| ViewRegistry::new(data_dir));
495 Ok(Engine {
496 catalog,
497 _dir_lock: dir_lock,
498 plan_cache: Mutex::new(PlanCache::new(PLAN_CACHE_CAPACITY)),
499 insert_values_scratch: Vec::new(),
500 view_registry,
501 in_transaction: false,
502 query_memory_limit: mem_budget::DEFAULT_QUERY_MEMORY_LIMIT,
503 nested_loop_pair_limit: MAX_NESTED_LOOP_PAIRS,
504 wal_archive_hook,
505 read_only: false,
506 })
507 }
508
509 /// Open an engine **read-only** over a quiescent data directory for snapshot
510 /// serving (tier 1 of the replica story). This is the supported way to serve
511 /// a restored backup or a checkpointed replica with no write gate at all:
512 ///
513 /// - the catalog and every heap/index/WAL file are opened read-only
514 /// ([`Catalog::open_read_only`]), so nothing on disk is ever mutated;
515 /// - a **shared reader** [`DirLock`] is taken, so N read-only processes may
516 /// serve the same directory concurrently, while a read-write open refuses
517 /// to start against live readers (and readers refuse a live writer);
518 /// - a non-empty WAL is refused with an actionable error rather than replayed
519 /// (the directory must be recovered by a read-write engine first);
520 /// - every mutating statement returns the terminal [`QueryError::ReadonlyMode`].
521 ///
522 /// Materialized-view refresh must happen before snapshotting: a query over a
523 /// stale (dirty) view is refused in this mode rather than silently escalating.
524 pub fn open_read_only(data_dir: &Path) -> io::Result<Self> {
525 // Validate readability without ever chmod-ing the directory (a read-only
526 // open must leave it byte-identical).
527 powdb_storage::validate_data_dir_read_only(data_dir)?;
528 // A shared reader lock: coexists with other readers, refuses a live writer.
529 let dir_lock = powdb_storage::dir_lock::DirLock::acquire_reader(data_dir)?;
530 let catalog = Catalog::open_read_only(data_dir)?;
531 info!(data_dir = %data_dir.display(), "engine opened read-only for snapshot serving");
532 let view_registry =
533 ViewRegistry::open(data_dir).unwrap_or_else(|_| ViewRegistry::new(data_dir));
534 Ok(Engine {
535 catalog,
536 _dir_lock: dir_lock,
537 plan_cache: Mutex::new(PlanCache::new(PLAN_CACHE_CAPACITY)),
538 insert_values_scratch: Vec::new(),
539 view_registry,
540 in_transaction: false,
541 query_memory_limit: mem_budget::DEFAULT_QUERY_MEMORY_LIMIT,
542 nested_loop_pair_limit: MAX_NESTED_LOOP_PAIRS,
543 // No WAL-archive hook: a read-only engine never writes, so its Drop
544 // must never checkpoint (the hook is what would drive that).
545 wal_archive_hook: None,
546 read_only: true,
547 })
548 }
549
550 /// Read-only open with an explicit per-query memory budget (bytes).
551 pub fn open_read_only_with_memory_limit(
552 data_dir: &Path,
553 limit_bytes: usize,
554 ) -> io::Result<Self> {
555 let mut engine = Engine::open_read_only(data_dir)?;
556 engine.set_query_memory_limit(limit_bytes);
557 Ok(engine)
558 }
559
560 /// Whether this engine was opened read-only for snapshot serving.
561 pub fn is_read_only(&self) -> bool {
562 self.read_only
563 }
564
565 /// Open or create an engine with an explicit per-query memory limit
566 /// (bytes). Used by the server to apply `POWDB_QUERY_MEMORY_LIMIT`, and by
567 /// tests that need a tiny limit to exercise the budget guard.
568 pub fn with_memory_limit(data_dir: &Path, limit_bytes: usize) -> io::Result<Self> {
569 let mut engine = Engine::new(data_dir)?;
570 engine.set_query_memory_limit(limit_bytes);
571 Ok(engine)
572 }
573
574 /// Open or create an archive-aware engine with an explicit per-query memory
575 /// limit.
576 pub fn with_memory_limit_and_wal_archive<F>(
577 data_dir: &Path,
578 limit_bytes: usize,
579 archive: F,
580 ) -> io::Result<Self>
581 where
582 F: Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync + 'static,
583 {
584 let mut engine = Engine::new_with_wal_archive(data_dir, archive)?;
585 engine.set_query_memory_limit(limit_bytes);
586 Ok(engine)
587 }
588
589 /// Current per-query memory limit in bytes.
590 pub fn query_memory_limit(&self) -> usize {
591 self.query_memory_limit
592 }
593
594 /// Override the per-query memory limit in bytes (builder-style).
595 pub fn set_query_memory_limit(&mut self, limit_bytes: usize) {
596 self.query_memory_limit = limit_bytes;
597 }
598
599 /// Current fallback nested-loop join candidate-pair cap.
600 pub fn nested_loop_pair_limit(&self) -> usize {
601 self.nested_loop_pair_limit
602 }
603
604 /// Override the fallback nested-loop join candidate-pair cap. Used by the
605 /// server to apply `POWDB_MAX_NESTED_LOOP_PAIRS`, and by tests that need a
606 /// tiny cap to exercise the guard on a small join. A zero limit is clamped
607 /// to 1 so a valid single-pair join is never rejected outright.
608 pub fn set_nested_loop_pair_limit(&mut self, limit: usize) {
609 self.nested_loop_pair_limit = limit.max(1);
610 }
611
612 /// Set the WAL durability mode (see [`WalSyncMode`]). `Full` (the default)
613 /// fsyncs every commit; `Normal` moves the fsync to a background flusher
614 /// with a bounded crash-loss window; `Off` is bench-only (no durability).
615 /// Wired from the server's `POWDB_SYNC_MODE` / `--sync-mode` config.
616 pub fn set_wal_sync_mode(&mut self, mode: WalSyncMode) {
617 self.catalog.set_wal_sync_mode(mode);
618 }
619
620 /// Run `f` with commit durability deferred — the WAL group-commit entry
621 /// point for callers that serialize writers behind an exclusive lock.
622 ///
623 /// Inside `f`, Full-mode commit points register the WAL generation they
624 /// need durable instead of fsyncing inline. The returned ticket (if any)
625 /// must be waited on before the statement's result is acknowledged; the
626 /// caller should release its exclusive engine lock first, so other
627 /// committers can append while the fsync runs. That overlap is what lets
628 /// one fsync cover many commits. A lone committer's wait performs the
629 /// fsync immediately — group commit never introduces a delay.
630 ///
631 /// `Normal`/`Off` sync modes return no ticket; their durability
632 /// contracts are unchanged. If `f` panics the engine must not be reused
633 /// (the deferral flag may still be set); lock poisoning enforces this
634 /// for callers that share the engine behind a lock.
635 pub fn run_with_deferred_durability<T>(
636 &mut self,
637 f: impl FnOnce(&mut Engine) -> T,
638 ) -> (T, Option<WalDurabilityTicket>) {
639 self.catalog.set_wal_sync_deferred(true);
640 let out = f(self);
641 self.catalog.set_wal_sync_deferred(false);
642 let ticket = self.catalog.take_wal_durability_ticket();
643 (out, ticket)
644 }
645
646 /// Number of fsyncs issued against the WAL (test/metrics hook).
647 pub fn wal_fsync_count(&self) -> u64 {
648 self.catalog.wal_fsync_count()
649 }
650
651 /// Roll back the active explicit transaction while archiving any committed
652 /// pre-transaction WAL records that recovery must replay and truncate.
653 /// This is the sync-aware counterpart to the ordinary `rollback` statement;
654 /// callers provide the archive hook so the query crate stays independent of
655 /// replication metadata.
656 pub fn rollback_transaction_with_wal_archive<F>(
657 &mut self,
658 archive: F,
659 ) -> Result<QueryResult, QueryError>
660 where
661 F: FnMut(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()>,
662 {
663 if !self.in_transaction {
664 return Err(QueryError::Execution(
665 "no active transaction to roll back".into(),
666 ));
667 }
668 self.catalog
669 .rollback_to_last_sync_with_wal_archive(archive)
670 .map_err(|e| QueryError::StorageError(e.to_string()))?;
671 self.finish_rollback_after_catalog_restore()
672 }
673
674 pub fn rollback_transaction_preserving_wal_archive(
675 &mut self,
676 ) -> Result<QueryResult, QueryError> {
677 let Some(hook) = self.wal_archive_hook.clone() else {
678 if !self.in_transaction {
679 return Err(QueryError::Execution(
680 "no active transaction to roll back".into(),
681 ));
682 }
683 self.catalog
684 .rollback_to_last_sync()
685 .map_err(|e| QueryError::StorageError(e.to_string()))?;
686 return self.finish_rollback_after_catalog_restore();
687 };
688 self.rollback_transaction_with_wal_archive(move |dir, records| hook(dir, records))
689 }
690
691 fn finish_rollback_after_catalog_restore(&mut self) -> Result<QueryResult, QueryError> {
692 self.in_transaction = false;
693 if let Ok(mut cache) = self.plan_cache.lock() {
694 cache.clear();
695 }
696 self.view_registry = ViewRegistry::open(self.catalog.data_dir())
697 .unwrap_or_else(|_| ViewRegistry::new(self.catalog.data_dir()));
698 Ok(QueryResult::Executed {
699 message: "transaction rolled back".to_string(),
700 })
701 }
702
703 /// Enter a budgeted-statement frame for the current query. The returned
704 /// guard must be held for the duration of the statement; on its drop the
705 /// reentrancy depth is decremented. Only the *outermost* statement entry
706 /// zeroes this thread's running total, so a nested `execute_powql` (the
707 /// source query of a `create_view`/`refresh_view`) does NOT discard the
708 /// outer frame's accounting. The accumulator is thread-local, so this never
709 /// touches another concurrent query's total.
710 #[must_use = "the budget guard must outlive the statement body"]
711 pub(super) fn enter_memory_budget(&self) -> mem_budget::EnterGuard {
712 mem_budget::enter()
713 }
714
715 /// Charge the estimated footprint of a freshly materialized batch of rows
716 /// against the current per-query budget. Returns
717 /// [`QueryError::MemoryLimitExceeded`] cleanly if the batch would push the
718 /// query over its limit. Used at every full-materialization point (sort
719 /// buffer, join build side, GROUP BY hash table, IN-list).
720 pub(super) fn charge_rows(&self, rows: &[Vec<Value>]) -> Result<(), QueryError> {
721 let mut total = 0usize;
722 let mut cancel = crate::cancel::CancelCheck::new();
723 for row in rows {
724 cancel.tick()?;
725 total = total.saturating_add(mem_budget::estimate_row_size(row));
726 }
727 mem_budget::charge(total, self.query_memory_limit)
728 }
729
730 /// Charge a materialized IN-list (the literal expressions pulled out of an
731 /// uncorrelated `IN (subquery)`) against the current per-query budget.
732 /// Each item is conservatively sized at the `Expr` slot plus, for string
733 /// literals, the owned heap bytes.
734 pub(super) fn charge_in_list(&self, list: &[crate::ast::Expr]) -> Result<(), QueryError> {
735 let base = std::mem::size_of::<crate::ast::Expr>();
736 let mut total = std::mem::size_of::<Vec<crate::ast::Expr>>();
737 let mut cancel = crate::cancel::CancelCheck::new();
738 for item in list {
739 cancel.tick()?;
740 total = total.saturating_add(base);
741 if let crate::ast::Expr::Literal(crate::ast::Literal::String(s)) = item {
742 total = total.saturating_add(s.capacity());
743 }
744 }
745 mem_budget::charge(total, self.query_memory_limit)
746 }
747
748 /// Dispatch to the requested query frontend.
749 pub fn execute_with_dialect(
750 &mut self,
751 dialect: QueryDialect,
752 input: &str,
753 ) -> Result<QueryResult, QueryError> {
754 match dialect {
755 QueryDialect::PowQL => self.execute_powql(input),
756 QueryDialect::Sql => self.execute_sql(input),
757 }
758 }
759
760 /// Read-only variant of [`Engine::execute_with_dialect`].
761 pub fn execute_readonly_with_dialect(
762 &self,
763 dialect: QueryDialect,
764 input: &str,
765 ) -> Result<QueryResult, QueryError> {
766 match dialect {
767 QueryDialect::PowQL => self.execute_powql_readonly(input),
768 QueryDialect::Sql => self.execute_sql_readonly(input),
769 }
770 }
771
772 /// Parse + plan + execute a PowQL query.
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// use powdb_query::executor::Engine;
778 /// use powdb_query::result::QueryResult;
779 ///
780 /// let dir = tempfile::tempdir().unwrap();
781 /// let mut engine = Engine::new(dir.path()).unwrap();
782 ///
783 /// // Create a table and insert a row.
784 /// engine.execute_powql("type User { required name: str, age: int }").unwrap();
785 /// engine.execute_powql(r#"insert User { name := "Alice", age := 30 }"#).unwrap();
786 ///
787 /// // Query rows back.
788 /// let result = engine.execute_powql("User").unwrap();
789 /// assert_eq!(result.row_count(), 1);
790 /// ```
791 ///
792 /// Mission D6 — tracing collapse: the previous implementation ran 4
793 /// `Instant::now()` + 3 `elapsed().as_micros()` calls + formatted an
794 /// `info!` span on every query, even when tracing was disabled. On a
795 /// sub-microsecond `point_lookup_indexed` call that overhead was
796 /// 100-200ns — 20%+ of the whole query. We now measure time only when
797 /// INFO is actually enabled via `tracing::enabled!`, and we moved the
798 /// noisy `debug!(?plan)` line behind the same gate so the Debug
799 /// formatter can't run unconditionally either.
800 ///
801 /// Mission D9 — plan cache: on the hot path we canonicalise the query
802 /// text (lex + FNV-1a hash with literal values stripped), check the
803 /// cache, and on a hit substitute the new literals into a clone of the
804 /// cached plan. This skips re-lexing, re-parsing, and re-planning —
805 /// around 3μs per call on bench workloads. On a miss we plan as before
806 /// and insert the plan under its canonical hash.
807 pub fn execute_powql(&mut self, input: &str) -> Result<QueryResult, QueryError> {
808 if self.read_only {
809 // Snapshot-serving mode: run reads through the read-only executor and
810 // turn the "this statement writes" sentinel into the terminal
811 // ReadonlyMode error. No mutation ever reaches disk.
812 return to_readonly_terminal(self.execute_powql_readonly(input));
813 }
814 // WS2: each *outermost* statement starts with the full memory
815 // allowance. The guard holds the reentrancy depth so a nested
816 // `execute_powql` (e.g. a view's source query) does not reset the
817 // outer frame's accounting mid-statement.
818 let _budget = self.enter_memory_budget();
819 // A token may be cancelled before execution starts (for example, EOF
820 // detected while this job was waiting for the engine lock). Check once
821 // at the statement boundary so even point operations with no long loop
822 // honor cancellation before they can mutate state.
823 crate::cancel::check()?;
824 // Hot path: tracing disabled. Zero syscalls, zero formatting.
825 if !tracing::enabled!(Level::INFO) {
826 // D9: try the plan cache first. Canonicalisation lexes the
827 // query once; on a hit we skip the parser and planner entirely.
828 if let Ok((hash, literals)) = canonicalize(input) {
829 let cached = self
830 .plan_cache
831 .lock()
832 .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
833 .get_with_substitution(hash, &literals);
834 if let Some(plan) = cached {
835 let plan = lower_unindexed_scans(&self.catalog, &plan);
836 let result = self.execute_plan(&plan);
837 // Mission B (post-review): statement-boundary WAL
838 // group commit. Catalog::wal_log now only appends;
839 // the fsync happens here exactly once per statement.
840 // `sync_wal` is a no-op when nothing was buffered
841 // (pure reads pay zero fsync).
842 if !self.in_transaction {
843 self.catalog
844 .commit_autocommit()
845 .map_err(|e| QueryError::StorageError(e.to_string()))?;
846 }
847 return result;
848 }
849 // Miss — plan, insert, execute.
850 return match planner::plan(input) {
851 Ok(plan) => {
852 self.plan_cache
853 .lock()
854 .map_err(|e| {
855 QueryError::Execution(format!("plan cache lock poisoned: {e}"))
856 })?
857 .insert(hash, plan.clone(), literals.len());
858 let plan = lower_unindexed_scans(&self.catalog, &plan);
859 let result = self.execute_plan(&plan);
860 if !self.in_transaction {
861 self.catalog
862 .commit_autocommit()
863 .map_err(|e| QueryError::StorageError(e.to_string()))?;
864 }
865 result
866 }
867 Err(e) => Err(QueryError::Parse(e.to_string())),
868 };
869 }
870 // Lex error — fall through to the planner so the caller gets a
871 // consistent error shape.
872 return match planner::plan(input) {
873 Ok(plan) => {
874 let plan = lower_unindexed_scans(&self.catalog, &plan);
875 let result = self.execute_plan(&plan);
876 if !self.in_transaction {
877 self.catalog
878 .commit_autocommit()
879 .map_err(|e| QueryError::StorageError(e.to_string()))?;
880 }
881 result
882 }
883 Err(e) => Err(QueryError::Parse(e.to_string())),
884 };
885 }
886
887 // Instrumented path — only taken under explicit tracing subscribers.
888 let total_start = Instant::now();
889 let plan_start = Instant::now();
890 let plan = planner::plan(input).map_err(|e| {
891 let msg = e.to_string();
892 error!(query = %input, error = %msg, "query plan failed");
893 QueryError::Parse(msg)
894 })?;
895 let plan_us = plan_start.elapsed().as_micros();
896
897 let exec_start = Instant::now();
898 let plan = lower_unindexed_scans(&self.catalog, &plan);
899 let result = self.execute_plan(&plan);
900 if !self.in_transaction {
901 self.catalog
902 .commit_autocommit()
903 .map_err(|e| QueryError::StorageError(e.to_string()))?;
904 }
905 let exec_us = exec_start.elapsed().as_micros();
906
907 let total_us = total_start.elapsed().as_micros();
908 match &result {
909 Ok(r) => {
910 info!(
911 query = %input,
912 plan_us = plan_us,
913 exec_us = exec_us,
914 total_us = total_us,
915 rows = r.row_count(),
916 "query ok"
917 );
918 }
919 Err(e) => {
920 error!(
921 query = %input,
922 plan_us = plan_us,
923 exec_us = exec_us,
924 error = %e,
925 "query failed"
926 );
927 }
928 }
929 result
930 }
931
932 /// Parse + plan + execute a SQL query through the SQL frontend.
933 ///
934 /// SQL is lowered to the existing PowDB AST and to canonical PowQL text.
935 /// The canonical PowQL text is used as the plan-cache key, so equivalent
936 /// SQL and PowQL spellings share cached plans.
937 pub fn execute_sql(&mut self, input: &str) -> Result<QueryResult, QueryError> {
938 if self.read_only {
939 return to_readonly_terminal(self.execute_sql_readonly(input));
940 }
941 let _budget = self.enter_memory_budget();
942 crate::cancel::check()?;
943 let parsed = crate::sql::parse_sql_with_canonical(input)
944 .map_err(|e| QueryError::Parse(e.to_string()))?;
945
946 if !tracing::enabled!(Level::INFO) {
947 if let Ok((hash, literals)) = canonicalize(&parsed.canonical_powql) {
948 let hash = if crate::sql::statement_has_aggregate(&parsed.statement) {
949 sql_raw_cache_hash(hash)
950 } else {
951 hash
952 };
953 let cached = self
954 .plan_cache
955 .lock()
956 .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
957 .get_with_substitution(hash, &literals);
958 if let Some(plan) = cached {
959 let plan = lower_unindexed_scans(&self.catalog, &plan);
960 let result = self.execute_plan(&plan);
961 if !self.in_transaction {
962 self.catalog
963 .commit_autocommit()
964 .map_err(|e| QueryError::StorageError(e.to_string()))?;
965 }
966 return result;
967 }
968
969 let plan = crate::planner::plan_statement(parsed.statement)
970 .map_err(|e| QueryError::Parse(e.to_string()))?;
971 self.plan_cache
972 .lock()
973 .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
974 .insert(hash, plan.clone(), literals.len());
975 let plan = lower_unindexed_scans(&self.catalog, &plan);
976 let result = self.execute_plan(&plan);
977 if !self.in_transaction {
978 self.catalog
979 .commit_autocommit()
980 .map_err(|e| QueryError::StorageError(e.to_string()))?;
981 }
982 return result;
983 }
984 }
985
986 let plan = crate::planner::plan_statement(parsed.statement)
987 .map_err(|e| QueryError::Parse(e.to_string()))?;
988 let plan = lower_unindexed_scans(&self.catalog, &plan);
989 let result = self.execute_plan(&plan);
990 if !self.in_transaction {
991 self.catalog
992 .commit_autocommit()
993 .map_err(|e| QueryError::StorageError(e.to_string()))?;
994 }
995 result
996 }
997
998 /// Read-only variant of [`Engine::execute_sql`].
999 pub fn execute_sql_readonly(&self, input: &str) -> Result<QueryResult, QueryError> {
1000 let _budget = self.enter_memory_budget();
1001 crate::cancel::check()?;
1002 let parsed = crate::sql::parse_sql_with_canonical(input)
1003 .map_err(|e| QueryError::Parse(e.to_string()))?;
1004 if !is_read_only_statement(&parsed.statement) {
1005 return Err(QueryError::ReadonlyNeedsWrite);
1006 }
1007
1008 if let Ok((hash, literals)) = canonicalize(&parsed.canonical_powql) {
1009 let hash = if crate::sql::statement_has_aggregate(&parsed.statement) {
1010 sql_raw_cache_hash(hash)
1011 } else {
1012 hash
1013 };
1014 let cached = self
1015 .plan_cache
1016 .lock()
1017 .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1018 .get_with_substitution(hash, &literals);
1019 if let Some(plan) = cached {
1020 let plan = lower_unindexed_scans(&self.catalog, &plan);
1021 return self.execute_plan_readonly(&plan);
1022 }
1023 let plan = crate::planner::plan_statement(parsed.statement)
1024 .map_err(|e| QueryError::Parse(e.to_string()))?;
1025 self.plan_cache
1026 .lock()
1027 .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1028 .insert(hash, plan.clone(), literals.len());
1029 let plan = lower_unindexed_scans(&self.catalog, &plan);
1030 return self.execute_plan_readonly(&plan);
1031 }
1032
1033 let plan = crate::planner::plan_statement(parsed.statement)
1034 .map_err(|e| QueryError::Parse(e.to_string()))?;
1035 let plan = lower_unindexed_scans(&self.catalog, &plan);
1036 self.execute_plan_readonly(&plan)
1037 }
1038
1039 /// Execute PowQL with `$N` placeholders bound to positional `params`.
1040 ///
1041 /// Task 4: parameters are substituted as literal *tokens* before
1042 /// parsing (see [`crate::parser::parse_with_params`]), so untrusted
1043 /// input can never change the query's shape. This path deliberately
1044 /// **bypasses the plan cache** — template caching is a follow-up — and
1045 /// otherwise mirrors the non-cached tail of [`Engine::execute_powql`].
1046 pub fn execute_powql_with_params(
1047 &mut self,
1048 input: &str,
1049 params: &[crate::ast::ParamValue],
1050 ) -> Result<QueryResult, QueryError> {
1051 if self.read_only {
1052 return to_readonly_terminal(self.execute_powql_readonly_with_params(input, params));
1053 }
1054 let _budget = self.enter_memory_budget();
1055 crate::cancel::check()?;
1056 let stmt = crate::parser::parse_with_params(input, params)
1057 .map_err(|e| QueryError::Parse(e.to_string()))?;
1058 let plan =
1059 crate::planner::plan_statement(stmt).map_err(|e| QueryError::Parse(e.to_string()))?;
1060 let plan = lower_unindexed_scans(&self.catalog, &plan);
1061 let result = self.execute_plan(&plan);
1062 if !self.in_transaction {
1063 self.catalog
1064 .commit_autocommit()
1065 .map_err(|e| QueryError::StorageError(e.to_string()))?;
1066 }
1067 result
1068 }
1069
1070 /// Read-only variant of [`Engine::execute_powql_with_params`].
1071 ///
1072 /// Mirrors [`Engine::execute_powql_readonly`]: parses with bound
1073 /// params, rejects any write statement with
1074 /// [`QueryError::ReadonlyNeedsWrite`] so the caller can escalate to the
1075 /// write lock, then executes under a shared borrow. No plan-cache
1076 /// interaction.
1077 pub fn execute_powql_readonly_with_params(
1078 &self,
1079 input: &str,
1080 params: &[crate::ast::ParamValue],
1081 ) -> Result<QueryResult, QueryError> {
1082 let _budget = self.enter_memory_budget();
1083 crate::cancel::check()?;
1084 let stmt = crate::parser::parse_with_params(input, params)
1085 .map_err(|e| QueryError::Parse(e.to_string()))?;
1086 if !is_read_only_statement(&stmt) {
1087 return Err(QueryError::ReadonlyNeedsWrite);
1088 }
1089 let plan =
1090 crate::planner::plan_statement(stmt).map_err(|e| QueryError::Parse(e.to_string()))?;
1091 let plan = lower_unindexed_scans(&self.catalog, &plan);
1092 self.execute_plan_readonly(&plan)
1093 }
1094
1095 /// Cancellation-aware variant of [`Engine::execute_powql`]. Installs
1096 /// `cancel` as the current thread's cancellation token for the duration of
1097 /// the statement, so cancellable read and mutation-target discovery loops
1098 /// poll it. Mutation application checks once before its first write, then
1099 /// finishes without polling because the engine has no statement savepoint
1100 /// with which to undo a written prefix. The base methods also honor an
1101 /// already installed token; a caller with no token (embedded/direct use)
1102 /// never cancels.
1103 pub fn execute_powql_with_cancel(
1104 &mut self,
1105 input: &str,
1106 cancel: Arc<crate::cancel::ExecCancel>,
1107 ) -> Result<QueryResult, QueryError> {
1108 let _cancel_guard = crate::cancel::install(cancel);
1109 self.execute_powql(input)
1110 }
1111
1112 /// Cancellation-aware variant of [`Engine::execute_sql`].
1113 pub fn execute_sql_with_cancel(
1114 &mut self,
1115 input: &str,
1116 cancel: Arc<crate::cancel::ExecCancel>,
1117 ) -> Result<QueryResult, QueryError> {
1118 let _cancel_guard = crate::cancel::install(cancel);
1119 self.execute_sql(input)
1120 }
1121
1122 /// Cancellation-aware variant of [`Engine::execute_powql_readonly`].
1123 pub fn execute_powql_readonly_with_cancel(
1124 &self,
1125 input: &str,
1126 cancel: Arc<crate::cancel::ExecCancel>,
1127 ) -> Result<QueryResult, QueryError> {
1128 let _cancel_guard = crate::cancel::install(cancel);
1129 self.execute_powql_readonly(input)
1130 }
1131
1132 /// Cancellation-aware variant of [`Engine::execute_sql_readonly`].
1133 pub fn execute_sql_readonly_with_cancel(
1134 &self,
1135 input: &str,
1136 cancel: Arc<crate::cancel::ExecCancel>,
1137 ) -> Result<QueryResult, QueryError> {
1138 let _cancel_guard = crate::cancel::install(cancel);
1139 self.execute_sql_readonly(input)
1140 }
1141
1142 /// Cancellation-aware variant of [`Engine::execute_powql_with_params`].
1143 pub fn execute_powql_with_params_and_cancel(
1144 &mut self,
1145 input: &str,
1146 params: &[crate::ast::ParamValue],
1147 cancel: Arc<crate::cancel::ExecCancel>,
1148 ) -> Result<QueryResult, QueryError> {
1149 let _cancel_guard = crate::cancel::install(cancel);
1150 self.execute_powql_with_params(input, params)
1151 }
1152
1153 /// Cancellation-aware variant of [`Engine::execute_powql_readonly_with_params`].
1154 pub fn execute_powql_readonly_with_params_and_cancel(
1155 &self,
1156 input: &str,
1157 params: &[crate::ast::ParamValue],
1158 cancel: Arc<crate::cancel::ExecCancel>,
1159 ) -> Result<QueryResult, QueryError> {
1160 let _cancel_guard = crate::cancel::install(cancel);
1161 self.execute_powql_readonly_with_params(input, params)
1162 }
1163
1164 /// Plan cache stats — useful for benches and debugging.
1165 pub fn plan_cache_stats(&self) -> (u64, u64, usize) {
1166 let cache = self.plan_cache.lock().unwrap_or_else(|e| e.into_inner());
1167 (cache.hits, cache.misses, cache.len())
1168 }
1169
1170 /// Mission infra-1: read-only entry point.
1171 ///
1172 /// Parses + plans + executes a PowQL query using only a shared borrow
1173 /// on the engine. Rejects any statement that would mutate state
1174 /// (Insert/Update/Delete/CreateTable/AlterTable/DropTable/CreateView/
1175 /// RefreshView/DropView) by returning [`READONLY_NEEDS_WRITE`] so the
1176 /// caller can escalate to the write lock.
1177 ///
1178 /// Also returns [`READONLY_NEEDS_WRITE`] if a materialized view in the
1179 /// query is dirty — refreshing one requires `&mut self`, so the caller
1180 /// must retake the write lock for the first refresh.
1181 ///
1182 /// This method is the concurrent-read fast path behind
1183 /// `Arc<RwLock<Engine>>`: multiple threads can call it simultaneously
1184 /// under a shared `.read()` lock and each will scan independently.
1185 pub fn execute_powql_readonly(&self, input: &str) -> Result<QueryResult, QueryError> {
1186 // WS2: each *outermost* statement starts with the full memory
1187 // allowance. The guard holds the reentrancy depth so a nested
1188 // `execute_powql*` does not reset the outer frame's accounting.
1189 let _budget = self.enter_memory_budget();
1190 crate::cancel::check()?;
1191 // Parse the statement first so we can classify read vs. write
1192 // without touching the catalog. This is the same lex+parse cost
1193 // the hot path would pay anyway.
1194 let stmt = crate::parser::parse(input).map_err(|e| QueryError::Parse(e.to_string()))?;
1195 if !is_read_only_statement(&stmt) {
1196 return Err(QueryError::ReadonlyNeedsWrite);
1197 }
1198
1199 // Try the plan cache first — identical hash scheme to
1200 // `execute_powql` so both paths share cache state. The mutex
1201 // section is just a hashmap lookup + plan clone.
1202 if let Ok((hash, literals)) = canonicalize(input) {
1203 let cached = self
1204 .plan_cache
1205 .lock()
1206 .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1207 .get_with_substitution(hash, &literals);
1208 if let Some(plan) = cached {
1209 let plan = lower_unindexed_scans(&self.catalog, &plan);
1210 return self.execute_plan_readonly(&plan);
1211 }
1212 // Miss: plan + insert + execute. The planner is pure, so this
1213 // is safe from `&self`.
1214 let plan = crate::planner::plan_statement(stmt)
1215 .map_err(|e| QueryError::Parse(e.to_string()))?;
1216 self.plan_cache
1217 .lock()
1218 .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1219 .insert(hash, plan.clone(), literals.len());
1220 let plan = lower_unindexed_scans(&self.catalog, &plan);
1221 return self.execute_plan_readonly(&plan);
1222 }
1223 // Lex error — fall through to the planner for a consistent error
1224 // shape (though `parse` above would usually have caught it).
1225 let plan =
1226 crate::planner::plan_statement(stmt).map_err(|e| QueryError::Parse(e.to_string()))?;
1227 let plan = lower_unindexed_scans(&self.catalog, &plan);
1228 self.execute_plan_readonly(&plan)
1229 }
1230
1231 /// Read-only version of [`Engine::execute_plan`]. Dispatches the
1232 /// read-path plan variants by calling `&self` helpers and errors with
1233 /// [`READONLY_NEEDS_WRITE`] on any write variant. This is the
1234 /// recursion target for composite read plans under the RwLock reader.
1235 ///
1236 /// The dispatch mirrors `execute_plan` for the read branches but does
1237 /// not carry any of the fast-paths that need `&mut self` (e.g. plan-
1238 /// cache mutation on inner subqueries is handled via the shared mutex
1239 /// in [`Engine::execute_powql_readonly`]; in-flight subquery
1240 /// materialisation uses [`Engine::materialize_subqueries_readonly`]).
1241 fn execute_plan_readonly(&self, plan: &PlanNode) -> Result<QueryResult, QueryError> {
1242 // Detect every dirty materialized-view source before executing any
1243 // branch of the plan. Without this preflight, a join could fully scan
1244 // its clean left input before discovering a dirty right input, then
1245 // repeat that work after the server upgrades to writer admission.
1246 // Alias scans also need this centralized check: they do not pass
1247 // through the SeqScan arm below.
1248 if plan_reads_dirty_view(plan, &self.view_registry) {
1249 return Err(QueryError::ReadonlyNeedsWrite);
1250 }
1251 // Mirror the mutable path: reject a stray aggregate FunctionCall before
1252 // evaluating any row (see execute_plan for the rationale).
1253 validate_no_stray_aggregates(plan)?;
1254 validate_json_path_types(&self.catalog, plan)?;
1255 match plan {
1256 PlanNode::ExprIndexScan { .. }
1257 | PlanNode::ExprRangeScan { .. }
1258 | PlanNode::OrderedExprIndexScan { .. } => {
1259 if let Some(result) = self.execute_expression_index_plan(plan, None)? {
1260 return Ok(result);
1261 }
1262 let fallback = lower_unindexed_scans(&self.catalog, plan);
1263 self.execute_plan_readonly(&fallback)
1264 }
1265 PlanNode::SeqScan { table } => {
1266 // Dirty view means we'd need to refresh it — can't do that
1267 // under `&self`. Escalate to the write path.
1268 if self.view_registry.is_dirty(table) {
1269 return Err(QueryError::ReadonlyNeedsWrite);
1270 }
1271 let schema = self
1272 .catalog
1273 .schema(table)
1274 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1275 .clone();
1276 let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
1277 // Cooperative cancellation: a full-table scan of a huge table
1278 // must stay stoppable.
1279 let mut cancel = crate::cancel::CancelCheck::new();
1280 let mut rows: Vec<Vec<Value>> = Vec::new();
1281 for (_, row) in self.catalog.scan(table).map_err(|e| e.to_string())? {
1282 cancel.tick()?;
1283 rows.push(row);
1284 }
1285 Ok(QueryResult::Rows { columns, rows })
1286 }
1287
1288 PlanNode::AliasScan { table, alias } => {
1289 let schema = self
1290 .catalog
1291 .schema(table)
1292 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1293 .clone();
1294 let columns: Vec<String> = schema
1295 .columns
1296 .iter()
1297 .map(|c| format!("{alias}.{}", c.name))
1298 .collect();
1299 let mut cancel = crate::cancel::CancelCheck::new();
1300 let mut rows: Vec<Vec<Value>> = Vec::new();
1301 for (_, row) in self.catalog.scan(table).map_err(|e| e.to_string())? {
1302 cancel.tick()?;
1303 rows.push(row);
1304 }
1305 Ok(QueryResult::Rows { columns, rows })
1306 }
1307
1308 PlanNode::NestedProject { input, fields } => {
1309 // Dirty child views were escalated by the preflight above;
1310 // the assembly itself only reads.
1311 // Resolve link traversals against the persistent catalog before
1312 // assembly (like the mutable dispatch), so child tables and
1313 // scalar hop chains are concrete.
1314 let resolved;
1315 let fields: &[crate::plan::NestedProjectField] =
1316 if plan_exec::nested_fields_have_via_link(fields) {
1317 let outer = plan_exec::scan_source_table(input).ok_or_else(|| {
1318 QueryError::Execution(
1319 "link traversal requires a plain aliased table scan as its parent"
1320 .into(),
1321 )
1322 })?;
1323 resolved = self.resolve_nested_via_links(fields, outer)?;
1324 &resolved
1325 } else {
1326 fields
1327 };
1328 let parent = self.execute_plan_readonly(input)?;
1329 self.execute_nested_project(parent, fields)
1330 }
1331
1332 PlanNode::IndexScan { table, column, key } => {
1333 let schema = self
1334 .catalog
1335 .schema(table)
1336 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1337 .clone();
1338 let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
1339 let key_value = literal_to_value(key)?;
1340 let tbl = self
1341 .catalog
1342 .get_table(table)
1343 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1344
1345 if tbl.has_index(column) {
1346 // Use index_lookup_all to handle both unique and
1347 // non-unique indexes — returns all matching RowIds.
1348 let rids = tbl.index_lookup_all(column, &key_value);
1349 let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
1350 let mut cancel = crate::cancel::CancelCheck::new();
1351 for rid in rids {
1352 cancel.tick()?;
1353 // Overflow safety (P0-3/P0-4): `tbl.get` reassembles
1354 // spilled columns (the old `heap.get` + `decode_row`
1355 // returned Empty / wrapped a >= 64KB value).
1356 if let Some(row) = tbl.get(rid) {
1357 rows.push(row);
1358 }
1359 }
1360 return Ok(QueryResult::Rows { columns, rows });
1361 }
1362
1363 // No index: synthetic eq predicate + compiled scan.
1364 // Overflow safety (P0-4/P1): v2-capable tables use the decoded
1365 // last-resort scan below (raw scan drops/mis-reads spilled cols).
1366 let fast = FastLayout::new(&schema);
1367 let synth_pred = Expr::BinaryOp(
1368 Box::new(Expr::Field(column.clone())),
1369 BinOp::Eq,
1370 Box::new(key.clone()),
1371 );
1372 if !tbl.has_overflow_rows() {
1373 if let Some(compiled) = compile_predicate(&synth_pred, &columns, &fast, &schema)
1374 {
1375 let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1376 for_each_row_raw_cancellable(&self.catalog, table, |_rid, data| {
1377 if compiled(data) {
1378 rows.push(decode_row(&schema, data));
1379 }
1380 })?;
1381 return Ok(QueryResult::Rows { columns, rows });
1382 }
1383 }
1384
1385 // Last resort: slow eq-check.
1386 let col_idx =
1387 schema
1388 .column_index(column)
1389 .ok_or_else(|| QueryError::ColumnNotFound {
1390 table: String::new(),
1391 column: column.clone(),
1392 })?;
1393 let mut cancel = crate::cancel::CancelCheck::new();
1394 let mut rows: Vec<Vec<Value>> = Vec::new();
1395 for (_, row) in tbl.scan() {
1396 cancel.tick()?;
1397 if row[col_idx] == key_value {
1398 rows.push(row);
1399 }
1400 }
1401 Ok(QueryResult::Rows { columns, rows })
1402 }
1403
1404 PlanNode::RangeScan {
1405 table,
1406 column,
1407 start,
1408 end,
1409 } => {
1410 let tbl = self
1411 .catalog
1412 .get_table(table)
1413 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1414 let columns: Vec<String> = tbl
1415 .schema()
1416 .columns
1417 .iter()
1418 .map(|c| c.name.clone())
1419 .collect();
1420 let schema = tbl.schema().clone();
1421
1422 let start_val = match start {
1423 Some((expr, _)) => Some(literal_to_value(expr)?),
1424 None => None,
1425 };
1426 let end_val = match end {
1427 Some((expr, _)) => Some(literal_to_value(expr)?),
1428 None => None,
1429 };
1430 let start_inclusive = start.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
1431 let end_inclusive = end.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
1432
1433 // Range scans only use the btree fast path for unique indexes.
1434 // Non-unique indexes store composite keys that don't compare
1435 // directly against raw column values.
1436 if tbl.is_index_unique(column) == Some(true) {
1437 if let Some(btree) = tbl.index(column) {
1438 let hits: Vec<(Value, RowId)> = match (&start_val, &end_val) {
1439 (Some(s), Some(e)) => btree.range(s, e).collect(),
1440 (Some(s), None) => btree.range_from(s),
1441 (None, Some(e)) => btree.range_to(e),
1442 (None, None) => {
1443 // Unbounded both sides — equivalent to seq scan.
1444 let mut cancel = crate::cancel::CancelCheck::new();
1445 let mut rows: Vec<Vec<Value>> = Vec::new();
1446 for (_, row) in tbl.scan() {
1447 cancel.tick()?;
1448 rows.push(row);
1449 }
1450 return Ok(QueryResult::Rows { columns, rows });
1451 }
1452 };
1453 let mut rows: Vec<Vec<Value>> = Vec::with_capacity(hits.len());
1454 let mut cancel = crate::cancel::CancelCheck::new();
1455 for (key, rid) in hits {
1456 cancel.tick()?;
1457 // Filter for exclusive bounds.
1458 if !start_inclusive {
1459 if let Some(ref s) = start_val {
1460 if &key == s {
1461 continue;
1462 }
1463 }
1464 }
1465 if !end_inclusive {
1466 if let Some(ref e) = end_val {
1467 if &key == e {
1468 continue;
1469 }
1470 }
1471 }
1472 // Overflow safety (P0-3): reassemble spilled cols.
1473 if let Some(row) = tbl.get(rid) {
1474 rows.push(row);
1475 }
1476 }
1477 return Ok(QueryResult::Rows { columns, rows });
1478 }
1479 }
1480
1481 // Fallback: no index — synthesize the range predicate and scan.
1482 // Overflow safety (P0-4): v2-capable tables use the decoded
1483 // last-resort scan below.
1484 let fast = FastLayout::new(&schema);
1485 let synth = synthesize_range_predicate(column, start, end);
1486 if !tbl.has_overflow_rows() {
1487 if let Some(compiled) = compile_predicate(&synth, &columns, &fast, &schema) {
1488 let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1489 for_each_row_raw_cancellable(&self.catalog, table, |_rid, data| {
1490 if compiled(data) {
1491 rows.push(decode_row(&schema, data));
1492 }
1493 })?;
1494 return Ok(QueryResult::Rows { columns, rows });
1495 }
1496 }
1497
1498 // Last resort: decoded row eval.
1499 let col_idx =
1500 schema
1501 .column_index(column)
1502 .ok_or_else(|| QueryError::ColumnNotFound {
1503 table: String::new(),
1504 column: column.clone(),
1505 })?;
1506 let mut cancel = crate::cancel::CancelCheck::new();
1507 let mut rows: Vec<Vec<Value>> = Vec::new();
1508 for (_, row) in tbl.scan() {
1509 cancel.tick()?;
1510 if range_matches(
1511 &row[col_idx],
1512 &start_val,
1513 start_inclusive,
1514 &end_val,
1515 end_inclusive,
1516 ) {
1517 rows.push(row);
1518 }
1519 }
1520 Ok(QueryResult::Rows { columns, rows })
1521 }
1522
1523 PlanNode::Filter { input, predicate } => {
1524 // Materialise subqueries using the `&self` variant.
1525 // Uncorrelated subqueries are replaced with InList/Bool;
1526 // correlated ones are left as InSubquery/ExistsSubquery
1527 // for per-row materialisation below.
1528 let materialized;
1529 let predicate = if contains_subquery(predicate) {
1530 materialized = self.materialize_subqueries_readonly(predicate)?;
1531 &materialized
1532 } else {
1533 predicate
1534 };
1535
1536 // Correlated subquery path: per-row materialisation.
1537 if contains_subquery(predicate) {
1538 let result = self.execute_plan_readonly(input)?;
1539 return match result {
1540 QueryResult::Rows { columns, rows } => {
1541 let mut filtered = Vec::new();
1542 // Cooperative cancellation: this runs a subquery per
1543 // outer row, so a large outer scan must stay stoppable.
1544 let mut cancel = crate::cancel::CancelCheck::new();
1545 for row in rows {
1546 cancel.tick()?;
1547 let row_pred = self.materialize_correlated_for_row_readonly(
1548 predicate, &row, &columns,
1549 )?;
1550 if eval_predicate(&row_pred, &row, &columns) {
1551 filtered.push(row);
1552 }
1553 }
1554 Ok(QueryResult::Rows {
1555 columns,
1556 rows: filtered,
1557 })
1558 }
1559 _ => Err("filter requires row input".into()),
1560 };
1561 }
1562
1563 // Lane A fast path: Filter over an equality-driven index scan
1564 // (mirrors the mutable path). Pure `&self`, so it is shared.
1565 if matches!(
1566 input.as_ref(),
1567 PlanNode::IndexScan { .. } | PlanNode::ExprIndexScan { .. }
1568 ) {
1569 if let Some(result) = self.try_filter_index_residual_fast(input, predicate)? {
1570 return Ok(result);
1571 }
1572 }
1573
1574 // Fused Filter+SeqScan fast path.
1575 // Overflow safety (P0-4/P1): v2-capable tables fall through to
1576 // the decoded general path below.
1577 if let PlanNode::SeqScan { table } = input.as_ref() {
1578 if !self.catalog.table_has_overflow(table) {
1579 if self.view_registry.is_dirty(table) {
1580 return Err(QueryError::ReadonlyNeedsWrite);
1581 }
1582 let schema = self
1583 .catalog
1584 .schema(table)
1585 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1586 .clone();
1587 let columns: Vec<String> =
1588 schema.columns.iter().map(|c| c.name.clone()).collect();
1589 let fast = FastLayout::new(&schema);
1590 let row_layout = RowLayout::new(&schema);
1591 let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1592
1593 // Cooperative cancellation: full-table compiled/selective
1594 // predicate scan must stay stoppable (see the write-path
1595 // Filter fast path for the same pattern).
1596 let mut cancel = crate::cancel::CancelCheck::new();
1597 let mut cancel_err: Option<QueryError> = None;
1598 if let Some(compiled) =
1599 compile_predicate(predicate, &columns, &fast, &schema)
1600 {
1601 self.catalog
1602 .try_for_each_row_raw(table, |_rid, data| {
1603 if let Err(e) = cancel.tick() {
1604 cancel_err = Some(e);
1605 return std::ops::ControlFlow::Break(());
1606 }
1607 if compiled(data) {
1608 rows.push(decode_row(&schema, data));
1609 }
1610 std::ops::ControlFlow::Continue(())
1611 })
1612 .map_err(|e| QueryError::StorageError(e.to_string()))?;
1613 } else {
1614 let pred_cols = predicate_column_indices_json(predicate, &columns);
1615 self.catalog
1616 .try_for_each_row_raw(table, |_rid, data| {
1617 if let Err(e) = cancel.tick() {
1618 cancel_err = Some(e);
1619 return std::ops::ControlFlow::Break(());
1620 }
1621 let pred_row =
1622 decode_selective(&schema, &row_layout, data, &pred_cols);
1623 if eval_predicate(predicate, &pred_row, &columns) {
1624 rows.push(decode_row(&schema, data));
1625 }
1626 std::ops::ControlFlow::Continue(())
1627 })
1628 .map_err(|e| QueryError::StorageError(e.to_string()))?;
1629 }
1630 if let Some(e) = cancel_err {
1631 return Err(e);
1632 }
1633
1634 return Ok(QueryResult::Rows { columns, rows });
1635 }
1636 }
1637
1638 // General path.
1639 let result = self.execute_plan_readonly(input)?;
1640 match result {
1641 QueryResult::Rows { columns, rows } => {
1642 let mut cancel = crate::cancel::CancelCheck::new();
1643 let mut filtered: Vec<Vec<Value>> = Vec::new();
1644 for row in rows {
1645 cancel.tick()?;
1646 if eval_predicate(predicate, &row, &columns) {
1647 filtered.push(row);
1648 }
1649 }
1650 Ok(QueryResult::Rows {
1651 columns,
1652 rows: filtered,
1653 })
1654 }
1655 _ => Err("filter requires row input".into()),
1656 }
1657 }
1658
1659 PlanNode::Project { input, fields } => {
1660 if matches!(
1661 input.as_ref(),
1662 PlanNode::ExprIndexScan { .. }
1663 | PlanNode::ExprRangeScan { .. }
1664 | PlanNode::OrderedExprIndexScan { .. }
1665 ) {
1666 if let Some(result) = self.execute_expression_index_plan(input, Some(fields))? {
1667 return Ok(result);
1668 }
1669 }
1670 // Fast path: Project over IndexScan. Avoids full-row decode
1671 // by calling decode_column only for projected fields.
1672 if let PlanNode::IndexScan { table, column, key } = input.as_ref() {
1673 let key_value = literal_to_value(key)?;
1674 let tbl = self
1675 .catalog
1676 .get_table(table)
1677 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1678 let schema = tbl.schema();
1679
1680 let proj_columns: Vec<String> = fields
1681 .iter()
1682 .map(|f| {
1683 f.alias.clone().unwrap_or_else(|| match &f.expr {
1684 Expr::Field(name) => name.clone(),
1685 _ => "?".into(),
1686 })
1687 })
1688 .collect();
1689
1690 let proj_indices: Vec<usize> = fields
1691 .iter()
1692 .filter_map(|f| {
1693 if let Expr::Field(name) = &f.expr {
1694 schema.column_index(name)
1695 } else {
1696 None
1697 }
1698 })
1699 .collect();
1700
1701 // Plain-field projections only; a computed projection
1702 // (e.g. `length(.v)`) falls through to the generic
1703 // expression-evaluating path (its column is otherwise
1704 // dropped — proj_indices only collects Fields).
1705 let all_plain_fields = fields.iter().all(|f| matches!(f.expr, Expr::Field(_)));
1706 if tbl.has_index(column) && all_plain_fields {
1707 let rids = tbl.index_lookup_all(column, &key_value);
1708 let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
1709 let mut cancel = crate::cancel::CancelCheck::new();
1710 for rid in rids {
1711 cancel.tick()?;
1712 // Overflow safety (P0-3/P0-4): reassemble via
1713 // `tbl.get` so spilled projected columns return
1714 // their value, not Empty / a wrapped >= 64KB blob.
1715 if let Some(full) = tbl.get(rid) {
1716 let row: Vec<Value> =
1717 proj_indices.iter().map(|&ci| full[ci].clone()).collect();
1718 rows.push(row);
1719 }
1720 }
1721 return Ok(QueryResult::Rows {
1722 columns: proj_columns,
1723 rows,
1724 });
1725 }
1726 }
1727
1728 // Fast paths over Limit(Sort(...)) / Limit(Filter(...)) / Limit(SeqScan).
1729 if let PlanNode::Limit {
1730 input: inner,
1731 count: limit_expr,
1732 } = input.as_ref()
1733 {
1734 if let PlanNode::Sort {
1735 input: sort_input,
1736 keys,
1737 } = inner.as_ref()
1738 {
1739 if keys.len() == 1 {
1740 if let Expr::Field(sort_field) = &keys[0].expr {
1741 let descending = keys[0].descending;
1742 let limit = match limit_expr {
1743 Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
1744 _ => usize::MAX,
1745 };
1746 let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
1747 match sort_input.as_ref() {
1748 PlanNode::SeqScan { table } => (Some(table.as_str()), None),
1749 PlanNode::Filter {
1750 input: fi,
1751 predicate,
1752 } => {
1753 if let PlanNode::SeqScan { table } = fi.as_ref() {
1754 (Some(table.as_str()), Some(predicate))
1755 } else {
1756 (None, None)
1757 }
1758 }
1759 _ => (None, None),
1760 };
1761 if let Some(table) = table_opt {
1762 if let Some(result) = self.project_filter_sort_limit_fast(
1763 table, fields, sort_field, descending, limit, pred_opt,
1764 )? {
1765 return Ok(result);
1766 }
1767 }
1768 }
1769 }
1770 }
1771 if let PlanNode::Filter {
1772 input: fi,
1773 predicate,
1774 } = inner.as_ref()
1775 {
1776 if let PlanNode::SeqScan { table } = fi.as_ref() {
1777 let limit = match limit_expr {
1778 Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
1779 _ => usize::MAX,
1780 };
1781 if let Some(result) = self.project_filter_limit_fast(
1782 table,
1783 fields,
1784 limit,
1785 Some(predicate),
1786 )? {
1787 return Ok(result);
1788 }
1789 }
1790 }
1791 if let PlanNode::SeqScan { table } = inner.as_ref() {
1792 let limit = match limit_expr {
1793 Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
1794 _ => usize::MAX,
1795 };
1796 if let Some(result) =
1797 self.project_filter_limit_fast(table, fields, limit, None)?
1798 {
1799 return Ok(result);
1800 }
1801 }
1802 }
1803
1804 // Project(Filter(SeqScan)) without Limit.
1805 if let PlanNode::Filter {
1806 input: fi,
1807 predicate,
1808 } = input.as_ref()
1809 {
1810 if let PlanNode::SeqScan { table } = fi.as_ref() {
1811 if let Some(result) = self.project_filter_limit_fast(
1812 table,
1813 fields,
1814 usize::MAX,
1815 Some(predicate),
1816 )? {
1817 return Ok(result);
1818 }
1819 }
1820 }
1821
1822 // Project(SeqScan) without Filter or Limit.
1823 if let PlanNode::SeqScan { table } = input.as_ref() {
1824 if let Some(result) =
1825 self.project_filter_limit_fast(table, fields, usize::MAX, None)?
1826 {
1827 return Ok(result);
1828 }
1829 }
1830
1831 // Generic path.
1832 let result = self.execute_plan_readonly(input)?;
1833 match result {
1834 QueryResult::Rows { columns, rows } => {
1835 let proj_columns: Vec<String> = fields
1836 .iter()
1837 .map(|f| {
1838 f.alias.clone().unwrap_or_else(|| match &f.expr {
1839 Expr::Field(name) => name.clone(),
1840 Expr::QualifiedField { qualifier, field } => {
1841 format!("{qualifier}.{field}")
1842 }
1843 _ => "?".into(),
1844 })
1845 })
1846 .collect();
1847 let mut cancel = crate::cancel::CancelCheck::new();
1848 let mut proj_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
1849 for row in &rows {
1850 cancel.tick()?;
1851 proj_rows.push(
1852 fields
1853 .iter()
1854 .map(|f| eval_expr(&f.expr, row, &columns))
1855 .collect(),
1856 );
1857 }
1858 Ok(QueryResult::Rows {
1859 columns: proj_columns,
1860 rows: proj_rows,
1861 })
1862 }
1863 _ => Err("project requires row input".into()),
1864 }
1865 }
1866
1867 PlanNode::Sort { input, keys } => {
1868 let result = self.execute_plan_readonly(input)?;
1869 match result {
1870 QueryResult::Rows { columns, mut rows } => {
1871 if rows.len() > MAX_SORT_ROWS {
1872 return Err(QueryError::SortLimitExceeded);
1873 }
1874 // WS2: byte-budget guard on the sort buffer.
1875 self.charge_rows(&rows)?;
1876 let key_specs: Vec<(Option<usize>, &Expr, bool)> = keys
1877 .iter()
1878 .map(|k| {
1879 let stored_name = match &k.expr {
1880 Expr::Field(name) => Some(name.clone()),
1881 Expr::QualifiedField { qualifier, field } => {
1882 Some(format!("{qualifier}.{field}"))
1883 }
1884 _ => None,
1885 };
1886 let index = stored_name
1887 .as_ref()
1888 .and_then(|name| columns.iter().position(|c| c == name));
1889 if let Some(name) = stored_name {
1890 if index.is_none() {
1891 return Err(QueryError::ColumnNotFound {
1892 table: String::new(),
1893 column: name,
1894 });
1895 }
1896 }
1897 Ok((index, &k.expr, k.descending))
1898 })
1899 .collect::<Result<_, QueryError>>()?;
1900 cooperative_stable_sort_by(&mut rows, self.query_memory_limit, |a, b| {
1901 for &(col_idx, expr, descending) in &key_specs {
1902 let (left_value, right_value) = match col_idx {
1903 Some(index) => (&a[index], &b[index]),
1904 None => {
1905 let left = eval_expr(expr, a, &columns);
1906 let right = eval_expr(expr, b, &columns);
1907 let cmp = compare_order_values(&left, &right, descending);
1908 if cmp != std::cmp::Ordering::Equal {
1909 return cmp;
1910 }
1911 continue;
1912 }
1913 };
1914 let cmp = compare_order_values(left_value, right_value, descending);
1915 if cmp != std::cmp::Ordering::Equal {
1916 return cmp;
1917 }
1918 }
1919 std::cmp::Ordering::Equal
1920 })?;
1921 Ok(QueryResult::Rows { columns, rows })
1922 }
1923 _ => Err("sort requires row input".into()),
1924 }
1925 }
1926
1927 PlanNode::Limit { input, count } => {
1928 let result = self.execute_plan_readonly(input)?;
1929 let n = match count {
1930 Expr::Literal(Literal::Int(v)) => *v as usize,
1931 _ => return Err("limit must be integer literal".into()),
1932 };
1933 match result {
1934 QueryResult::Rows { columns, rows } => {
1935 let mut cancel = crate::cancel::CancelCheck::new();
1936 let mut limited = Vec::with_capacity(n.min(rows.len()));
1937 for row in rows.into_iter().take(n) {
1938 cancel.tick()?;
1939 limited.push(row);
1940 }
1941 Ok(QueryResult::Rows {
1942 columns,
1943 rows: limited,
1944 })
1945 }
1946 _ => Err("limit requires row input".into()),
1947 }
1948 }
1949
1950 PlanNode::Offset { input, count } => {
1951 let result = self.execute_plan_readonly(input)?;
1952 let n = match count {
1953 Expr::Literal(Literal::Int(v)) => *v as usize,
1954 _ => return Err("offset must be integer literal".into()),
1955 };
1956 match result {
1957 QueryResult::Rows { columns, rows } => {
1958 let mut cancel = crate::cancel::CancelCheck::new();
1959 let mut offset = Vec::with_capacity(rows.len().saturating_sub(n));
1960 for (index, row) in rows.into_iter().enumerate() {
1961 cancel.tick()?;
1962 if index >= n {
1963 offset.push(row);
1964 }
1965 }
1966 Ok(QueryResult::Rows {
1967 columns,
1968 rows: offset,
1969 })
1970 }
1971 _ => Err("offset requires row input".into()),
1972 }
1973 }
1974
1975 PlanNode::Aggregate {
1976 input,
1977 function,
1978 argument,
1979 mode: _,
1980 provenance_alias,
1981 } => {
1982 if let Some(provenance_alias) = provenance_alias {
1983 let input = self.materialize_rows_with_provenance(input)?;
1984 self.charge_rows(&input.rows)?;
1985 return aggregate_rows_with_provenance(
1986 *function,
1987 argument.as_ref(),
1988 &input,
1989 provenance_alias,
1990 self.query_memory_limit,
1991 );
1992 }
1993 // Fast path: count() over SeqScan.
1994 // Overflow safety (P0-4): v2-capable tables use the decoded
1995 // generic path (raw count drops >= 64KB rows).
1996 if *function == AggFunc::Count {
1997 if let PlanNode::SeqScan { table } = input.as_ref() {
1998 if !self.catalog.table_has_overflow(table) {
1999 // A dirty materialized view must be refreshed before
2000 // it can be counted, which needs `&mut self`. Escalate
2001 // to the write path (F3: count(View) returned stale).
2002 if self.view_registry.is_dirty(table) {
2003 return Err(QueryError::ReadonlyNeedsWrite);
2004 }
2005 let mut count: i64 = 0;
2006 for_each_row_raw_cancellable(&self.catalog, table, |_rid, _data| {
2007 count += 1;
2008 })?;
2009 return Ok(QueryResult::Scalar(Value::Int(count)));
2010 }
2011 }
2012 if let PlanNode::Filter {
2013 input: inner,
2014 predicate,
2015 } = input.as_ref()
2016 {
2017 // Only take the fast path for a plain Filter(SeqScan)
2018 // with no subquery in the predicate. A subquery
2019 // predicate (`count(T filter .x in (...))`) must be
2020 // resolved first; the fast path evaluates the raw
2021 // predicate with no subquery materialisation, which
2022 // silently yields 0 (F1). Falling through routes it to
2023 // the generic path that runs the subquery correctly.
2024 if let PlanNode::SeqScan { table } = inner.as_ref() {
2025 if self.view_registry.is_dirty(table) {
2026 // F3: count(View filter ...) over a dirty view.
2027 return Err(QueryError::ReadonlyNeedsWrite);
2028 }
2029 }
2030 if let (PlanNode::SeqScan { table }, false) =
2031 (inner.as_ref(), contains_subquery(predicate))
2032 {
2033 if !self.catalog.table_has_overflow(table) {
2034 let schema = self
2035 .catalog
2036 .schema(table)
2037 .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
2038 .clone();
2039 let columns: Vec<String> =
2040 schema.columns.iter().map(|c| c.name.clone()).collect();
2041 let fast = FastLayout::new(&schema);
2042 let row_layout = RowLayout::new(&schema);
2043
2044 if let Some(compiled) =
2045 compile_predicate(predicate, &columns, &fast, &schema)
2046 {
2047 let mut count: i64 = 0;
2048 for_each_row_raw_cancellable(
2049 &self.catalog,
2050 table,
2051 |_rid, data| {
2052 if compiled(data) {
2053 count += 1;
2054 }
2055 },
2056 )?;
2057 return Ok(QueryResult::Scalar(Value::Int(count)));
2058 }
2059
2060 let pred_cols = predicate_column_indices_json(predicate, &columns);
2061 let mut count: i64 = 0;
2062 for_each_row_raw_cancellable(
2063 &self.catalog,
2064 table,
2065 |_rid, data| {
2066 let pred_row = decode_selective(
2067 &schema,
2068 &row_layout,
2069 data,
2070 &pred_cols,
2071 );
2072 if eval_predicate(predicate, &pred_row, &columns) {
2073 count += 1;
2074 }
2075 },
2076 )?;
2077 return Ok(QueryResult::Scalar(Value::Int(count)));
2078 }
2079 }
2080 }
2081 }
2082
2083 // Fast path: sum/avg/min/max over single fixed-size numeric.
2084 if matches!(
2085 function,
2086 AggFunc::Sum
2087 | AggFunc::Avg
2088 | AggFunc::Min
2089 | AggFunc::Max
2090 | AggFunc::CountDistinct
2091 ) {
2092 if let Some(Expr::Field(col)) = argument.as_ref() {
2093 let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
2094 match input.as_ref() {
2095 PlanNode::SeqScan { table } => (Some(table.as_str()), None),
2096 PlanNode::Filter {
2097 input: inner,
2098 predicate,
2099 } => {
2100 if let PlanNode::SeqScan { table } = inner.as_ref() {
2101 (Some(table.as_str()), Some(predicate))
2102 } else {
2103 (None, None)
2104 }
2105 }
2106 _ => (None, None),
2107 };
2108 if let Some(table) = table_opt {
2109 if let Some(result) =
2110 self.agg_single_col_fast(table, col, *function, pred_opt)?
2111 {
2112 return Ok(result);
2113 }
2114 }
2115 }
2116 }
2117
2118 // Generic path.
2119 let result = self.execute_plan_readonly(input)?;
2120 match result {
2121 QueryResult::Rows { columns, rows } => {
2122 aggregate_rows(*function, argument.as_ref(), &columns, &rows)
2123 }
2124 _ => Err("aggregate requires row input".into()),
2125 }
2126 }
2127
2128 PlanNode::Distinct { input } => {
2129 let result = self.execute_plan_readonly(input)?;
2130 match result {
2131 QueryResult::Rows { columns, rows } => {
2132 let mut seen = std::collections::HashSet::new();
2133 let mut unique_rows = Vec::new();
2134 let mut cancel = crate::cancel::CancelCheck::new();
2135 for row in rows {
2136 cancel.tick()?;
2137 if seen.insert(row.clone()) {
2138 unique_rows.push(row);
2139 }
2140 }
2141 Ok(QueryResult::Rows {
2142 columns,
2143 rows: unique_rows,
2144 })
2145 }
2146 other => Ok(other),
2147 }
2148 }
2149
2150 PlanNode::GroupBy {
2151 input,
2152 keys,
2153 aggregates,
2154 having,
2155 } => {
2156 if aggregates
2157 .iter()
2158 .any(|aggregate| aggregate.provenance_alias.is_some())
2159 {
2160 let input = self.materialize_rows_with_provenance(input)?;
2161 self.charge_rows(&input.rows)?;
2162 return exec_group_by_with_provenance(
2163 input,
2164 keys,
2165 aggregates,
2166 having,
2167 self.query_memory_limit,
2168 );
2169 }
2170 let result = self.execute_plan_readonly(input)?;
2171 match result {
2172 QueryResult::Rows { columns, rows } => {
2173 // WS2: byte-budget guard on the GROUP BY input buffer
2174 // (the hash table is bounded by the input it groups).
2175 self.charge_rows(&rows)?;
2176 exec_group_by(columns, rows, keys, aggregates, having)
2177 }
2178 _ => Err("group by requires row input".into()),
2179 }
2180 }
2181
2182 PlanNode::NestedLoopJoin {
2183 left,
2184 right,
2185 on,
2186 kind,
2187 } => {
2188 let left_result = self.execute_plan_readonly(left)?;
2189 let right_result = self.execute_plan_readonly(right)?;
2190 let (left_columns, left_rows) = match left_result {
2191 QueryResult::Rows { columns, rows } => (columns, rows),
2192 _ => return Err("join left side must produce rows".into()),
2193 };
2194 let (right_columns, right_rows) = match right_result {
2195 QueryResult::Rows { columns, rows } => (columns, rows),
2196 _ => return Err("join right side must produce rows".into()),
2197 };
2198
2199 // WS2: byte-budget guard on the join build side.
2200 self.charge_rows(&left_rows)?;
2201 self.charge_rows(&right_rows)?;
2202
2203 execute_materialized_join(
2204 left_columns,
2205 left_rows,
2206 right_columns,
2207 right_rows,
2208 on.as_ref(),
2209 *kind,
2210 self.nested_loop_pair_limit,
2211 )
2212 }
2213
2214 PlanNode::Window { input, windows } => {
2215 let result = self.execute_plan_readonly(input)?;
2216 execute_window(result, windows, self.query_memory_limit)
2217 }
2218
2219 PlanNode::Union { left, right, all } => {
2220 let left_result = self.execute_plan_readonly(left)?;
2221 let right_result = self.execute_plan_readonly(right)?;
2222 let (left_cols, left_rows) = match left_result {
2223 QueryResult::Rows { columns, rows } => (columns, rows),
2224 _ => return Err("UNION requires query results on left side".into()),
2225 };
2226 let (_, right_rows) = match right_result {
2227 QueryResult::Rows { columns, rows } => (columns, rows),
2228 _ => return Err("UNION requires query results on right side".into()),
2229 };
2230 let mut combined = left_rows;
2231 let mut cancel = crate::cancel::CancelCheck::new();
2232 if *all {
2233 for row in right_rows {
2234 cancel.tick()?;
2235 combined.push(row);
2236 }
2237 } else {
2238 let mut seen = std::collections::HashSet::new();
2239 for row in &combined {
2240 cancel.tick()?;
2241 seen.insert(row.clone());
2242 }
2243 for row in right_rows {
2244 cancel.tick()?;
2245 if seen.insert(row.clone()) {
2246 combined.push(row);
2247 }
2248 }
2249 }
2250 Ok(QueryResult::Rows {
2251 columns: left_cols,
2252 rows: combined,
2253 })
2254 }
2255
2256 PlanNode::Explain { input } => {
2257 // Every execute entry point runs lower_unindexed_scans before
2258 // dispatch and lowering recurses into Explain, so `input` is
2259 // already the plan that will actually run.
2260 let text = format_plan_tree(&self.catalog, input, 0);
2261 Ok(QueryResult::Rows {
2262 columns: vec!["plan".to_string()],
2263 rows: text
2264 .lines()
2265 .map(|line| vec![Value::Str(line.to_string())])
2266 .collect(),
2267 })
2268 }
2269
2270 PlanNode::ListTypes => self.introspect_list_types(),
2271
2272 PlanNode::Describe { table } => self.introspect_describe(table),
2273
2274 // All write variants — caller must escalate to the write lock.
2275 PlanNode::Insert { .. }
2276 | PlanNode::Update { .. }
2277 | PlanNode::Delete { .. }
2278 | PlanNode::Upsert { .. }
2279 | PlanNode::CreateTable { .. }
2280 | PlanNode::CreateLink { .. }
2281 | PlanNode::AlterTable { .. }
2282 | PlanNode::DropTable { .. }
2283 | PlanNode::CreateView { .. }
2284 | PlanNode::RefreshView { .. }
2285 | PlanNode::DropView { .. }
2286 | PlanNode::Begin
2287 | PlanNode::Commit
2288 | PlanNode::Rollback => Err(QueryError::ReadonlyNeedsWrite),
2289 }
2290 }
2291
2292 /// `&self` variant of [`Engine::materialize_subqueries`]. Used by the
2293 /// read path so `Filter` predicates with `InSubquery`/`ExistsSubquery`
2294 /// children can evaluate their inner queries without taking the write
2295 /// lock. Inner queries that would themselves need a write (e.g. dirty
2296 /// view) escalate via [`READONLY_NEEDS_WRITE`] just like the top-level
2297 /// read path does.
2298 fn materialize_subqueries_readonly(&self, expr: &Expr) -> Result<Expr, QueryError> {
2299 match expr {
2300 Expr::InSubquery {
2301 expr: inner,
2302 subquery,
2303 negated,
2304 } => {
2305 if is_correlated_subquery(subquery, &self.catalog) {
2306 // Pass through — will be materialized per-row in the
2307 // Filter handler's correlated subquery path.
2308 let inner = self.materialize_subqueries_readonly(inner)?;
2309 return Ok(Expr::InSubquery {
2310 expr: Box::new(inner),
2311 subquery: subquery.clone(),
2312 negated: *negated,
2313 });
2314 }
2315 let inner = self.materialize_subqueries_readonly(inner)?;
2316 let sub_plan = crate::planner::plan_statement(Statement::Query(*subquery.clone()))
2317 .map_err(|e| QueryError::StorageError(e.to_string()))?;
2318 let result = self.execute_plan_readonly(&sub_plan)?;
2319 let values = match result {
2320 QueryResult::Rows { rows, .. } => {
2321 let mut values = Vec::with_capacity(rows.len());
2322 let mut cancel = crate::cancel::CancelCheck::new();
2323 for mut row in rows {
2324 cancel.tick()?;
2325 if !row.is_empty() {
2326 values.push(value_to_expr(row.swap_remove(0)));
2327 }
2328 }
2329 values
2330 }
2331 _ => Vec::new(),
2332 };
2333 // WS2: byte-budget guard on the materialized IN-list.
2334 self.charge_in_list(&values)?;
2335 Ok(Expr::InList {
2336 expr: Box::new(inner),
2337 list: values,
2338 negated: *negated,
2339 })
2340 }
2341 Expr::ExistsSubquery { subquery, negated } => {
2342 if is_correlated_subquery(subquery, &self.catalog) {
2343 return Ok(expr.clone());
2344 }
2345 let sub_plan = crate::planner::plan_statement(Statement::Query(*subquery.clone()))
2346 .map_err(|e| QueryError::StorageError(e.to_string()))?;
2347 let result = self.execute_plan_readonly(&sub_plan)?;
2348 let has_rows = match result {
2349 QueryResult::Rows { rows, .. } => !rows.is_empty(),
2350 _ => false,
2351 };
2352 let truth = if *negated { !has_rows } else { has_rows };
2353 Ok(Expr::Literal(Literal::Bool(truth)))
2354 }
2355 Expr::BinaryOp(l, op, r) => {
2356 let l = self.materialize_subqueries_readonly(l)?;
2357 let r = self.materialize_subqueries_readonly(r)?;
2358 Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
2359 }
2360 Expr::UnaryOp(op, inner) => {
2361 let inner = self.materialize_subqueries_readonly(inner)?;
2362 Ok(Expr::UnaryOp(*op, Box::new(inner)))
2363 }
2364 Expr::Case { whens, else_expr } => {
2365 let whens = whens
2366 .iter()
2367 .map(|(c, r)| {
2368 let c = self.materialize_subqueries_readonly(c)?;
2369 let r = self.materialize_subqueries_readonly(r)?;
2370 Ok((Box::new(c), Box::new(r)))
2371 })
2372 .collect::<Result<Vec<_>, QueryError>>()?;
2373 let else_expr = match else_expr {
2374 Some(e) => Some(Box::new(self.materialize_subqueries_readonly(e)?)),
2375 None => None,
2376 };
2377 Ok(Expr::Case { whens, else_expr })
2378 }
2379 other => Ok(other.clone()),
2380 }
2381 }
2382
2383 /// Per-row materialisation of correlated subqueries. For each row in the
2384 /// outer query, substitute outer column references in the subquery's
2385 /// filter with the current row's literal values, execute the modified
2386 /// subquery, and return the result as an InList or Bool literal.
2387 fn materialize_correlated_for_row_readonly(
2388 &self,
2389 expr: &Expr,
2390 outer_row: &[Value],
2391 outer_columns: &[String],
2392 ) -> Result<Expr, QueryError> {
2393 match expr {
2394 Expr::InSubquery {
2395 expr: inner,
2396 subquery,
2397 negated,
2398 } => {
2399 let inner =
2400 self.materialize_correlated_for_row_readonly(inner, outer_row, outer_columns)?;
2401 let mut sub = *subquery.clone();
2402 if let Some(ref filter) = sub.filter {
2403 sub.filter = Some(substitute_outer_refs(
2404 filter,
2405 &sub.source,
2406 &self.catalog,
2407 outer_row,
2408 outer_columns,
2409 ));
2410 }
2411 let sub_plan = crate::planner::plan_statement(Statement::Query(sub))
2412 .map_err(|e| QueryError::StorageError(e.to_string()))?;
2413 let result = self.execute_plan_readonly(&sub_plan)?;
2414 let values = match result {
2415 QueryResult::Rows { rows, .. } => {
2416 let mut values = Vec::with_capacity(rows.len());
2417 let mut cancel = crate::cancel::CancelCheck::new();
2418 for mut row in rows {
2419 cancel.tick()?;
2420 if !row.is_empty() {
2421 values.push(value_to_expr(row.swap_remove(0)));
2422 }
2423 }
2424 values
2425 }
2426 _ => Vec::new(),
2427 };
2428 // WS2: byte-budget guard on the per-row materialized IN-list.
2429 self.charge_in_list(&values)?;
2430 Ok(Expr::InList {
2431 expr: Box::new(inner),
2432 list: values,
2433 negated: *negated,
2434 })
2435 }
2436 Expr::ExistsSubquery { subquery, negated } => {
2437 let mut sub = *subquery.clone();
2438 if let Some(ref filter) = sub.filter {
2439 sub.filter = Some(substitute_outer_refs(
2440 filter,
2441 &sub.source,
2442 &self.catalog,
2443 outer_row,
2444 outer_columns,
2445 ));
2446 }
2447 let sub_plan = crate::planner::plan_statement(Statement::Query(sub))
2448 .map_err(|e| QueryError::StorageError(e.to_string()))?;
2449 let result = self.execute_plan_readonly(&sub_plan)?;
2450 let has_rows = match result {
2451 QueryResult::Rows { rows, .. } => !rows.is_empty(),
2452 _ => false,
2453 };
2454 let truth = if *negated { !has_rows } else { has_rows };
2455 Ok(Expr::Literal(Literal::Bool(truth)))
2456 }
2457 Expr::BinaryOp(l, op, r) => {
2458 let l =
2459 self.materialize_correlated_for_row_readonly(l, outer_row, outer_columns)?;
2460 let r =
2461 self.materialize_correlated_for_row_readonly(r, outer_row, outer_columns)?;
2462 Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
2463 }
2464 Expr::UnaryOp(op, inner) => {
2465 let inner =
2466 self.materialize_correlated_for_row_readonly(inner, outer_row, outer_columns)?;
2467 Ok(Expr::UnaryOp(*op, Box::new(inner)))
2468 }
2469 other => Ok(other.clone()),
2470 }
2471 }
2472
2473 pub fn catalog(&self) -> &Catalog {
2474 &self.catalog
2475 }
2476
2477 pub fn catalog_mut(&mut self) -> &mut Catalog {
2478 &mut self.catalog
2479 }
2480}
2481
2482impl Drop for Engine {
2483 fn drop(&mut self) {
2484 let Some(hook) = self.wal_archive_hook.clone() else {
2485 return;
2486 };
2487 if let Err(err) = self
2488 .catalog
2489 .checkpoint_with_wal_archive(move |dir, records| hook(dir, records))
2490 {
2491 error!(error = %err, "sync-aware engine checkpoint on drop failed");
2492 }
2493 }
2494}