• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

joaoh82 / rust_sqlite / 25425173432

06 May 2026 08:41AM UTC coverage: 65.306% (+0.7%) from 64.597%
25425173432

push

github

web-flow
feat(sql): JOINs — INNER, LEFT OUTER, RIGHT OUTER, FULL OUTER (SQLR-5) (#99)

Adds the four-flavor JOIN quartet with explicit ON conditions and
table aliases. SQLite ships only INNER and LEFT OUTER; we implement
RIGHT and FULL OUTER as well because the per-flavor delta on top of
a shared nested-loop driver is just NULL-padding policy. See
docs/design-decisions.md §14a for the reasoning.

Engine changes:
  - New RowScope trait abstracts column lookup; SingleTableScope
    preserves the legacy fast path verbatim, JoinedScope handles
    multi-table resolution with NULL padding.
  - eval_expr / eval_predicate / eval_function / json_fn_* / FTS
    helpers / vector-arg extractor refactored to take &dyn RowScope.
  - execute_select_rows_joined: left-folded nested-loop driver,
    O(N×M) per join level. ON only sees tables in scope at that
    join level (forward refs error). ON reuses eval_predicate_scope
    so non-zero ints are truthy, matching WHERE.
  - Parser: SelectQuery gains table_alias + joins; ProjectionKind
    Column carries an optional qualifier for t.col disambiguation.
    USING / NATURAL / CROSS / comma joins, plus aggregates / GROUP
    BY / DISTINCT over JOIN, surface as friendly NotImplemented.

17 new tests covering all four flavors, NULL padding both ways,
qualified/unqualified resolution, ambiguity, self-join rejection,
three-table chaining, chained LEFT OUTER, NULL ordering on outer
joins, ON-references-later-table errors, and truthy-int ON.

Docs: README + supported-sql.md + design-decisions.md +
architecture.md + sql-engine.md updated.

526 tests passing, 0 failures. Build, fmt, clippy clean.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

387 of 450 new or added lines in 2 files covered. (86.0%)

3 existing lines in 2 files now uncovered.

8704 of 13328 relevant lines covered (65.31%)

1.21 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.54
/src/sql/executor.rs
1
//! Query executors — evaluate parsed SQL statements against the in-memory
2
//! storage and produce formatted output.
3

4
use std::cmp::Ordering;
5

6
use prettytable::{Cell as PrintCell, Row as PrintRow, Table as PrintTable};
7
use sqlparser::ast::{
8
    AlterTable, AlterTableOperation, AssignmentTarget, BinaryOperator, CreateIndex, Delete, Expr,
9
    FromTable, FunctionArg, FunctionArgExpr, FunctionArguments, IndexType, ObjectName,
10
    ObjectNamePart, RenameTableNameKind, Statement, TableFactor, TableWithJoins, UnaryOperator,
11
    Update, Value as AstValue,
12
};
13

14
use crate::error::{Result, SQLRiteError};
15
use crate::sql::agg::{AggState, DistinctKey, like_match};
16
use crate::sql::db::database::Database;
17
use crate::sql::db::secondary_index::{IndexOrigin, SecondaryIndex};
18
use crate::sql::db::table::{
19
    DataType, FtsIndexEntry, HnswIndexEntry, Table, Value, parse_vector_literal,
20
};
21
use crate::sql::fts::{Bm25Params, PostingList};
22
use crate::sql::hnsw::{DistanceMetric, HnswIndex};
23
use crate::sql::parser::select::{
24
    AggregateArg, JoinType, OrderByClause, Projection, ProjectionItem, ProjectionKind, SelectQuery,
25
};
26

27
// -----------------------------------------------------------------
28
// SQLR-5 — Row-scope abstraction
29
// -----------------------------------------------------------------
30
//
31
// Single-table SELECT / UPDATE / DELETE evaluate WHERE / ORDER BY /
32
// projection expressions over `(&Table, rowid)`. JOIN evaluation
33
// needs the same expression evaluator to look up columns across
34
// multiple tables, with NULL padding for unmatched outer-join rows.
35
//
36
// Rather than fork the evaluator, we abstract "what's in scope when
37
// I see a column reference" behind a trait. Every callsite that
38
// previously took `(table, rowid)` now takes `&dyn RowScope`. The
39
// single-table case constructs a tiny `SingleTableScope`; the join
40
// case constructs a `JoinedScope` that knows about every table in
41
// scope plus the per-table rowid (or `None` for a NULL-padded row).
42
//
43
// The trait stays small on purpose:
44
//
45
//   - `lookup` resolves a column reference (`col` or `t.col`) to a
46
//     `Value`. NULL-padded joined rows yield `Value::Null` for any
47
//     column from their side. Ambiguous unqualified references in
48
//     joined scope error.
49
//
50
//   - `single_table_view` lets index-probing helpers (FTS, HNSW,
51
//     vec_distance) bail out cleanly when invoked over a join — they
52
//     need a `(Table, rowid)` pair to look up an index, and the
53
//     joined case can't answer without per-call disambiguation we
54
//     haven't plumbed yet. Returns `None` in joined scope.
55
pub(crate) trait RowScope {
56
    fn lookup(&self, qualifier: Option<&str>, col: &str) -> Result<Value>;
57

58
    /// `Some((table, rowid))` for a single-table scope; `None` for a
59
    /// joined scope. v1 join support delegates "needs single-table"
60
    /// helpers (FTS / HNSW / vec_distance with column args) to the
61
    /// single-table path; calling them from a joined query produces
62
    /// a `NotImplemented` error rather than wrong results.
63
    fn single_table_view(&self) -> Option<(&Table, i64)>;
64
}
65

66
/// The default scope for non-join queries: one table, one rowid.
67
pub(crate) struct SingleTableScope<'a> {
68
    table: &'a Table,
69
    rowid: i64,
70
}
71

72
impl<'a> SingleTableScope<'a> {
73
    pub(crate) fn new(table: &'a Table, rowid: i64) -> Self {
1✔
74
        Self { table, rowid }
75
    }
76
}
77

78
impl RowScope for SingleTableScope<'_> {
79
    fn lookup(&self, qualifier: Option<&str>, col: &str) -> Result<Value> {
1✔
80
        // The qualifier (if any) is ignored — we only have one table
81
        // in scope, so `t.col` resolves the same as `col`. This
82
        // matches the historical single-table path which did the
83
        // same thing in `eval_expr`.
NEW
84
        let _ = qualifier;
×
85
        Ok(self.table.get_value(col, self.rowid).unwrap_or(Value::Null))
1✔
86
    }
87

88
    fn single_table_view(&self) -> Option<(&Table, i64)> {
1✔
89
        Some((self.table, self.rowid))
1✔
90
    }
91
}
92

93
/// One table participating in a joined query, plus the user-visible
94
/// name to match against `t.col` qualifiers (alias if present, else
95
/// the bare table name).
96
pub(crate) struct JoinedTableRef<'a> {
97
    pub table: &'a Table,
98
    pub scope_name: String,
99
}
100

101
/// Multi-table scope used during join execution. `rowids[i]` is the
102
/// rowid in `tables[i]`, or `None` for a NULL-padded row coming out
103
/// of an outer join.
104
pub(crate) struct JoinedScope<'a> {
105
    pub tables: &'a [JoinedTableRef<'a>],
106
    pub rowids: &'a [Option<i64>],
107
}
108

109
impl RowScope for JoinedScope<'_> {
110
    fn lookup(&self, qualifier: Option<&str>, col: &str) -> Result<Value> {
1✔
111
        if let Some(q) = qualifier {
1✔
112
            // Qualified reference: pick the matching table; if it's
113
            // NULL-padded, the column is NULL; else fetch from row.
114
            let pos = self
3✔
NEW
115
                .tables
×
116
                .iter()
1✔
117
                .position(|t| t.scope_name.eq_ignore_ascii_case(q))
3✔
118
                .ok_or_else(|| {
2✔
119
                    SQLRiteError::Internal(format!(
1✔
NEW
120
                        "unknown table qualifier '{q}' in column reference '{q}.{col}'"
×
121
                    ))
122
                })?;
123
            if !self.tables[pos].table.contains_column(col.to_string()) {
1✔
NEW
124
                return Err(SQLRiteError::Internal(format!(
×
NEW
125
                    "column '{col}' does not exist on '{}'",
×
NEW
126
                    self.tables[pos].scope_name
×
127
                )));
128
            }
129
            return Ok(match self.rowids[pos] {
3✔
130
                None => Value::Null,
1✔
131
                Some(r) => self.tables[pos]
2✔
NEW
132
                    .table
×
133
                    .get_value(col, r)
1✔
134
                    .unwrap_or(Value::Null),
1✔
135
            });
136
        }
137
        // Unqualified: search every in-scope table. Exactly-one match
138
        // wins; zero matches → unknown column; multi matches →
139
        // ambiguous, prompt the user to qualify.
140
        let mut hit: Option<usize> = None;
1✔
141
        for (i, t) in self.tables.iter().enumerate() {
2✔
142
            if t.table.contains_column(col.to_string()) {
2✔
143
                if hit.is_some() {
1✔
144
                    return Err(SQLRiteError::Internal(format!(
1✔
NEW
145
                        "column reference '{col}' is ambiguous — qualify it as <table>.{col}"
×
146
                    )));
147
                }
148
                hit = Some(i);
1✔
149
            }
150
        }
NEW
151
        let i = hit.ok_or_else(|| {
×
NEW
152
            SQLRiteError::Internal(format!(
×
NEW
153
                "unknown column '{col}' in joined SELECT (no in-scope table has it)"
×
154
            ))
155
        })?;
NEW
156
        Ok(match self.rowids[i] {
×
NEW
157
            None => Value::Null,
×
NEW
158
            Some(r) => self.tables[i]
×
NEW
159
                .table
×
NEW
160
                .get_value(col, r)
×
NEW
161
                .unwrap_or(Value::Null),
×
162
        })
163
    }
164

NEW
165
    fn single_table_view(&self) -> Option<(&Table, i64)> {
×
NEW
166
        None
×
167
    }
168
}
169

170
/// Executes a parsed `SelectQuery` against the database and returns a
171
/// human-readable rendering of the result set (prettytable). Also returns
172
/// the number of rows produced, for the top-level status message.
173
/// Structured result of a SELECT: column names in projection order,
174
/// and each matching row as a `Vec<Value>` aligned with the columns.
175
/// Phase 5a introduced this so the public `Connection` / `Statement`
176
/// API has typed rows to yield; the existing `execute_select` that
177
/// returns pre-rendered text is now a thin wrapper on top.
178
pub struct SelectResult {
179
    pub columns: Vec<String>,
180
    pub rows: Vec<Vec<Value>>,
181
}
182

183
/// Executes a SELECT and returns structured rows. The typed rows are
184
/// what the new public API streams to callers; the REPL / Tauri app
185
/// pre-render into a prettytable via `execute_select`.
186
pub fn execute_select_rows(query: SelectQuery, db: &Database) -> Result<SelectResult> {
1✔
187
    // SQLR-5 — joined SELECTs go through a dedicated executor that
188
    // knows how to thread a multi-table scope through expression
189
    // evaluation. The single-table fast path below stays untouched
190
    // (and so do its HNSW / FTS / bounded-heap optimizations).
191
    if !query.joins.is_empty() {
2✔
192
        return execute_select_rows_joined(query, db);
2✔
193
    }
194

195
    let table = db
3✔
196
        .get_table(query.table_name.clone())
2✔
197
        .map_err(|_| SQLRiteError::Internal(format!("Table '{}' not found", query.table_name)))?;
4✔
198

199
    // SQLR-3: Materialize the projection as `Vec<ProjectionItem>` so
200
    // both the simple-row path and the aggregation path can iterate the
201
    // same shape. `Projection::All` expands to bare-column items in
202
    // declaration order; that path then runs the existing rowid pipeline.
203
    let proj_items: Vec<ProjectionItem> = match &query.projection {
1✔
204
        Projection::All => table
1✔
205
            .column_names()
206
            .into_iter()
207
            .map(|c| ProjectionItem {
3✔
208
                kind: ProjectionKind::Column {
1✔
209
                    qualifier: None,
1✔
210
                    name: c,
211
                },
212
                alias: None,
1✔
213
            })
214
            .collect(),
215
        Projection::Items(items) => items.clone(),
2✔
216
    };
217
    let has_aggregates = proj_items
3✔
218
        .iter()
219
        .any(|i| matches!(i.kind, ProjectionKind::Aggregate(_)));
3✔
220
    // Validate bare-column references against the table schema.
221
    for item in &proj_items {
1✔
222
        if let ProjectionKind::Column { name: c, .. } = &item.kind
2✔
223
            && !table.contains_column(c.clone())
1✔
224
        {
225
            return Err(SQLRiteError::Internal(format!(
1✔
226
                "Column '{c}' does not exist on table '{}'",
227
                query.table_name
228
            )));
229
        }
230
    }
231
    for c in &query.group_by {
1✔
232
        if !table.contains_column(c.clone()) {
2✔
233
            return Err(SQLRiteError::Internal(format!(
×
234
                "GROUP BY references unknown column '{c}' on table '{}'",
235
                query.table_name
236
            )));
237
        }
238
    }
239
    // Collect matching rowids. If the WHERE is the shape `col = literal`
240
    // and `col` has a secondary index, probe the index for an O(log N)
241
    // seek; otherwise fall back to the full table scan.
242
    let matching = match select_rowids(table, query.selection.as_ref())? {
1✔
243
        RowidSource::IndexProbe(rowids) => rowids,
1✔
244
        RowidSource::FullScan => {
245
            let mut out = Vec::new();
1✔
246
            for rowid in table.rowids() {
3✔
247
                if let Some(expr) = &query.selection
2✔
248
                    && !eval_predicate(expr, table, rowid)?
2✔
249
                {
250
                    continue;
251
                }
252
                out.push(rowid);
2✔
253
            }
254
            out
1✔
255
        }
256
    };
257
    let mut matching = matching;
1✔
258

259
    let aggregating = has_aggregates || !query.group_by.is_empty();
3✔
260

261
    // SQLR-3: aggregation path. When the SELECT contains aggregates or a
262
    // GROUP BY, the rowid-shaped optimizations (HNSW / FTS / bounded
263
    // heap) don't compose with grouping — every row contributes to its
264
    // group, so we walk the full filtered rowid set, accumulate, then
265
    // sort/truncate the resulting *output rows*.
266
    if aggregating {
1✔
267
        // Validate aggregate column args.
268
        for item in &proj_items {
2✔
269
            if let ProjectionKind::Aggregate(call) = &item.kind
2✔
270
                && let AggregateArg::Column(c) = &call.arg
1✔
271
                && !table.contains_column(c.clone())
1✔
272
            {
273
                return Err(SQLRiteError::Internal(format!(
×
274
                    "{}({}) references unknown column '{c}' on table '{}'",
275
                    call.func.as_str(),
×
276
                    c,
277
                    query.table_name
278
                )));
279
            }
280
        }
281

282
        let columns: Vec<String> = proj_items.iter().map(|i| i.output_name()).collect();
3✔
283
        let mut rows = aggregate_rows(table, &matching, &query.group_by, &proj_items)?;
2✔
284

285
        if query.distinct {
1✔
286
            rows = dedupe_rows(rows);
×
287
        }
288

289
        if let Some(order) = &query.order_by {
2✔
290
            sort_output_rows(&mut rows, &columns, &proj_items, order)?;
2✔
291
        }
292
        if let Some(k) = query.limit {
2✔
293
            rows.truncate(k);
2✔
294
        }
295

296
        return Ok(SelectResult { columns, rows });
1✔
297
    }
298

299
    // Non-aggregating path — same flow as before, with the extra
300
    // affordances that (a) the projection list now goes through
301
    // `ProjectionItem` and (b) DISTINCT applies after row materialization.
302

303
    // Phase 7c — bounded-heap top-k optimization.
304
    //
305
    // The naive "ORDER BY <expr>" path (Phase 7b) sorts every matching
306
    // rowid: O(N log N) sort_by + a truncate. For KNN queries
307
    //
308
    //     SELECT id FROM docs
309
    //     ORDER BY vec_distance_l2(embedding, [...])
310
    //     LIMIT 10;
311
    //
312
    // N is the table row count and k is the LIMIT. With a bounded
313
    // max-heap of size k we can find the top-k in O(N log k) — same
314
    // sort_by-per-row cost on the heap operations, but k is typically
315
    // 10-100 while N can be millions.
316
    //
317
    // Phase 7d.2 — HNSW ANN probe.
318
    //
319
    // Even better than the bounded heap: if the ORDER BY expression is
320
    // exactly `vec_distance_l2(<col>, <bracket-array literal>)` AND
321
    // `<col>` has an HNSW index attached, skip the linear scan
322
    // entirely and probe the graph in O(log N). Approximate but
323
    // typically ≥ 0.95 recall (verified by the recall tests in
324
    // src/sql/hnsw.rs).
325
    //
326
    // We branch in cases:
327
    //   1. ORDER BY + LIMIT k matches the HNSW probe pattern  → graph probe.
328
    //   2. ORDER BY + LIMIT k matches the FTS probe pattern   → posting probe.
329
    //   3. ORDER BY + LIMIT k where k < |matching|            → bounded heap (7c).
330
    //   4. ORDER BY without LIMIT, or LIMIT >= |matching|     → full sort.
331
    //   5. LIMIT without ORDER BY                              → just truncate.
332
    //
333
    // DISTINCT is applied post-projection (we'd over-truncate if LIMIT
334
    // ran before DISTINCT had a chance to collapse duplicates), so when
335
    // DISTINCT is on we defer truncation past the dedupe step.
336
    let defer_limit_for_distinct = query.distinct;
1✔
337
    match (&query.order_by, query.limit) {
2✔
338
        (Some(order), Some(k)) if try_hnsw_probe(table, &order.expr, k).is_some() => {
3✔
339
            matching = try_hnsw_probe(table, &order.expr, k).unwrap();
1✔
340
        }
341
        (Some(order), Some(k))
2✔
342
            if try_fts_probe(table, &order.expr, order.ascending, k).is_some() =>
1✔
343
        {
344
            matching = try_fts_probe(table, &order.expr, order.ascending, k).unwrap();
1✔
345
        }
346
        (Some(order), Some(k)) if !defer_limit_for_distinct && k < matching.len() => {
1✔
347
            matching = select_topk(&matching, table, order, k)?;
2✔
348
        }
349
        (Some(order), _) => {
1✔
350
            sort_rowids(&mut matching, table, order)?;
2✔
351
            if let Some(k) = query.limit
1✔
352
                && !defer_limit_for_distinct
1✔
353
            {
354
                matching.truncate(k);
1✔
355
            }
356
        }
357
        (None, Some(k)) if !defer_limit_for_distinct => {
×
358
            matching.truncate(k);
×
359
        }
360
        _ => {}
361
    }
362

363
    let columns: Vec<String> = proj_items.iter().map(|i| i.output_name()).collect();
4✔
364
    let projected_cols: Vec<String> = proj_items
1✔
365
        .iter()
366
        .map(|i| match &i.kind {
3✔
367
            ProjectionKind::Column { name, .. } => name.clone(),
1✔
368
            ProjectionKind::Aggregate(_) => unreachable!("aggregation handled above"),
×
369
        })
370
        .collect();
371

372
    // Build typed rows. Missing cells surface as `Value::Null` — that
373
    // maps a column-not-present-for-this-rowid case onto the public
374
    // `Row::get` → `Option<T>` surface cleanly.
375
    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(matching.len());
2✔
376
    for rowid in &matching {
2✔
377
        let row: Vec<Value> = projected_cols
1✔
378
            .iter()
379
            .map(|col| table.get_value(col, *rowid).unwrap_or(Value::Null))
3✔
380
            .collect();
381
        rows.push(row);
1✔
382
    }
383

384
    if query.distinct {
1✔
385
        rows = dedupe_rows(rows);
1✔
386
        if let Some(k) = query.limit {
1✔
387
            rows.truncate(k);
×
388
        }
389
    }
390

391
    Ok(SelectResult { columns, rows })
1✔
392
}
393

394
// -----------------------------------------------------------------
395
// SQLR-5 — Joined SELECT execution
396
// -----------------------------------------------------------------
397
//
398
// The strategy is a left-folded nested-loop join: start with the
399
// rowids of the leading FROM table, then for each JOIN clause
400
// combine the accumulator (`Vec<Vec<Option<i64>>>`) with the rowids
401
// of the next table. Each join flavor differs only in how it
402
// handles unmatched left / right rows:
403
//
404
//   INNER       — drop unmatched on both sides
405
//   LEFT OUTER  — keep every left row; pad right side with NULL
406
//   RIGHT OUTER — keep every right row; pad left side with NULL
407
//   FULL OUTER  — keep both unmatched sets, NULL-padding the other
408
//
409
// This isn't a hash join — every join is O(N×M) in the size of the
410
// accumulator and the right table. Adequate for SQLRite's "embedded
411
// learning database" niche; a future phase could layer hash / merge
412
// joins on equi-join shapes without changing the surface API.
413
//
414
// Aggregates / GROUP BY / DISTINCT over joined results are rejected
415
// at parse time (see SelectQuery::new). They aren't impossible —
416
// the joined-row stream is just a different rowid source feeding
417
// the same aggregator — but we left the validator that ties bare
418
// columns to GROUP BY a single-table assumption, and reworking it
419
// is outside this phase. Surfaces as a clean NotImplemented today.
420
fn execute_select_rows_joined(query: SelectQuery, db: &Database) -> Result<SelectResult> {
1✔
421
    // Resolve every participating table once and capture its scope
422
    // name (alias if supplied, else table name). Scope names are
423
    // case-sensitive in matching the original identifier text;
424
    // qualifier matches in `JoinedScope::lookup` use
425
    // `eq_ignore_ascii_case` so `T1.c1` works whether the user
426
    // wrote `T1`, `t1`, or `T1` differently than the alias.
427
    let mut joined_tables: Vec<JoinedTableRef<'_>> = Vec::with_capacity(1 + query.joins.len());
2✔
428

429
    let primary = db
1✔
430
        .get_table(query.table_name.clone())
2✔
431
        .map_err(|_| SQLRiteError::Internal(format!("Table '{}' not found", query.table_name)))?;
1✔
432
    joined_tables.push(JoinedTableRef {
1✔
433
        table: primary,
434
        scope_name: query
1✔
435
            .table_alias
436
            .clone()
1✔
437
            .unwrap_or_else(|| query.table_name.clone()),
3✔
438
    });
439
    for j in &query.joins {
1✔
440
        let t = db
1✔
441
            .get_table(j.right_table.clone())
2✔
442
            .map_err(|_| SQLRiteError::Internal(format!("Table '{}' not found", j.right_table)))?;
1✔
443
        joined_tables.push(JoinedTableRef {
1✔
444
            table: t,
445
            scope_name: j
1✔
446
                .right_alias
447
                .clone()
1✔
448
                .unwrap_or_else(|| j.right_table.clone()),
3✔
449
        });
450
    }
451

452
    // Reject duplicate scope names — `FROM t JOIN t ON ...` without
453
    // an alias on one side would silently collapse qualifiers and
454
    // produce confusing results. Forcing the user to alias one side
455
    // keeps `t1.col` / `t2.col` unambiguous.
456
    {
457
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1✔
458
        for t in &joined_tables {
2✔
459
            let key = t.scope_name.to_ascii_lowercase();
2✔
460
            if !seen.insert(key) {
1✔
461
                return Err(SQLRiteError::Internal(format!(
1✔
462
                    "duplicate table reference '{}' in FROM/JOIN — use AS to alias one side",
463
                    t.scope_name
464
                )));
465
            }
466
        }
467
    }
468

469
    // Validate qualified projection column references against the
470
    // table they qualify. Unqualified names are validated by the
471
    // first scope lookup at row materialization — the runtime check
472
    // there gives the same "ambiguous / unknown" message we'd want
473
    // here, so we don't pre-resolve them.
474
    let proj_items: Vec<ProjectionItem> = match &query.projection {
1✔
475
        Projection::All => {
476
            // `SELECT *` over a join expands to every column of every
477
            // in-scope table, in source order. We use the bare column
478
            // name as both the projected identifier and the output
479
            // header — qualified expansion (`t1.col`) would force
480
            // composite headers like `t1.col` which conflict with
481
            // alias-less convention. Duplicate header names are
482
            // permitted (matches SQLite); callers needing
483
            // disambiguation can `SELECT t.col AS t_col`.
484
            let mut all = Vec::new();
1✔
485
            for t in &joined_tables {
2✔
486
                for col in t.table.column_names() {
4✔
487
                    all.push(ProjectionItem {
1✔
488
                        kind: ProjectionKind::Column {
1✔
489
                            // Qualify the synthetic items so duplicate
490
                            // column names across tables route to the
491
                            // right side at projection time. The output
492
                            // header still uses the bare `name`.
493
                            qualifier: Some(t.scope_name.clone()),
2✔
494
                            name: col,
1✔
495
                        },
496
                        alias: None,
1✔
497
                    });
498
                }
499
            }
500
            all
1✔
501
        }
502
        Projection::Items(items) => items.clone(),
2✔
503
    };
504

505
    let columns: Vec<String> = proj_items.iter().map(|i| i.output_name()).collect();
4✔
506

507
    // Stage 1: enumerate rows of the leading table. The accumulator
508
    // is `Vec<Vec<Option<i64>>>` where each inner `Vec` is a join
509
    // row whose i-th slot is the rowid of `joined_tables[i]` (or
510
    // None for a NULL-padded row from an outer join).
511
    let mut acc: Vec<Vec<Option<i64>>> = primary
512
        .rowids()
513
        .into_iter()
514
        .map(|r| {
2✔
515
            let mut row = Vec::with_capacity(joined_tables.len());
1✔
516
            row.push(Some(r));
1✔
517
            row
1✔
518
        })
519
        .collect();
520

521
    // Stage 2: fold each JOIN clause into the accumulator. After
522
    // join `i`, every row in `acc` has length `i + 2` (primary +
523
    // i+1 right tables joined). Unmatched-side handling depends on
524
    // the join flavor.
525
    for (j_idx, join) in query.joins.iter().enumerate() {
2✔
526
        let right_pos = j_idx + 1;
2✔
527
        let right_table = joined_tables[right_pos].table;
2✔
528
        let right_rowids: Vec<i64> = right_table.rowids();
1✔
529

530
        // Track which right rowids matched at least once across the
531
        // entire left accumulator. Used by RIGHT / FULL to emit
532
        // unmatched right rows after the loop.
533
        let mut right_matched: Vec<bool> = vec![false; right_rowids.len()];
2✔
534

535
        let mut next_acc: Vec<Vec<Option<i64>>> = Vec::with_capacity(acc.len());
2✔
536

537
        // ON evaluation only sees tables that are in scope *at this
538
        // join level* — the leading FROM table plus every right
539
        // table joined so far, including the one we're matching.
540
        // Restricting the scope means a typo like `JOIN c ON a.id =
541
        // c.id JOIN c ON ...` (referencing `c` before it joins)
542
        // surfaces as "unknown table qualifier 'c'" rather than
543
        // silently `NULL → false`-ing every row.
544
        let on_scope_tables: &[JoinedTableRef<'_>] = &joined_tables[..=right_pos];
2✔
545

546
        for left_row in acc.into_iter() {
3✔
547
            // Build a row prefix and extend it with each candidate
548
            // right rowid; record whether any matched (for outer
549
            // padding on the left side).
550
            let mut left_match_count = 0usize;
1✔
551
            for (r_idx, &rrid) in right_rowids.iter().enumerate() {
3✔
552
                let mut on_rowids: Vec<Option<i64>> = left_row.clone();
2✔
553
                on_rowids.push(Some(rrid));
1✔
554
                debug_assert_eq!(on_rowids.len(), on_scope_tables.len());
1✔
555
                let scope = JoinedScope {
556
                    tables: on_scope_tables,
557
                    rowids: &on_rowids,
1✔
558
                };
559
                // Reuse `eval_predicate_scope` so ON shares the same
560
                // truthiness rule WHERE uses — non-zero integers are
561
                // truthy, NULL is false, etc. — instead of rejecting
562
                // anything that isn't a literal bool.
563
                if eval_predicate_scope(&join.on, &scope)? {
1✔
564
                    left_match_count += 1;
1✔
565
                    right_matched[r_idx] = true;
2✔
566
                    // Accumulator entries carry only as many slots
567
                    // as join levels processed so far; the next
568
                    // iteration extends them again. No trailing
569
                    // padding needed here.
570
                    next_acc.push(on_rowids);
1✔
571
                }
572
            }
573

574
            if left_match_count == 0
2✔
575
                && matches!(join.join_type, JoinType::LeftOuter | JoinType::FullOuter)
1✔
576
            {
577
                // Outer-join NULL pad on the right side: keep the
578
                // left row, push None for the right rowid.
579
                let mut padded = left_row;
1✔
580
                padded.push(None);
1✔
581
                next_acc.push(padded);
1✔
582
            }
583
        }
584

585
        // Right-only emission for RIGHT / FULL: any right rowid that
586
        // never matched on the entire accumulator surfaces with all
587
        // left positions NULL-padded.
588
        if matches!(join.join_type, JoinType::RightOuter | JoinType::FullOuter) {
1✔
589
            for (r_idx, matched) in right_matched.iter().enumerate() {
2✔
590
                if *matched {
1✔
591
                    continue;
592
                }
593
                let mut row: Vec<Option<i64>> = vec![None; right_pos];
1✔
594
                row.push(Some(right_rowids[r_idx]));
2✔
595
                next_acc.push(row);
1✔
596
            }
597
        }
598

599
        acc = next_acc;
1✔
600
    }
601

602
    // Stage 3: apply WHERE on each fully-joined row. Outer-join
603
    // NULL-padded rows where WHERE references a NULL'd column will
604
    // (per SQL three-valued logic) be excluded — this is the same
605
    // posture as the single-table path.
606
    let mut filtered: Vec<Vec<Option<i64>>> = if let Some(where_expr) = &query.selection {
2✔
607
        let mut out = Vec::with_capacity(acc.len());
2✔
608
        for row in acc {
4✔
609
            let scope = JoinedScope {
610
                tables: &joined_tables,
1✔
611
                rowids: &row,
1✔
612
            };
613
            if eval_predicate_scope(where_expr, &scope)? {
1✔
614
                out.push(row);
1✔
615
            }
616
        }
617
        out
1✔
618
    } else {
619
        acc
1✔
620
    };
621

622
    // Stage 4: ORDER BY across the joined scope. We pre-compute the
623
    // sort key per row (same approach as `sort_rowids`) so the
624
    // comparator runs on Values, not against the expression tree.
625
    if let Some(order) = &query.order_by {
3✔
626
        // Validate up front so a bad ORDER BY surfaces a clear
627
        // error before sort starts.
628
        let mut keys: Vec<(usize, Value)> = Vec::with_capacity(filtered.len());
2✔
629
        for (i, row) in filtered.iter().enumerate() {
3✔
630
            let scope = JoinedScope {
631
                tables: &joined_tables,
1✔
632
                rowids: row,
633
            };
634
            let v = eval_expr_scope(&order.expr, &scope)?;
1✔
635
            keys.push((i, v));
1✔
636
        }
637
        keys.sort_by(|(_, a), (_, b)| {
3✔
638
            let ord = compare_values(Some(a), Some(b));
1✔
639
            if order.ascending { ord } else { ord.reverse() }
1✔
640
        });
641
        let mut sorted = Vec::with_capacity(filtered.len());
1✔
642
        for (i, _) in keys {
3✔
643
            sorted.push(filtered[i].clone());
2✔
644
        }
645
        filtered = sorted;
1✔
646
    }
647

648
    // Stage 5: LIMIT.
649
    if let Some(k) = query.limit {
2✔
650
        filtered.truncate(k);
2✔
651
    }
652

653
    // Stage 6: project. For each row, evaluate every projection item
654
    // through the joined scope.
655
    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(filtered.len());
2✔
656
    for row in &filtered {
3✔
657
        let scope = JoinedScope {
658
            tables: &joined_tables,
1✔
659
            rowids: row,
660
        };
661
        let mut out_row = Vec::with_capacity(proj_items.len());
1✔
662
        for item in &proj_items {
2✔
663
            let v = match &item.kind {
1✔
664
                ProjectionKind::Column { qualifier, name } => {
1✔
665
                    scope.lookup(qualifier.as_deref(), name)?
2✔
666
                }
667
                ProjectionKind::Aggregate(_) => {
668
                    // SelectQuery::new already rejects this combination,
669
                    // but defense in depth keeps the pattern match total.
NEW
670
                    return Err(SQLRiteError::Internal(
×
NEW
671
                        "aggregate functions over JOIN are not supported".to_string(),
×
672
                    ));
673
                }
674
            };
675
            out_row.push(v);
1✔
676
        }
677
        rows.push(out_row);
1✔
678
    }
679

680
    Ok(SelectResult { columns, rows })
1✔
681
}
682

683
/// Executes a SELECT and returns `(rendered_table, row_count)`. The
684
/// REPL and Tauri app use this to keep the table-printing behaviour
685
/// the engine has always shipped. Structured callers use
686
/// `execute_select_rows` instead.
687
pub fn execute_select(query: SelectQuery, db: &Database) -> Result<(String, usize)> {
1✔
688
    let result = execute_select_rows(query, db)?;
1✔
689
    let row_count = result.rows.len();
2✔
690

691
    let mut print_table = PrintTable::new();
1✔
692
    let header_cells: Vec<PrintCell> = result.columns.iter().map(|c| PrintCell::new(c)).collect();
4✔
693
    print_table.add_row(PrintRow::new(header_cells));
1✔
694

695
    for row in &result.rows {
1✔
696
        let cells: Vec<PrintCell> = row
1✔
697
            .iter()
698
            .map(|v| PrintCell::new(&v.to_display_string()))
3✔
699
            .collect();
700
        print_table.add_row(PrintRow::new(cells));
1✔
701
    }
702

703
    Ok((print_table.to_string(), row_count))
1✔
704
}
705

706
/// Executes a DELETE statement. Returns the number of rows removed.
707
pub fn execute_delete(stmt: &Statement, db: &mut Database) -> Result<usize> {
1✔
708
    let Statement::Delete(Delete {
1✔
709
        from, selection, ..
1✔
710
    }) = stmt
1✔
711
    else {
712
        return Err(SQLRiteError::Internal(
×
713
            "execute_delete called on a non-DELETE statement".to_string(),
×
714
        ));
715
    };
716

717
    let tables = match from {
1✔
718
        FromTable::WithFromKeyword(t) | FromTable::WithoutKeyword(t) => t,
2✔
719
    };
720
    let table_name = extract_single_table_name(tables)?;
1✔
721

722
    // Compute matching rowids with an immutable borrow, then mutate.
723
    let matching: Vec<i64> = {
724
        let table = db
1✔
725
            .get_table(table_name.clone())
2✔
726
            .map_err(|_| SQLRiteError::Internal(format!("Table '{table_name}' not found")))?;
1✔
727
        match select_rowids(table, selection.as_ref())? {
1✔
728
            RowidSource::IndexProbe(rowids) => rowids,
1✔
729
            RowidSource::FullScan => {
730
                let mut out = Vec::new();
1✔
731
                for rowid in table.rowids() {
3✔
732
                    if let Some(expr) = selection {
2✔
733
                        if !eval_predicate(expr, table, rowid)? {
2✔
734
                            continue;
735
                        }
736
                    }
737
                    out.push(rowid);
2✔
738
                }
739
                out
1✔
740
            }
741
        }
742
    };
743

744
    let table = db.get_table_mut(table_name)?;
2✔
745
    for rowid in &matching {
1✔
746
        table.delete_row(*rowid);
2✔
747
    }
748
    // Phase 7d.3 — any DELETE invalidates every HNSW index on this
749
    // table (the deleted node could still appear in other nodes'
750
    // neighbor lists, breaking subsequent searches). Mark dirty so
751
    // the next save rebuilds from current rows before serializing.
752
    //
753
    // Phase 8b — same posture for FTS indexes (Q7 — rebuild-on-save
754
    // mirrors HNSW). The deleted rowid still appears in posting
755
    // lists; leaving it would surface zombie hits in future queries.
756
    if !matching.is_empty() {
1✔
757
        for entry in &mut table.hnsw_indexes {
3✔
758
            entry.needs_rebuild = true;
1✔
759
        }
760
        for entry in &mut table.fts_indexes {
2✔
761
            entry.needs_rebuild = true;
1✔
762
        }
763
    }
764
    Ok(matching.len())
2✔
765
}
766

767
/// Executes an UPDATE statement. Returns the number of rows updated.
768
pub fn execute_update(stmt: &Statement, db: &mut Database) -> Result<usize> {
1✔
769
    let Statement::Update(Update {
1✔
770
        table,
1✔
771
        assignments,
1✔
772
        from,
1✔
773
        selection,
1✔
774
        ..
775
    }) = stmt
1✔
776
    else {
777
        return Err(SQLRiteError::Internal(
×
778
            "execute_update called on a non-UPDATE statement".to_string(),
×
779
        ));
780
    };
781

782
    if from.is_some() {
1✔
783
        return Err(SQLRiteError::NotImplemented(
×
784
            "UPDATE ... FROM is not supported yet".to_string(),
×
785
        ));
786
    }
787

788
    let table_name = extract_table_name(table)?;
1✔
789

790
    // Resolve assignment targets to plain column names and verify they exist.
791
    let mut parsed_assignments: Vec<(String, Expr)> = Vec::with_capacity(assignments.len());
2✔
792
    {
793
        let tbl = db
1✔
794
            .get_table(table_name.clone())
2✔
795
            .map_err(|_| SQLRiteError::Internal(format!("Table '{table_name}' not found")))?;
1✔
796
        for a in assignments {
2✔
797
            let col = match &a.target {
1✔
798
                AssignmentTarget::ColumnName(name) => name
2✔
799
                    .0
800
                    .last()
1✔
801
                    .map(|p| p.to_string())
3✔
802
                    .ok_or_else(|| SQLRiteError::Internal("empty column name".to_string()))?,
1✔
803
                AssignmentTarget::Tuple(_) => {
804
                    return Err(SQLRiteError::NotImplemented(
×
805
                        "tuple assignment targets are not supported".to_string(),
×
806
                    ));
807
                }
808
            };
809
            if !tbl.contains_column(col.clone()) {
2✔
810
                return Err(SQLRiteError::Internal(format!(
×
811
                    "UPDATE references unknown column '{col}'"
812
                )));
813
            }
814
            parsed_assignments.push((col, a.value.clone()));
1✔
815
        }
816
    }
817

818
    // Gather matching rowids + the new values to write for each assignment, under
819
    // an immutable borrow. Uses the index-probe fast path when the WHERE is
820
    // `col = literal` on an indexed column.
821
    let work: Vec<(i64, Vec<(String, Value)>)> = {
822
        let tbl = db.get_table(table_name.clone())?;
1✔
823
        let matched_rowids: Vec<i64> = match select_rowids(tbl, selection.as_ref())? {
1✔
824
            RowidSource::IndexProbe(rowids) => rowids,
1✔
825
            RowidSource::FullScan => {
826
                let mut out = Vec::new();
1✔
827
                for rowid in tbl.rowids() {
3✔
828
                    if let Some(expr) = selection {
2✔
829
                        if !eval_predicate(expr, tbl, rowid)? {
2✔
830
                            continue;
831
                        }
832
                    }
833
                    out.push(rowid);
2✔
834
                }
835
                out
1✔
836
            }
837
        };
838
        let mut rows_to_update = Vec::new();
1✔
839
        for rowid in matched_rowids {
4✔
840
            let mut values = Vec::with_capacity(parsed_assignments.len());
2✔
841
            for (col, expr) in &parsed_assignments {
3✔
842
                // UPDATE's RHS is evaluated in the context of the row being updated,
843
                // so column references on the right resolve to the current row's values.
844
                let v = eval_expr(expr, tbl, rowid)?;
2✔
845
                values.push((col.clone(), v));
2✔
846
            }
847
            rows_to_update.push((rowid, values));
1✔
848
        }
849
        rows_to_update
1✔
850
    };
851

852
    let tbl = db.get_table_mut(table_name)?;
2✔
853
    for (rowid, values) in &work {
1✔
854
        for (col, v) in values {
2✔
855
            tbl.set_value(col, *rowid, v.clone())?;
1✔
856
        }
857
    }
858

859
    // Phase 7d.3 — UPDATE may have changed a vector column that an
860
    // HNSW index covers. Mark every covering index dirty so save
861
    // rebuilds from current rows. (Updates that only touched
862
    // non-vector columns also mark dirty, which is over-conservative
863
    // but harmless — the rebuild walks rows anyway, and the cost is
864
    // only paid on save.)
865
    //
866
    // Phase 8b — same shape for FTS indexes covering updated TEXT cols.
867
    if !work.is_empty() {
1✔
868
        let updated_columns: std::collections::HashSet<&str> = work
1✔
869
            .iter()
870
            .flat_map(|(_, values)| values.iter().map(|(c, _)| c.as_str()))
5✔
871
            .collect();
872
        for entry in &mut tbl.hnsw_indexes {
2✔
873
            if updated_columns.contains(entry.column_name.as_str()) {
3✔
874
                entry.needs_rebuild = true;
1✔
875
            }
876
        }
877
        for entry in &mut tbl.fts_indexes {
1✔
878
            if updated_columns.contains(entry.column_name.as_str()) {
3✔
879
                entry.needs_rebuild = true;
1✔
880
            }
881
        }
882
    }
883
    Ok(work.len())
2✔
884
}
885

886
/// Handles `CREATE INDEX [UNIQUE] <name> ON <table> [USING <method>] (<column>)`.
887
/// Single-column indexes only.
888
///
889
/// Two flavours, branching on the optional `USING <method>` clause:
890
///   - **No USING, or `USING btree`**: regular B-Tree secondary index
891
///     (Phase 3e). Indexable types: Integer, Text.
892
///   - **`USING hnsw`**: HNSW ANN index (Phase 7d.2). Indexable types:
893
///     Vector(N) only. Distance metric is L2 by default; cosine and
894
///     dot variants are deferred to Phase 7d.x.
895
///
896
/// Returns the (possibly synthesized) index name for the status message.
897
pub fn execute_create_index(stmt: &Statement, db: &mut Database) -> Result<String> {
1✔
898
    let Statement::CreateIndex(CreateIndex {
1✔
899
        name,
1✔
900
        table_name,
1✔
901
        columns,
1✔
902
        using,
1✔
903
        unique,
1✔
904
        if_not_exists,
1✔
905
        predicate,
1✔
906
        ..
907
    }) = stmt
1✔
908
    else {
909
        return Err(SQLRiteError::Internal(
×
910
            "execute_create_index called on a non-CREATE-INDEX statement".to_string(),
×
911
        ));
912
    };
913

914
    if predicate.is_some() {
1✔
915
        return Err(SQLRiteError::NotImplemented(
×
916
            "partial indexes (CREATE INDEX ... WHERE) are not supported yet".to_string(),
×
917
        ));
918
    }
919

920
    if columns.len() != 1 {
1✔
921
        return Err(SQLRiteError::NotImplemented(format!(
×
922
            "multi-column indexes are not supported yet ({} columns given)",
923
            columns.len()
×
924
        )));
925
    }
926

927
    let index_name = name.as_ref().map(|n| n.to_string()).ok_or_else(|| {
3✔
928
        SQLRiteError::NotImplemented(
×
929
            "anonymous CREATE INDEX (no name) is not supported — give it a name".to_string(),
×
930
        )
931
    })?;
932

933
    // Detect USING <method>. The `using` field on CreateIndex covers the
934
    // pre-column form `CREATE INDEX … USING hnsw (col)`. (sqlparser also
935
    // accepts a post-column form `… (col) USING hnsw` and parks that in
936
    // `index_options`; we don't bother with it — the canonical form is
937
    // pre-column and matches PG/pgvector convention.)
938
    let method = match using {
1✔
939
        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("hnsw") => {
2✔
940
            IndexMethod::Hnsw
1✔
941
        }
942
        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("fts") => {
2✔
943
            IndexMethod::Fts
1✔
944
        }
945
        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("btree") => {
×
946
            IndexMethod::Btree
×
947
        }
948
        Some(other) => {
×
949
            return Err(SQLRiteError::NotImplemented(format!(
×
950
                "CREATE INDEX … USING {other:?} is not supported \
951
                 (try `hnsw`, `fts`, or no USING clause)"
952
            )));
953
        }
954
        None => IndexMethod::Btree,
1✔
955
    };
956

957
    let table_name_str = table_name.to_string();
1✔
958
    let column_name = match &columns[0].column.expr {
2✔
959
        Expr::Identifier(ident) => ident.value.clone(),
2✔
960
        Expr::CompoundIdentifier(parts) => parts
×
961
            .last()
×
962
            .map(|p| p.value.clone())
×
963
            .ok_or_else(|| SQLRiteError::Internal("empty compound identifier".to_string()))?,
×
964
        other => {
×
965
            return Err(SQLRiteError::NotImplemented(format!(
×
966
                "CREATE INDEX only supports simple column references, got {other:?}"
967
            )));
968
        }
969
    };
970

971
    // Validate: table exists, column exists, type matches the index method,
972
    // name is unique across both index kinds. Snapshot (rowid, value) pairs
973
    // up front under the immutable borrow so the mutable attach later
974
    // doesn't fight over `self`.
975
    let (datatype, existing_rowids_and_values): (DataType, Vec<(i64, Value)>) = {
1✔
976
        let table = db.get_table(table_name_str.clone()).map_err(|_| {
2✔
977
            SQLRiteError::General(format!(
×
978
                "CREATE INDEX references unknown table '{table_name_str}'"
979
            ))
980
        })?;
981
        if !table.contains_column(column_name.clone()) {
1✔
982
            return Err(SQLRiteError::General(format!(
×
983
                "CREATE INDEX references unknown column '{column_name}' on table '{table_name_str}'"
984
            )));
985
        }
986
        let col = table
3✔
987
            .columns
988
            .iter()
989
            .find(|c| c.column_name == column_name)
3✔
990
            .expect("we just verified the column exists");
991

992
        // Name uniqueness check spans ALL index kinds — btree, hnsw, and
993
        // fts share one namespace per table.
994
        if table.index_by_name(&index_name).is_some()
1✔
995
            || table.hnsw_indexes.iter().any(|i| i.name == index_name)
4✔
996
            || table.fts_indexes.iter().any(|i| i.name == index_name)
3✔
997
        {
998
            if *if_not_exists {
1✔
999
                return Ok(index_name);
1✔
1000
            }
1001
            return Err(SQLRiteError::General(format!(
2✔
1002
                "index '{index_name}' already exists"
1003
            )));
1004
        }
1005
        let datatype = clone_datatype(&col.datatype);
1✔
1006

1007
        let mut pairs = Vec::new();
1✔
1008
        for rowid in table.rowids() {
3✔
1009
            if let Some(v) = table.get_value(&column_name, rowid) {
2✔
1010
                pairs.push((rowid, v));
1✔
1011
            }
1012
        }
1013
        (datatype, pairs)
1✔
1014
    };
1015

1016
    match method {
1✔
1017
        IndexMethod::Btree => create_btree_index(
1018
            db,
1019
            &table_name_str,
1✔
1020
            &index_name,
1✔
1021
            &column_name,
1✔
1022
            &datatype,
1023
            *unique,
1✔
1024
            &existing_rowids_and_values,
1✔
1025
        ),
1026
        IndexMethod::Hnsw => create_hnsw_index(
1027
            db,
1028
            &table_name_str,
1✔
1029
            &index_name,
1✔
1030
            &column_name,
1✔
1031
            &datatype,
1032
            *unique,
1✔
1033
            &existing_rowids_and_values,
1✔
1034
        ),
1035
        IndexMethod::Fts => create_fts_index(
1036
            db,
1037
            &table_name_str,
1✔
1038
            &index_name,
1✔
1039
            &column_name,
1✔
1040
            &datatype,
1041
            *unique,
1✔
1042
            &existing_rowids_and_values,
1✔
1043
        ),
1044
    }
1045
}
1046

1047
/// Executes `DROP TABLE [IF EXISTS] <name>;`. Mirrors SQLite's single-target
1048
/// shape: sqlparser parses `DROP TABLE a, b` as one statement with
1049
/// `names: vec![a, b]`, but we reject the multi-target form to keep error
1050
/// semantics simple (no partial-failure rollback).
1051
///
1052
/// On success the table — and every index attached to it — disappears from
1053
/// the in-memory `Database`. The next auto-save rebuilds `sqlrite_master`
1054
/// from scratch and simply doesn't write a row for the dropped table or
1055
/// its indexes; pages previously occupied by them become orphans on disk
1056
/// (no free-list yet — file size doesn't shrink until a future VACUUM).
1057
pub fn execute_drop_table(
1✔
1058
    names: &[ObjectName],
1059
    if_exists: bool,
1060
    db: &mut Database,
1061
) -> Result<usize> {
1062
    if names.len() != 1 {
1✔
1063
        return Err(SQLRiteError::NotImplemented(
1✔
1064
            "DROP TABLE supports a single table per statement".to_string(),
1✔
1065
        ));
1066
    }
1067
    let name = names[0].to_string();
2✔
1068

1069
    if name == crate::sql::pager::MASTER_TABLE_NAME {
2✔
1070
        return Err(SQLRiteError::General(format!(
2✔
1071
            "'{}' is a reserved name used by the internal schema catalog",
1072
            crate::sql::pager::MASTER_TABLE_NAME
1073
        )));
1074
    }
1075

1076
    if !db.contains_table(name.clone()) {
2✔
1077
        return if if_exists {
2✔
1078
            Ok(0)
1✔
1079
        } else {
1080
            Err(SQLRiteError::General(format!(
2✔
1081
                "Table '{name}' does not exist"
1082
            )))
1083
        };
1084
    }
1085

1086
    db.tables.remove(&name);
2✔
1087
    Ok(1)
1088
}
1089

1090
/// Executes `DROP INDEX [IF EXISTS] <name>;`. The statement does not name a
1091
/// table, so we walk every table looking for the index across all three
1092
/// index families (B-Tree secondary, HNSW, FTS).
1093
///
1094
/// Refuses to drop auto-indexes (`origin == IndexOrigin::Auto`) — those are
1095
/// invariants of the table's PRIMARY KEY / UNIQUE constraints and should
1096
/// only disappear when the column or table they depend on is dropped.
1097
/// SQLite has the same rule for its `sqlite_autoindex_*` indexes.
1098
pub fn execute_drop_index(
1✔
1099
    names: &[ObjectName],
1100
    if_exists: bool,
1101
    db: &mut Database,
1102
) -> Result<usize> {
1103
    if names.len() != 1 {
1✔
1104
        return Err(SQLRiteError::NotImplemented(
×
1105
            "DROP INDEX supports a single index per statement".to_string(),
×
1106
        ));
1107
    }
1108
    let name = names[0].to_string();
2✔
1109

1110
    for table in db.tables.values_mut() {
2✔
1111
        if let Some(secondary) = table.secondary_indexes.iter().find(|i| i.name == name) {
4✔
1112
            if secondary.origin == IndexOrigin::Auto {
2✔
1113
                return Err(SQLRiteError::General(format!(
2✔
1114
                    "cannot drop auto-created index '{name}' (drop the column or table instead)"
1115
                )));
1116
            }
1117
            table.secondary_indexes.retain(|i| i.name != name);
3✔
1118
            return Ok(1);
1✔
1119
        }
1120
        if table.hnsw_indexes.iter().any(|i| i.name == name) {
×
1121
            table.hnsw_indexes.retain(|i| i.name != name);
×
1122
            return Ok(1);
×
1123
        }
1124
        if table.fts_indexes.iter().any(|i| i.name == name) {
×
1125
            table.fts_indexes.retain(|i| i.name != name);
×
1126
            return Ok(1);
×
1127
        }
1128
    }
1129

1130
    if if_exists {
2✔
1131
        Ok(0)
1132
    } else {
1133
        Err(SQLRiteError::General(format!(
2✔
1134
            "Index '{name}' does not exist"
1135
        )))
1136
    }
1137
}
1138

1139
/// Executes `ALTER TABLE [IF EXISTS] <name> <op>;` for one operation per
1140
/// statement. Supports four sub-operations matching SQLite:
1141
///
1142
///   - `RENAME TO <new>`
1143
///   - `RENAME COLUMN <old> TO <new>`
1144
///   - `ADD COLUMN <coldef>` (NOT NULL requires DEFAULT on a non-empty table;
1145
///     PK / UNIQUE constraints rejected — would need backfill + uniqueness)
1146
///   - `DROP COLUMN <name>` (refuses PK column and only-column)
1147
///
1148
/// Multi-operation ALTER (`ALTER TABLE foo RENAME TO bar, ADD COLUMN x ...`)
1149
/// is rejected; SQLite forbids it too.
1150
pub fn execute_alter_table(alter: AlterTable, db: &mut Database) -> Result<String> {
1✔
1151
    let table_name = alter.name.to_string();
1✔
1152

1153
    if table_name == crate::sql::pager::MASTER_TABLE_NAME {
2✔
1154
        return Err(SQLRiteError::General(format!(
×
1155
            "'{}' is a reserved name used by the internal schema catalog",
1156
            crate::sql::pager::MASTER_TABLE_NAME
1157
        )));
1158
    }
1159

1160
    if !db.contains_table(table_name.clone()) {
2✔
1161
        return if alter.if_exists {
2✔
1162
            Ok("ALTER TABLE: no-op (table does not exist)".to_string())
2✔
1163
        } else {
1164
            Err(SQLRiteError::General(format!(
2✔
1165
                "Table '{table_name}' does not exist"
1166
            )))
1167
        };
1168
    }
1169

1170
    if alter.operations.len() != 1 {
2✔
1171
        return Err(SQLRiteError::NotImplemented(
×
1172
            "ALTER TABLE supports one operation per statement".to_string(),
×
1173
        ));
1174
    }
1175

1176
    match &alter.operations[0] {
2✔
1177
        AlterTableOperation::RenameTable { table_name: kind } => {
1✔
1178
            let new_name = match kind {
1✔
1179
                RenameTableNameKind::To(name) => name.to_string(),
1✔
1180
                RenameTableNameKind::As(_) => {
1181
                    return Err(SQLRiteError::NotImplemented(
×
1182
                        "ALTER TABLE ... RENAME AS (MySQL-only) is not supported; use RENAME TO"
1183
                            .to_string(),
×
1184
                    ));
1185
                }
1186
            };
1187
            alter_rename_table(db, &table_name, &new_name)?;
2✔
1188
            Ok(format!(
1✔
1189
                "ALTER TABLE '{table_name}' RENAME TO '{new_name}' executed."
1190
            ))
1191
        }
1192
        AlterTableOperation::RenameColumn {
1193
            old_column_name,
1✔
1194
            new_column_name,
1✔
1195
        } => {
1196
            let old = old_column_name.value.clone();
1✔
1197
            let new = new_column_name.value.clone();
1✔
1198
            db.get_table_mut(table_name.clone())?
5✔
1199
                .rename_column(&old, &new)?;
2✔
1200
            Ok(format!(
1✔
1201
                "ALTER TABLE '{table_name}' RENAME COLUMN '{old}' TO '{new}' executed."
1202
            ))
1203
        }
1204
        AlterTableOperation::AddColumn {
1205
            column_def,
1✔
1206
            if_not_exists,
1✔
1207
            ..
1208
        } => {
1209
            let parsed = crate::sql::parser::create::parse_one_column(column_def)?;
2✔
1210
            let table = db.get_table_mut(table_name.clone())?;
2✔
1211
            if *if_not_exists && table.contains_column(parsed.name.clone()) {
1✔
1212
                return Ok(format!(
×
1213
                    "ALTER TABLE '{table_name}' ADD COLUMN: no-op (column '{}' already exists)",
1214
                    parsed.name
1215
                ));
1216
            }
1217
            let col_name = parsed.name.clone();
1✔
1218
            table.add_column(parsed)?;
2✔
1219
            Ok(format!(
1✔
1220
                "ALTER TABLE '{table_name}' ADD COLUMN '{col_name}' executed."
1221
            ))
1222
        }
1223
        AlterTableOperation::DropColumn {
1224
            column_names,
1✔
1225
            if_exists,
1✔
1226
            ..
1227
        } => {
1228
            if column_names.len() != 1 {
2✔
1229
                return Err(SQLRiteError::NotImplemented(
×
1230
                    "ALTER TABLE DROP COLUMN supports a single column per statement".to_string(),
×
1231
                ));
1232
            }
1233
            let col_name = column_names[0].value.clone();
2✔
1234
            let table = db.get_table_mut(table_name.clone())?;
2✔
1235
            if *if_exists && !table.contains_column(col_name.clone()) {
1✔
1236
                return Ok(format!(
×
1237
                    "ALTER TABLE '{table_name}' DROP COLUMN: no-op (column '{col_name}' does not exist)"
1238
                ));
1239
            }
1240
            table.drop_column(&col_name)?;
3✔
1241
            Ok(format!(
1✔
1242
                "ALTER TABLE '{table_name}' DROP COLUMN '{col_name}' executed."
1243
            ))
1244
        }
1245
        other => Err(SQLRiteError::NotImplemented(format!(
×
1246
            "ALTER TABLE operation {other:?} is not supported"
1247
        ))),
1248
    }
1249
}
1250

1251
/// Executes `VACUUM;` (SQLR-6). Compacts the database file: rewrites
1252
/// every live table, index, and the catalog contiguously from page 1,
1253
/// drops the freelist, and truncates the tail at the next checkpoint.
1254
///
1255
/// Refuses to run inside a transaction (would publish in-flight writes
1256
/// out of band); refuses on read-only databases (handled upstream by
1257
/// the read-only mutation gate); and is a no-op on in-memory databases
1258
/// (no file to compact). Bare `VACUUM;` only — non-default options
1259
/// (`FULL`, `REINDEX`, table targets, etc.) are rejected.
1260
pub fn execute_vacuum(db: &mut Database) -> Result<String> {
2✔
1261
    if db.in_transaction() {
1✔
1262
        return Err(SQLRiteError::General(
1✔
1263
            "VACUUM cannot run inside a transaction".to_string(),
1✔
1264
        ));
1265
    }
1266
    let path = match db.source_path.clone() {
1✔
1267
        Some(p) => p,
1✔
1268
        None => {
1269
            return Ok("VACUUM is a no-op for in-memory databases".to_string());
1✔
1270
        }
1271
    };
1272
    // Checkpoint before AND after VACUUM so the main-file size we report
1273
    // reflects only what VACUUM actually reclaimed — without the leading
1274
    // checkpoint, `size_before` would be the stale main-file snapshot
1275
    // (typically 2 pages) while WAL holds the live bytes, making the
1276
    // bytes-reclaimed delta meaningless.
1277
    if let Some(pager) = db.pager.as_mut() {
2✔
1278
        let _ = pager.checkpoint();
2✔
1279
    }
1280
    let size_before = std::fs::metadata(&path).ok().map(|m| m.len()).unwrap_or(0);
4✔
1281
    let pages_before = db
2✔
1282
        .pager
1283
        .as_ref()
1284
        .map(|p| p.header().page_count)
3✔
1285
        .unwrap_or(0);
1286
    crate::sql::pager::vacuum_database(db, &path)?;
1✔
1287
    // Second checkpoint so the main file shrinks now — VACUUM's whole
1288
    // purpose is to reclaim bytes, so paying the I/O up front is fair.
1289
    if let Some(pager) = db.pager.as_mut() {
1✔
1290
        let _ = pager.checkpoint();
2✔
1291
    }
1292
    let size_after = std::fs::metadata(&path).ok().map(|m| m.len()).unwrap_or(0);
4✔
1293
    let pages_after = db
2✔
1294
        .pager
1295
        .as_ref()
1296
        .map(|p| p.header().page_count)
3✔
1297
        .unwrap_or(0);
1298
    let pages_reclaimed = pages_before.saturating_sub(pages_after);
1✔
1299
    let bytes_reclaimed = size_before.saturating_sub(size_after);
1✔
1300
    Ok(format!(
1✔
1301
        "VACUUM completed. {pages_reclaimed} pages reclaimed ({bytes_reclaimed} bytes)."
1302
    ))
1303
}
1304

1305
/// Renames a table in `db.tables`. Updates `tb_name`, every secondary
1306
/// index's `table_name` field, and any auto-index whose name embedded
1307
/// the old table name. HNSW / FTS index entries don't carry a
1308
/// `table_name` field — they're addressed implicitly via the `Table`
1309
/// they live inside, so they move with the rename for free.
1310
fn alter_rename_table(db: &mut Database, old: &str, new: &str) -> Result<()> {
1✔
1311
    if new == crate::sql::pager::MASTER_TABLE_NAME {
1✔
1312
        return Err(SQLRiteError::General(format!(
1✔
1313
            "'{}' is a reserved name used by the internal schema catalog",
1314
            crate::sql::pager::MASTER_TABLE_NAME
1315
        )));
1316
    }
1317
    if old == new {
1✔
1318
        return Ok(());
×
1319
    }
1320
    if db.contains_table(new.to_string()) {
1✔
1321
        return Err(SQLRiteError::General(format!(
1✔
1322
            "target table '{new}' already exists"
1323
        )));
1324
    }
1325

1326
    let mut table = db
3✔
1327
        .tables
1328
        .remove(old)
1✔
1329
        .ok_or_else(|| SQLRiteError::General(format!("Table '{old}' does not exist")))?;
1✔
1330
    table.tb_name = new.to_string();
2✔
1331
    for idx in table.secondary_indexes.iter_mut() {
1✔
1332
        idx.table_name = new.to_string();
2✔
1333
        if idx.origin == IndexOrigin::Auto
2✔
1334
            && idx.name == SecondaryIndex::auto_name(old, &idx.column_name)
1✔
1335
        {
1336
            idx.name = SecondaryIndex::auto_name(new, &idx.column_name);
1✔
1337
        }
1338
    }
1339
    db.tables.insert(new.to_string(), table);
1✔
1340
    Ok(())
1✔
1341
}
1342

1343
/// `USING <method>` choices recognized by `execute_create_index`. A
1344
/// missing USING clause defaults to `Btree` so existing CREATE INDEX
1345
/// statements (Phase 3e) keep working unchanged.
1346
#[derive(Debug, Clone, Copy)]
1347
enum IndexMethod {
1348
    Btree,
1349
    Hnsw,
1350
    /// Phase 8b — full-text inverted index over a TEXT column.
1351
    Fts,
1352
}
1353

1354
/// Builds a Phase 3e B-Tree secondary index and attaches it to the table.
1355
fn create_btree_index(
1✔
1356
    db: &mut Database,
1357
    table_name: &str,
1358
    index_name: &str,
1359
    column_name: &str,
1360
    datatype: &DataType,
1361
    unique: bool,
1362
    existing: &[(i64, Value)],
1363
) -> Result<String> {
1364
    let mut idx = SecondaryIndex::new(
3✔
1365
        index_name.to_string(),
1✔
1366
        table_name.to_string(),
2✔
1367
        column_name.to_string(),
1✔
1368
        datatype,
1369
        unique,
1370
        IndexOrigin::Explicit,
1371
    )?;
1372

1373
    // Populate from existing rows. UNIQUE violations here mean the
1374
    // existing data already breaks the new index's constraint — a
1375
    // common source of user confusion, so be explicit.
1376
    for (rowid, v) in existing {
2✔
1377
        if unique && idx.would_violate_unique(v) {
2✔
1378
            return Err(SQLRiteError::General(format!(
1✔
1379
                "cannot create UNIQUE index '{index_name}': column '{column_name}' \
1380
                 already contains the duplicate value {}",
1381
                v.to_display_string()
1✔
1382
            )));
1383
        }
1384
        idx.insert(v, *rowid)?;
2✔
1385
    }
1386

1387
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1388
    table_mut.secondary_indexes.push(idx);
1✔
1389
    Ok(index_name.to_string())
1✔
1390
}
1391

1392
/// Builds a Phase 7d.2 HNSW index and attaches it to the table.
1393
fn create_hnsw_index(
1✔
1394
    db: &mut Database,
1395
    table_name: &str,
1396
    index_name: &str,
1397
    column_name: &str,
1398
    datatype: &DataType,
1399
    unique: bool,
1400
    existing: &[(i64, Value)],
1401
) -> Result<String> {
1402
    // HNSW only makes sense on VECTOR columns. Reject anything else
1403
    // with a clear message — this is the most likely user error.
1404
    let dim = match datatype {
1✔
1405
        DataType::Vector(d) => *d,
1✔
1406
        other => {
1✔
1407
            return Err(SQLRiteError::General(format!(
1✔
1408
                "USING hnsw requires a VECTOR column; '{column_name}' is {other}"
1409
            )));
1410
        }
1411
    };
1412

1413
    if unique {
1✔
1414
        return Err(SQLRiteError::General(
×
1415
            "UNIQUE has no meaning for HNSW indexes".to_string(),
×
1416
        ));
1417
    }
1418

1419
    // Build the in-memory graph. Distance metric is L2 by default
1420
    // (Phase 7d.2 doesn't yet expose a knob for picking cosine/dot —
1421
    // see `docs/phase-7-plan.md` for the deferral).
1422
    //
1423
    // Seed: hash the index name so different indexes get different
1424
    // graph topologies, but the same index always gets the same one
1425
    // — useful when debugging recall / index size.
1426
    let seed = hash_str_to_seed(index_name);
1✔
1427
    let mut idx = HnswIndex::new(DistanceMetric::L2, seed);
1✔
1428

1429
    // Snapshot the (rowid, vector) pairs into a side map so the
1430
    // get_vec closure below can serve them by id without re-borrowing
1431
    // the table (we're already holding `existing` — flatten it).
1432
    let mut vec_map: std::collections::HashMap<i64, Vec<f32>> =
1✔
1433
        std::collections::HashMap::with_capacity(existing.len());
1434
    for (rowid, v) in existing {
2✔
1435
        match v {
1✔
1436
            Value::Vector(vec) => {
1✔
1437
                if vec.len() != dim {
1✔
1438
                    return Err(SQLRiteError::Internal(format!(
×
1439
                        "row {rowid} stores a {}-dim vector in column '{column_name}' \
1440
                         declared as VECTOR({dim}) — schema invariant violated",
1441
                        vec.len()
×
1442
                    )));
1443
                }
1444
                vec_map.insert(*rowid, vec.clone());
2✔
1445
            }
1446
            // Non-vector values (theoretical NULL, type coercion bug)
1447
            // get skipped — they wouldn't have a sensible graph
1448
            // position anyway.
1449
            _ => continue,
1450
        }
1451
    }
1452

1453
    for (rowid, _) in existing {
1✔
1454
        if let Some(v) = vec_map.get(rowid) {
2✔
1455
            let v_clone = v.clone();
1✔
1456
            idx.insert(*rowid, &v_clone, |id| {
3✔
1457
                vec_map.get(&id).cloned().unwrap_or_default()
1✔
1458
            });
1459
        }
1460
    }
1461

1462
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1463
    table_mut.hnsw_indexes.push(HnswIndexEntry {
2✔
1464
        name: index_name.to_string(),
1✔
1465
        column_name: column_name.to_string(),
1✔
1466
        index: idx,
1✔
1467
        // Freshly built — no DELETE/UPDATE has invalidated it yet.
1468
        needs_rebuild: false,
1469
    });
1470
    Ok(index_name.to_string())
1✔
1471
}
1472

1473
/// Builds a Phase 8b FTS inverted index and attaches it to the table.
1474
/// Mirrors [`create_hnsw_index`] in shape: validate column type,
1475
/// tokenize each existing row's text into the in-memory posting list,
1476
/// push an `FtsIndexEntry`.
1477
fn create_fts_index(
1✔
1478
    db: &mut Database,
1479
    table_name: &str,
1480
    index_name: &str,
1481
    column_name: &str,
1482
    datatype: &DataType,
1483
    unique: bool,
1484
    existing: &[(i64, Value)],
1485
) -> Result<String> {
1486
    // FTS is a TEXT-only feature for the MVP. JSON columns share the
1487
    // Row::Text storage but their content is structured — full-text
1488
    // indexing JSON keys + values would need a different design (and
1489
    // is out of scope per the Phase 8 plan's "Out of scope" section).
1490
    match datatype {
1✔
1491
        DataType::Text => {}
1492
        other => {
1✔
1493
            return Err(SQLRiteError::General(format!(
1✔
1494
                "USING fts requires a TEXT column; '{column_name}' is {other}"
1495
            )));
1496
        }
1497
    }
1498

1499
    if unique {
1✔
1500
        return Err(SQLRiteError::General(
1✔
1501
            "UNIQUE has no meaning for FTS indexes".to_string(),
1✔
1502
        ));
1503
    }
1504

1505
    let mut idx = PostingList::new();
1✔
1506
    for (rowid, v) in existing {
2✔
1507
        if let Value::Text(text) = v {
2✔
1508
            idx.insert(*rowid, text);
1✔
1509
        }
1510
        // Non-text values (Null, type coercion bugs) get skipped — same
1511
        // posture as create_hnsw_index for non-vector values.
1512
    }
1513

1514
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1515
    table_mut.fts_indexes.push(FtsIndexEntry {
2✔
1516
        name: index_name.to_string(),
1✔
1517
        column_name: column_name.to_string(),
1✔
1518
        index: idx,
1✔
1519
        needs_rebuild: false,
1520
    });
1521
    Ok(index_name.to_string())
1✔
1522
}
1523

1524
/// Stable, deterministic hash of a string into a u64 RNG seed. FNV-1a;
1525
/// avoids pulling in `std::hash::DefaultHasher` (which is randomized
1526
/// per process).
1527
fn hash_str_to_seed(s: &str) -> u64 {
1✔
1528
    let mut h: u64 = 0xCBF29CE484222325;
1✔
1529
    for b in s.as_bytes() {
2✔
1530
        h ^= *b as u64;
1✔
1531
        h = h.wrapping_mul(0x100000001B3);
1✔
1532
    }
1533
    h
1✔
1534
}
1535

1536
/// Cheap clone helper — `DataType` intentionally doesn't derive `Clone`
1537
/// because the enum has no ergonomic reason to be cloneable elsewhere.
1538
fn clone_datatype(dt: &DataType) -> DataType {
1✔
1539
    match dt {
1✔
1540
        DataType::Integer => DataType::Integer,
1✔
1541
        DataType::Text => DataType::Text,
1✔
1542
        DataType::Real => DataType::Real,
×
1543
        DataType::Bool => DataType::Bool,
×
1544
        DataType::Vector(dim) => DataType::Vector(*dim),
1✔
1545
        DataType::Json => DataType::Json,
×
1546
        DataType::None => DataType::None,
×
1547
        DataType::Invalid => DataType::Invalid,
×
1548
    }
1549
}
1550

1551
fn extract_single_table_name(tables: &[TableWithJoins]) -> Result<String> {
1✔
1552
    if tables.len() != 1 {
1✔
1553
        return Err(SQLRiteError::NotImplemented(
×
1554
            "multi-table DELETE is not supported yet".to_string(),
×
1555
        ));
1556
    }
1557
    extract_table_name(&tables[0])
2✔
1558
}
1559

1560
fn extract_table_name(twj: &TableWithJoins) -> Result<String> {
1✔
1561
    if !twj.joins.is_empty() {
1✔
1562
        return Err(SQLRiteError::NotImplemented(
×
1563
            "JOIN is not supported yet".to_string(),
×
1564
        ));
1565
    }
1566
    match &twj.relation {
1✔
1567
        TableFactor::Table { name, .. } => Ok(name.to_string()),
1✔
1568
        _ => Err(SQLRiteError::NotImplemented(
×
1569
            "only plain table references are supported".to_string(),
×
1570
        )),
1571
    }
1572
}
1573

1574
/// Tells the executor how to produce its candidate rowid list.
1575
enum RowidSource {
1576
    /// The WHERE was simple enough to probe a secondary index directly.
1577
    /// The `Vec` already contains exactly the rows the index matched;
1578
    /// no further WHERE evaluation is needed (the probe is precise).
1579
    IndexProbe(Vec<i64>),
1580
    /// No applicable index; caller falls back to walking `table.rowids()`
1581
    /// and evaluating the WHERE on each row.
1582
    FullScan,
1583
}
1584

1585
/// Try to satisfy `WHERE` with an index probe. Currently supports the
1586
/// simplest shape: a single `col = literal` (or `literal = col`) where
1587
/// `col` is on a secondary index. AND/OR/range predicates fall back to
1588
/// full scan — those can be layered on later without changing the caller.
1589
fn select_rowids(table: &Table, selection: Option<&Expr>) -> Result<RowidSource> {
1✔
1590
    let Some(expr) = selection else {
1✔
1591
        return Ok(RowidSource::FullScan);
1✔
1592
    };
1593
    let Some((col, literal)) = try_extract_equality(expr) else {
2✔
1594
        return Ok(RowidSource::FullScan);
1✔
1595
    };
1596
    let Some(idx) = table.index_for_column(&col) else {
2✔
1597
        return Ok(RowidSource::FullScan);
1✔
1598
    };
1599

1600
    // Convert the literal into a runtime Value. If the literal type doesn't
1601
    // match the column's index we still need correct semantics — evaluate
1602
    // the WHERE against every row. Fall back to full scan.
1603
    let literal_value = match convert_literal(&literal) {
2✔
1604
        Ok(v) => v,
1✔
1605
        Err(_) => return Ok(RowidSource::FullScan),
×
1606
    };
1607

1608
    // Index lookup returns the full list of rowids matching this equality
1609
    // predicate. For unique indexes that's at most one; for non-unique it
1610
    // can be many.
1611
    let mut rowids = idx.lookup(&literal_value);
1✔
1612
    rowids.sort_unstable();
2✔
1613
    Ok(RowidSource::IndexProbe(rowids))
1✔
1614
}
1615

1616
/// Recognizes `expr` as a simple equality on a column reference against a
1617
/// literal. Returns `(column_name, literal_value)` if the shape matches;
1618
/// `None` otherwise. Accepts both `col = literal` and `literal = col`.
1619
fn try_extract_equality(expr: &Expr) -> Option<(String, sqlparser::ast::Value)> {
1✔
1620
    // Peel off Nested parens so `WHERE (x = 1)` is recognized too.
1621
    let peeled = match expr {
1✔
1622
        Expr::Nested(inner) => inner.as_ref(),
1✔
1623
        other => other,
1✔
1624
    };
1625
    let Expr::BinaryOp { left, op, right } = peeled else {
1✔
1626
        return None;
1✔
1627
    };
1628
    if !matches!(op, BinaryOperator::Eq) {
1✔
1629
        return None;
1✔
1630
    }
1631
    let col_from = |e: &Expr| -> Option<String> {
1✔
1632
        match e {
1✔
1633
            Expr::Identifier(ident) => Some(ident.value.clone()),
1✔
1634
            Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
×
1635
            _ => None,
1✔
1636
        }
1637
    };
1638
    let literal_from = |e: &Expr| -> Option<sqlparser::ast::Value> {
1✔
1639
        if let Expr::Value(v) = e {
2✔
1640
            Some(v.value.clone())
1✔
1641
        } else {
1642
            None
1✔
1643
        }
1644
    };
1645
    if let (Some(c), Some(l)) = (col_from(left), literal_from(right)) {
3✔
1646
        return Some((c, l));
1✔
1647
    }
1648
    if let (Some(l), Some(c)) = (literal_from(left), col_from(right)) {
3✔
1649
        return Some((c, l));
1✔
1650
    }
1651
    None
1✔
1652
}
1653

1654
/// Recognizes the HNSW-probable query pattern and probes the graph
1655
/// if a matching index exists.
1656
///
1657
/// Looks for ORDER BY `vec_distance_l2(<col>, <bracket-array literal>)`
1658
/// where the table has an HNSW index attached to `<col>`. On a match,
1659
/// returns the top-k rowids straight from the graph (O(log N)). On
1660
/// any miss — different function name, no matching index, query
1661
/// dimension wrong, etc. — returns `None` and the caller falls through
1662
/// to the bounded-heap brute-force path (7c) or the full sort (7b),
1663
/// preserving correct results regardless of whether the HNSW pathway
1664
/// kicked in.
1665
///
1666
/// Phase 7d.2 caveats:
1667
/// - Only `vec_distance_l2` is recognized. Cosine and dot fall through
1668
///   to brute-force because we don't yet expose a per-index distance
1669
///   knob (deferred to Phase 7d.x — see `docs/phase-7-plan.md`).
1670
/// - Only ASCENDING order makes sense for "k nearest" — DESC ORDER BY
1671
///   `vec_distance_l2(...) LIMIT k` would mean "k farthest", which
1672
///   isn't what the index is built for. We don't bother to detect
1673
///   `ascending == false` here; the optimizer just skips and the
1674
///   fallback path handles it correctly (slower).
1675
fn try_hnsw_probe(table: &Table, order_expr: &Expr, k: usize) -> Option<Vec<i64>> {
1✔
1676
    if k == 0 {
1✔
1677
        return None;
×
1678
    }
1679

1680
    // Pattern-match: order expr must be a function call vec_distance_l2(a, b).
1681
    let func = match order_expr {
1✔
1682
        Expr::Function(f) => f,
1✔
1683
        _ => return None,
1✔
1684
    };
1685
    let fname = match func.name.0.as_slice() {
2✔
1686
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
1687
        _ => return None,
×
1688
    };
1689
    if fname != "vec_distance_l2" {
2✔
1690
        return None;
1✔
1691
    }
1692

1693
    // Extract the two args as raw Exprs.
1694
    let arg_list = match &func.args {
1✔
1695
        FunctionArguments::List(l) => &l.args,
1✔
1696
        _ => return None,
×
1697
    };
1698
    if arg_list.len() != 2 {
2✔
1699
        return None;
×
1700
    }
1701
    let exprs: Vec<&Expr> = arg_list
1✔
1702
        .iter()
1703
        .filter_map(|a| match a {
3✔
1704
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Some(e),
1✔
1705
            _ => None,
×
1706
        })
1707
        .collect();
1708
    if exprs.len() != 2 {
2✔
1709
        return None;
×
1710
    }
1711

1712
    // One arg must be a column reference (the indexed col); the other
1713
    // must be a bracket-array literal (the query vector). Try both
1714
    // orderings — pgvector's idiom puts the column on the left, but
1715
    // SQL is commutative for distance.
1716
    let (col_name, query_vec) = match identify_indexed_arg_and_literal(exprs[0], exprs[1]) {
3✔
1717
        Some(v) => v,
1✔
1718
        None => match identify_indexed_arg_and_literal(exprs[1], exprs[0]) {
×
1719
            Some(v) => v,
×
1720
            None => return None,
×
1721
        },
1722
    };
1723

1724
    // Find the HNSW index on this column.
1725
    let entry = table
4✔
1726
        .hnsw_indexes
1727
        .iter()
1✔
1728
        .find(|e| e.column_name == col_name)?;
3✔
1729

1730
    // Dimension sanity check — the query vector must match the
1731
    // indexed column's declared dimension. If it doesn't, the brute-
1732
    // force fallback would also error at the vec_distance_l2 dim-check;
1733
    // returning None here lets that path produce the user-visible
1734
    // error message.
1735
    let declared_dim = match table.columns.iter().find(|c| c.column_name == col_name) {
3✔
1736
        Some(c) => match &c.datatype {
1✔
1737
            DataType::Vector(d) => *d,
1✔
1738
            _ => return None,
×
1739
        },
1740
        None => return None,
×
1741
    };
1742
    if query_vec.len() != declared_dim {
2✔
1743
        return None;
×
1744
    }
1745

1746
    // Probe the graph. Vectors are looked up from the table's row
1747
    // storage — a closure rather than a `&Table` so the algorithm
1748
    // module stays decoupled from the SQL types.
1749
    let column_for_closure = col_name.clone();
1✔
1750
    let table_ref = table;
1751
    let result = entry.index.search(&query_vec, k, |id| {
3✔
1752
        match table_ref.get_value(&column_for_closure, id) {
1✔
1753
            Some(Value::Vector(v)) => v,
1✔
1754
            _ => Vec::new(),
×
1755
        }
1756
    });
1757
    Some(result)
1✔
1758
}
1759

1760
/// Phase 8b — FTS optimizer hook.
1761
///
1762
/// Recognizes `ORDER BY bm25_score(<col>, '<query>') DESC LIMIT <k>`
1763
/// and serves it from the FTS index instead of full-scanning. Returns
1764
/// `Some(rowids)` already sorted by descending BM25 (with rowid
1765
/// ascending as tie-break), or `None` to fall through to scalar eval.
1766
///
1767
/// **Known limitation (mirrors `try_hnsw_probe`).** This shortcut
1768
/// ignores any `WHERE` clause. The canonical FTS query has a
1769
/// `WHERE fts_match(<col>, '<q>')` predicate, which is implicitly
1770
/// satisfied by the probe results — so dropping it is harmless.
1771
/// Anything *else* in the WHERE (`AND status = 'published'`) gets
1772
/// silently skipped on the optimizer path. Per Phase 8 plan Q6 we
1773
/// match HNSW's posture here; a correctness-preserving multi-index
1774
/// composer is deferred.
1775
fn try_fts_probe(table: &Table, order_expr: &Expr, ascending: bool, k: usize) -> Option<Vec<i64>> {
1✔
1776
    if k == 0 || ascending {
1✔
1777
        // BM25 is "higher = better"; ASC ranking is almost certainly a
1778
        // user mistake. Fall through so the caller gets either an
1779
        // explicit error from scalar eval or the slow correct path.
1780
        return None;
1✔
1781
    }
1782

1783
    let func = match order_expr {
1✔
1784
        Expr::Function(f) => f,
1✔
1785
        _ => return None,
×
1786
    };
1787
    let fname = match func.name.0.as_slice() {
2✔
1788
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
1789
        _ => return None,
×
1790
    };
1791
    if fname != "bm25_score" {
2✔
1792
        return None;
×
1793
    }
1794

1795
    let arg_list = match &func.args {
1✔
1796
        FunctionArguments::List(l) => &l.args,
1✔
1797
        _ => return None,
×
1798
    };
1799
    if arg_list.len() != 2 {
2✔
1800
        return None;
×
1801
    }
1802
    let exprs: Vec<&Expr> = arg_list
1✔
1803
        .iter()
1804
        .filter_map(|a| match a {
3✔
1805
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Some(e),
1✔
1806
            _ => None,
×
1807
        })
1808
        .collect();
1809
    if exprs.len() != 2 {
2✔
1810
        return None;
×
1811
    }
1812

1813
    // Arg 0 must be a bare column identifier.
1814
    let col_name = match exprs[0] {
2✔
1815
        Expr::Identifier(ident) if ident.quote_style.is_none() => ident.value.clone(),
2✔
1816
        _ => return None,
×
1817
    };
1818

1819
    // Arg 1 must be a single-quoted string literal. Anything else
1820
    // (column reference, function call) requires per-row evaluation —
1821
    // we'd lose the whole point of the probe.
1822
    let query = match exprs[1] {
2✔
1823
        Expr::Value(v) => match &v.value {
1✔
1824
            AstValue::SingleQuotedString(s) => s.clone(),
1✔
1825
            _ => return None,
×
1826
        },
1827
        _ => return None,
×
1828
    };
1829

1830
    let entry = table
3✔
1831
        .fts_indexes
1832
        .iter()
1✔
1833
        .find(|e| e.column_name == col_name)?;
3✔
1834

1835
    let scored = entry.index.query(&query, &Bm25Params::default());
1✔
1836
    let mut out: Vec<i64> = scored.into_iter().map(|(id, _)| id).collect();
3✔
1837
    if out.len() > k {
2✔
1838
        out.truncate(k);
1✔
1839
    }
1840
    Some(out)
1✔
1841
}
1842

1843
/// Helper for `try_hnsw_probe`: given two function args, identify which
1844
/// one is a bare column identifier (the indexed column) and which is a
1845
/// bracket-array literal (the query vector). Returns
1846
/// `Some((column_name, query_vec))` on a match, `None` otherwise.
1847
fn identify_indexed_arg_and_literal(a: &Expr, b: &Expr) -> Option<(String, Vec<f32>)> {
1✔
1848
    let col_name = match a {
1✔
1849
        Expr::Identifier(ident) if ident.quote_style.is_none() => ident.value.clone(),
2✔
1850
        _ => return None,
×
1851
    };
1852
    let lit_str = match b {
1✔
1853
        Expr::Identifier(ident) if ident.quote_style == Some('[') => {
2✔
1854
            format!("[{}]", ident.value)
1✔
1855
        }
1856
        _ => return None,
×
1857
    };
1858
    let v = parse_vector_literal(&lit_str).ok()?;
2✔
1859
    Some((col_name, v))
1✔
1860
}
1861

1862
/// One entry in the bounded-heap top-k path. Holds a pre-evaluated
1863
/// sort key + the rowid it came from. The `asc` flag inverts `Ord`
1864
/// so a single `BinaryHeap<HeapEntry>` works for both ASC and DESC
1865
/// without wrapping in `std::cmp::Reverse` at the call site:
1866
///
1867
///   - ASC LIMIT k = "k smallest": natural Ord. Max-heap top is the
1868
///     largest currently kept; new items smaller than top displace.
1869
///   - DESC LIMIT k = "k largest": Ord reversed. Max-heap top is now
1870
///     the smallest currently kept (under reversed Ord, smallest
1871
///     looks largest); new items larger than top displace.
1872
///
1873
/// In both cases the displacement test reduces to "new entry < heap top".
1874
struct HeapEntry {
1875
    key: Value,
1876
    rowid: i64,
1877
    asc: bool,
1878
}
1879

1880
impl PartialEq for HeapEntry {
1881
    fn eq(&self, other: &Self) -> bool {
×
1882
        self.cmp(other) == Ordering::Equal
×
1883
    }
1884
}
1885

1886
impl Eq for HeapEntry {}
1887

1888
impl PartialOrd for HeapEntry {
1889
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1✔
1890
        Some(self.cmp(other))
1✔
1891
    }
1892
}
1893

1894
impl Ord for HeapEntry {
1895
    fn cmp(&self, other: &Self) -> Ordering {
1✔
1896
        let raw = compare_values(Some(&self.key), Some(&other.key));
1✔
1897
        if self.asc { raw } else { raw.reverse() }
1✔
1898
    }
1899
}
1900

1901
/// Bounded-heap top-k selection. Returns at most `k` rowids in the
1902
/// caller's desired order (ascending key for `order.ascending`,
1903
/// descending otherwise).
1904
///
1905
/// O(N log k) where N = `matching.len()`. Caller must check
1906
/// `k < matching.len()` for this to be a win — for k ≥ N the
1907
/// `sort_rowids` full-sort path is the same asymptotic cost without
1908
/// the heap overhead.
1909
fn select_topk(
1✔
1910
    matching: &[i64],
1911
    table: &Table,
1912
    order: &OrderByClause,
1913
    k: usize,
1914
) -> Result<Vec<i64>> {
1915
    use std::collections::BinaryHeap;
1916

1917
    if k == 0 || matching.is_empty() {
1✔
1918
        return Ok(Vec::new());
1✔
1919
    }
1920

1921
    let mut heap: BinaryHeap<HeapEntry> = BinaryHeap::with_capacity(k + 1);
1✔
1922

1923
    for &rowid in matching {
3✔
1924
        let key = eval_expr(&order.expr, table, rowid)?;
2✔
1925
        let entry = HeapEntry {
1926
            key,
1927
            rowid,
1928
            asc: order.ascending,
1✔
1929
        };
1930

1931
        if heap.len() < k {
2✔
1932
            heap.push(entry);
2✔
1933
        } else {
1934
            // peek() returns the largest under our direction-aware Ord
1935
            // — the worst entry currently kept. Displace it iff the
1936
            // new entry is "better" (i.e. compares Less).
1937
            if entry < *heap.peek().unwrap() {
2✔
1938
                heap.pop();
1✔
1939
                heap.push(entry);
1✔
1940
            }
1941
        }
1942
    }
1943

1944
    // `into_sorted_vec` returns ascending under our direction-aware Ord:
1945
    //   ASC: ascending by raw key (what we want)
1946
    //   DESC: ascending under reversed Ord = descending by raw key (what
1947
    //         we want for an ORDER BY DESC LIMIT k result)
1948
    Ok(heap
2✔
1949
        .into_sorted_vec()
1✔
1950
        .into_iter()
1✔
1951
        .map(|e| e.rowid)
3✔
1952
        .collect())
1✔
1953
}
1954

1955
fn sort_rowids(rowids: &mut [i64], table: &Table, order: &OrderByClause) -> Result<()> {
1✔
1956
    // Phase 7b: ORDER BY now accepts any expression (column ref,
1957
    // arithmetic, function call, …). Pre-compute the sort key for
1958
    // every rowid up front so the comparator is called O(N log N)
1959
    // times against pre-evaluated Values rather than re-evaluating
1960
    // the expression O(N log N) times. Not strictly necessary today,
1961
    // but vital once 7d's HNSW index lands and this same code path
1962
    // could be running tens of millions of distance computations.
1963
    let mut keys: Vec<(i64, Result<Value>)> = rowids
2✔
1964
        .iter()
1965
        .map(|r| (*r, eval_expr(&order.expr, table, *r)))
3✔
1966
        .collect();
1967

1968
    // Surface the FIRST evaluation error if any. We could be lazy
1969
    // and let sort_by encounter it, but `Ord::cmp` can't return a
1970
    // Result and we'd have to swallow errors silently.
1971
    for (_, k) in &keys {
2✔
1972
        if let Err(e) = k {
1✔
1973
            return Err(SQLRiteError::General(format!(
×
1974
                "ORDER BY expression failed: {e}"
1975
            )));
1976
        }
1977
    }
1978

1979
    keys.sort_by(|(_, ka), (_, kb)| {
3✔
1980
        // Both unwrap()s are safe — we just verified above that
1981
        // every key Result is Ok.
1982
        let va = ka.as_ref().unwrap();
1✔
1983
        let vb = kb.as_ref().unwrap();
1✔
1984
        let ord = compare_values(Some(va), Some(vb));
1✔
1985
        if order.ascending { ord } else { ord.reverse() }
1✔
1986
    });
1987

1988
    // Write the sorted rowids back into the caller's slice.
1989
    for (i, (rowid, _)) in keys.into_iter().enumerate() {
2✔
1990
        rowids[i] = rowid;
2✔
1991
    }
1992
    Ok(())
1✔
1993
}
1994

1995
fn compare_values(a: Option<&Value>, b: Option<&Value>) -> Ordering {
1✔
1996
    match (a, b) {
2✔
1997
        (None, None) => Ordering::Equal,
×
1998
        (None, _) => Ordering::Less,
×
1999
        (_, None) => Ordering::Greater,
×
2000
        (Some(a), Some(b)) => match (a, b) {
3✔
2001
            (Value::Null, Value::Null) => Ordering::Equal,
×
2002
            (Value::Null, _) => Ordering::Less,
1✔
2003
            (_, Value::Null) => Ordering::Greater,
×
2004
            (Value::Integer(x), Value::Integer(y)) => x.cmp(y),
1✔
2005
            (Value::Real(x), Value::Real(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
1✔
2006
            (Value::Integer(x), Value::Real(y)) => {
×
2007
                (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal)
×
2008
            }
2009
            (Value::Real(x), Value::Integer(y)) => {
×
2010
                x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal)
×
2011
            }
2012
            (Value::Text(x), Value::Text(y)) => x.cmp(y),
1✔
2013
            (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
×
2014
            // Cross-type fallback: stringify and compare; keeps ORDER BY total.
2015
            (x, y) => x.to_display_string().cmp(&y.to_display_string()),
×
2016
        },
2017
    }
2018
}
2019

2020
/// Returns `true` if the row at `rowid` matches the predicate expression.
2021
pub fn eval_predicate(expr: &Expr, table: &Table, rowid: i64) -> Result<bool> {
1✔
2022
    eval_predicate_scope(expr, &SingleTableScope::new(table, rowid))
1✔
2023
}
2024

2025
/// Scope-aware predicate evaluation. The single-table fast path wraps
2026
/// this with a [`SingleTableScope`]; the join executor wraps it with
2027
/// a [`JoinedScope`].
2028
pub(crate) fn eval_predicate_scope(expr: &Expr, scope: &dyn RowScope) -> Result<bool> {
1✔
2029
    let v = eval_expr_scope(expr, scope)?;
2✔
2030
    match v {
1✔
2031
        Value::Bool(b) => Ok(b),
1✔
2032
        Value::Null => Ok(false), // SQL NULL in a WHERE is treated as false
2033
        Value::Integer(i) => Ok(i != 0),
1✔
2034
        other => Err(SQLRiteError::Internal(format!(
×
2035
            "WHERE clause must evaluate to boolean, got {}",
2036
            other.to_display_string()
×
2037
        ))),
2038
    }
2039
}
2040

2041
/// Single-table convenience wrapper around [`eval_expr_scope`].
2042
fn eval_expr(expr: &Expr, table: &Table, rowid: i64) -> Result<Value> {
1✔
2043
    eval_expr_scope(expr, &SingleTableScope::new(table, rowid))
1✔
2044
}
2045

2046
fn eval_expr_scope(expr: &Expr, scope: &dyn RowScope) -> Result<Value> {
1✔
2047
    match expr {
1✔
2048
        Expr::Nested(inner) => eval_expr_scope(inner, scope),
2✔
2049

2050
        Expr::Identifier(ident) => {
1✔
2051
            // Phase 7b — sqlparser parses bracket-array literals like
2052
            // `[0.1, 0.2, 0.3]` as bracket-quoted identifiers (it inherits
2053
            // MSSQL `[name]` syntax). When we see `quote_style == Some('[')`
2054
            // in expression-evaluation position (SELECT projection, WHERE,
2055
            // ORDER BY, function args), parse the bracketed content as a
2056
            // vector literal so the rest of the executor can compare /
2057
            // distance-compute against it. Same trick the INSERT parser
2058
            // uses; the executor needed its own copy because expression
2059
            // eval runs on a different code path.
2060
            if ident.quote_style == Some('[') {
1✔
2061
                let raw = format!("[{}]", ident.value);
1✔
2062
                let v = parse_vector_literal(&raw)?;
2✔
2063
                return Ok(Value::Vector(v));
1✔
2064
            }
2065
            scope.lookup(None, &ident.value)
1✔
2066
        }
2067

2068
        Expr::CompoundIdentifier(parts) => {
1✔
2069
            // `qualifier.col` — single-table scope ignores the qualifier
2070
            // (legacy behavior). Joined scope dispatches to the table
2071
            // matching `qualifier`. The compound form must have at
2072
            // least two parts; deeper paths (`db.schema.t.col`) are
2073
            // not supported.
2074
            match parts.as_slice() {
1✔
2075
                [only] => scope.lookup(None, &only.value),
1✔
2076
                [q, c] => scope.lookup(Some(&q.value), &c.value),
2✔
NEW
2077
                _ => Err(SQLRiteError::NotImplemented(format!(
×
2078
                    "compound identifier with {} parts is not supported",
NEW
2079
                    parts.len()
×
2080
                ))),
2081
            }
2082
        }
2083

2084
        Expr::Value(v) => convert_literal(&v.value),
1✔
2085

2086
        Expr::UnaryOp { op, expr } => {
×
NEW
2087
            let inner = eval_expr_scope(expr, scope)?;
×
2088
            match op {
×
2089
                UnaryOperator::Not => match inner {
×
2090
                    Value::Bool(b) => Ok(Value::Bool(!b)),
×
2091
                    Value::Null => Ok(Value::Null),
×
2092
                    other => Err(SQLRiteError::Internal(format!(
×
2093
                        "NOT applied to non-boolean value: {}",
2094
                        other.to_display_string()
×
2095
                    ))),
2096
                },
2097
                UnaryOperator::Minus => match inner {
×
2098
                    Value::Integer(i) => Ok(Value::Integer(-i)),
×
2099
                    Value::Real(f) => Ok(Value::Real(-f)),
×
2100
                    Value::Null => Ok(Value::Null),
×
2101
                    other => Err(SQLRiteError::Internal(format!(
×
2102
                        "unary minus on non-numeric value: {}",
2103
                        other.to_display_string()
×
2104
                    ))),
2105
                },
2106
                UnaryOperator::Plus => Ok(inner),
×
2107
                other => Err(SQLRiteError::NotImplemented(format!(
×
2108
                    "unary operator {other:?} is not supported"
2109
                ))),
2110
            }
2111
        }
2112

2113
        Expr::BinaryOp { left, op, right } => match op {
1✔
2114
            BinaryOperator::And => {
2115
                let l = eval_expr_scope(left, scope)?;
2✔
2116
                let r = eval_expr_scope(right, scope)?;
2✔
2117
                Ok(Value::Bool(as_bool(&l)? && as_bool(&r)?))
3✔
2118
            }
2119
            BinaryOperator::Or => {
NEW
2120
                let l = eval_expr_scope(left, scope)?;
×
NEW
2121
                let r = eval_expr_scope(right, scope)?;
×
UNCOV
2122
                Ok(Value::Bool(as_bool(&l)? || as_bool(&r)?))
×
2123
            }
2124
            cmp @ (BinaryOperator::Eq
2125
            | BinaryOperator::NotEq
2126
            | BinaryOperator::Lt
2127
            | BinaryOperator::LtEq
2128
            | BinaryOperator::Gt
2129
            | BinaryOperator::GtEq) => {
2130
                let l = eval_expr_scope(left, scope)?;
2✔
2131
                let r = eval_expr_scope(right, scope)?;
3✔
2132
                // Any comparison involving NULL is unknown → false in a WHERE.
2133
                if matches!(l, Value::Null) || matches!(r, Value::Null) {
1✔
2134
                    return Ok(Value::Bool(false));
1✔
2135
                }
2136
                let ord = compare_values(Some(&l), Some(&r));
2✔
2137
                let result = match cmp {
1✔
2138
                    BinaryOperator::Eq => ord == Ordering::Equal,
2✔
2139
                    BinaryOperator::NotEq => ord != Ordering::Equal,
×
2140
                    BinaryOperator::Lt => ord == Ordering::Less,
2✔
2141
                    BinaryOperator::LtEq => ord != Ordering::Greater,
×
2142
                    BinaryOperator::Gt => ord == Ordering::Greater,
2✔
2143
                    BinaryOperator::GtEq => ord != Ordering::Less,
2✔
2144
                    _ => unreachable!(),
2145
                };
2146
                Ok(Value::Bool(result))
1✔
2147
            }
2148
            arith @ (BinaryOperator::Plus
2149
            | BinaryOperator::Minus
2150
            | BinaryOperator::Multiply
2151
            | BinaryOperator::Divide
2152
            | BinaryOperator::Modulo) => {
2153
                let l = eval_expr_scope(left, scope)?;
2✔
2154
                let r = eval_expr_scope(right, scope)?;
2✔
2155
                eval_arith(arith, &l, &r)
1✔
2156
            }
2157
            BinaryOperator::StringConcat => {
NEW
2158
                let l = eval_expr_scope(left, scope)?;
×
NEW
2159
                let r = eval_expr_scope(right, scope)?;
×
2160
                if matches!(l, Value::Null) || matches!(r, Value::Null) {
×
2161
                    return Ok(Value::Null);
×
2162
                }
2163
                Ok(Value::Text(format!(
×
2164
                    "{}{}",
2165
                    l.to_display_string(),
×
2166
                    r.to_display_string()
×
2167
                )))
2168
            }
2169
            other => Err(SQLRiteError::NotImplemented(format!(
×
2170
                "binary operator {other:?} is not supported yet"
2171
            ))),
2172
        },
2173

2174
        // SQLR-7 — `col IS NULL` / `col IS NOT NULL`. Identifier
2175
        // evaluation already maps a missing rowid in the column's
2176
        // BTreeMap to `Value::Null`, so this works uniformly for
2177
        // explicit NULL inserts, omitted columns, and (post-Phase 7e)
2178
        // legacy "Null"-sentinel TEXT cells. NULLs are never inserted
2179
        // into secondary / HNSW / FTS indexes, so an IS NULL probe
2180
        // correctly falls through to a full scan via `select_rowids`.
2181
        Expr::IsNull(inner) => {
1✔
2182
            let v = eval_expr_scope(inner, scope)?;
2✔
2183
            Ok(Value::Bool(matches!(v, Value::Null)))
1✔
2184
        }
2185
        Expr::IsNotNull(inner) => {
1✔
2186
            let v = eval_expr_scope(inner, scope)?;
2✔
2187
            Ok(Value::Bool(!matches!(v, Value::Null)))
1✔
2188
        }
2189

2190
        // SQLR-3 — LIKE / NOT LIKE / ILIKE. Pattern matching uses our
2191
        // own iterative two-pointer matcher (see `agg::like_match`).
2192
        // SQLite's default is case-insensitive ASCII; we follow that.
2193
        // ILIKE is also case-insensitive (a no-op switch here, but we
2194
        // keep the arm explicit so SQLite users typing ILIKE get the
2195
        // expected semantics rather than a NotImplemented).
2196
        Expr::Like {
2197
            negated,
1✔
2198
            any,
1✔
2199
            expr: lhs,
1✔
2200
            pattern,
1✔
2201
            escape_char,
1✔
2202
        } => eval_like(
2203
            scope,
2204
            *negated,
1✔
2205
            *any,
1✔
2206
            lhs,
2✔
2207
            pattern,
2✔
2208
            escape_char.as_ref(),
1✔
2209
            true,
2210
        ),
2211
        Expr::ILike {
2212
            negated,
×
2213
            any,
×
2214
            expr: lhs,
×
2215
            pattern,
×
2216
            escape_char,
×
2217
        } => eval_like(
2218
            scope,
UNCOV
2219
            *negated,
×
2220
            *any,
×
2221
            lhs,
×
2222
            pattern,
×
2223
            escape_char.as_ref(),
×
2224
            true,
2225
        ),
2226

2227
        // SQLR-3 — IN (list) / NOT IN (list). Subquery form is rejected.
2228
        // Three-valued logic: if the LHS is NULL, return NULL; if any
2229
        // list entry is NULL and no match was found, return NULL too.
2230
        // WHERE coerces NULL → false at line ~1494, so the practical
2231
        // effect is "row excluded" — matches SQLite.
2232
        Expr::InList {
2233
            expr: lhs,
1✔
2234
            list,
1✔
2235
            negated,
1✔
2236
        } => eval_in_list(scope, lhs, list, *negated),
2✔
2237
        Expr::InSubquery { .. } => Err(SQLRiteError::NotImplemented(
×
2238
            "IN (subquery) is not supported (only literal lists are)".to_string(),
×
2239
        )),
2240

2241
        // Phase 7b — function-call dispatch. Currently only the three
2242
        // vector-distance functions; this match arm becomes the single
2243
        // place to register more SQL functions later (e.g. abs(),
2244
        // length(), …) without re-touching the rest of the executor.
2245
        //
2246
        // Operator forms (`<->` `<=>` `<#>`) are NOT plumbed here: two
2247
        // of three don't parse natively in sqlparser (we'd need a
2248
        // string-preprocessing pass or a sqlparser fork). Deferred to
2249
        // a follow-up sub-phase; see docs/phase-7-plan.md's "Scope
2250
        // corrections" note.
2251
        Expr::Function(func) => eval_function(func, scope),
1✔
2252

2253
        other => Err(SQLRiteError::NotImplemented(format!(
×
2254
            "unsupported expression in WHERE/projection: {other:?}"
2255
        ))),
2256
    }
2257
}
2258

2259
/// Dispatches an `Expr::Function` to its built-in implementation.
2260
/// Currently only the three vec_distance_* functions; other functions
2261
/// surface as `NotImplemented` errors with the function name in the
2262
/// message so users see what they tried.
2263
fn eval_function(func: &sqlparser::ast::Function, scope: &dyn RowScope) -> Result<Value> {
1✔
2264
    // Function name lives in `name.0[0]` for unqualified calls. Anything
2265
    // qualified (e.g. `pkg.fn(...)`) falls through to NotImplemented.
2266
    let name = match func.name.0.as_slice() {
2✔
2267
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
2268
        _ => {
2269
            return Err(SQLRiteError::NotImplemented(format!(
×
2270
                "qualified function names not supported: {:?}",
2271
                func.name
2272
            )));
2273
        }
2274
    };
2275

2276
    match name.as_str() {
2✔
2277
        "vec_distance_l2" | "vec_distance_cosine" | "vec_distance_dot" => {
2✔
2278
            let (a, b) = extract_two_vector_args(&name, &func.args, scope)?;
3✔
2279
            let dist = match name.as_str() {
2✔
2280
                "vec_distance_l2" => vec_distance_l2(&a, &b),
3✔
2281
                "vec_distance_cosine" => vec_distance_cosine(&a, &b)?,
4✔
2282
                "vec_distance_dot" => vec_distance_dot(&a, &b),
3✔
2283
                _ => unreachable!(),
2284
            };
2285
            // Widen f32 → f64 for the runtime Value. Vectors are stored
2286
            // as f32 (consistent with industry convention for embeddings),
2287
            // but the executor's numeric type is f64 so distances slot
2288
            // into Value::Real cleanly and can be compared / ordered with
2289
            // other reals via the existing arithmetic + comparison paths.
2290
            Ok(Value::Real(dist as f64))
1✔
2291
        }
2292
        // Phase 7e — JSON functions. All four parse the JSON text on
2293
        // demand (we don't cache parsed values), then resolve a path
2294
        // (default `$` = root). The path resolver handles `.key` for
2295
        // object access and `[N]` for array index. SQLite-style.
2296
        "json_extract" => json_fn_extract(&name, &func.args, scope),
3✔
2297
        "json_type" => json_fn_type(&name, &func.args, scope),
4✔
2298
        "json_array_length" => json_fn_array_length(&name, &func.args, scope),
4✔
2299
        "json_object_keys" => json_fn_object_keys(&name, &func.args, scope),
2✔
2300
        // Phase 8b — FTS scalars. Both consult an FTS index attached to
2301
        // the named column; both error if no index exists (the index is
2302
        // a hard prerequisite, mirroring SQLite FTS5's MATCH).
2303
        //
2304
        // SQLR-5 — these only work in a single-table scope because they
2305
        // need the owning `Table` to look up an FTS index by name and
2306
        // they key results by the row's rowid. In a joined query the
2307
        // index lookup would be ambiguous (which table's FTS?) and the
2308
        // scoring rowid is per-table. Reject up front rather than
2309
        // silently wrong-result.
2310
        "fts_match" | "bm25_score" => {
3✔
2311
            let Some((table, rowid)) = scope.single_table_view() else {
2✔
NEW
2312
                return Err(SQLRiteError::NotImplemented(format!(
×
2313
                    "{name}() is not yet supported inside a JOIN query — \
2314
                     use it on a single-table SELECT or move the FTS lookup into a subquery"
2315
                )));
2316
            };
2317
            let (entry, query) = resolve_fts_args(&name, &func.args, table, scope)?;
3✔
2318
            Ok(match name.as_str() {
3✔
2319
                "fts_match" => Value::Bool(entry.index.matches(rowid, &query)),
3✔
2320
                "bm25_score" => {
2✔
2321
                    Value::Real(entry.index.score(rowid, &query, &Bm25Params::default()))
1✔
2322
                }
NEW
2323
                _ => unreachable!(),
×
2324
            })
2325
        }
2326
        // SQLR-3: catch aggregate names used in scalar position (e.g.
2327
        // `WHERE COUNT(*) > 1`) with a clearer message than "unknown
2328
        // function". HAVING isn't supported yet, hence the explicit nudge.
2329
        "count" | "sum" | "avg" | "min" | "max" => Err(SQLRiteError::NotImplemented(format!(
2✔
2330
            "aggregate function '{name}' is not allowed in WHERE / projection-scalar position; \
2331
             use it as a top-level projection item (HAVING is not yet supported)"
2332
        ))),
2333
        other => Err(SQLRiteError::NotImplemented(format!(
1✔
2334
            "unknown function: {other}(...)"
2335
        ))),
2336
    }
2337
}
2338

2339
/// Helper for `fts_match` / `bm25_score`: pull the column reference out
2340
/// of arg 0 (a bare identifier — we need the *name*, not the per-row
2341
/// value), evaluate arg 1 as a Text query string, and look up the FTS
2342
/// index attached to that column. Errors if any step fails.
2343
fn resolve_fts_args<'t>(
1✔
2344
    fn_name: &str,
2345
    args: &FunctionArguments,
2346
    table: &'t Table,
2347
    scope: &dyn RowScope,
2348
) -> Result<(&'t FtsIndexEntry, String)> {
2349
    let arg_list = match args {
1✔
2350
        FunctionArguments::List(l) => &l.args,
1✔
2351
        _ => {
2352
            return Err(SQLRiteError::General(format!(
×
2353
                "{fn_name}() expects exactly two arguments: (column, query_text)"
2354
            )));
2355
        }
2356
    };
2357
    if arg_list.len() != 2 {
1✔
2358
        return Err(SQLRiteError::General(format!(
×
2359
            "{fn_name}() expects exactly 2 arguments, got {}",
2360
            arg_list.len()
×
2361
        )));
2362
    }
2363

2364
    // Arg 0: bare column identifier. Must resolve syntactically to a
2365
    // column name (we can't accept arbitrary expressions because we
2366
    // need the column to look up the index, not the column's value).
2367
    let col_expr = match &arg_list[0] {
2✔
2368
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2369
        other => {
×
2370
            return Err(SQLRiteError::NotImplemented(format!(
×
2371
                "{fn_name}() argument 0 must be a column name, got {other:?}"
2372
            )));
2373
        }
2374
    };
2375
    let col_name = match col_expr {
1✔
2376
        Expr::Identifier(ident) => ident.value.clone(),
1✔
2377
        Expr::CompoundIdentifier(parts) => parts
×
2378
            .last()
×
2379
            .map(|p| p.value.clone())
×
2380
            .ok_or_else(|| SQLRiteError::Internal("empty compound identifier".to_string()))?,
×
2381
        other => {
×
2382
            return Err(SQLRiteError::General(format!(
×
2383
                "{fn_name}() argument 0 must be a column reference, got {other:?}"
2384
            )));
2385
        }
2386
    };
2387

2388
    // Arg 1: query string. Evaluated through the normal expression
2389
    // pipeline so callers can pass a literal `'rust db'` or an
2390
    // expression that yields TEXT.
2391
    let q_expr = match &arg_list[1] {
2✔
2392
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2393
        other => {
×
2394
            return Err(SQLRiteError::NotImplemented(format!(
×
2395
                "{fn_name}() argument 1 must be a text expression, got {other:?}"
2396
            )));
2397
        }
2398
    };
2399
    let query = match eval_expr_scope(q_expr, scope)? {
1✔
2400
        Value::Text(s) => s,
1✔
2401
        other => {
×
2402
            return Err(SQLRiteError::General(format!(
×
2403
                "{fn_name}() argument 1 must be TEXT, got {}",
2404
                other.to_display_string()
×
2405
            )));
2406
        }
2407
    };
2408

2409
    let entry = table
4✔
2410
        .fts_indexes
2411
        .iter()
1✔
2412
        .find(|e| e.column_name == col_name)
3✔
2413
        .ok_or_else(|| {
2✔
2414
            SQLRiteError::General(format!(
1✔
2415
                "{fn_name}({col_name}, ...): no FTS index on column '{col_name}' \
2416
                 (run CREATE INDEX <name> ON <table> USING fts({col_name}) first)"
2417
            ))
2418
        })?;
2419
    Ok((entry, query))
1✔
2420
}
2421

2422
// -----------------------------------------------------------------
2423
// Phase 7e — JSON path-extraction functions
2424
// -----------------------------------------------------------------
2425

2426
/// Extracts the JSON-typed text + optional path string out of a
2427
/// function call's args. Used by all four json_* functions.
2428
///
2429
/// Arity rules (matching SQLite JSON1):
2430
///   - 1 arg  → JSON value, path defaults to `$` (root)
2431
///   - 2 args → (JSON value, path text)
2432
///
2433
/// Returns `(json_text, path)` so caller can serde_json::from_str
2434
/// + walk_json_path on it.
2435
fn extract_json_and_path(
1✔
2436
    fn_name: &str,
2437
    args: &FunctionArguments,
2438
    scope: &dyn RowScope,
2439
) -> Result<(String, String)> {
2440
    let arg_list = match args {
1✔
2441
        FunctionArguments::List(l) => &l.args,
1✔
2442
        _ => {
2443
            return Err(SQLRiteError::General(format!(
×
2444
                "{fn_name}() expects 1 or 2 arguments"
2445
            )));
2446
        }
2447
    };
2448
    if !(arg_list.len() == 1 || arg_list.len() == 2) {
2✔
2449
        return Err(SQLRiteError::General(format!(
×
2450
            "{fn_name}() expects 1 or 2 arguments, got {}",
2451
            arg_list.len()
×
2452
        )));
2453
    }
2454
    // Evaluate first arg → must produce text.
2455
    let first_expr = match &arg_list[0] {
2✔
2456
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2457
        other => {
×
2458
            return Err(SQLRiteError::NotImplemented(format!(
×
2459
                "{fn_name}() argument 0 has unsupported shape: {other:?}"
2460
            )));
2461
        }
2462
    };
2463
    let json_text = match eval_expr_scope(first_expr, scope)? {
1✔
2464
        Value::Text(s) => s,
1✔
2465
        Value::Null => {
2466
            return Err(SQLRiteError::General(format!(
×
2467
                "{fn_name}() called on NULL — JSON column has no value for this row"
2468
            )));
2469
        }
2470
        other => {
×
2471
            return Err(SQLRiteError::General(format!(
×
2472
                "{fn_name}() argument 0 is not JSON-typed: got {}",
2473
                other.to_display_string()
×
2474
            )));
2475
        }
2476
    };
2477

2478
    // Path defaults to root `$` when omitted.
2479
    let path = if arg_list.len() == 2 {
2✔
2480
        let path_expr = match &arg_list[1] {
2✔
2481
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2482
            other => {
×
2483
                return Err(SQLRiteError::NotImplemented(format!(
×
2484
                    "{fn_name}() argument 1 has unsupported shape: {other:?}"
2485
                )));
2486
            }
2487
        };
2488
        match eval_expr_scope(path_expr, scope)? {
1✔
2489
            Value::Text(s) => s,
1✔
2490
            other => {
×
2491
                return Err(SQLRiteError::General(format!(
×
2492
                    "{fn_name}() path argument must be a string literal, got {}",
2493
                    other.to_display_string()
×
2494
                )));
2495
            }
2496
        }
2497
    } else {
2498
        "$".to_string()
×
2499
    };
2500

2501
    Ok((json_text, path))
1✔
2502
}
2503

2504
/// Walks a `serde_json::Value` along a JSONPath subset:
2505
///   - `$` is the root
2506
///   - `.key` for object access (key may not contain `.` or `[`)
2507
///   - `[N]` for array index (N a non-negative integer)
2508
///   - chains arbitrarily: `$.foo.bar[0].baz`
2509
///
2510
/// Returns `Ok(None)` for "path didn't match anything" (NULL in SQL),
2511
/// `Err` for malformed paths. Matches SQLite JSON1's semantic
2512
/// distinction: missing-key = NULL, malformed-path = error.
2513
fn walk_json_path<'a>(
1✔
2514
    value: &'a serde_json::Value,
2515
    path: &str,
2516
) -> Result<Option<&'a serde_json::Value>> {
2517
    let mut chars = path.chars().peekable();
1✔
2518
    if chars.next() != Some('$') {
1✔
2519
        return Err(SQLRiteError::General(format!(
1✔
2520
            "JSON path must start with '$', got `{path}`"
2521
        )));
2522
    }
2523
    let mut current = value;
1✔
2524
    while let Some(&c) = chars.peek() {
2✔
2525
        match c {
1✔
2526
            '.' => {
2527
                chars.next();
1✔
2528
                let mut key = String::new();
1✔
2529
                while let Some(&c) = chars.peek() {
2✔
2530
                    if c == '.' || c == '[' {
2✔
2531
                        break;
2532
                    }
2533
                    key.push(c);
1✔
2534
                    chars.next();
1✔
2535
                }
2536
                if key.is_empty() {
2✔
2537
                    return Err(SQLRiteError::General(format!(
×
2538
                        "JSON path has empty key after '.' in `{path}`"
2539
                    )));
2540
                }
2541
                match current.get(&key) {
2✔
2542
                    Some(v) => current = v,
1✔
2543
                    None => return Ok(None),
1✔
2544
                }
2545
            }
2546
            '[' => {
2547
                chars.next();
1✔
2548
                let mut idx_str = String::new();
1✔
2549
                while let Some(&c) = chars.peek() {
2✔
2550
                    if c == ']' {
1✔
2551
                        break;
2552
                    }
2553
                    idx_str.push(c);
1✔
2554
                    chars.next();
1✔
2555
                }
2556
                if chars.next() != Some(']') {
2✔
2557
                    return Err(SQLRiteError::General(format!(
×
2558
                        "JSON path has unclosed `[` in `{path}`"
2559
                    )));
2560
                }
2561
                let idx: usize = idx_str.trim().parse().map_err(|_| {
2✔
2562
                    SQLRiteError::General(format!(
×
2563
                        "JSON path has non-integer index `[{idx_str}]` in `{path}`"
2564
                    ))
2565
                })?;
2566
                match current.get(idx) {
1✔
2567
                    Some(v) => current = v,
1✔
2568
                    None => return Ok(None),
×
2569
                }
2570
            }
2571
            other => {
×
2572
                return Err(SQLRiteError::General(format!(
×
2573
                    "JSON path has unexpected character `{other}` in `{path}` \
2574
                     (expected `.`, `[`, or end-of-path)"
2575
                )));
2576
            }
2577
        }
2578
    }
2579
    Ok(Some(current))
1✔
2580
}
2581

2582
/// Converts a serde_json scalar to a SQLRite Value. For composite
2583
/// types (object, array) returns the JSON-encoded text — callers
2584
/// pattern-match on shape from the calling json_* function.
2585
fn json_value_to_sql(v: &serde_json::Value) -> Value {
1✔
2586
    match v {
1✔
2587
        serde_json::Value::Null => Value::Null,
×
2588
        serde_json::Value::Bool(b) => Value::Bool(*b),
×
2589
        serde_json::Value::Number(n) => {
1✔
2590
            // Match SQLite: integer if it fits an i64, else f64.
2591
            if let Some(i) = n.as_i64() {
3✔
2592
                Value::Integer(i)
1✔
2593
            } else if let Some(f) = n.as_f64() {
×
2594
                Value::Real(f)
×
2595
            } else {
2596
                Value::Null
×
2597
            }
2598
        }
2599
        serde_json::Value::String(s) => Value::Text(s.clone()),
1✔
2600
        // Objects + arrays come out as JSON-encoded text. Same as
2601
        // SQLite's json_extract: composite results round-trip through
2602
        // text rather than being modeled as a richer Value type.
2603
        composite => Value::Text(composite.to_string()),
×
2604
    }
2605
}
2606

2607
fn json_fn_extract(name: &str, args: &FunctionArguments, scope: &dyn RowScope) -> Result<Value> {
1✔
2608
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
2609
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
2610
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2611
    })?;
2612
    match walk_json_path(&parsed, &path)? {
2✔
2613
        Some(v) => Ok(json_value_to_sql(v)),
2✔
2614
        None => Ok(Value::Null),
1✔
2615
    }
2616
}
2617

2618
fn json_fn_type(name: &str, args: &FunctionArguments, scope: &dyn RowScope) -> Result<Value> {
1✔
2619
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
2620
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
2621
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2622
    })?;
2623
    let resolved = match walk_json_path(&parsed, &path)? {
2✔
2624
        Some(v) => v,
1✔
2625
        None => return Ok(Value::Null),
×
2626
    };
2627
    let ty = match resolved {
2✔
2628
        serde_json::Value::Null => "null",
1✔
2629
        serde_json::Value::Bool(true) => "true",
1✔
2630
        serde_json::Value::Bool(false) => "false",
×
2631
        serde_json::Value::Number(n) => {
1✔
2632
            if n.is_i64() || n.is_u64() {
4✔
2633
                "integer"
1✔
2634
            } else {
2635
                "real"
1✔
2636
            }
2637
        }
2638
        serde_json::Value::String(_) => "text",
1✔
2639
        serde_json::Value::Array(_) => "array",
1✔
2640
        serde_json::Value::Object(_) => "object",
1✔
2641
    };
2642
    Ok(Value::Text(ty.to_string()))
2✔
2643
}
2644

2645
fn json_fn_array_length(
1✔
2646
    name: &str,
2647
    args: &FunctionArguments,
2648
    scope: &dyn RowScope,
2649
) -> Result<Value> {
2650
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
2651
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
2652
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2653
    })?;
2654
    let resolved = match walk_json_path(&parsed, &path)? {
2✔
2655
        Some(v) => v,
1✔
2656
        None => return Ok(Value::Null),
×
2657
    };
2658
    match resolved.as_array() {
2✔
2659
        Some(arr) => Ok(Value::Integer(arr.len() as i64)),
2✔
2660
        None => Err(SQLRiteError::General(format!(
1✔
2661
            "{name}() resolved to a non-array value at path `{path}`"
2662
        ))),
2663
    }
2664
}
2665

2666
fn json_fn_object_keys(
×
2667
    name: &str,
2668
    args: &FunctionArguments,
2669
    scope: &dyn RowScope,
2670
) -> Result<Value> {
NEW
2671
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
×
2672
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
×
2673
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2674
    })?;
2675
    let resolved = match walk_json_path(&parsed, &path)? {
×
2676
        Some(v) => v,
×
2677
        None => return Ok(Value::Null),
×
2678
    };
2679
    let obj = resolved.as_object().ok_or_else(|| {
×
2680
        SQLRiteError::General(format!(
×
2681
            "{name}() resolved to a non-object value at path `{path}`"
2682
        ))
2683
    })?;
2684
    // SQLite's json_object_keys is a table-valued function (one row
2685
    // per key). Without set-returning function support we can't
2686
    // reproduce that shape; instead return the keys as a JSON array
2687
    // text. Caller can iterate via json_array_length + json_extract,
2688
    // or just treat it as a serialized list. Document this divergence
2689
    // in supported-sql.md.
2690
    let keys: Vec<serde_json::Value> = obj
2691
        .keys()
2692
        .map(|k| serde_json::Value::String(k.clone()))
×
2693
        .collect();
2694
    Ok(Value::Text(serde_json::Value::Array(keys).to_string()))
×
2695
}
2696

2697
/// Extracts exactly two `Vec<f32>` arguments from a function call,
2698
/// validating arity and that both sides are Vector-typed with matching
2699
/// dimensions. Used by all three vec_distance_* functions.
2700
fn extract_two_vector_args(
1✔
2701
    fn_name: &str,
2702
    args: &FunctionArguments,
2703
    scope: &dyn RowScope,
2704
) -> Result<(Vec<f32>, Vec<f32>)> {
2705
    let arg_list = match args {
1✔
2706
        FunctionArguments::List(l) => &l.args,
1✔
2707
        _ => {
2708
            return Err(SQLRiteError::General(format!(
×
2709
                "{fn_name}() expects exactly two vector arguments"
2710
            )));
2711
        }
2712
    };
2713
    if arg_list.len() != 2 {
1✔
2714
        return Err(SQLRiteError::General(format!(
×
2715
            "{fn_name}() expects exactly 2 arguments, got {}",
2716
            arg_list.len()
×
2717
        )));
2718
    }
2719
    let mut out: Vec<Vec<f32>> = Vec::with_capacity(2);
1✔
2720
    for (i, arg) in arg_list.iter().enumerate() {
3✔
2721
        let expr = match arg {
2✔
2722
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2723
            other => {
×
2724
                return Err(SQLRiteError::NotImplemented(format!(
×
2725
                    "{fn_name}() argument {i} has unsupported shape: {other:?}"
2726
                )));
2727
            }
2728
        };
2729
        let val = eval_expr_scope(expr, scope)?;
1✔
2730
        match val {
1✔
2731
            Value::Vector(v) => out.push(v),
1✔
2732
            other => {
×
2733
                return Err(SQLRiteError::General(format!(
×
2734
                    "{fn_name}() argument {i} is not a vector: got {}",
2735
                    other.to_display_string()
×
2736
                )));
2737
            }
2738
        }
2739
    }
2740
    let b = out.pop().unwrap();
1✔
2741
    let a = out.pop().unwrap();
2✔
2742
    if a.len() != b.len() {
2✔
2743
        return Err(SQLRiteError::General(format!(
1✔
2744
            "{fn_name}(): vector dimensions don't match (lhs={}, rhs={})",
2745
            a.len(),
2✔
2746
            b.len()
1✔
2747
        )));
2748
    }
2749
    Ok((a, b))
1✔
2750
}
2751

2752
/// Euclidean (L2) distance: √Σ(aᵢ − bᵢ)².
2753
/// Smaller-is-closer; identical vectors return 0.0.
2754
pub(crate) fn vec_distance_l2(a: &[f32], b: &[f32]) -> f32 {
1✔
2755
    debug_assert_eq!(a.len(), b.len());
1✔
2756
    let mut sum = 0.0f32;
1✔
2757
    for i in 0..a.len() {
2✔
2758
        let d = a[i] - b[i];
2✔
2759
        sum += d * d;
1✔
2760
    }
2761
    sum.sqrt()
1✔
2762
}
2763

2764
/// Cosine distance: 1 − (a·b) / (‖a‖·‖b‖).
2765
/// Smaller-is-closer; identical (non-zero) vectors return 0.0,
2766
/// orthogonal vectors return 1.0, opposite-direction vectors return 2.0.
2767
///
2768
/// Errors if either vector has zero magnitude — cosine similarity is
2769
/// undefined for the zero vector and silently returning NaN would
2770
/// poison `ORDER BY` ranking. Callers who want the silent-NaN
2771
/// behavior can compute `vec_distance_dot(a, b) / (norm(a) * norm(b))`
2772
/// themselves.
2773
pub(crate) fn vec_distance_cosine(a: &[f32], b: &[f32]) -> Result<f32> {
1✔
2774
    debug_assert_eq!(a.len(), b.len());
1✔
2775
    let mut dot = 0.0f32;
1✔
2776
    let mut norm_a_sq = 0.0f32;
1✔
2777
    let mut norm_b_sq = 0.0f32;
1✔
2778
    for i in 0..a.len() {
2✔
2779
        dot += a[i] * b[i];
2✔
2780
        norm_a_sq += a[i] * a[i];
2✔
2781
        norm_b_sq += b[i] * b[i];
2✔
2782
    }
2783
    let denom = (norm_a_sq * norm_b_sq).sqrt();
1✔
2784
    if denom == 0.0 {
1✔
2785
        return Err(SQLRiteError::General(
1✔
2786
            "vec_distance_cosine() is undefined for zero-magnitude vectors".to_string(),
1✔
2787
        ));
2788
    }
2789
    Ok(1.0 - dot / denom)
1✔
2790
}
2791

2792
/// Negated dot product: −(a·b).
2793
/// pgvector convention — negated so smaller-is-closer like L2 / cosine.
2794
/// For unit-norm vectors `vec_distance_dot(a, b) == vec_distance_cosine(a, b) - 1`.
2795
pub(crate) fn vec_distance_dot(a: &[f32], b: &[f32]) -> f32 {
1✔
2796
    debug_assert_eq!(a.len(), b.len());
1✔
2797
    let mut dot = 0.0f32;
1✔
2798
    for i in 0..a.len() {
2✔
2799
        dot += a[i] * b[i];
2✔
2800
    }
2801
    -dot
1✔
2802
}
2803

2804
/// Evaluates an integer/real arithmetic op. NULL on either side propagates.
2805
/// Mixed Integer/Real promotes to Real. Divide/Modulo by zero → error.
2806
fn eval_arith(op: &BinaryOperator, l: &Value, r: &Value) -> Result<Value> {
1✔
2807
    if matches!(l, Value::Null) || matches!(r, Value::Null) {
1✔
2808
        return Ok(Value::Null);
×
2809
    }
2810
    match (l, r) {
1✔
2811
        (Value::Integer(a), Value::Integer(b)) => match op {
1✔
2812
            BinaryOperator::Plus => Ok(Value::Integer(a.wrapping_add(*b))),
1✔
2813
            BinaryOperator::Minus => Ok(Value::Integer(a.wrapping_sub(*b))),
×
2814
            BinaryOperator::Multiply => Ok(Value::Integer(a.wrapping_mul(*b))),
1✔
2815
            BinaryOperator::Divide => {
2816
                if *b == 0 {
×
2817
                    Err(SQLRiteError::General("division by zero".to_string()))
×
2818
                } else {
2819
                    Ok(Value::Integer(a / b))
×
2820
                }
2821
            }
2822
            BinaryOperator::Modulo => {
2823
                if *b == 0 {
×
2824
                    Err(SQLRiteError::General("modulo by zero".to_string()))
×
2825
                } else {
2826
                    Ok(Value::Integer(a % b))
×
2827
                }
2828
            }
2829
            _ => unreachable!(),
2830
        },
2831
        // Anything involving a Real promotes both sides to f64.
2832
        (a, b) => {
×
2833
            let af = as_number(a)?;
×
2834
            let bf = as_number(b)?;
×
2835
            match op {
×
2836
                BinaryOperator::Plus => Ok(Value::Real(af + bf)),
×
2837
                BinaryOperator::Minus => Ok(Value::Real(af - bf)),
×
2838
                BinaryOperator::Multiply => Ok(Value::Real(af * bf)),
×
2839
                BinaryOperator::Divide => {
2840
                    if bf == 0.0 {
×
2841
                        Err(SQLRiteError::General("division by zero".to_string()))
×
2842
                    } else {
2843
                        Ok(Value::Real(af / bf))
×
2844
                    }
2845
                }
2846
                BinaryOperator::Modulo => {
2847
                    if bf == 0.0 {
×
2848
                        Err(SQLRiteError::General("modulo by zero".to_string()))
×
2849
                    } else {
2850
                        Ok(Value::Real(af % bf))
×
2851
                    }
2852
                }
2853
                _ => unreachable!(),
2854
            }
2855
        }
2856
    }
2857
}
2858

2859
fn as_number(v: &Value) -> Result<f64> {
×
2860
    match v {
×
2861
        Value::Integer(i) => Ok(*i as f64),
×
2862
        Value::Real(f) => Ok(*f),
×
2863
        Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
×
2864
        other => Err(SQLRiteError::General(format!(
×
2865
            "arithmetic on non-numeric value '{}'",
2866
            other.to_display_string()
×
2867
        ))),
2868
    }
2869
}
2870

2871
fn as_bool(v: &Value) -> Result<bool> {
1✔
2872
    match v {
1✔
2873
        Value::Bool(b) => Ok(*b),
1✔
2874
        Value::Null => Ok(false),
2875
        Value::Integer(i) => Ok(*i != 0),
×
2876
        other => Err(SQLRiteError::Internal(format!(
×
2877
            "expected boolean, got {}",
2878
            other.to_display_string()
×
2879
        ))),
2880
    }
2881
}
2882

2883
// -----------------------------------------------------------------
2884
// SQLR-3 — LIKE / IN evaluators
2885
// -----------------------------------------------------------------
2886

2887
#[allow(clippy::too_many_arguments)]
2888
fn eval_like(
1✔
2889
    scope: &dyn RowScope,
2890
    negated: bool,
2891
    any: bool,
2892
    lhs: &Expr,
2893
    pattern: &Expr,
2894
    escape_char: Option<&AstValue>,
2895
    case_insensitive: bool,
2896
) -> Result<Value> {
2897
    if any {
1✔
2898
        return Err(SQLRiteError::NotImplemented(
×
2899
            "LIKE ANY (...) is not supported".to_string(),
×
2900
        ));
2901
    }
2902
    if escape_char.is_some() {
1✔
2903
        return Err(SQLRiteError::NotImplemented(
×
2904
            "LIKE ... ESCAPE '<char>' is not supported (default `\\` escape only)".to_string(),
×
2905
        ));
2906
    }
2907

2908
    let l = eval_expr_scope(lhs, scope)?;
1✔
2909
    let p = eval_expr_scope(pattern, scope)?;
2✔
2910
    if matches!(l, Value::Null) || matches!(p, Value::Null) {
1✔
2911
        return Ok(Value::Null);
×
2912
    }
2913
    let text = match l {
1✔
2914
        Value::Text(s) => s,
1✔
2915
        other => other.to_display_string(),
×
2916
    };
2917
    let pat = match p {
1✔
2918
        Value::Text(s) => s,
1✔
2919
        other => other.to_display_string(),
×
2920
    };
2921
    let m = like_match(&text, &pat, case_insensitive);
2✔
2922
    Ok(Value::Bool(if negated { !m } else { m }))
1✔
2923
}
2924

2925
fn eval_in_list(scope: &dyn RowScope, lhs: &Expr, list: &[Expr], negated: bool) -> Result<Value> {
1✔
2926
    let l = eval_expr_scope(lhs, scope)?;
1✔
2927
    if matches!(l, Value::Null) {
1✔
2928
        return Ok(Value::Null);
×
2929
    }
2930
    let mut saw_null = false;
1✔
2931
    for item in list {
2✔
2932
        let r = eval_expr_scope(item, scope)?;
2✔
2933
        if matches!(r, Value::Null) {
1✔
2934
            saw_null = true;
1✔
2935
            continue;
2936
        }
2937
        if compare_values(Some(&l), Some(&r)) == Ordering::Equal {
2✔
2938
            return Ok(Value::Bool(!negated));
1✔
2939
        }
2940
    }
2941
    if saw_null {
2✔
2942
        // SQLite three-valued IN: unmatched + a NULL on the RHS → NULL.
2943
        // WHERE coerces NULL → false, so the row is excluded either way.
2944
        Ok(Value::Null)
1✔
2945
    } else {
2946
        Ok(Value::Bool(negated))
1✔
2947
    }
2948
}
2949

2950
// -----------------------------------------------------------------
2951
// SQLR-3 — Aggregation phase, DISTINCT, post-projection sort
2952
// -----------------------------------------------------------------
2953

2954
/// Walk `matching` rowids, partition into groups (one synthetic group
2955
/// when `group_by` is empty), update one `AggState` per aggregate
2956
/// projection slot per group, then materialize one output row per
2957
/// group in projection order. Group-key columns surface their original
2958
/// `Value` (captured the first time the group was seen); aggregate
2959
/// slots surface `AggState::finalize()`.
2960
fn aggregate_rows(
1✔
2961
    table: &Table,
2962
    matching: &[i64],
2963
    group_by: &[String],
2964
    proj_items: &[ProjectionItem],
2965
) -> Result<Vec<Vec<Value>>> {
2966
    // Build the per-projection-slot accumulator template once. Each
2967
    // group clones this template on first sight. Non-aggregate slots
2968
    // hold a "captured group-key value" (`None` until set).
2969
    let template: Vec<Option<AggState>> = proj_items
1✔
2970
        .iter()
2971
        .map(|i| match &i.kind {
3✔
2972
            ProjectionKind::Aggregate(call) => Some(AggState::new(call)),
1✔
2973
            ProjectionKind::Column { .. } => None,
1✔
2974
        })
2975
        .collect();
2976

2977
    // Linear-scan group lookup. For typical ad-hoc queries (cardinality
2978
    // ≪ 10k), this is fine; if grouping cardinality grows, swap to a
2979
    // HashMap<Vec<DistinctKey>, usize> keyed by the same DistinctKey
2980
    // wrapper. Order-preserving for readable output (groups appear in
2981
    // first-occurrence order, matching SQLite's typical behavior).
2982
    let mut keys: Vec<Vec<DistinctKey>> = Vec::new();
1✔
2983
    let mut group_states: Vec<Vec<Option<AggState>>> = Vec::new();
1✔
2984
    let mut group_key_values: Vec<Vec<Value>> = Vec::new();
1✔
2985

2986
    for &rowid in matching {
3✔
2987
        let mut key_values: Vec<Value> = Vec::with_capacity(group_by.len());
2✔
2988
        let mut key: Vec<DistinctKey> = Vec::with_capacity(group_by.len());
2✔
2989
        for col in group_by {
3✔
2990
            let v = table.get_value(col, rowid).unwrap_or(Value::Null);
2✔
2991
            key.push(DistinctKey::from_value(&v));
2✔
2992
            key_values.push(v);
1✔
2993
        }
2994
        let idx = match keys.iter().position(|k| k == &key) {
3✔
2995
            Some(i) => i,
1✔
2996
            None => {
2997
                keys.push(key);
1✔
2998
                group_states.push(template.clone());
1✔
2999
                group_key_values.push(key_values);
1✔
3000
                keys.len() - 1
1✔
3001
            }
3002
        };
3003

3004
        for (slot, item) in proj_items.iter().enumerate() {
1✔
3005
            if let ProjectionKind::Aggregate(call) = &item.kind {
2✔
3006
                let v = match &call.arg {
1✔
3007
                    AggregateArg::Star => Value::Null,
1✔
3008
                    AggregateArg::Column(c) => table.get_value(c, rowid).unwrap_or(Value::Null),
2✔
3009
                };
3010
                if let Some(state) = group_states[idx][slot].as_mut() {
2✔
3011
                    state.update(&v)?;
2✔
3012
                }
3013
            }
3014
        }
3015
    }
3016

3017
    // No groups but no aggregate-only "implicit one row" semantic to
3018
    // emit: e.g. `SELECT dept FROM t GROUP BY dept` over an empty
3019
    // matching set should produce zero rows. `SELECT COUNT(*) FROM t`
3020
    // (no GROUP BY) DOES produce one row even on empty input — the
3021
    // single-synthetic-group path below handles it.
3022
    if keys.is_empty() && group_by.is_empty() {
2✔
3023
        // Synthetic single empty group so we still emit one row with
3024
        // initial accumulator finals (e.g. COUNT(*) → 0).
3025
        keys.push(Vec::new());
1✔
3026
        group_states.push(template.clone());
1✔
3027
        group_key_values.push(Vec::new());
1✔
3028
    }
3029

3030
    // Project: one row per group, in projection order.
3031
    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(keys.len());
2✔
3032
    for (group_idx, _) in keys.iter().enumerate() {
3✔
3033
        let mut row: Vec<Value> = Vec::with_capacity(proj_items.len());
2✔
3034
        for (slot, item) in proj_items.iter().enumerate() {
2✔
3035
            match &item.kind {
1✔
3036
                ProjectionKind::Column { name: c, .. } => {
1✔
3037
                    // The validation in execute_select_rows guarantees
3038
                    // bare-column projections are also in `group_by`.
3039
                    let pos = group_by
2✔
3040
                        .iter()
3041
                        .position(|g| g == c)
3✔
3042
                        .expect("validated to be in GROUP BY");
3043
                    row.push(group_key_values[group_idx][pos].clone());
1✔
3044
                }
3045
                ProjectionKind::Aggregate(_) => {
3046
                    let state = group_states[group_idx][slot]
3✔
3047
                        .as_ref()
3048
                        .expect("aggregate slot has state");
3049
                    row.push(state.finalize());
1✔
3050
                }
3051
            }
3052
        }
3053
        rows.push(row);
1✔
3054
    }
3055
    Ok(rows)
1✔
3056
}
3057

3058
/// SELECT DISTINCT post-pass. Walks the rows once with a `HashSet` of
3059
/// row-keys, preserving first-occurrence order. NULL == NULL for
3060
/// dedupe purposes, which matches the SQL DISTINCT semantic.
3061
fn dedupe_rows(rows: Vec<Vec<Value>>) -> Vec<Vec<Value>> {
1✔
3062
    use std::collections::HashSet;
3063
    let mut seen: HashSet<Vec<DistinctKey>> = HashSet::new();
1✔
3064
    let mut out = Vec::with_capacity(rows.len());
2✔
3065
    for row in rows {
4✔
3066
        let key: Vec<DistinctKey> = row.iter().map(DistinctKey::from_value).collect();
2✔
3067
        if seen.insert(key) {
1✔
3068
            out.push(row);
1✔
3069
        }
3070
    }
3071
    out
1✔
3072
}
3073

3074
/// Sort output rows for the aggregating path. ORDER BY can reference
3075
/// either an output column name (alias or bare GROUP BY column) or an
3076
/// aggregate function call by display form (e.g. `COUNT(*)`).
3077
fn sort_output_rows(
1✔
3078
    rows: &mut [Vec<Value>],
3079
    columns: &[String],
3080
    proj_items: &[ProjectionItem],
3081
    order: &OrderByClause,
3082
) -> Result<()> {
3083
    let target_idx = resolve_order_by_index(&order.expr, columns, proj_items)?;
1✔
3084
    rows.sort_by(|a, b| {
2✔
3085
        let va = &a[target_idx];
1✔
3086
        let vb = &b[target_idx];
1✔
3087
        let ord = compare_values(Some(va), Some(vb));
1✔
3088
        if order.ascending { ord } else { ord.reverse() }
1✔
3089
    });
3090
    Ok(())
1✔
3091
}
3092

3093
/// Map an ORDER BY expression to the index of the output column that
3094
/// should drive the sort.
3095
fn resolve_order_by_index(
1✔
3096
    expr: &Expr,
3097
    columns: &[String],
3098
    proj_items: &[ProjectionItem],
3099
) -> Result<usize> {
3100
    // Bare identifier — match against output names (alias-first).
3101
    let target_name: Option<String> = match expr {
1✔
3102
        Expr::Identifier(ident) => Some(ident.value.clone()),
1✔
3103
        Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
×
3104
        Expr::Function(_) => None,
1✔
3105
        Expr::Nested(inner) => return resolve_order_by_index(inner, columns, proj_items),
×
3106
        other => {
×
3107
            return Err(SQLRiteError::NotImplemented(format!(
×
3108
                "ORDER BY expression not supported on aggregating queries: {other:?}"
3109
            )));
3110
        }
3111
    };
3112
    if let Some(name) = target_name {
2✔
3113
        if let Some(i) = columns.iter().position(|c| c.eq_ignore_ascii_case(&name)) {
4✔
3114
            return Ok(i);
1✔
3115
        }
3116
        return Err(SQLRiteError::Internal(format!(
×
3117
            "ORDER BY references unknown column '{name}' in the SELECT output"
3118
        )));
3119
    }
3120
    // Function form: match by display name against any aggregate item
3121
    // whose canonical display equals the user's call. Tolerate case
3122
    // differences in the function name.
3123
    if let Expr::Function(func) = expr {
2✔
3124
        let user_disp = format_function_display(func);
1✔
3125
        for (i, item) in proj_items.iter().enumerate() {
2✔
3126
            if let ProjectionKind::Aggregate(call) = &item.kind
2✔
3127
                && call.display_name().eq_ignore_ascii_case(&user_disp)
1✔
3128
            {
3129
                return Ok(i);
1✔
3130
            }
3131
        }
3132
        return Err(SQLRiteError::Internal(format!(
×
3133
            "ORDER BY references aggregate '{user_disp}' that isn't in the SELECT output"
3134
        )));
3135
    }
3136
    Err(SQLRiteError::Internal(
×
3137
        "ORDER BY expression could not be resolved against the output columns".to_string(),
×
3138
    ))
3139
}
3140

3141
/// Format a sqlparser function call into the same canonical form
3142
/// `AggregateCall::display_name()` uses, so ORDER BY on
3143
/// `COUNT(*)` / `SUM(salary)` matches its projection counterpart.
3144
fn format_function_display(func: &sqlparser::ast::Function) -> String {
1✔
3145
    let name = match func.name.0.as_slice() {
2✔
3146
        [ObjectNamePart::Identifier(ident)] => ident.value.to_uppercase(),
2✔
3147
        _ => format!("{:?}", func.name).to_uppercase(),
×
3148
    };
3149
    let inner = match &func.args {
1✔
3150
        FunctionArguments::List(l) => {
1✔
3151
            let distinct = matches!(
1✔
3152
                l.duplicate_treatment,
1✔
3153
                Some(sqlparser::ast::DuplicateTreatment::Distinct)
3154
            );
3155
            let arg = l.args.first().map(|a| match a {
4✔
3156
                FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => "*".to_string(),
1✔
3157
                FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Identifier(i))) => i.value.clone(),
×
3158
                FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::CompoundIdentifier(parts))) => {
×
3159
                    parts.last().map(|p| p.value.clone()).unwrap_or_default()
×
3160
                }
3161
                _ => String::new(),
×
3162
            });
3163
            match (distinct, arg) {
2✔
3164
                (true, Some(a)) if a != "*" => format!("DISTINCT {a}"),
×
3165
                (_, Some(a)) => a,
1✔
3166
                _ => String::new(),
×
3167
            }
3168
        }
3169
        _ => String::new(),
×
3170
    };
3171
    format!("{name}({inner})")
2✔
3172
}
3173

3174
fn convert_literal(v: &sqlparser::ast::Value) -> Result<Value> {
1✔
3175
    use sqlparser::ast::Value as AstValue;
3176
    match v {
1✔
3177
        AstValue::Number(n, _) => {
1✔
3178
            if let Ok(i) = n.parse::<i64>() {
2✔
3179
                Ok(Value::Integer(i))
1✔
3180
            } else if let Ok(f) = n.parse::<f64>() {
2✔
3181
                Ok(Value::Real(f))
1✔
3182
            } else {
3183
                Err(SQLRiteError::Internal(format!(
×
3184
                    "could not parse numeric literal '{n}'"
3185
                )))
3186
            }
3187
        }
3188
        AstValue::SingleQuotedString(s) => Ok(Value::Text(s.clone())),
1✔
3189
        AstValue::Boolean(b) => Ok(Value::Bool(*b)),
×
3190
        AstValue::Null => Ok(Value::Null),
1✔
3191
        other => Err(SQLRiteError::NotImplemented(format!(
×
3192
            "unsupported literal value: {other:?}"
3193
        ))),
3194
    }
3195
}
3196

3197
#[cfg(test)]
3198
mod tests {
3199
    use super::*;
3200

3201
    // -----------------------------------------------------------------
3202
    // Phase 7b — Vector distance function math
3203
    // -----------------------------------------------------------------
3204

3205
    /// Float comparison helper — distance results need a small epsilon
3206
    /// because we accumulate sums across many f32 multiplies.
3207
    fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
1✔
3208
        (a - b).abs() < eps
1✔
3209
    }
3210

3211
    #[test]
3212
    fn vec_distance_l2_identical_is_zero() {
3✔
3213
        let v = vec![0.1, 0.2, 0.3];
1✔
3214
        assert_eq!(vec_distance_l2(&v, &v), 0.0);
2✔
3215
    }
3216

3217
    #[test]
3218
    fn vec_distance_l2_unit_basis_is_sqrt2() {
3✔
3219
        // [1, 0] vs [0, 1]: distance = √((1-0)² + (0-1)²) = √2 ≈ 1.414
3220
        let a = vec![1.0, 0.0];
1✔
3221
        let b = vec![0.0, 1.0];
2✔
3222
        assert!(approx_eq(vec_distance_l2(&a, &b), 2.0_f32.sqrt(), 1e-6));
2✔
3223
    }
3224

3225
    #[test]
3226
    fn vec_distance_l2_known_value() {
3✔
3227
        // [0, 0, 0] vs [3, 4, 0]: √(9 + 16 + 0) = 5 (the classic 3-4-5 triangle).
3228
        let a = vec![0.0, 0.0, 0.0];
1✔
3229
        let b = vec![3.0, 4.0, 0.0];
2✔
3230
        assert!(approx_eq(vec_distance_l2(&a, &b), 5.0, 1e-6));
2✔
3231
    }
3232

3233
    #[test]
3234
    fn vec_distance_cosine_identical_is_zero() {
3✔
3235
        let v = vec![0.1, 0.2, 0.3];
1✔
3236
        let d = vec_distance_cosine(&v, &v).unwrap();
2✔
3237
        assert!(approx_eq(d, 0.0, 1e-6), "cos(v,v) = {d}, expected ≈ 0");
1✔
3238
    }
3239

3240
    #[test]
3241
    fn vec_distance_cosine_orthogonal_is_one() {
3✔
3242
        // Two orthogonal unit vectors should have cosine distance = 1.0
3243
        // (cosine similarity = 0 → distance = 1 - 0 = 1).
3244
        let a = vec![1.0, 0.0];
1✔
3245
        let b = vec![0.0, 1.0];
2✔
3246
        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 1.0, 1e-6));
2✔
3247
    }
3248

3249
    #[test]
3250
    fn vec_distance_cosine_opposite_is_two() {
3✔
3251
        // a and -a have cosine similarity = -1 → distance = 1 - (-1) = 2.
3252
        let a = vec![1.0, 0.0, 0.0];
1✔
3253
        let b = vec![-1.0, 0.0, 0.0];
2✔
3254
        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 2.0, 1e-6));
2✔
3255
    }
3256

3257
    #[test]
3258
    fn vec_distance_cosine_zero_magnitude_errors() {
3✔
3259
        // Cosine is undefined for the zero vector — error rather than NaN.
3260
        let a = vec![0.0, 0.0];
1✔
3261
        let b = vec![1.0, 0.0];
2✔
3262
        let err = vec_distance_cosine(&a, &b).unwrap_err();
2✔
3263
        assert!(format!("{err}").contains("zero-magnitude"));
2✔
3264
    }
3265

3266
    #[test]
3267
    fn vec_distance_dot_negates() {
3✔
3268
        // a·b = 1*4 + 2*5 + 3*6 = 32. Negated → -32.
3269
        let a = vec![1.0, 2.0, 3.0];
1✔
3270
        let b = vec![4.0, 5.0, 6.0];
2✔
3271
        assert!(approx_eq(vec_distance_dot(&a, &b), -32.0, 1e-6));
2✔
3272
    }
3273

3274
    #[test]
3275
    fn vec_distance_dot_orthogonal_is_zero() {
3✔
3276
        // Orthogonal vectors have dot product 0 → negated is also 0.
3277
        let a = vec![1.0, 0.0];
1✔
3278
        let b = vec![0.0, 1.0];
2✔
3279
        assert_eq!(vec_distance_dot(&a, &b), 0.0);
2✔
3280
    }
3281

3282
    #[test]
3283
    fn vec_distance_dot_unit_norm_matches_cosine_minus_one() {
3✔
3284
        // For unit-norm vectors: dot(a,b) = cos(a,b)
3285
        // → -dot(a,b) = -cos(a,b) = (1 - cos(a,b)) - 1 = vec_distance_cosine(a,b) - 1.
3286
        // Useful sanity check that the two functions agree on unit vectors.
3287
        let a = vec![0.6f32, 0.8]; // unit norm: √(0.36+0.64) = 1
1✔
3288
        let b = vec![0.8f32, 0.6]; // unit norm too
2✔
3289
        let dot = vec_distance_dot(&a, &b);
2✔
3290
        let cos = vec_distance_cosine(&a, &b).unwrap();
1✔
3291
        assert!(approx_eq(dot, cos - 1.0, 1e-5));
1✔
3292
    }
3293

3294
    // -----------------------------------------------------------------
3295
    // Phase 7c — bounded-heap top-k correctness + benchmark
3296
    // -----------------------------------------------------------------
3297

3298
    use crate::sql::db::database::Database;
3299
    use crate::sql::parser::select::SelectQuery;
3300
    use sqlparser::dialect::SQLiteDialect;
3301
    use sqlparser::parser::Parser;
3302

3303
    /// Builds a `docs(id INTEGER PK, score REAL)` table with N rows of
3304
    /// distinct positive scores so top-k tests aren't sensitive to
3305
    /// tie-breaking (heap is unstable; full-sort is stable; we want
3306
    /// both to agree without arguing about equal-score row order).
3307
    ///
3308
    /// **Why positive scores:** the INSERT parser doesn't currently
3309
    /// handle `Expr::UnaryOp(Minus, …)` for negative number literals
3310
    /// (it would parse `-3.14` as a unary expression and the value
3311
    /// extractor would skip it). That's a pre-existing bug, out of
3312
    /// scope for 7c. Using the Knuth multiplicative hash gives us
3313
    /// distinct positive scrambled values without dancing around the
3314
    /// negative-literal limitation.
3315
    fn seed_score_table(n: usize) -> Database {
1✔
3316
        let mut db = Database::new("tempdb".to_string());
1✔
3317
        crate::sql::process_command(
3318
            "CREATE TABLE docs (id INTEGER PRIMARY KEY, score REAL);",
3319
            &mut db,
3320
        )
3321
        .expect("create");
3322
        for i in 0..n {
1✔
3323
            // Knuth multiplicative hash mod 1_000_000 — distinct,
3324
            // dense in [0, 999_999], no collisions for n up to ~tens
3325
            // of thousands.
3326
            let score = ((i as u64).wrapping_mul(2_654_435_761) % 1_000_000) as f64;
2✔
3327
            let sql = format!("INSERT INTO docs (score) VALUES ({score});");
1✔
3328
            crate::sql::process_command(&sql, &mut db).expect("insert");
2✔
3329
        }
3330
        db
1✔
3331
    }
3332

3333
    /// Helper: parses an SQL SELECT into a SelectQuery so we can drive
3334
    /// `select_topk` / `sort_rowids` directly without the rest of the
3335
    /// process_command pipeline.
3336
    fn parse_select(sql: &str) -> SelectQuery {
1✔
3337
        let dialect = SQLiteDialect {};
3338
        let mut ast = Parser::parse_sql(&dialect, sql).expect("parse");
1✔
3339
        let stmt = ast.pop().expect("one statement");
2✔
3340
        SelectQuery::new(&stmt).expect("select-query")
2✔
3341
    }
3342

3343
    #[test]
3344
    fn topk_matches_full_sort_asc() {
3✔
3345
        // Build N=200, top-k=10. Bounded heap output must equal
3346
        // full-sort-then-truncate output (both produce ASC order).
3347
        let db = seed_score_table(200);
1✔
3348
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3349
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
1✔
3350
        let order = q.order_by.as_ref().unwrap();
2✔
3351
        let all_rowids = table.rowids();
1✔
3352

3353
        // Full-sort path
3354
        let mut full = all_rowids.clone();
1✔
3355
        sort_rowids(&mut full, table, order).unwrap();
2✔
3356
        full.truncate(10);
1✔
3357

3358
        // Bounded-heap path
3359
        let topk = select_topk(&all_rowids, table, order, 10).unwrap();
1✔
3360

3361
        assert_eq!(topk, full, "top-k via heap should match full-sort+truncate");
2✔
3362
    }
3363

3364
    #[test]
3365
    fn topk_matches_full_sort_desc() {
3✔
3366
        // Same with DESC — verifies the direction-aware Ord wrapper.
3367
        let db = seed_score_table(200);
1✔
3368
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3369
        let q = parse_select("SELECT * FROM docs ORDER BY score DESC LIMIT 10;");
1✔
3370
        let order = q.order_by.as_ref().unwrap();
2✔
3371
        let all_rowids = table.rowids();
1✔
3372

3373
        let mut full = all_rowids.clone();
1✔
3374
        sort_rowids(&mut full, table, order).unwrap();
2✔
3375
        full.truncate(10);
1✔
3376

3377
        let topk = select_topk(&all_rowids, table, order, 10).unwrap();
1✔
3378

3379
        assert_eq!(
2✔
3380
            topk, full,
3381
            "top-k DESC via heap should match full-sort+truncate"
3382
        );
3383
    }
3384

3385
    #[test]
3386
    fn topk_k_larger_than_n_returns_everything_sorted() {
3✔
3387
        // The executor branches off to the full-sort path when k >= N,
3388
        // but if a caller invokes select_topk directly with k > N, it
3389
        // should still produce all-sorted output (no truncation
3390
        // because we don't have N items to truncate to k).
3391
        let db = seed_score_table(50);
1✔
3392
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3393
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1000;");
1✔
3394
        let order = q.order_by.as_ref().unwrap();
2✔
3395
        let topk = select_topk(&table.rowids(), table, order, 1000).unwrap();
1✔
3396
        assert_eq!(topk.len(), 50);
1✔
3397
        // All scores in ascending order.
3398
        let scores: Vec<f64> = topk
1✔
3399
            .iter()
3400
            .filter_map(|r| match table.get_value("score", *r) {
3✔
3401
                Some(Value::Real(f)) => Some(f),
1✔
3402
                _ => None,
×
3403
            })
3404
            .collect();
3405
        assert!(scores.windows(2).all(|w| w[0] <= w[1]));
4✔
3406
    }
3407

3408
    #[test]
3409
    fn topk_k_zero_returns_empty() {
3✔
3410
        let db = seed_score_table(10);
1✔
3411
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3412
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1;");
1✔
3413
        let order = q.order_by.as_ref().unwrap();
2✔
3414
        let topk = select_topk(&table.rowids(), table, order, 0).unwrap();
1✔
3415
        assert!(topk.is_empty());
1✔
3416
    }
3417

3418
    #[test]
3419
    fn topk_empty_input_returns_empty() {
3✔
3420
        let db = seed_score_table(0);
1✔
3421
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3422
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 5;");
1✔
3423
        let order = q.order_by.as_ref().unwrap();
2✔
3424
        let topk = select_topk(&[], table, order, 5).unwrap();
1✔
3425
        assert!(topk.is_empty());
2✔
3426
    }
3427

3428
    #[test]
3429
    fn topk_works_through_select_executor_with_distance_function() {
4✔
3430
        // Integration check that the executor actually picks the
3431
        // bounded-heap path on a KNN-shaped query and produces the
3432
        // correct top-k.
3433
        let mut db = Database::new("tempdb".to_string());
1✔
3434
        crate::sql::process_command(
3435
            "CREATE TABLE docs (id INTEGER PRIMARY KEY, e VECTOR(2));",
3436
            &mut db,
3437
        )
3438
        .unwrap();
3439
        // Five rows with distinct distances from probe [1.0, 0.0]:
3440
        //   id=1 [1.0, 0.0]   distance=0
3441
        //   id=2 [2.0, 0.0]   distance=1
3442
        //   id=3 [0.0, 3.0]   distance=√(1+9) = √10 ≈ 3.16
3443
        //   id=4 [1.0, 4.0]   distance=4
3444
        //   id=5 [10.0, 10.0] distance=√(81+100) ≈ 13.45
3445
        for v in &[
1✔
3446
            "[1.0, 0.0]",
3447
            "[2.0, 0.0]",
3448
            "[0.0, 3.0]",
3449
            "[1.0, 4.0]",
3450
            "[10.0, 10.0]",
3451
        ] {
3452
            crate::sql::process_command(&format!("INSERT INTO docs (e) VALUES ({v});"), &mut db)
3✔
3453
                .unwrap();
3454
        }
3455
        let resp = crate::sql::process_command(
3456
            "SELECT id FROM docs ORDER BY vec_distance_l2(e, [1.0, 0.0]) ASC LIMIT 3;",
3457
            &mut db,
3458
        )
3459
        .unwrap();
3460
        // Top-3 closest to [1.0, 0.0] are id=1, id=2, id=3 (in that order).
3461
        // The status message tells us how many rows came back.
3462
        assert!(resp.contains("3 rows returned"), "got: {resp}");
2✔
3463
    }
3464

3465
    /// Manual benchmark — not run by default. Recommended invocation:
3466
    ///
3467
    ///     cargo test -p sqlrite-engine --lib topk_benchmark --release \
3468
    ///         -- --ignored --nocapture
3469
    ///
3470
    /// (`--release` matters: Rust's optimized sort gets very fast under
3471
    /// optimization, so the heap's relative advantage is best observed
3472
    /// against a sort that's also been optimized.)
3473
    ///
3474
    /// Measured numbers on an Apple Silicon laptop with N=10_000 + k=10:
3475
    ///   - bounded heap:    ~820µs
3476
    ///   - full sort+trunc: ~1.5ms
3477
    ///   - ratio:           ~1.8×
3478
    ///
3479
    /// The advantage is real but moderate at this size because the sort
3480
    /// key here is a single REAL column read (cheap) and Rust's sort_by
3481
    /// has a very low constant factor. The asymptotic O(N log k) vs
3482
    /// O(N log N) advantage scales with N and with per-row work — KNN
3483
    /// queries where the sort key is `vec_distance_l2(col, [...])` are
3484
    /// where this path really pays off, because each key evaluation is
3485
    /// itself O(dim) and the heap path skips the per-row evaluation
3486
    /// in the comparator (see `sort_rowids` for the contrast).
3487
    #[test]
3488
    #[ignore]
3489
    fn topk_benchmark() {
3490
        use std::time::Instant;
3491
        const N: usize = 10_000;
3492
        const K: usize = 10;
3493

3494
        let db = seed_score_table(N);
3495
        let table = db.get_table("docs".to_string()).unwrap();
3496
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
3497
        let order = q.order_by.as_ref().unwrap();
3498
        let all_rowids = table.rowids();
3499

3500
        // Time bounded heap.
3501
        let t0 = Instant::now();
3502
        let _topk = select_topk(&all_rowids, table, order, K).unwrap();
3503
        let heap_dur = t0.elapsed();
3504

3505
        // Time full sort + truncate.
3506
        let t1 = Instant::now();
3507
        let mut full = all_rowids.clone();
3508
        sort_rowids(&mut full, table, order).unwrap();
3509
        full.truncate(K);
3510
        let sort_dur = t1.elapsed();
3511

3512
        let ratio = sort_dur.as_secs_f64() / heap_dur.as_secs_f64().max(1e-9);
3513
        println!("\n--- topk_benchmark (N={N}, k={K}) ---");
3514
        println!("  bounded heap:   {heap_dur:?}");
3515
        println!("  full sort+trunc: {sort_dur:?}");
3516
        println!("  speedup ratio:  {ratio:.2}×");
3517

3518
        // Soft assertion. Floor is 1.4× because the cheap-key
3519
        // benchmark hovers around 1.8× empirically; setting this too
3520
        // close to the measured value risks flaky CI on slower
3521
        // runners. Floor of 1.4× still catches an actual regression
3522
        // (e.g., if select_topk became O(N²) or stopped using the
3523
        // heap entirely).
3524
        assert!(
3525
            ratio > 1.4,
3526
            "bounded heap should be substantially faster than full sort, but ratio = {ratio:.2}"
3527
        );
3528
    }
3529

3530
    // ---------------------------------------------------------------------
3531
    // SQLR-7 — IS NULL / IS NOT NULL
3532
    // ---------------------------------------------------------------------
3533

3534
    /// Helper for IS NULL tests: run a SELECT through process_command and
3535
    /// return the rendered table as a String so the test can assert on the
3536
    /// row-count line without re-implementing the executor.
3537
    fn run_select(db: &mut Database, sql: &str) -> String {
1✔
3538
        crate::sql::process_command(sql, db).expect("select")
1✔
3539
    }
3540

3541
    #[test]
3542
    fn where_is_null_returns_null_rows() {
3✔
3543
        let mut db = Database::new("t".to_string());
1✔
3544
        crate::sql::process_command(
3545
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
3546
            &mut db,
3547
        )
3548
        .unwrap();
3549
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, 10);", &mut db).unwrap();
1✔
3550
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
3551
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
3552
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (4, NULL);", &mut db).unwrap();
1✔
3553

3554
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NULL;");
1✔
3555
        assert!(
×
3556
            response.contains("2 rows returned"),
2✔
3557
            "IS NULL should return 2 rows, got: {response}"
3558
        );
3559
    }
3560

3561
    #[test]
3562
    fn where_is_not_null_returns_non_null_rows() {
3✔
3563
        let mut db = Database::new("t".to_string());
1✔
3564
        crate::sql::process_command(
3565
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
3566
            &mut db,
3567
        )
3568
        .unwrap();
3569
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, 10);", &mut db).unwrap();
1✔
3570
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
3571
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
3572

3573
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NOT NULL;");
1✔
3574
        assert!(
×
3575
            response.contains("2 rows returned"),
2✔
3576
            "IS NOT NULL should return 2 rows, got: {response}"
3577
        );
3578
    }
3579

3580
    #[test]
3581
    fn where_is_null_on_indexed_column() {
3✔
3582
        // UNIQUE on a TEXT column gets an automatic secondary index.
3583
        // NULLs aren't stored in the index, so IS NULL falls through to
3584
        // a full scan via select_rowids — verify the full-scan path is
3585
        // still correct.
3586
        let mut db = Database::new("t".to_string());
1✔
3587
        crate::sql::process_command(
3588
            "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT UNIQUE);",
3589
            &mut db,
3590
        )
3591
        .unwrap();
3592
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (1, 'alice');", &mut db)
1✔
3593
            .unwrap();
3594
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (2, NULL);", &mut db).unwrap();
1✔
3595
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (3, 'bob');", &mut db)
1✔
3596
            .unwrap();
3597

3598
        let null_rows = run_select(&mut db, "SELECT id FROM t WHERE name IS NULL;");
1✔
3599
        assert!(
×
3600
            null_rows.contains("1 row returned"),
2✔
3601
            "indexed IS NULL should return 1 row, got: {null_rows}"
3602
        );
3603
        let not_null_rows = run_select(&mut db, "SELECT id FROM t WHERE name IS NOT NULL;");
1✔
3604
        assert!(
×
3605
            not_null_rows.contains("2 rows returned"),
2✔
3606
            "indexed IS NOT NULL should return 2 rows, got: {not_null_rows}"
3607
        );
3608
    }
3609

3610
    #[test]
3611
    fn where_is_null_works_on_omitted_column() {
3✔
3612
        // No DEFAULT, column missing from the INSERT column list — the
3613
        // BTreeMap entry never gets written, get_value returns None,
3614
        // eval_expr maps that to Value::Null, and IS NULL matches.
3615
        let mut db = Database::new("t".to_string());
1✔
3616
        crate::sql::process_command(
3617
            "CREATE TABLE t (id INTEGER PRIMARY KEY, qty INTEGER, label TEXT);",
3618
            &mut db,
3619
        )
3620
        .unwrap();
3621
        crate::sql::process_command(
3622
            "INSERT INTO t (id, qty, label) VALUES (1, 7, 'a');",
3623
            &mut db,
3624
        )
3625
        .unwrap();
3626
        // qty omitted on row 2.
3627
        crate::sql::process_command("INSERT INTO t (id, label) VALUES (2, 'b');", &mut db).unwrap();
1✔
3628

3629
        let response = run_select(&mut db, "SELECT id FROM t WHERE qty IS NULL;");
1✔
3630
        assert!(
×
3631
            response.contains("1 row returned"),
2✔
3632
            "IS NULL should match the omitted-column row, got: {response}"
3633
        );
3634
    }
3635

3636
    #[test]
3637
    fn where_is_null_combines_with_and_or() {
3✔
3638
        // Sanity check that the new arms compose with the existing
3639
        // boolean operators in eval_expr — `n IS NULL AND id > 1`
3640
        // should narrow correctly.
3641
        let mut db = Database::new("t".to_string());
1✔
3642
        crate::sql::process_command(
3643
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
3644
            &mut db,
3645
        )
3646
        .unwrap();
3647
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, NULL);", &mut db).unwrap();
1✔
3648
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
3649
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
3650

3651
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NULL AND id > 1;");
1✔
3652
        assert!(
×
3653
            response.contains("1 row returned"),
2✔
3654
            "IS NULL combined with AND should match exactly row 2, got: {response}"
3655
        );
3656
    }
3657

3658
    // ---------------------------------------------------------------------
3659
    // SQLR-3 — LIKE / IN / DISTINCT / GROUP BY / aggregates
3660
    // ---------------------------------------------------------------------
3661

3662
    /// Seed a small employees table the analytical tests share.
3663
    fn seed_employees() -> Database {
1✔
3664
        let mut db = Database::new("t".to_string());
1✔
3665
        crate::sql::process_command(
3666
            "CREATE TABLE emp (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER);",
3667
            &mut db,
3668
        )
3669
        .unwrap();
3670
        let rows = [
1✔
3671
            "INSERT INTO emp (name, dept, salary) VALUES ('Alice', 'eng', 100);",
3672
            "INSERT INTO emp (name, dept, salary) VALUES ('alex',  'eng', 120);",
3673
            "INSERT INTO emp (name, dept, salary) VALUES ('Bob',   'eng', 100);",
3674
            "INSERT INTO emp (name, dept, salary) VALUES ('Carol', 'sales', 90);",
3675
            "INSERT INTO emp (name, dept, salary) VALUES ('Dave',  'sales', NULL);",
3676
            "INSERT INTO emp (name, dept, salary) VALUES ('Eve',   'ops', 80);",
3677
        ];
3678
        for sql in rows {
2✔
3679
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
3680
        }
3681
        db
1✔
3682
    }
3683

3684
    /// Drive `execute_select_rows` directly so tests can assert on typed values.
3685
    fn run_rows(db: &Database, sql: &str) -> SelectResult {
1✔
3686
        let q = parse_select(sql);
1✔
3687
        execute_select_rows(q, db).expect("select")
1✔
3688
    }
3689

3690
    // ----- LIKE -----
3691

3692
    #[test]
3693
    fn like_percent_prefix_case_insensitive() {
3✔
3694
        let db = seed_employees();
1✔
3695
        let r = run_rows(&db, "SELECT name FROM emp WHERE name LIKE 'a%';");
1✔
3696
        // Matches Alice and alex (case-insensitive ASCII).
3697
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
3698
        assert_eq!(names.len(), 2, "expected 2 rows, got {names:?}");
2✔
3699
        assert!(names.contains(&"Alice".to_string()));
2✔
3700
        assert!(names.contains(&"alex".to_string()));
1✔
3701
    }
3702

3703
    #[test]
3704
    fn like_underscore_singlechar() {
3✔
3705
        let db = seed_employees();
1✔
3706
        let r = run_rows(&db, "SELECT name FROM emp WHERE name LIKE '_ve';");
1✔
3707
        // Eve matches; alex does not (3 chars vs 4).
3708
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
3709
        assert_eq!(names, vec!["Eve".to_string()]);
2✔
3710
    }
3711

3712
    #[test]
3713
    fn not_like_excludes_match() {
3✔
3714
        let db = seed_employees();
1✔
3715
        let r = run_rows(&db, "SELECT name FROM emp WHERE name NOT LIKE 'a%';");
1✔
3716
        // Excludes Alice + alex; 4 rows remain.
3717
        assert_eq!(r.rows.len(), 4);
2✔
3718
    }
3719

3720
    #[test]
3721
    fn like_with_null_excludes_row() {
3✔
3722
        let db = seed_employees();
1✔
3723
        // Match 'sales' rows where salary is NULL → just Dave.
3724
        let r = run_rows(
3725
            &db,
3726
            "SELECT name FROM emp WHERE dept LIKE 'sales' AND salary IS NULL;",
3727
        );
3728
        assert_eq!(r.rows.len(), 1);
2✔
3729
        assert_eq!(r.rows[0][0].to_display_string(), "Dave");
1✔
3730
    }
3731

3732
    // ----- IN -----
3733

3734
    #[test]
3735
    fn in_list_positive() {
4✔
3736
        let db = seed_employees();
1✔
3737
        let r = run_rows(&db, "SELECT name FROM emp WHERE id IN (1, 3, 5);");
1✔
3738
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
3739
        assert_eq!(names.len(), 3);
2✔
3740
        assert!(names.contains(&"Alice".to_string()));
1✔
3741
        assert!(names.contains(&"Bob".to_string()));
1✔
3742
        assert!(names.contains(&"Dave".to_string()));
1✔
3743
    }
3744

3745
    #[test]
3746
    fn not_in_excludes_listed() {
3✔
3747
        let db = seed_employees();
1✔
3748
        let r = run_rows(&db, "SELECT name FROM emp WHERE id NOT IN (1, 2);");
1✔
3749
        // 6 rows total - 2 excluded = 4.
3750
        assert_eq!(r.rows.len(), 4);
2✔
3751
    }
3752

3753
    #[test]
3754
    fn in_list_with_null_three_valued() {
3✔
3755
        let db = seed_employees();
1✔
3756
        // x = 1 should match; for other rows the NULL in the list yields
3757
        // unknown → false in WHERE → excluded.
3758
        let r = run_rows(&db, "SELECT name FROM emp WHERE id IN (1, NULL);");
1✔
3759
        assert_eq!(r.rows.len(), 1);
2✔
3760
        assert_eq!(r.rows[0][0].to_display_string(), "Alice");
1✔
3761
    }
3762

3763
    // ----- DISTINCT -----
3764

3765
    #[test]
3766
    fn distinct_single_column() {
3✔
3767
        let db = seed_employees();
1✔
3768
        let r = run_rows(&db, "SELECT DISTINCT dept FROM emp;");
1✔
3769
        // 3 distinct depts: eng, sales, ops.
3770
        assert_eq!(r.rows.len(), 3);
2✔
3771
    }
3772

3773
    #[test]
3774
    fn distinct_multi_column_with_null() {
3✔
3775
        let db = seed_employees();
1✔
3776
        // (dept, salary) tuples — the two 'eng' / 100 rows collapse.
3777
        let r = run_rows(&db, "SELECT DISTINCT dept, salary FROM emp;");
1✔
3778
        // 6 input rows; (eng, 100) appears twice → 5 distinct tuples.
3779
        assert_eq!(r.rows.len(), 5);
2✔
3780
    }
3781

3782
    // ----- Aggregates without GROUP BY -----
3783

3784
    #[test]
3785
    fn count_star_no_groupby() {
3✔
3786
        let db = seed_employees();
1✔
3787
        let r = run_rows(&db, "SELECT COUNT(*) FROM emp;");
1✔
3788
        assert_eq!(r.rows.len(), 1);
2✔
3789
        assert_eq!(r.rows[0][0], Value::Integer(6));
1✔
3790
    }
3791

3792
    #[test]
3793
    fn count_col_skips_nulls() {
3✔
3794
        let db = seed_employees();
1✔
3795
        let r = run_rows(&db, "SELECT COUNT(salary) FROM emp;");
1✔
3796
        // 6 rows, 1 NULL salary → COUNT(salary) = 5.
3797
        assert_eq!(r.rows[0][0], Value::Integer(5));
2✔
3798
    }
3799

3800
    #[test]
3801
    fn count_distinct_dedupes_and_skips_nulls() {
3✔
3802
        let db = seed_employees();
1✔
3803
        let r = run_rows(&db, "SELECT COUNT(DISTINCT salary) FROM emp;");
1✔
3804
        // Distinct non-null salaries: {100, 120, 90, 80} → 4.
3805
        assert_eq!(r.rows[0][0], Value::Integer(4));
2✔
3806
    }
3807

3808
    #[test]
3809
    fn sum_int_stays_integer() {
3✔
3810
        let db = seed_employees();
1✔
3811
        let r = run_rows(&db, "SELECT SUM(salary) FROM emp;");
1✔
3812
        // 100 + 120 + 100 + 90 + 80 = 490 (NULL skipped).
3813
        assert_eq!(r.rows[0][0], Value::Integer(490));
2✔
3814
    }
3815

3816
    #[test]
3817
    fn avg_returns_real() {
3✔
3818
        let db = seed_employees();
1✔
3819
        let r = run_rows(&db, "SELECT AVG(salary) FROM emp;");
1✔
3820
        // 490 / 5 = 98.0
3821
        match &r.rows[0][0] {
2✔
3822
            Value::Real(v) => assert!((v - 98.0).abs() < 1e-9),
2✔
3823
            other => panic!("expected Real, got {other:?}"),
×
3824
        }
3825
    }
3826

3827
    #[test]
3828
    fn min_max_skip_nulls() {
3✔
3829
        let db = seed_employees();
1✔
3830
        let r = run_rows(&db, "SELECT MIN(salary), MAX(salary) FROM emp;");
1✔
3831
        assert_eq!(r.rows[0][0], Value::Integer(80));
2✔
3832
        assert_eq!(r.rows[0][1], Value::Integer(120));
1✔
3833
    }
3834

3835
    #[test]
3836
    fn aggregates_on_empty_table_emit_one_row() {
3✔
3837
        let mut db = Database::new("t".to_string());
1✔
3838
        crate::sql::process_command("CREATE TABLE t (x INTEGER);", &mut db).unwrap();
2✔
3839
        let r = run_rows(
3840
            &db,
3841
            "SELECT COUNT(*), SUM(x), AVG(x), MIN(x), MAX(x) FROM t;",
3842
        );
3843
        assert_eq!(r.rows.len(), 1);
2✔
3844
        assert_eq!(r.rows[0][0], Value::Integer(0));
1✔
3845
        assert_eq!(r.rows[0][1], Value::Null);
1✔
3846
        assert_eq!(r.rows[0][2], Value::Null);
1✔
3847
        assert_eq!(r.rows[0][3], Value::Null);
1✔
3848
        assert_eq!(r.rows[0][4], Value::Null);
1✔
3849
    }
3850

3851
    // ----- GROUP BY -----
3852

3853
    #[test]
3854
    fn group_by_single_col_with_count() {
3✔
3855
        let db = seed_employees();
1✔
3856
        let r = run_rows(&db, "SELECT dept, COUNT(*) FROM emp GROUP BY dept;");
1✔
3857
        assert_eq!(r.rows.len(), 3);
2✔
3858
        // Build a map for a stable assertion regardless of group order.
3859
        let mut by_dept: std::collections::HashMap<String, i64> = Default::default();
1✔
3860
        for row in &r.rows {
3✔
3861
            let d = row[0].to_display_string();
2✔
3862
            let c = match &row[1] {
2✔
3863
                Value::Integer(i) => *i,
1✔
3864
                v => panic!("expected Integer count, got {v:?}"),
×
3865
            };
3866
            by_dept.insert(d, c);
1✔
3867
        }
3868
        assert_eq!(by_dept["eng"], 3);
1✔
3869
        assert_eq!(by_dept["sales"], 2);
1✔
3870
        assert_eq!(by_dept["ops"], 1);
1✔
3871
    }
3872

3873
    #[test]
3874
    fn group_by_with_where_filter() {
4✔
3875
        let db = seed_employees();
1✔
3876
        let r = run_rows(
3877
            &db,
3878
            "SELECT dept, SUM(salary) FROM emp WHERE salary > 80 GROUP BY dept;",
3879
        );
3880
        // After WHERE, ops drops out (Eve = 80 excluded). eng has 3 rows
3881
        // contributing (100+120+100=320); sales has 1 (90; Dave NULL skipped).
3882
        let by: std::collections::HashMap<String, i64> = r
1✔
3883
            .rows
3884
            .iter()
3885
            .map(|row| {
2✔
3886
                (
3887
                    row[0].to_display_string(),
1✔
3888
                    match &row[1] {
2✔
3889
                        Value::Integer(i) => *i,
1✔
3890
                        v => panic!("expected Integer sum, got {v:?}"),
×
3891
                    },
3892
                )
3893
            })
3894
            .collect();
3895
        assert_eq!(by.len(), 2);
2✔
3896
        assert_eq!(by["eng"], 320);
1✔
3897
        assert_eq!(by["sales"], 90);
1✔
3898
    }
3899

3900
    #[test]
3901
    fn group_by_without_aggregates_is_distinct() {
3✔
3902
        let db = seed_employees();
1✔
3903
        let r = run_rows(&db, "SELECT dept FROM emp GROUP BY dept;");
1✔
3904
        assert_eq!(r.rows.len(), 3);
2✔
3905
    }
3906

3907
    #[test]
3908
    fn order_by_count_desc() {
3✔
3909
        let db = seed_employees();
1✔
3910
        let r = run_rows(
3911
            &db,
3912
            "SELECT dept, COUNT(*) AS n FROM emp GROUP BY dept ORDER BY n DESC LIMIT 2;",
3913
        );
3914
        assert_eq!(r.rows.len(), 2);
2✔
3915
        // Top group is 'eng' with 3.
3916
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
3917
        assert_eq!(r.rows[0][1], Value::Integer(3));
1✔
3918
    }
3919

3920
    #[test]
3921
    fn order_by_aggregate_call_form() {
3✔
3922
        let db = seed_employees();
1✔
3923
        // No alias — ORDER BY references the aggregate by its display form.
3924
        let r = run_rows(
3925
            &db,
3926
            "SELECT dept, COUNT(*) FROM emp GROUP BY dept ORDER BY COUNT(*) DESC;",
3927
        );
3928
        assert_eq!(r.rows.len(), 3);
2✔
3929
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
3930
    }
3931

3932
    #[test]
3933
    fn group_by_invalid_bare_column_errors() {
3✔
3934
        // `name` is neither aggregated nor in GROUP BY → must error at parse.
3935
        let mut db = Database::new("t".to_string());
1✔
3936
        crate::sql::process_command(
3937
            "CREATE TABLE t (id INTEGER PRIMARY KEY, dept TEXT, name TEXT);",
3938
            &mut db,
3939
        )
3940
        .unwrap();
3941
        let err = crate::sql::process_command("SELECT dept, name FROM t GROUP BY dept;", &mut db);
1✔
3942
        assert!(err.is_err(), "should reject bare 'name' not in GROUP BY");
2✔
3943
    }
3944

3945
    #[test]
3946
    fn aggregate_in_where_errors_friendly() {
3✔
3947
        let mut db = Database::new("t".to_string());
1✔
3948
        crate::sql::process_command("CREATE TABLE t (x INTEGER);", &mut db).unwrap();
2✔
3949
        crate::sql::process_command("INSERT INTO t (x) VALUES (1);", &mut db).unwrap();
1✔
3950
        let err = crate::sql::process_command("SELECT x FROM t WHERE COUNT(*) > 0;", &mut db);
1✔
3951
        assert!(err.is_err(), "aggregates must not be allowed in WHERE");
2✔
3952
    }
3953

3954
    // ---------------------------------------------------------------------
3955
    // SQLR-5 — JOINs (INNER / LEFT OUTER / RIGHT OUTER / FULL OUTER)
3956
    // ---------------------------------------------------------------------
3957

3958
    /// Two-table fixture used across the join tests. `customers` has
3959
    /// (1: Alice, 2: Bob, 3: Carol). `orders` has (id, customer_id,
3960
    /// amount): (1, 1, 100), (2, 1, 200), (3, 2, 50), (4, 4, 999).
3961
    /// Customer 3 (Carol) has no orders; order 4 has no customer
3962
    /// (dangling foreign key) — together they exercise both sides of
3963
    /// the outer-join NULL-padding.
3964
    fn seed_join_fixture() -> Database {
1✔
3965
        let mut db = Database::new("t".to_string());
1✔
3966
        for sql in [
3✔
3967
            "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);",
3968
            "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, amount INTEGER);",
3969
            "INSERT INTO customers (name) VALUES ('Alice');",
3970
            "INSERT INTO customers (name) VALUES ('Bob');",
3971
            "INSERT INTO customers (name) VALUES ('Carol');",
3972
            "INSERT INTO orders (customer_id, amount) VALUES (1, 100);",
3973
            "INSERT INTO orders (customer_id, amount) VALUES (1, 200);",
3974
            "INSERT INTO orders (customer_id, amount) VALUES (2, 50);",
3975
            "INSERT INTO orders (customer_id, amount) VALUES (4, 999);",
3976
        ] {
3977
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
3978
        }
3979
        db
1✔
3980
    }
3981

3982
    #[test]
3983
    fn inner_join_returns_only_matched_rows() {
3✔
3984
        let db = seed_join_fixture();
1✔
3985
        let r = run_rows(
3986
            &db,
3987
            "SELECT customers.name, orders.amount FROM customers \
3988
             INNER JOIN orders ON customers.id = orders.customer_id;",
3989
        );
3990
        assert_eq!(r.columns, vec!["name".to_string(), "amount".to_string()]);
2✔
3991
        // Alice: 100, 200; Bob: 50. Carol drops (no orders), order 4 drops
3992
        // (no customer). 3 rows.
3993
        let pairs: Vec<(String, i64)> = r
1✔
3994
            .rows
3995
            .iter()
3996
            .map(|row| {
2✔
3997
                (
3998
                    row[0].to_display_string(),
1✔
3999
                    match row[1] {
2✔
4000
                        Value::Integer(i) => i,
1✔
NEW
4001
                        ref v => panic!("expected integer amount, got {v:?}"),
×
4002
                    },
4003
                )
4004
            })
4005
            .collect();
4006
        assert_eq!(pairs.len(), 3);
2✔
4007
        assert!(pairs.contains(&("Alice".to_string(), 100)));
1✔
4008
        assert!(pairs.contains(&("Alice".to_string(), 200)));
1✔
4009
        assert!(pairs.contains(&("Bob".to_string(), 50)));
1✔
4010
    }
4011

4012
    #[test]
4013
    fn bare_join_defaults_to_inner() {
3✔
4014
        let db = seed_join_fixture();
1✔
4015
        let r = run_rows(
4016
            &db,
4017
            "SELECT customers.name FROM customers \
4018
             JOIN orders ON customers.id = orders.customer_id;",
4019
        );
4020
        assert_eq!(r.rows.len(), 3, "JOIN without prefix should be INNER");
2✔
4021
    }
4022

4023
    #[test]
4024
    fn left_outer_join_preserves_unmatched_left() {
3✔
4025
        let db = seed_join_fixture();
1✔
4026
        let r = run_rows(
4027
            &db,
4028
            "SELECT customers.name, orders.amount FROM customers \
4029
             LEFT OUTER JOIN orders ON customers.id = orders.customer_id;",
4030
        );
4031
        // Alice: two rows. Bob: one row. Carol: one NULL-padded row.
4032
        // Order 4 is dropped (left side has no customer for id=4).
4033
        assert_eq!(r.rows.len(), 4);
2✔
4034
        let carol = r
3✔
4035
            .rows
4036
            .iter()
4037
            .find(|row| row[0].to_display_string() == "Carol")
3✔
4038
            .expect("Carol should appear with a NULL-padded right side");
4039
        assert_eq!(carol[1], Value::Null);
1✔
4040
    }
4041

4042
    #[test]
4043
    fn right_outer_join_preserves_unmatched_right() {
3✔
4044
        let db = seed_join_fixture();
1✔
4045
        let r = run_rows(
4046
            &db,
4047
            "SELECT customers.name, orders.amount FROM customers \
4048
             RIGHT OUTER JOIN orders ON customers.id = orders.customer_id;",
4049
        );
4050
        // 3 matched rows + 1 dangling order (id=4, customer_id=4 with no
4051
        // matching customer). Total 4. Carol drops because the right
4052
        // table has no row pointing at her.
4053
        assert_eq!(r.rows.len(), 4);
2✔
4054
        let dangling = r
3✔
4055
            .rows
4056
            .iter()
4057
            .find(|row| matches!(row[1], Value::Integer(999)))
3✔
4058
            .expect("dangling order 999 should appear with a NULL-padded customer name");
4059
        assert_eq!(dangling[0], Value::Null);
1✔
4060
    }
4061

4062
    #[test]
4063
    fn full_outer_join_preserves_both_sides() {
3✔
4064
        let db = seed_join_fixture();
1✔
4065
        let r = run_rows(
4066
            &db,
4067
            "SELECT customers.name, orders.amount FROM customers \
4068
             FULL OUTER JOIN orders ON customers.id = orders.customer_id;",
4069
        );
4070
        // 3 matched + 1 unmatched left (Carol) + 1 unmatched right
4071
        // (order 999) = 5 rows.
4072
        assert_eq!(r.rows.len(), 5);
2✔
4073
        // Carol with NULL amount.
NEW
4074
        assert!(
×
4075
            r.rows
3✔
4076
                .iter()
1✔
4077
                .any(|row| row[0].to_display_string() == "Carol" && matches!(row[1], Value::Null))
3✔
4078
        );
4079
        // 999 with NULL name.
NEW
4080
        assert!(
×
4081
            r.rows
3✔
4082
                .iter()
1✔
4083
                .any(|row| matches!(row[1], Value::Integer(999)) && matches!(row[0], Value::Null))
3✔
4084
        );
4085
    }
4086

4087
    #[test]
4088
    fn join_with_table_aliases_resolves_qualifiers() {
3✔
4089
        let db = seed_join_fixture();
1✔
4090
        let r = run_rows(
4091
            &db,
4092
            "SELECT c.name, o.amount FROM customers AS c \
4093
             INNER JOIN orders AS o ON c.id = o.customer_id;",
4094
        );
4095
        assert_eq!(r.rows.len(), 3);
2✔
4096
        assert_eq!(r.columns, vec!["name".to_string(), "amount".to_string()]);
1✔
4097
    }
4098

4099
    #[test]
4100
    fn join_with_where_filter_applies_after_join() {
3✔
4101
        let db = seed_join_fixture();
1✔
4102
        // Filter to only orders >= 100. With INNER JOIN, this drops Bob's
4103
        // 50-amount order, leaving Alice's 100 and 200.
4104
        let r = run_rows(
4105
            &db,
4106
            "SELECT customers.name, orders.amount FROM customers \
4107
             INNER JOIN orders ON customers.id = orders.customer_id \
4108
             WHERE orders.amount >= 100;",
4109
        );
4110
        assert_eq!(r.rows.len(), 2);
2✔
NEW
4111
        assert!(
×
4112
            r.rows
3✔
4113
                .iter()
1✔
4114
                .all(|row| row[0].to_display_string() == "Alice")
3✔
4115
        );
4116
    }
4117

4118
    #[test]
4119
    fn left_join_with_where_on_right_side_is_not_inner() {
3✔
4120
        // WHERE on the right side that excludes NULL turns LEFT JOIN
4121
        // back into INNER JOIN semantically. Verify the executor
4122
        // applies the WHERE *after* the join padded NULLs in.
4123
        let db = seed_join_fixture();
1✔
4124
        let r = run_rows(
4125
            &db,
4126
            "SELECT customers.name, orders.amount FROM customers \
4127
             LEFT OUTER JOIN orders ON customers.id = orders.customer_id \
4128
             WHERE orders.amount IS NULL;",
4129
        );
4130
        // Only Carol survives — she's the only customer with no order.
4131
        assert_eq!(r.rows.len(), 1);
2✔
4132
        assert_eq!(r.rows[0][0].to_display_string(), "Carol");
1✔
4133
        assert_eq!(r.rows[0][1], Value::Null);
1✔
4134
    }
4135

4136
    #[test]
4137
    fn select_star_over_join_emits_all_columns_from_both_tables() {
3✔
4138
        let db = seed_join_fixture();
1✔
4139
        let r = run_rows(
4140
            &db,
4141
            "SELECT * FROM customers \
4142
             INNER JOIN orders ON customers.id = orders.customer_id;",
4143
        );
4144
        // customers has 2 cols (id, name), orders has 3 cols
4145
        // (id, customer_id, amount). 5 columns total. Header order
4146
        // follows source order — primary table first.
4147
        assert_eq!(
1✔
4148
            r.columns,
4149
            vec![
3✔
4150
                "id".to_string(),
1✔
4151
                "name".to_string(),
1✔
4152
                "id".to_string(),
1✔
4153
                "customer_id".to_string(),
1✔
4154
                "amount".to_string(),
1✔
4155
            ]
4156
        );
4157
        assert_eq!(r.rows.len(), 3);
1✔
4158
    }
4159

4160
    #[test]
4161
    fn join_order_by_sorts_full_joined_rows() {
3✔
4162
        let db = seed_join_fixture();
1✔
4163
        let r = run_rows(
4164
            &db,
4165
            "SELECT c.name, o.amount FROM customers AS c \
4166
             INNER JOIN orders AS o ON c.id = o.customer_id \
4167
             ORDER BY o.amount;",
4168
        );
4169
        let amounts: Vec<i64> = r
1✔
4170
            .rows
4171
            .iter()
4172
            .map(|row| match row[1] {
3✔
4173
                Value::Integer(i) => i,
1✔
NEW
4174
                ref v => panic!("expected integer, got {v:?}"),
×
4175
            })
4176
            .collect();
4177
        assert_eq!(amounts, vec![50, 100, 200]);
2✔
4178
    }
4179

4180
    #[test]
4181
    fn join_limit_truncates_after_join_and_sort() {
3✔
4182
        let db = seed_join_fixture();
1✔
4183
        let r = run_rows(
4184
            &db,
4185
            "SELECT c.name, o.amount FROM customers AS c \
4186
             INNER JOIN orders AS o ON c.id = o.customer_id \
4187
             ORDER BY o.amount DESC LIMIT 2;",
4188
        );
4189
        assert_eq!(r.rows.len(), 2);
2✔
4190
        // Top two by amount DESC: 200 (Alice), 100 (Alice).
4191
        let amounts: Vec<i64> = r
1✔
4192
            .rows
4193
            .iter()
4194
            .map(|row| match row[1] {
3✔
4195
                Value::Integer(i) => i,
1✔
NEW
4196
                ref v => panic!("expected integer, got {v:?}"),
×
4197
            })
4198
            .collect();
4199
        assert_eq!(amounts, vec![200, 100]);
2✔
4200
    }
4201

4202
    #[test]
4203
    fn three_table_join_chains_correctly() {
3✔
4204
        let mut db = Database::new("t".to_string());
1✔
4205
        for sql in [
3✔
4206
            "CREATE TABLE a (id INTEGER PRIMARY KEY, label TEXT);",
4207
            "CREATE TABLE b (id INTEGER PRIMARY KEY, a_id INTEGER, tag TEXT);",
4208
            "CREATE TABLE c (id INTEGER PRIMARY KEY, b_id INTEGER, note TEXT);",
4209
            "INSERT INTO a (label) VALUES ('a-one');",
4210
            "INSERT INTO a (label) VALUES ('a-two');",
4211
            "INSERT INTO b (a_id, tag) VALUES (1, 'b1');",
4212
            "INSERT INTO b (a_id, tag) VALUES (2, 'b2');",
4213
            "INSERT INTO c (b_id, note) VALUES (1, 'c1');",
4214
        ] {
4215
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4216
        }
4217
        let r = run_rows(
4218
            &db,
4219
            "SELECT a.label, b.tag, c.note FROM a \
4220
             INNER JOIN b ON a.id = b.a_id \
4221
             INNER JOIN c ON b.id = c.b_id;",
4222
        );
4223
        // Only b1 has a c row. So one combined row.
4224
        assert_eq!(r.rows.len(), 1);
2✔
4225
        assert_eq!(r.rows[0][0].to_display_string(), "a-one");
1✔
4226
        assert_eq!(r.rows[0][1].to_display_string(), "b1");
1✔
4227
        assert_eq!(r.rows[0][2].to_display_string(), "c1");
1✔
4228
    }
4229

4230
    #[test]
4231
    fn ambiguous_unqualified_column_in_join_errors() {
3✔
4232
        // Both customers and orders have a column named `id`. An
4233
        // unqualified `id` in the SELECT must error rather than
4234
        // silently picking one side.
4235
        let db = seed_join_fixture();
1✔
4236
        let q = parse_select(
4237
            "SELECT id FROM customers INNER JOIN orders ON customers.id = orders.customer_id;",
4238
        );
4239
        let res = execute_select_rows(q, &db);
1✔
4240
        assert!(res.is_err(), "unqualified ambiguous 'id' should error");
2✔
4241
    }
4242

4243
    #[test]
4244
    fn join_self_without_alias_is_rejected() {
3✔
4245
        let mut db = Database::new("t".to_string());
1✔
4246
        crate::sql::process_command(
4247
            "CREATE TABLE n (id INTEGER PRIMARY KEY, parent INTEGER);",
4248
            &mut db,
4249
        )
4250
        .unwrap();
4251
        let q = parse_select("SELECT n.id FROM n INNER JOIN n ON n.id = n.parent;");
1✔
4252
        let res = execute_select_rows(q, &db);
1✔
NEW
4253
        assert!(
×
4254
            res.is_err(),
2✔
4255
            "self-join without an alias should error on duplicate qualifier"
4256
        );
4257
    }
4258

4259
    #[test]
4260
    fn using_or_natural_join_returns_not_implemented() {
3✔
4261
        let mut db = Database::new("t".to_string());
1✔
4262
        crate::sql::process_command("CREATE TABLE a (id INTEGER PRIMARY KEY);", &mut db).unwrap();
2✔
4263
        crate::sql::process_command("CREATE TABLE b (id INTEGER PRIMARY KEY);", &mut db).unwrap();
1✔
4264
        let err = crate::sql::process_command("SELECT * FROM a INNER JOIN b USING (id);", &mut db);
1✔
4265
        assert!(err.is_err(), "USING is not yet supported");
2✔
4266

4267
        let err = crate::sql::process_command("SELECT * FROM a NATURAL JOIN b;", &mut db);
1✔
4268
        assert!(err.is_err(), "NATURAL is not supported");
2✔
4269
    }
4270

4271
    #[test]
4272
    fn aggregates_over_join_are_rejected() {
3✔
4273
        let db = seed_join_fixture();
1✔
4274
        let err = crate::sql::process_command(
4275
            "SELECT COUNT(*) FROM customers \
4276
             INNER JOIN orders ON customers.id = orders.customer_id;",
4277
            &mut seed_join_fixture(),
1✔
4278
        );
4279
        assert!(err.is_err(), "aggregates over JOIN are not yet supported");
1✔
4280
        let _ = db; // keep compiler happy if unused
4281
    }
4282

4283
    #[test]
4284
    fn left_join_with_no_matches_pads_every_row() {
3✔
4285
        let mut db = Database::new("t".to_string());
1✔
4286
        for sql in [
3✔
4287
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4288
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
4289
            "INSERT INTO a (x) VALUES (1);",
4290
            "INSERT INTO a (x) VALUES (2);",
4291
            "INSERT INTO b (y) VALUES (10);",
4292
        ] {
4293
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4294
        }
4295
        // ON condition matches nothing.
4296
        let r = run_rows(
4297
            &db,
4298
            "SELECT a.x, b.y FROM a LEFT OUTER JOIN b ON a.x = b.y;",
4299
        );
4300
        assert_eq!(r.rows.len(), 2);
2✔
4301
        for row in &r.rows {
1✔
4302
            assert_eq!(row[1], Value::Null);
2✔
4303
        }
4304
    }
4305

4306
    #[test]
4307
    fn left_outer_join_order_by_places_nulls_first() {
3✔
4308
        // NULL ordering matches the engine-wide rule: NULL is Less
4309
        // than every concrete value (see compare_values). So an
4310
        // ORDER BY of a NULL-padded right column puts the
4311
        // outer-join row at the top under ASC.
4312
        let db = seed_join_fixture();
1✔
4313
        let r = run_rows(
4314
            &db,
4315
            "SELECT c.name, o.amount FROM customers AS c \
4316
             LEFT OUTER JOIN orders AS o ON c.id = o.customer_id \
4317
             ORDER BY o.amount ASC;",
4318
        );
4319
        assert_eq!(r.rows.len(), 4);
2✔
4320
        // Carol's NULL amount sorts first.
4321
        assert_eq!(r.rows[0][0].to_display_string(), "Carol");
1✔
4322
        assert_eq!(r.rows[0][1], Value::Null);
1✔
4323
    }
4324

4325
    #[test]
4326
    fn chained_left_outer_join_preserves_left_through_two_levels() {
4✔
4327
        // A LEFT JOIN B LEFT JOIN C — a row in A with no match in B
4328
        // must survive both joins with NULL padding for both sides.
4329
        let mut db = Database::new("t".to_string());
1✔
4330
        for sql in [
3✔
4331
            "CREATE TABLE a (id INTEGER PRIMARY KEY, label TEXT);",
4332
            "CREATE TABLE b (id INTEGER PRIMARY KEY, a_id INTEGER, tag TEXT);",
4333
            "CREATE TABLE c (id INTEGER PRIMARY KEY, b_id INTEGER, note TEXT);",
4334
            "INSERT INTO a (label) VALUES ('a-one');",
4335
            "INSERT INTO a (label) VALUES ('a-two');",
4336
            // b only matches a-one.
4337
            "INSERT INTO b (a_id, tag) VALUES (1, 'b1');",
4338
            // No c rows at all.
4339
        ] {
4340
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4341
        }
4342
        let r = run_rows(
4343
            &db,
4344
            "SELECT a.label, b.tag, c.note FROM a \
4345
             LEFT OUTER JOIN b ON a.id = b.a_id \
4346
             LEFT OUTER JOIN c ON b.id = c.b_id;",
4347
        );
4348
        // Two rows: a-one + b1 with c=NULL, and a-two with b=NULL+c=NULL.
4349
        assert_eq!(r.rows.len(), 2);
2✔
4350
        let by_label: std::collections::HashMap<String, &Vec<Value>> = r
1✔
4351
            .rows
4352
            .iter()
4353
            .map(|row| (row[0].to_display_string(), row))
3✔
4354
            .collect();
4355
        assert_eq!(by_label["a-one"][1].to_display_string(), "b1");
2✔
4356
        assert_eq!(by_label["a-one"][2], Value::Null);
1✔
4357
        assert_eq!(by_label["a-two"][1], Value::Null);
1✔
4358
        assert_eq!(by_label["a-two"][2], Value::Null);
1✔
4359
    }
4360

4361
    #[test]
4362
    fn on_clause_referencing_not_yet_joined_table_errors_clearly() {
3✔
4363
        // ON should only see tables joined so far. Referencing a
4364
        // table that hasn't joined yet is a clean error rather than
4365
        // silently NULL-coalescing into "ON evaluated false".
4366
        let mut db = Database::new("t".to_string());
1✔
4367
        for sql in [
3✔
4368
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4369
            "CREATE TABLE b (id INTEGER PRIMARY KEY, x INTEGER);",
4370
            "CREATE TABLE c (id INTEGER PRIMARY KEY, x INTEGER);",
4371
            "INSERT INTO a (x) VALUES (1);",
4372
            "INSERT INTO b (x) VALUES (1);",
4373
            "INSERT INTO c (x) VALUES (1);",
4374
        ] {
4375
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4376
        }
4377
        let q =
4378
            parse_select("SELECT a.x FROM a INNER JOIN b ON a.x = c.x INNER JOIN c ON b.x = c.x;");
4379
        let res = execute_select_rows(q, &db);
1✔
NEW
4380
        assert!(
×
4381
            res.is_err(),
2✔
4382
            "ON referencing not-yet-joined table 'c' should error"
4383
        );
4384
    }
4385

4386
    #[test]
4387
    fn join_on_truthy_integer_is_accepted() {
3✔
4388
        // ON `1` should be treated as true, like WHERE 1. Verifies
4389
        // the executor reuses eval_predicate_scope's truthiness
4390
        // semantic on JOIN conditions.
4391
        let mut db = Database::new("t".to_string());
1✔
4392
        for sql in [
3✔
4393
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4394
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
4395
            "INSERT INTO a (x) VALUES (1);",
4396
            "INSERT INTO a (x) VALUES (2);",
4397
            "INSERT INTO b (y) VALUES (10);",
4398
            "INSERT INTO b (y) VALUES (20);",
4399
        ] {
4400
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4401
        }
4402
        let r = run_rows(&db, "SELECT a.x, b.y FROM a INNER JOIN b ON 1;");
1✔
4403
        // ON 1 is always true → cross product → 2 × 2 = 4 rows.
4404
        assert_eq!(r.rows.len(), 4);
2✔
4405
    }
4406

4407
    #[test]
4408
    fn full_join_on_empty_tables_returns_empty() {
3✔
4409
        let mut db = Database::new("t".to_string());
1✔
4410
        for sql in [
3✔
4411
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4412
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
4413
        ] {
4414
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4415
        }
4416
        let r = run_rows(
4417
            &db,
4418
            "SELECT a.x, b.y FROM a FULL OUTER JOIN b ON a.x = b.y;",
4419
        );
4420
        assert!(r.rows.is_empty());
2✔
4421
    }
4422
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc