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

joaoh82 / rust_sqlite / 25563224520

08 May 2026 03:09PM UTC coverage: 65.365% (+0.3%) from 65.094%
25563224520

push

github

web-flow
feat(engine): HNSW probe widened to cosine + dot via per-index metric (SQLR-28) (#113)

Phase 7d.2's `try_hnsw_probe` was L2-only, so any KNN query using
`vec_distance_cosine` or `vec_distance_dot` silently fell through to
brute-force even with an HNSW index attached. Surfaced by the SQLR-23
v2 W10 bench: the HNSW variant clocked ~181 ms vs ~129 ms for
brute-force because the cosine hot loop never touched the graph.

Lands as sub-phase 7d.4 — per-index distance metric, no file format
bump (the metric round-trips via the synthesized CREATE INDEX SQL in
`sqlrite_master`):

- New SQL surface: `CREATE INDEX … USING hnsw (col) WITH (metric =
  '<l2|cosine|dot>')`. Omitting the WITH clause defaults to L2,
  so pre-SQLR-28 catalogs round-trip byte-identical. Typo'd metric
  names error at CREATE INDEX time rather than silently defaulting
  to L2 — that silent fallback is exactly what we're fixing.
- New `SqlriteDialect` (wraps sqlparser's `SQLiteDialect`, only
  override is `supports_create_index_with_clause = true`).
- `HnswIndexEntry` grows a `metric: DistanceMetric` field; the load,
  rebuild, and dirty-rebuild paths all consume the per-entry metric
  instead of hard-coded L2.
- `try_hnsw_probe` widens to all three `vec_distance_*` functions
  and only fires when the index entry's metric matches the query
  function. Mismatch → brute-force fallback (correct, just slow).
- W10 bench bumped to v3; the HNSW variant creates the index
  `WITH (metric = 'cosine')`. v1/v2 numbers are not comparable.
- Tests: cosine + dot self-query through the optimizer,
  metric-mismatch fallback, unknown-metric rejection, WITH-on-btree
  rejection, save+reopen preserves cosine metric.

Unblocks SQLR-25 (republish v2/v3 bench numbers).

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

176 of 207 new or added lines in 10 files covered. (85.02%)

1 existing line in 1 file now uncovered.

9140 of 13983 relevant lines covered (65.37%)

1.2 hits per line

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

81.27
/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`.
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✔
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✔
120
                        "unknown table qualifier '{q}' in column reference '{q}.{col}'"
×
121
                    ))
122
                })?;
123
            if !self.tables[pos].table.contains_column(col.to_string()) {
1✔
124
                return Err(SQLRiteError::Internal(format!(
×
125
                    "column '{col}' does not exist on '{}'",
×
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✔
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✔
145
                        "column reference '{col}' is ambiguous — qualify it as <table>.{col}"
×
146
                    )));
147
                }
148
                hit = Some(i);
1✔
149
            }
150
        }
151
        let i = hit.ok_or_else(|| {
×
152
            SQLRiteError::Internal(format!(
×
153
                "unknown column '{col}' in joined SELECT (no in-scope table has it)"
×
154
            ))
155
        })?;
156
        Ok(match self.rowids[i] {
×
157
            None => Value::Null,
×
158
            Some(r) => self.tables[i]
×
159
                .table
×
160
                .get_value(col, r)
×
161
                .unwrap_or(Value::Null),
×
162
        })
163
    }
164

165
    fn single_table_view(&self) -> Option<(&Table, i64)> {
×
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.
670
                    return Err(SQLRiteError::Internal(
×
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
        with,
1✔
907
        ..
908
    }) = stmt
1✔
909
    else {
910
        return Err(SQLRiteError::Internal(
×
911
            "execute_create_index called on a non-CREATE-INDEX statement".to_string(),
×
912
        ));
913
    };
914

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

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

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

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

958
    // Parse `WITH (key = value, …)` options (SQLR-28). The only key
959
    // recognized today is `metric` for HNSW indexes — `'l2'` /
960
    // `'cosine'` / `'dot'`. The clause is rejected on non-HNSW indexes
961
    // so a typo doesn't silently sit on a btree index where it can't
962
    // do anything useful.
963
    let hnsw_metric = parse_hnsw_with_options(with, &index_name, method)?;
3✔
964

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

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

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

1015
        let mut pairs = Vec::new();
1✔
1016
        for rowid in table.rowids() {
3✔
1017
            if let Some(v) = table.get_value(&column_name, rowid) {
2✔
1018
                pairs.push((rowid, v));
1✔
1019
            }
1020
        }
1021
        (datatype, pairs)
1✔
1022
    };
1023

1024
    match method {
1✔
1025
        IndexMethod::Btree => create_btree_index(
1026
            db,
1027
            &table_name_str,
1✔
1028
            &index_name,
1✔
1029
            &column_name,
1✔
1030
            &datatype,
1031
            *unique,
1✔
1032
            &existing_rowids_and_values,
1✔
1033
        ),
1034
        IndexMethod::Hnsw => create_hnsw_index(
1035
            db,
1036
            &table_name_str,
1✔
1037
            &index_name,
1✔
1038
            &column_name,
1✔
1039
            &datatype,
1040
            *unique,
1✔
1041
            hnsw_metric.unwrap_or(DistanceMetric::L2),
1✔
1042
            &existing_rowids_and_values,
1✔
1043
        ),
1044
        IndexMethod::Fts => create_fts_index(
1045
            db,
1046
            &table_name_str,
1✔
1047
            &index_name,
1✔
1048
            &column_name,
1✔
1049
            &datatype,
1050
            *unique,
1✔
1051
            &existing_rowids_and_values,
1✔
1052
        ),
1053
    }
1054
}
1055

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

1078
    if name == crate::sql::pager::MASTER_TABLE_NAME {
2✔
1079
        return Err(SQLRiteError::General(format!(
2✔
1080
            "'{}' is a reserved name used by the internal schema catalog",
1081
            crate::sql::pager::MASTER_TABLE_NAME
1082
        )));
1083
    }
1084

1085
    if !db.contains_table(name.clone()) {
2✔
1086
        return if if_exists {
2✔
1087
            Ok(0)
1✔
1088
        } else {
1089
            Err(SQLRiteError::General(format!(
2✔
1090
                "Table '{name}' does not exist"
1091
            )))
1092
        };
1093
    }
1094

1095
    db.tables.remove(&name);
2✔
1096
    Ok(1)
1097
}
1098

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

1119
    for table in db.tables.values_mut() {
2✔
1120
        if let Some(secondary) = table.secondary_indexes.iter().find(|i| i.name == name) {
4✔
1121
            if secondary.origin == IndexOrigin::Auto {
2✔
1122
                return Err(SQLRiteError::General(format!(
2✔
1123
                    "cannot drop auto-created index '{name}' (drop the column or table instead)"
1124
                )));
1125
            }
1126
            table.secondary_indexes.retain(|i| i.name != name);
3✔
1127
            return Ok(1);
1✔
1128
        }
1129
        if table.hnsw_indexes.iter().any(|i| i.name == name) {
×
1130
            table.hnsw_indexes.retain(|i| i.name != name);
×
1131
            return Ok(1);
×
1132
        }
1133
        if table.fts_indexes.iter().any(|i| i.name == name) {
×
1134
            table.fts_indexes.retain(|i| i.name != name);
×
1135
            return Ok(1);
×
1136
        }
1137
    }
1138

1139
    if if_exists {
2✔
1140
        Ok(0)
1141
    } else {
1142
        Err(SQLRiteError::General(format!(
2✔
1143
            "Index '{name}' does not exist"
1144
        )))
1145
    }
1146
}
1147

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

1162
    if table_name == crate::sql::pager::MASTER_TABLE_NAME {
2✔
1163
        return Err(SQLRiteError::General(format!(
×
1164
            "'{}' is a reserved name used by the internal schema catalog",
1165
            crate::sql::pager::MASTER_TABLE_NAME
1166
        )));
1167
    }
1168

1169
    if !db.contains_table(table_name.clone()) {
2✔
1170
        return if alter.if_exists {
2✔
1171
            Ok("ALTER TABLE: no-op (table does not exist)".to_string())
2✔
1172
        } else {
1173
            Err(SQLRiteError::General(format!(
2✔
1174
                "Table '{table_name}' does not exist"
1175
            )))
1176
        };
1177
    }
1178

1179
    if alter.operations.len() != 1 {
2✔
1180
        return Err(SQLRiteError::NotImplemented(
×
1181
            "ALTER TABLE supports one operation per statement".to_string(),
×
1182
        ));
1183
    }
1184

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

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

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

1335
    let mut table = db
3✔
1336
        .tables
1337
        .remove(old)
1✔
1338
        .ok_or_else(|| SQLRiteError::General(format!("Table '{old}' does not exist")))?;
1✔
1339
    table.tb_name = new.to_string();
2✔
1340
    for idx in table.secondary_indexes.iter_mut() {
1✔
1341
        idx.table_name = new.to_string();
2✔
1342
        if idx.origin == IndexOrigin::Auto
2✔
1343
            && idx.name == SecondaryIndex::auto_name(old, &idx.column_name)
1✔
1344
        {
1345
            idx.name = SecondaryIndex::auto_name(new, &idx.column_name);
1✔
1346
        }
1347
    }
1348
    db.tables.insert(new.to_string(), table);
1✔
1349
    Ok(())
1✔
1350
}
1351

1352
/// `USING <method>` choices recognized by `execute_create_index`. A
1353
/// missing USING clause defaults to `Btree` so existing CREATE INDEX
1354
/// statements (Phase 3e) keep working unchanged.
1355
#[derive(Debug, Clone, Copy)]
1356
enum IndexMethod {
1357
    Btree,
1358
    Hnsw,
1359
    /// Phase 8b — full-text inverted index over a TEXT column.
1360
    Fts,
1361
}
1362

1363
/// Builds a Phase 3e B-Tree secondary index and attaches it to the table.
1364
fn create_btree_index(
1✔
1365
    db: &mut Database,
1366
    table_name: &str,
1367
    index_name: &str,
1368
    column_name: &str,
1369
    datatype: &DataType,
1370
    unique: bool,
1371
    existing: &[(i64, Value)],
1372
) -> Result<String> {
1373
    let mut idx = SecondaryIndex::new(
3✔
1374
        index_name.to_string(),
1✔
1375
        table_name.to_string(),
2✔
1376
        column_name.to_string(),
1✔
1377
        datatype,
1378
        unique,
1379
        IndexOrigin::Explicit,
1380
    )?;
1381

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

1396
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1397
    table_mut.secondary_indexes.push(idx);
1✔
1398
    Ok(index_name.to_string())
1✔
1399
}
1400

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

1423
    if unique {
1✔
1424
        return Err(SQLRiteError::General(
×
1425
            "UNIQUE has no meaning for HNSW indexes".to_string(),
×
1426
        ));
1427
    }
1428

1429
    // Build the in-memory graph. The distance metric was picked at
1430
    // CREATE INDEX time (defaults to L2 if no `WITH (metric = …)`
1431
    // clause was supplied). The graph topology is metric-specific —
1432
    // L2 neighbour pruning ≠ cosine neighbour pruning — so the
1433
    // optimizer's HNSW shortcut only fires when the query's
1434
    // `vec_distance_*` function matches this value (SQLR-28).
1435
    //
1436
    // Seed: hash the index name so different indexes get different
1437
    // graph topologies, but the same index always gets the same one
1438
    // — useful when debugging recall / index size.
1439
    let seed = hash_str_to_seed(index_name);
1✔
1440
    let mut idx = HnswIndex::new(metric, seed);
1✔
1441

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

1466
    for (rowid, _) in existing {
1✔
1467
        if let Some(v) = vec_map.get(rowid) {
2✔
1468
            let v_clone = v.clone();
1✔
1469
            idx.insert(*rowid, &v_clone, |id| {
3✔
1470
                vec_map.get(&id).cloned().unwrap_or_default()
1✔
1471
            });
1472
        }
1473
    }
1474

1475
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1476
    table_mut.hnsw_indexes.push(HnswIndexEntry {
2✔
1477
        name: index_name.to_string(),
1✔
1478
        column_name: column_name.to_string(),
1✔
1479
        metric,
1480
        index: idx,
1✔
1481
        // Freshly built — no DELETE/UPDATE has invalidated it yet.
1482
        needs_rebuild: false,
1483
    });
1484
    Ok(index_name.to_string())
1✔
1485
}
1486

1487
/// Parses the `WITH (metric = '<name>', …)` options bag on a CREATE
1488
/// INDEX statement. Returns the chosen metric (or `None` if no
1489
/// `metric` key was supplied) on HNSW indexes; raises a
1490
/// user-visible error on:
1491
///
1492
///   - WITH options on a non-HNSW index (btree / fts have no knobs we
1493
///     understand here),
1494
///   - unknown option keys,
1495
///   - unknown metric names (typo guard — silently falling back to L2
1496
///     would hide the user's intent and re-introduce the SQLR-28 bug).
1497
fn parse_hnsw_with_options(
1✔
1498
    with: &[Expr],
1499
    index_name: &str,
1500
    method: IndexMethod,
1501
) -> Result<Option<DistanceMetric>> {
1502
    if with.is_empty() {
1✔
1503
        return Ok(None);
1✔
1504
    }
1505
    if !matches!(method, IndexMethod::Hnsw) {
1✔
1506
        return Err(SQLRiteError::General(format!(
1✔
1507
            "CREATE INDEX '{index_name}' has a WITH (...) clause but its index method \
1508
             doesn't support any options — only `USING hnsw` recognises `WITH (metric = ...)`"
1509
        )));
1510
    }
1511

1512
    let mut metric: Option<DistanceMetric> = None;
1✔
1513
    for opt in with {
2✔
1514
        let Expr::BinaryOp { left, op, right } = opt else {
2✔
NEW
1515
            return Err(SQLRiteError::General(format!(
×
1516
                "CREATE INDEX '{index_name}': unsupported WITH option {opt:?} \
1517
                 (expected `key = 'value'`)"
1518
            )));
1519
        };
1520
        if !matches!(op, BinaryOperator::Eq) {
1✔
NEW
1521
            return Err(SQLRiteError::General(format!(
×
1522
                "CREATE INDEX '{index_name}': WITH options must use `=` (got {op:?})"
1523
            )));
1524
        }
1525
        let key = match left.as_ref() {
1✔
1526
            Expr::Identifier(ident) => ident.value.clone(),
1✔
NEW
1527
            other => {
×
NEW
1528
                return Err(SQLRiteError::General(format!(
×
1529
                    "CREATE INDEX '{index_name}': WITH option key must be a bare identifier, \
1530
                     got {other:?}"
1531
                )));
1532
            }
1533
        };
1534
        let value = match right.as_ref() {
2✔
1535
            Expr::Value(v) => match &v.value {
1✔
1536
                AstValue::SingleQuotedString(s) => s.clone(),
2✔
NEW
1537
                AstValue::DoubleQuotedString(s) => s.clone(),
×
NEW
1538
                other => {
×
NEW
1539
                    return Err(SQLRiteError::General(format!(
×
1540
                        "CREATE INDEX '{index_name}': WITH option '{key}' value must be \
1541
                         a quoted string, got {other:?}"
1542
                    )));
1543
                }
1544
            },
NEW
1545
            Expr::Identifier(ident) => ident.value.clone(),
×
NEW
1546
            other => {
×
NEW
1547
                return Err(SQLRiteError::General(format!(
×
1548
                    "CREATE INDEX '{index_name}': WITH option '{key}' value must be a \
1549
                     quoted string, got {other:?}"
1550
                )));
1551
            }
1552
        };
1553

1554
        if key.eq_ignore_ascii_case("metric") {
2✔
1555
            let parsed = DistanceMetric::from_sql_name(&value).ok_or_else(|| {
5✔
1556
                SQLRiteError::General(format!(
1✔
1557
                    "CREATE INDEX '{index_name}': unknown HNSW metric '{value}' \
1558
                     (try 'l2', 'cosine', or 'dot')"
1559
                ))
1560
            })?;
1561
            if metric.is_some() {
1✔
NEW
1562
                return Err(SQLRiteError::General(format!(
×
1563
                    "CREATE INDEX '{index_name}': metric specified more than once in WITH (...)"
1564
                )));
1565
            }
1566
            metric = Some(parsed);
1✔
1567
        } else {
NEW
1568
            return Err(SQLRiteError::General(format!(
×
1569
                "CREATE INDEX '{index_name}': unknown WITH option '{key}' \
1570
                 (only 'metric' is recognised on HNSW indexes)"
1571
            )));
1572
        }
1573
    }
1574

1575
    Ok(metric)
1✔
1576
}
1577

1578
/// Builds a Phase 8b FTS inverted index and attaches it to the table.
1579
/// Mirrors [`create_hnsw_index`] in shape: validate column type,
1580
/// tokenize each existing row's text into the in-memory posting list,
1581
/// push an `FtsIndexEntry`.
1582
fn create_fts_index(
1✔
1583
    db: &mut Database,
1584
    table_name: &str,
1585
    index_name: &str,
1586
    column_name: &str,
1587
    datatype: &DataType,
1588
    unique: bool,
1589
    existing: &[(i64, Value)],
1590
) -> Result<String> {
1591
    // FTS is a TEXT-only feature for the MVP. JSON columns share the
1592
    // Row::Text storage but their content is structured — full-text
1593
    // indexing JSON keys + values would need a different design (and
1594
    // is out of scope per the Phase 8 plan's "Out of scope" section).
1595
    match datatype {
1✔
1596
        DataType::Text => {}
1597
        other => {
1✔
1598
            return Err(SQLRiteError::General(format!(
1✔
1599
                "USING fts requires a TEXT column; '{column_name}' is {other}"
1600
            )));
1601
        }
1602
    }
1603

1604
    if unique {
1✔
1605
        return Err(SQLRiteError::General(
1✔
1606
            "UNIQUE has no meaning for FTS indexes".to_string(),
1✔
1607
        ));
1608
    }
1609

1610
    let mut idx = PostingList::new();
1✔
1611
    for (rowid, v) in existing {
2✔
1612
        if let Value::Text(text) = v {
2✔
1613
            idx.insert(*rowid, text);
1✔
1614
        }
1615
        // Non-text values (Null, type coercion bugs) get skipped — same
1616
        // posture as create_hnsw_index for non-vector values.
1617
    }
1618

1619
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1620
    table_mut.fts_indexes.push(FtsIndexEntry {
2✔
1621
        name: index_name.to_string(),
1✔
1622
        column_name: column_name.to_string(),
1✔
1623
        index: idx,
1✔
1624
        needs_rebuild: false,
1625
    });
1626
    Ok(index_name.to_string())
1✔
1627
}
1628

1629
/// Stable, deterministic hash of a string into a u64 RNG seed. FNV-1a;
1630
/// avoids pulling in `std::hash::DefaultHasher` (which is randomized
1631
/// per process).
1632
fn hash_str_to_seed(s: &str) -> u64 {
1✔
1633
    let mut h: u64 = 0xCBF29CE484222325;
1✔
1634
    for b in s.as_bytes() {
2✔
1635
        h ^= *b as u64;
1✔
1636
        h = h.wrapping_mul(0x100000001B3);
1✔
1637
    }
1638
    h
1✔
1639
}
1640

1641
/// Cheap clone helper — `DataType` intentionally doesn't derive `Clone`
1642
/// because the enum has no ergonomic reason to be cloneable elsewhere.
1643
fn clone_datatype(dt: &DataType) -> DataType {
1✔
1644
    match dt {
1✔
1645
        DataType::Integer => DataType::Integer,
1✔
1646
        DataType::Text => DataType::Text,
1✔
1647
        DataType::Real => DataType::Real,
×
1648
        DataType::Bool => DataType::Bool,
×
1649
        DataType::Vector(dim) => DataType::Vector(*dim),
1✔
1650
        DataType::Json => DataType::Json,
×
1651
        DataType::None => DataType::None,
×
1652
        DataType::Invalid => DataType::Invalid,
×
1653
    }
1654
}
1655

1656
fn extract_single_table_name(tables: &[TableWithJoins]) -> Result<String> {
1✔
1657
    if tables.len() != 1 {
1✔
1658
        return Err(SQLRiteError::NotImplemented(
×
1659
            "multi-table DELETE is not supported yet".to_string(),
×
1660
        ));
1661
    }
1662
    extract_table_name(&tables[0])
2✔
1663
}
1664

1665
fn extract_table_name(twj: &TableWithJoins) -> Result<String> {
1✔
1666
    if !twj.joins.is_empty() {
1✔
1667
        return Err(SQLRiteError::NotImplemented(
×
1668
            "JOIN is not supported yet".to_string(),
×
1669
        ));
1670
    }
1671
    match &twj.relation {
1✔
1672
        TableFactor::Table { name, .. } => Ok(name.to_string()),
1✔
1673
        _ => Err(SQLRiteError::NotImplemented(
×
1674
            "only plain table references are supported".to_string(),
×
1675
        )),
1676
    }
1677
}
1678

1679
/// Tells the executor how to produce its candidate rowid list.
1680
enum RowidSource {
1681
    /// The WHERE was simple enough to probe a secondary index directly.
1682
    /// The `Vec` already contains exactly the rows the index matched;
1683
    /// no further WHERE evaluation is needed (the probe is precise).
1684
    IndexProbe(Vec<i64>),
1685
    /// No applicable index; caller falls back to walking `table.rowids()`
1686
    /// and evaluating the WHERE on each row.
1687
    FullScan,
1688
}
1689

1690
/// Try to satisfy `WHERE` with an index probe. Currently supports the
1691
/// simplest shape: a single `col = literal` (or `literal = col`) where
1692
/// `col` is on a secondary index. AND/OR/range predicates fall back to
1693
/// full scan — those can be layered on later without changing the caller.
1694
fn select_rowids(table: &Table, selection: Option<&Expr>) -> Result<RowidSource> {
1✔
1695
    let Some(expr) = selection else {
1✔
1696
        return Ok(RowidSource::FullScan);
1✔
1697
    };
1698
    let Some((col, literal)) = try_extract_equality(expr) else {
2✔
1699
        return Ok(RowidSource::FullScan);
1✔
1700
    };
1701
    let Some(idx) = table.index_for_column(&col) else {
2✔
1702
        return Ok(RowidSource::FullScan);
1✔
1703
    };
1704

1705
    // Convert the literal into a runtime Value. If the literal type doesn't
1706
    // match the column's index we still need correct semantics — evaluate
1707
    // the WHERE against every row. Fall back to full scan.
1708
    let literal_value = match convert_literal(&literal) {
2✔
1709
        Ok(v) => v,
1✔
1710
        Err(_) => return Ok(RowidSource::FullScan),
×
1711
    };
1712

1713
    // Index lookup returns the full list of rowids matching this equality
1714
    // predicate. For unique indexes that's at most one; for non-unique it
1715
    // can be many.
1716
    let mut rowids = idx.lookup(&literal_value);
1✔
1717
    rowids.sort_unstable();
2✔
1718
    Ok(RowidSource::IndexProbe(rowids))
1✔
1719
}
1720

1721
/// Recognizes `expr` as a simple equality on a column reference against a
1722
/// literal. Returns `(column_name, literal_value)` if the shape matches;
1723
/// `None` otherwise. Accepts both `col = literal` and `literal = col`.
1724
fn try_extract_equality(expr: &Expr) -> Option<(String, sqlparser::ast::Value)> {
1✔
1725
    // Peel off Nested parens so `WHERE (x = 1)` is recognized too.
1726
    let peeled = match expr {
1✔
1727
        Expr::Nested(inner) => inner.as_ref(),
1✔
1728
        other => other,
1✔
1729
    };
1730
    let Expr::BinaryOp { left, op, right } = peeled else {
1✔
1731
        return None;
1✔
1732
    };
1733
    if !matches!(op, BinaryOperator::Eq) {
1✔
1734
        return None;
1✔
1735
    }
1736
    let col_from = |e: &Expr| -> Option<String> {
1✔
1737
        match e {
1✔
1738
            Expr::Identifier(ident) => Some(ident.value.clone()),
1✔
1739
            Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
×
1740
            _ => None,
1✔
1741
        }
1742
    };
1743
    let literal_from = |e: &Expr| -> Option<sqlparser::ast::Value> {
1✔
1744
        if let Expr::Value(v) = e {
2✔
1745
            Some(v.value.clone())
1✔
1746
        } else {
1747
            None
1✔
1748
        }
1749
    };
1750
    if let (Some(c), Some(l)) = (col_from(left), literal_from(right)) {
3✔
1751
        return Some((c, l));
1✔
1752
    }
1753
    if let (Some(l), Some(c)) = (literal_from(left), col_from(right)) {
3✔
1754
        return Some((c, l));
1✔
1755
    }
1756
    None
1✔
1757
}
1758

1759
/// Recognizes the HNSW-probable query pattern and probes the graph
1760
/// if a matching index exists.
1761
///
1762
/// Looks for ORDER BY `vec_distance_<l2|cosine|dot>(<col>, <bracket-
1763
/// array literal>)` where the table has an HNSW index attached to
1764
/// `<col>` *built for that same distance metric*. On a match, returns
1765
/// the top-k rowids straight from the graph (O(log N)). On any miss —
1766
/// different function name, no matching index, query dimension wrong,
1767
/// metric mismatch, etc. — returns `None` and the caller falls through
1768
/// to the bounded-heap brute-force path (7c) or the full sort (7b),
1769
/// preserving correct results regardless of whether the HNSW pathway
1770
/// kicked in.
1771
///
1772
/// Caveats:
1773
/// - The index's metric and the query's `vec_distance_*` function must
1774
///   agree. An L2-built graph silently doesn't help cosine queries
1775
///   (different neighbour pruning policy → potentially different
1776
///   topology), so we don't pretend to.  Pick the metric at CREATE
1777
///   INDEX time via `WITH (metric = '<l2|cosine|dot>')` (SQLR-28).
1778
/// - Only ASCENDING order makes sense for "k nearest" — DESC ORDER BY
1779
///   `vec_distance_*(...) LIMIT k` would mean "k farthest", which isn't
1780
///   what the index is built for. We don't bother to detect
1781
///   `ascending == false` here; the optimizer just skips and the
1782
///   fallback path handles it correctly (slower).
1783
fn try_hnsw_probe(table: &Table, order_expr: &Expr, k: usize) -> Option<Vec<i64>> {
1✔
1784
    if k == 0 {
1✔
1785
        return None;
×
1786
    }
1787

1788
    // Pattern-match: order expr must be a function call
1789
    // vec_distance_<l2|cosine|dot>(a, b).
1790
    let func = match order_expr {
1✔
1791
        Expr::Function(f) => f,
1✔
1792
        _ => return None,
1✔
1793
    };
1794
    let fname = match func.name.0.as_slice() {
2✔
1795
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
1796
        _ => return None,
×
1797
    };
1798
    let query_metric = match fname.as_str() {
2✔
1799
        "vec_distance_l2" => DistanceMetric::L2,
2✔
1800
        "vec_distance_cosine" => DistanceMetric::Cosine,
3✔
1801
        "vec_distance_dot" => DistanceMetric::Dot,
3✔
1802
        _ => return None,
1✔
1803
    };
1804

1805
    // Extract the two args as raw Exprs.
1806
    let arg_list = match &func.args {
1✔
1807
        FunctionArguments::List(l) => &l.args,
1✔
1808
        _ => return None,
×
1809
    };
1810
    if arg_list.len() != 2 {
2✔
1811
        return None;
×
1812
    }
1813
    let exprs: Vec<&Expr> = arg_list
1✔
1814
        .iter()
1815
        .filter_map(|a| match a {
3✔
1816
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Some(e),
1✔
1817
            _ => None,
×
1818
        })
1819
        .collect();
1820
    if exprs.len() != 2 {
2✔
1821
        return None;
×
1822
    }
1823

1824
    // One arg must be a column reference (the indexed col); the other
1825
    // must be a bracket-array literal (the query vector). Try both
1826
    // orderings — pgvector's idiom puts the column on the left, but
1827
    // SQL is commutative for distance.
1828
    let (col_name, query_vec) = match identify_indexed_arg_and_literal(exprs[0], exprs[1]) {
3✔
1829
        Some(v) => v,
1✔
1830
        None => match identify_indexed_arg_and_literal(exprs[1], exprs[0]) {
×
1831
            Some(v) => v,
×
1832
            None => return None,
×
1833
        },
1834
    };
1835

1836
    // Find the HNSW index on this column AND with a matching metric.
1837
    // Multiple indexes on the same column are allowed in principle
1838
    // (cosine-built + L2-built), and a query picks whichever metric
1839
    // its `vec_distance_*` function names.
1840
    let entry = table
4✔
1841
        .hnsw_indexes
1842
        .iter()
1✔
1843
        .find(|e| e.column_name == col_name && e.metric == query_metric)?;
3✔
1844

1845
    // Dimension sanity check — the query vector must match the
1846
    // indexed column's declared dimension. If it doesn't, the brute-
1847
    // force fallback would also error at the vec_distance_l2 dim-check;
1848
    // returning None here lets that path produce the user-visible
1849
    // error message.
1850
    let declared_dim = match table.columns.iter().find(|c| c.column_name == col_name) {
3✔
1851
        Some(c) => match &c.datatype {
1✔
1852
            DataType::Vector(d) => *d,
1✔
1853
            _ => return None,
×
1854
        },
1855
        None => return None,
×
1856
    };
1857
    if query_vec.len() != declared_dim {
2✔
1858
        return None;
×
1859
    }
1860

1861
    // Probe the graph. Vectors are looked up from the table's row
1862
    // storage — a closure rather than a `&Table` so the algorithm
1863
    // module stays decoupled from the SQL types.
1864
    let column_for_closure = col_name.clone();
1✔
1865
    let table_ref = table;
1866
    let result = entry.index.search(&query_vec, k, |id| {
3✔
1867
        match table_ref.get_value(&column_for_closure, id) {
1✔
1868
            Some(Value::Vector(v)) => v,
1✔
1869
            _ => Vec::new(),
×
1870
        }
1871
    });
1872
    Some(result)
1✔
1873
}
1874

1875
/// Phase 8b — FTS optimizer hook.
1876
///
1877
/// Recognizes `ORDER BY bm25_score(<col>, '<query>') DESC LIMIT <k>`
1878
/// and serves it from the FTS index instead of full-scanning. Returns
1879
/// `Some(rowids)` already sorted by descending BM25 (with rowid
1880
/// ascending as tie-break), or `None` to fall through to scalar eval.
1881
///
1882
/// **Known limitation (mirrors `try_hnsw_probe`).** This shortcut
1883
/// ignores any `WHERE` clause. The canonical FTS query has a
1884
/// `WHERE fts_match(<col>, '<q>')` predicate, which is implicitly
1885
/// satisfied by the probe results — so dropping it is harmless.
1886
/// Anything *else* in the WHERE (`AND status = 'published'`) gets
1887
/// silently skipped on the optimizer path. Per Phase 8 plan Q6 we
1888
/// match HNSW's posture here; a correctness-preserving multi-index
1889
/// composer is deferred.
1890
fn try_fts_probe(table: &Table, order_expr: &Expr, ascending: bool, k: usize) -> Option<Vec<i64>> {
1✔
1891
    if k == 0 || ascending {
1✔
1892
        // BM25 is "higher = better"; ASC ranking is almost certainly a
1893
        // user mistake. Fall through so the caller gets either an
1894
        // explicit error from scalar eval or the slow correct path.
1895
        return None;
1✔
1896
    }
1897

1898
    let func = match order_expr {
1✔
1899
        Expr::Function(f) => f,
1✔
1900
        _ => return None,
×
1901
    };
1902
    let fname = match func.name.0.as_slice() {
2✔
1903
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
1904
        _ => return None,
×
1905
    };
1906
    if fname != "bm25_score" {
2✔
1907
        return None;
×
1908
    }
1909

1910
    let arg_list = match &func.args {
1✔
1911
        FunctionArguments::List(l) => &l.args,
1✔
1912
        _ => return None,
×
1913
    };
1914
    if arg_list.len() != 2 {
2✔
1915
        return None;
×
1916
    }
1917
    let exprs: Vec<&Expr> = arg_list
1✔
1918
        .iter()
1919
        .filter_map(|a| match a {
3✔
1920
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Some(e),
1✔
1921
            _ => None,
×
1922
        })
1923
        .collect();
1924
    if exprs.len() != 2 {
2✔
1925
        return None;
×
1926
    }
1927

1928
    // Arg 0 must be a bare column identifier.
1929
    let col_name = match exprs[0] {
2✔
1930
        Expr::Identifier(ident) if ident.quote_style.is_none() => ident.value.clone(),
2✔
1931
        _ => return None,
×
1932
    };
1933

1934
    // Arg 1 must be a single-quoted string literal. Anything else
1935
    // (column reference, function call) requires per-row evaluation —
1936
    // we'd lose the whole point of the probe.
1937
    let query = match exprs[1] {
2✔
1938
        Expr::Value(v) => match &v.value {
1✔
1939
            AstValue::SingleQuotedString(s) => s.clone(),
1✔
1940
            _ => return None,
×
1941
        },
1942
        _ => return None,
×
1943
    };
1944

1945
    let entry = table
3✔
1946
        .fts_indexes
1947
        .iter()
1✔
1948
        .find(|e| e.column_name == col_name)?;
3✔
1949

1950
    let scored = entry.index.query(&query, &Bm25Params::default());
1✔
1951
    let mut out: Vec<i64> = scored.into_iter().map(|(id, _)| id).collect();
3✔
1952
    if out.len() > k {
2✔
1953
        out.truncate(k);
1✔
1954
    }
1955
    Some(out)
1✔
1956
}
1957

1958
/// Helper for `try_hnsw_probe`: given two function args, identify which
1959
/// one is a bare column identifier (the indexed column) and which is a
1960
/// bracket-array literal (the query vector). Returns
1961
/// `Some((column_name, query_vec))` on a match, `None` otherwise.
1962
fn identify_indexed_arg_and_literal(a: &Expr, b: &Expr) -> Option<(String, Vec<f32>)> {
1✔
1963
    let col_name = match a {
1✔
1964
        Expr::Identifier(ident) if ident.quote_style.is_none() => ident.value.clone(),
2✔
1965
        _ => return None,
×
1966
    };
1967
    let lit_str = match b {
1✔
1968
        Expr::Identifier(ident) if ident.quote_style == Some('[') => {
2✔
1969
            format!("[{}]", ident.value)
1✔
1970
        }
1971
        _ => return None,
×
1972
    };
1973
    let v = parse_vector_literal(&lit_str).ok()?;
2✔
1974
    Some((col_name, v))
1✔
1975
}
1976

1977
/// One entry in the bounded-heap top-k path. Holds a pre-evaluated
1978
/// sort key + the rowid it came from. The `asc` flag inverts `Ord`
1979
/// so a single `BinaryHeap<HeapEntry>` works for both ASC and DESC
1980
/// without wrapping in `std::cmp::Reverse` at the call site:
1981
///
1982
///   - ASC LIMIT k = "k smallest": natural Ord. Max-heap top is the
1983
///     largest currently kept; new items smaller than top displace.
1984
///   - DESC LIMIT k = "k largest": Ord reversed. Max-heap top is now
1985
///     the smallest currently kept (under reversed Ord, smallest
1986
///     looks largest); new items larger than top displace.
1987
///
1988
/// In both cases the displacement test reduces to "new entry < heap top".
1989
struct HeapEntry {
1990
    key: Value,
1991
    rowid: i64,
1992
    asc: bool,
1993
}
1994

1995
impl PartialEq for HeapEntry {
1996
    fn eq(&self, other: &Self) -> bool {
×
1997
        self.cmp(other) == Ordering::Equal
×
1998
    }
1999
}
2000

2001
impl Eq for HeapEntry {}
2002

2003
impl PartialOrd for HeapEntry {
2004
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1✔
2005
        Some(self.cmp(other))
1✔
2006
    }
2007
}
2008

2009
impl Ord for HeapEntry {
2010
    fn cmp(&self, other: &Self) -> Ordering {
1✔
2011
        let raw = compare_values(Some(&self.key), Some(&other.key));
1✔
2012
        if self.asc { raw } else { raw.reverse() }
1✔
2013
    }
2014
}
2015

2016
/// Bounded-heap top-k selection. Returns at most `k` rowids in the
2017
/// caller's desired order (ascending key for `order.ascending`,
2018
/// descending otherwise).
2019
///
2020
/// O(N log k) where N = `matching.len()`. Caller must check
2021
/// `k < matching.len()` for this to be a win — for k ≥ N the
2022
/// `sort_rowids` full-sort path is the same asymptotic cost without
2023
/// the heap overhead.
2024
fn select_topk(
1✔
2025
    matching: &[i64],
2026
    table: &Table,
2027
    order: &OrderByClause,
2028
    k: usize,
2029
) -> Result<Vec<i64>> {
2030
    use std::collections::BinaryHeap;
2031

2032
    if k == 0 || matching.is_empty() {
1✔
2033
        return Ok(Vec::new());
1✔
2034
    }
2035

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

2038
    for &rowid in matching {
3✔
2039
        let key = eval_expr(&order.expr, table, rowid)?;
2✔
2040
        let entry = HeapEntry {
2041
            key,
2042
            rowid,
2043
            asc: order.ascending,
1✔
2044
        };
2045

2046
        if heap.len() < k {
2✔
2047
            heap.push(entry);
2✔
2048
        } else {
2049
            // peek() returns the largest under our direction-aware Ord
2050
            // — the worst entry currently kept. Displace it iff the
2051
            // new entry is "better" (i.e. compares Less).
2052
            if entry < *heap.peek().unwrap() {
2✔
2053
                heap.pop();
1✔
2054
                heap.push(entry);
1✔
2055
            }
2056
        }
2057
    }
2058

2059
    // `into_sorted_vec` returns ascending under our direction-aware Ord:
2060
    //   ASC: ascending by raw key (what we want)
2061
    //   DESC: ascending under reversed Ord = descending by raw key (what
2062
    //         we want for an ORDER BY DESC LIMIT k result)
2063
    Ok(heap
2✔
2064
        .into_sorted_vec()
1✔
2065
        .into_iter()
1✔
2066
        .map(|e| e.rowid)
3✔
2067
        .collect())
1✔
2068
}
2069

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

2083
    // Surface the FIRST evaluation error if any. We could be lazy
2084
    // and let sort_by encounter it, but `Ord::cmp` can't return a
2085
    // Result and we'd have to swallow errors silently.
2086
    for (_, k) in &keys {
2✔
2087
        if let Err(e) = k {
1✔
2088
            return Err(SQLRiteError::General(format!(
×
2089
                "ORDER BY expression failed: {e}"
2090
            )));
2091
        }
2092
    }
2093

2094
    keys.sort_by(|(_, ka), (_, kb)| {
3✔
2095
        // Both unwrap()s are safe — we just verified above that
2096
        // every key Result is Ok.
2097
        let va = ka.as_ref().unwrap();
1✔
2098
        let vb = kb.as_ref().unwrap();
1✔
2099
        let ord = compare_values(Some(va), Some(vb));
1✔
2100
        if order.ascending { ord } else { ord.reverse() }
1✔
2101
    });
2102

2103
    // Write the sorted rowids back into the caller's slice.
2104
    for (i, (rowid, _)) in keys.into_iter().enumerate() {
2✔
2105
        rowids[i] = rowid;
2✔
2106
    }
2107
    Ok(())
1✔
2108
}
2109

2110
fn compare_values(a: Option<&Value>, b: Option<&Value>) -> Ordering {
1✔
2111
    match (a, b) {
2✔
2112
        (None, None) => Ordering::Equal,
×
2113
        (None, _) => Ordering::Less,
×
2114
        (_, None) => Ordering::Greater,
×
2115
        (Some(a), Some(b)) => match (a, b) {
3✔
2116
            (Value::Null, Value::Null) => Ordering::Equal,
×
2117
            (Value::Null, _) => Ordering::Less,
1✔
2118
            (_, Value::Null) => Ordering::Greater,
×
2119
            (Value::Integer(x), Value::Integer(y)) => x.cmp(y),
1✔
2120
            (Value::Real(x), Value::Real(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
1✔
2121
            (Value::Integer(x), Value::Real(y)) => {
×
2122
                (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal)
×
2123
            }
2124
            (Value::Real(x), Value::Integer(y)) => {
×
2125
                x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal)
×
2126
            }
2127
            (Value::Text(x), Value::Text(y)) => x.cmp(y),
1✔
2128
            (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
×
2129
            // Cross-type fallback: stringify and compare; keeps ORDER BY total.
2130
            (x, y) => x.to_display_string().cmp(&y.to_display_string()),
×
2131
        },
2132
    }
2133
}
2134

2135
/// Returns `true` if the row at `rowid` matches the predicate expression.
2136
pub fn eval_predicate(expr: &Expr, table: &Table, rowid: i64) -> Result<bool> {
1✔
2137
    eval_predicate_scope(expr, &SingleTableScope::new(table, rowid))
1✔
2138
}
2139

2140
/// Scope-aware predicate evaluation. The single-table fast path wraps
2141
/// this with a [`SingleTableScope`]; the join executor wraps it with
2142
/// a [`JoinedScope`].
2143
pub(crate) fn eval_predicate_scope(expr: &Expr, scope: &dyn RowScope) -> Result<bool> {
1✔
2144
    let v = eval_expr_scope(expr, scope)?;
2✔
2145
    match v {
1✔
2146
        Value::Bool(b) => Ok(b),
1✔
2147
        Value::Null => Ok(false), // SQL NULL in a WHERE is treated as false
2148
        Value::Integer(i) => Ok(i != 0),
1✔
2149
        other => Err(SQLRiteError::Internal(format!(
×
2150
            "WHERE clause must evaluate to boolean, got {}",
2151
            other.to_display_string()
×
2152
        ))),
2153
    }
2154
}
2155

2156
/// Single-table convenience wrapper around [`eval_expr_scope`].
2157
fn eval_expr(expr: &Expr, table: &Table, rowid: i64) -> Result<Value> {
1✔
2158
    eval_expr_scope(expr, &SingleTableScope::new(table, rowid))
1✔
2159
}
2160

2161
fn eval_expr_scope(expr: &Expr, scope: &dyn RowScope) -> Result<Value> {
1✔
2162
    match expr {
1✔
2163
        Expr::Nested(inner) => eval_expr_scope(inner, scope),
2✔
2164

2165
        Expr::Identifier(ident) => {
1✔
2166
            // Phase 7b — sqlparser parses bracket-array literals like
2167
            // `[0.1, 0.2, 0.3]` as bracket-quoted identifiers (it inherits
2168
            // MSSQL `[name]` syntax). When we see `quote_style == Some('[')`
2169
            // in expression-evaluation position (SELECT projection, WHERE,
2170
            // ORDER BY, function args), parse the bracketed content as a
2171
            // vector literal so the rest of the executor can compare /
2172
            // distance-compute against it. Same trick the INSERT parser
2173
            // uses; the executor needed its own copy because expression
2174
            // eval runs on a different code path.
2175
            if ident.quote_style == Some('[') {
1✔
2176
                let raw = format!("[{}]", ident.value);
1✔
2177
                let v = parse_vector_literal(&raw)?;
2✔
2178
                return Ok(Value::Vector(v));
1✔
2179
            }
2180
            scope.lookup(None, &ident.value)
1✔
2181
        }
2182

2183
        Expr::CompoundIdentifier(parts) => {
1✔
2184
            // `qualifier.col` — single-table scope ignores the qualifier
2185
            // (legacy behavior). Joined scope dispatches to the table
2186
            // matching `qualifier`. The compound form must have at
2187
            // least two parts; deeper paths (`db.schema.t.col`) are
2188
            // not supported.
2189
            match parts.as_slice() {
1✔
2190
                [only] => scope.lookup(None, &only.value),
1✔
2191
                [q, c] => scope.lookup(Some(&q.value), &c.value),
2✔
2192
                _ => Err(SQLRiteError::NotImplemented(format!(
×
2193
                    "compound identifier with {} parts is not supported",
2194
                    parts.len()
×
2195
                ))),
2196
            }
2197
        }
2198

2199
        Expr::Value(v) => convert_literal(&v.value),
1✔
2200

2201
        Expr::UnaryOp { op, expr } => {
×
2202
            let inner = eval_expr_scope(expr, scope)?;
×
2203
            match op {
×
2204
                UnaryOperator::Not => match inner {
×
2205
                    Value::Bool(b) => Ok(Value::Bool(!b)),
×
2206
                    Value::Null => Ok(Value::Null),
×
2207
                    other => Err(SQLRiteError::Internal(format!(
×
2208
                        "NOT applied to non-boolean value: {}",
2209
                        other.to_display_string()
×
2210
                    ))),
2211
                },
2212
                UnaryOperator::Minus => match inner {
×
2213
                    Value::Integer(i) => Ok(Value::Integer(-i)),
×
2214
                    Value::Real(f) => Ok(Value::Real(-f)),
×
2215
                    Value::Null => Ok(Value::Null),
×
2216
                    other => Err(SQLRiteError::Internal(format!(
×
2217
                        "unary minus on non-numeric value: {}",
2218
                        other.to_display_string()
×
2219
                    ))),
2220
                },
2221
                UnaryOperator::Plus => Ok(inner),
×
2222
                other => Err(SQLRiteError::NotImplemented(format!(
×
2223
                    "unary operator {other:?} is not supported"
2224
                ))),
2225
            }
2226
        }
2227

2228
        Expr::BinaryOp { left, op, right } => match op {
1✔
2229
            BinaryOperator::And => {
2230
                let l = eval_expr_scope(left, scope)?;
2✔
2231
                let r = eval_expr_scope(right, scope)?;
2✔
2232
                Ok(Value::Bool(as_bool(&l)? && as_bool(&r)?))
3✔
2233
            }
2234
            BinaryOperator::Or => {
2235
                let l = eval_expr_scope(left, scope)?;
×
2236
                let r = eval_expr_scope(right, scope)?;
×
2237
                Ok(Value::Bool(as_bool(&l)? || as_bool(&r)?))
×
2238
            }
2239
            cmp @ (BinaryOperator::Eq
2240
            | BinaryOperator::NotEq
2241
            | BinaryOperator::Lt
2242
            | BinaryOperator::LtEq
2243
            | BinaryOperator::Gt
2244
            | BinaryOperator::GtEq) => {
2245
                let l = eval_expr_scope(left, scope)?;
2✔
2246
                let r = eval_expr_scope(right, scope)?;
3✔
2247
                // Any comparison involving NULL is unknown → false in a WHERE.
2248
                if matches!(l, Value::Null) || matches!(r, Value::Null) {
1✔
2249
                    return Ok(Value::Bool(false));
1✔
2250
                }
2251
                let ord = compare_values(Some(&l), Some(&r));
2✔
2252
                let result = match cmp {
1✔
2253
                    BinaryOperator::Eq => ord == Ordering::Equal,
2✔
2254
                    BinaryOperator::NotEq => ord != Ordering::Equal,
×
2255
                    BinaryOperator::Lt => ord == Ordering::Less,
2✔
2256
                    BinaryOperator::LtEq => ord != Ordering::Greater,
×
2257
                    BinaryOperator::Gt => ord == Ordering::Greater,
2✔
2258
                    BinaryOperator::GtEq => ord != Ordering::Less,
2✔
2259
                    _ => unreachable!(),
2260
                };
2261
                Ok(Value::Bool(result))
1✔
2262
            }
2263
            arith @ (BinaryOperator::Plus
2264
            | BinaryOperator::Minus
2265
            | BinaryOperator::Multiply
2266
            | BinaryOperator::Divide
2267
            | BinaryOperator::Modulo) => {
2268
                let l = eval_expr_scope(left, scope)?;
2✔
2269
                let r = eval_expr_scope(right, scope)?;
2✔
2270
                eval_arith(arith, &l, &r)
1✔
2271
            }
2272
            BinaryOperator::StringConcat => {
2273
                let l = eval_expr_scope(left, scope)?;
×
2274
                let r = eval_expr_scope(right, scope)?;
×
2275
                if matches!(l, Value::Null) || matches!(r, Value::Null) {
×
2276
                    return Ok(Value::Null);
×
2277
                }
2278
                Ok(Value::Text(format!(
×
2279
                    "{}{}",
2280
                    l.to_display_string(),
×
2281
                    r.to_display_string()
×
2282
                )))
2283
            }
2284
            other => Err(SQLRiteError::NotImplemented(format!(
×
2285
                "binary operator {other:?} is not supported yet"
2286
            ))),
2287
        },
2288

2289
        // SQLR-7 — `col IS NULL` / `col IS NOT NULL`. Identifier
2290
        // evaluation already maps a missing rowid in the column's
2291
        // BTreeMap to `Value::Null`, so this works uniformly for
2292
        // explicit NULL inserts, omitted columns, and (post-Phase 7e)
2293
        // legacy "Null"-sentinel TEXT cells. NULLs are never inserted
2294
        // into secondary / HNSW / FTS indexes, so an IS NULL probe
2295
        // correctly falls through to a full scan via `select_rowids`.
2296
        Expr::IsNull(inner) => {
1✔
2297
            let v = eval_expr_scope(inner, scope)?;
2✔
2298
            Ok(Value::Bool(matches!(v, Value::Null)))
1✔
2299
        }
2300
        Expr::IsNotNull(inner) => {
1✔
2301
            let v = eval_expr_scope(inner, scope)?;
2✔
2302
            Ok(Value::Bool(!matches!(v, Value::Null)))
1✔
2303
        }
2304

2305
        // SQLR-3 — LIKE / NOT LIKE / ILIKE. Pattern matching uses our
2306
        // own iterative two-pointer matcher (see `agg::like_match`).
2307
        // SQLite's default is case-insensitive ASCII; we follow that.
2308
        // ILIKE is also case-insensitive (a no-op switch here, but we
2309
        // keep the arm explicit so SQLite users typing ILIKE get the
2310
        // expected semantics rather than a NotImplemented).
2311
        Expr::Like {
2312
            negated,
1✔
2313
            any,
1✔
2314
            expr: lhs,
1✔
2315
            pattern,
1✔
2316
            escape_char,
1✔
2317
        } => eval_like(
2318
            scope,
2319
            *negated,
1✔
2320
            *any,
1✔
2321
            lhs,
2✔
2322
            pattern,
2✔
2323
            escape_char.as_ref(),
1✔
2324
            true,
2325
        ),
2326
        Expr::ILike {
2327
            negated,
×
2328
            any,
×
2329
            expr: lhs,
×
2330
            pattern,
×
2331
            escape_char,
×
2332
        } => eval_like(
2333
            scope,
2334
            *negated,
×
2335
            *any,
×
2336
            lhs,
×
2337
            pattern,
×
2338
            escape_char.as_ref(),
×
2339
            true,
2340
        ),
2341

2342
        // SQLR-3 — IN (list) / NOT IN (list). Subquery form is rejected.
2343
        // Three-valued logic: if the LHS is NULL, return NULL; if any
2344
        // list entry is NULL and no match was found, return NULL too.
2345
        // WHERE coerces NULL → false at line ~1494, so the practical
2346
        // effect is "row excluded" — matches SQLite.
2347
        Expr::InList {
2348
            expr: lhs,
1✔
2349
            list,
1✔
2350
            negated,
1✔
2351
        } => eval_in_list(scope, lhs, list, *negated),
2✔
2352
        Expr::InSubquery { .. } => Err(SQLRiteError::NotImplemented(
×
2353
            "IN (subquery) is not supported (only literal lists are)".to_string(),
×
2354
        )),
2355

2356
        // Phase 7b — function-call dispatch. Currently only the three
2357
        // vector-distance functions; this match arm becomes the single
2358
        // place to register more SQL functions later (e.g. abs(),
2359
        // length(), …) without re-touching the rest of the executor.
2360
        //
2361
        // Operator forms (`<->` `<=>` `<#>`) are NOT plumbed here: two
2362
        // of three don't parse natively in sqlparser (we'd need a
2363
        // string-preprocessing pass or a sqlparser fork). Deferred to
2364
        // a follow-up sub-phase; see docs/phase-7-plan.md's "Scope
2365
        // corrections" note.
2366
        Expr::Function(func) => eval_function(func, scope),
1✔
2367

2368
        other => Err(SQLRiteError::NotImplemented(format!(
×
2369
            "unsupported expression in WHERE/projection: {other:?}"
2370
        ))),
2371
    }
2372
}
2373

2374
/// Dispatches an `Expr::Function` to its built-in implementation.
2375
/// Currently only the three vec_distance_* functions; other functions
2376
/// surface as `NotImplemented` errors with the function name in the
2377
/// message so users see what they tried.
2378
fn eval_function(func: &sqlparser::ast::Function, scope: &dyn RowScope) -> Result<Value> {
1✔
2379
    // Function name lives in `name.0[0]` for unqualified calls. Anything
2380
    // qualified (e.g. `pkg.fn(...)`) falls through to NotImplemented.
2381
    let name = match func.name.0.as_slice() {
2✔
2382
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
2383
        _ => {
2384
            return Err(SQLRiteError::NotImplemented(format!(
×
2385
                "qualified function names not supported: {:?}",
2386
                func.name
2387
            )));
2388
        }
2389
    };
2390

2391
    match name.as_str() {
2✔
2392
        "vec_distance_l2" | "vec_distance_cosine" | "vec_distance_dot" => {
2✔
2393
            let (a, b) = extract_two_vector_args(&name, &func.args, scope)?;
3✔
2394
            let dist = match name.as_str() {
2✔
2395
                "vec_distance_l2" => vec_distance_l2(&a, &b),
3✔
2396
                "vec_distance_cosine" => vec_distance_cosine(&a, &b)?,
4✔
2397
                "vec_distance_dot" => vec_distance_dot(&a, &b),
3✔
2398
                _ => unreachable!(),
2399
            };
2400
            // Widen f32 → f64 for the runtime Value. Vectors are stored
2401
            // as f32 (consistent with industry convention for embeddings),
2402
            // but the executor's numeric type is f64 so distances slot
2403
            // into Value::Real cleanly and can be compared / ordered with
2404
            // other reals via the existing arithmetic + comparison paths.
2405
            Ok(Value::Real(dist as f64))
1✔
2406
        }
2407
        // Phase 7e — JSON functions. All four parse the JSON text on
2408
        // demand (we don't cache parsed values), then resolve a path
2409
        // (default `$` = root). The path resolver handles `.key` for
2410
        // object access and `[N]` for array index. SQLite-style.
2411
        "json_extract" => json_fn_extract(&name, &func.args, scope),
3✔
2412
        "json_type" => json_fn_type(&name, &func.args, scope),
4✔
2413
        "json_array_length" => json_fn_array_length(&name, &func.args, scope),
4✔
2414
        "json_object_keys" => json_fn_object_keys(&name, &func.args, scope),
2✔
2415
        // Phase 8b — FTS scalars. Both consult an FTS index attached to
2416
        // the named column; both error if no index exists (the index is
2417
        // a hard prerequisite, mirroring SQLite FTS5's MATCH).
2418
        //
2419
        // SQLR-5 — these only work in a single-table scope because they
2420
        // need the owning `Table` to look up an FTS index by name and
2421
        // they key results by the row's rowid. In a joined query the
2422
        // index lookup would be ambiguous (which table's FTS?) and the
2423
        // scoring rowid is per-table. Reject up front rather than
2424
        // silently wrong-result.
2425
        "fts_match" | "bm25_score" => {
3✔
2426
            let Some((table, rowid)) = scope.single_table_view() else {
2✔
2427
                return Err(SQLRiteError::NotImplemented(format!(
×
2428
                    "{name}() is not yet supported inside a JOIN query — \
2429
                     use it on a single-table SELECT or move the FTS lookup into a subquery"
2430
                )));
2431
            };
2432
            let (entry, query) = resolve_fts_args(&name, &func.args, table, scope)?;
3✔
2433
            Ok(match name.as_str() {
3✔
2434
                "fts_match" => Value::Bool(entry.index.matches(rowid, &query)),
3✔
2435
                "bm25_score" => {
2✔
2436
                    Value::Real(entry.index.score(rowid, &query, &Bm25Params::default()))
1✔
2437
                }
2438
                _ => unreachable!(),
×
2439
            })
2440
        }
2441
        // SQLR-3: catch aggregate names used in scalar position (e.g.
2442
        // `WHERE COUNT(*) > 1`) with a clearer message than "unknown
2443
        // function". HAVING isn't supported yet, hence the explicit nudge.
2444
        "count" | "sum" | "avg" | "min" | "max" => Err(SQLRiteError::NotImplemented(format!(
2✔
2445
            "aggregate function '{name}' is not allowed in WHERE / projection-scalar position; \
2446
             use it as a top-level projection item (HAVING is not yet supported)"
2447
        ))),
2448
        other => Err(SQLRiteError::NotImplemented(format!(
1✔
2449
            "unknown function: {other}(...)"
2450
        ))),
2451
    }
2452
}
2453

2454
/// Helper for `fts_match` / `bm25_score`: pull the column reference out
2455
/// of arg 0 (a bare identifier — we need the *name*, not the per-row
2456
/// value), evaluate arg 1 as a Text query string, and look up the FTS
2457
/// index attached to that column. Errors if any step fails.
2458
fn resolve_fts_args<'t>(
1✔
2459
    fn_name: &str,
2460
    args: &FunctionArguments,
2461
    table: &'t Table,
2462
    scope: &dyn RowScope,
2463
) -> Result<(&'t FtsIndexEntry, String)> {
2464
    let arg_list = match args {
1✔
2465
        FunctionArguments::List(l) => &l.args,
1✔
2466
        _ => {
2467
            return Err(SQLRiteError::General(format!(
×
2468
                "{fn_name}() expects exactly two arguments: (column, query_text)"
2469
            )));
2470
        }
2471
    };
2472
    if arg_list.len() != 2 {
1✔
2473
        return Err(SQLRiteError::General(format!(
×
2474
            "{fn_name}() expects exactly 2 arguments, got {}",
2475
            arg_list.len()
×
2476
        )));
2477
    }
2478

2479
    // Arg 0: bare column identifier. Must resolve syntactically to a
2480
    // column name (we can't accept arbitrary expressions because we
2481
    // need the column to look up the index, not the column's value).
2482
    let col_expr = match &arg_list[0] {
2✔
2483
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2484
        other => {
×
2485
            return Err(SQLRiteError::NotImplemented(format!(
×
2486
                "{fn_name}() argument 0 must be a column name, got {other:?}"
2487
            )));
2488
        }
2489
    };
2490
    let col_name = match col_expr {
1✔
2491
        Expr::Identifier(ident) => ident.value.clone(),
1✔
2492
        Expr::CompoundIdentifier(parts) => parts
×
2493
            .last()
×
2494
            .map(|p| p.value.clone())
×
2495
            .ok_or_else(|| SQLRiteError::Internal("empty compound identifier".to_string()))?,
×
2496
        other => {
×
2497
            return Err(SQLRiteError::General(format!(
×
2498
                "{fn_name}() argument 0 must be a column reference, got {other:?}"
2499
            )));
2500
        }
2501
    };
2502

2503
    // Arg 1: query string. Evaluated through the normal expression
2504
    // pipeline so callers can pass a literal `'rust db'` or an
2505
    // expression that yields TEXT.
2506
    let q_expr = match &arg_list[1] {
2✔
2507
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2508
        other => {
×
2509
            return Err(SQLRiteError::NotImplemented(format!(
×
2510
                "{fn_name}() argument 1 must be a text expression, got {other:?}"
2511
            )));
2512
        }
2513
    };
2514
    let query = match eval_expr_scope(q_expr, scope)? {
1✔
2515
        Value::Text(s) => s,
1✔
2516
        other => {
×
2517
            return Err(SQLRiteError::General(format!(
×
2518
                "{fn_name}() argument 1 must be TEXT, got {}",
2519
                other.to_display_string()
×
2520
            )));
2521
        }
2522
    };
2523

2524
    let entry = table
4✔
2525
        .fts_indexes
2526
        .iter()
1✔
2527
        .find(|e| e.column_name == col_name)
3✔
2528
        .ok_or_else(|| {
2✔
2529
            SQLRiteError::General(format!(
1✔
2530
                "{fn_name}({col_name}, ...): no FTS index on column '{col_name}' \
2531
                 (run CREATE INDEX <name> ON <table> USING fts({col_name}) first)"
2532
            ))
2533
        })?;
2534
    Ok((entry, query))
1✔
2535
}
2536

2537
// -----------------------------------------------------------------
2538
// Phase 7e — JSON path-extraction functions
2539
// -----------------------------------------------------------------
2540

2541
/// Extracts the JSON-typed text + optional path string out of a
2542
/// function call's args. Used by all four json_* functions.
2543
///
2544
/// Arity rules (matching SQLite JSON1):
2545
///   - 1 arg  → JSON value, path defaults to `$` (root)
2546
///   - 2 args → (JSON value, path text)
2547
///
2548
/// Returns `(json_text, path)` so caller can serde_json::from_str
2549
/// + walk_json_path on it.
2550
fn extract_json_and_path(
1✔
2551
    fn_name: &str,
2552
    args: &FunctionArguments,
2553
    scope: &dyn RowScope,
2554
) -> Result<(String, String)> {
2555
    let arg_list = match args {
1✔
2556
        FunctionArguments::List(l) => &l.args,
1✔
2557
        _ => {
2558
            return Err(SQLRiteError::General(format!(
×
2559
                "{fn_name}() expects 1 or 2 arguments"
2560
            )));
2561
        }
2562
    };
2563
    if !(arg_list.len() == 1 || arg_list.len() == 2) {
2✔
2564
        return Err(SQLRiteError::General(format!(
×
2565
            "{fn_name}() expects 1 or 2 arguments, got {}",
2566
            arg_list.len()
×
2567
        )));
2568
    }
2569
    // Evaluate first arg → must produce text.
2570
    let first_expr = match &arg_list[0] {
2✔
2571
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2572
        other => {
×
2573
            return Err(SQLRiteError::NotImplemented(format!(
×
2574
                "{fn_name}() argument 0 has unsupported shape: {other:?}"
2575
            )));
2576
        }
2577
    };
2578
    let json_text = match eval_expr_scope(first_expr, scope)? {
1✔
2579
        Value::Text(s) => s,
1✔
2580
        Value::Null => {
2581
            return Err(SQLRiteError::General(format!(
×
2582
                "{fn_name}() called on NULL — JSON column has no value for this row"
2583
            )));
2584
        }
2585
        other => {
×
2586
            return Err(SQLRiteError::General(format!(
×
2587
                "{fn_name}() argument 0 is not JSON-typed: got {}",
2588
                other.to_display_string()
×
2589
            )));
2590
        }
2591
    };
2592

2593
    // Path defaults to root `$` when omitted.
2594
    let path = if arg_list.len() == 2 {
2✔
2595
        let path_expr = match &arg_list[1] {
2✔
2596
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2597
            other => {
×
2598
                return Err(SQLRiteError::NotImplemented(format!(
×
2599
                    "{fn_name}() argument 1 has unsupported shape: {other:?}"
2600
                )));
2601
            }
2602
        };
2603
        match eval_expr_scope(path_expr, scope)? {
1✔
2604
            Value::Text(s) => s,
1✔
2605
            other => {
×
2606
                return Err(SQLRiteError::General(format!(
×
2607
                    "{fn_name}() path argument must be a string literal, got {}",
2608
                    other.to_display_string()
×
2609
                )));
2610
            }
2611
        }
2612
    } else {
2613
        "$".to_string()
×
2614
    };
2615

2616
    Ok((json_text, path))
1✔
2617
}
2618

2619
/// Walks a `serde_json::Value` along a JSONPath subset:
2620
///   - `$` is the root
2621
///   - `.key` for object access (key may not contain `.` or `[`)
2622
///   - `[N]` for array index (N a non-negative integer)
2623
///   - chains arbitrarily: `$.foo.bar[0].baz`
2624
///
2625
/// Returns `Ok(None)` for "path didn't match anything" (NULL in SQL),
2626
/// `Err` for malformed paths. Matches SQLite JSON1's semantic
2627
/// distinction: missing-key = NULL, malformed-path = error.
2628
fn walk_json_path<'a>(
1✔
2629
    value: &'a serde_json::Value,
2630
    path: &str,
2631
) -> Result<Option<&'a serde_json::Value>> {
2632
    let mut chars = path.chars().peekable();
1✔
2633
    if chars.next() != Some('$') {
1✔
2634
        return Err(SQLRiteError::General(format!(
1✔
2635
            "JSON path must start with '$', got `{path}`"
2636
        )));
2637
    }
2638
    let mut current = value;
1✔
2639
    while let Some(&c) = chars.peek() {
2✔
2640
        match c {
1✔
2641
            '.' => {
2642
                chars.next();
1✔
2643
                let mut key = String::new();
1✔
2644
                while let Some(&c) = chars.peek() {
2✔
2645
                    if c == '.' || c == '[' {
2✔
2646
                        break;
2647
                    }
2648
                    key.push(c);
1✔
2649
                    chars.next();
1✔
2650
                }
2651
                if key.is_empty() {
2✔
2652
                    return Err(SQLRiteError::General(format!(
×
2653
                        "JSON path has empty key after '.' in `{path}`"
2654
                    )));
2655
                }
2656
                match current.get(&key) {
2✔
2657
                    Some(v) => current = v,
1✔
2658
                    None => return Ok(None),
1✔
2659
                }
2660
            }
2661
            '[' => {
2662
                chars.next();
1✔
2663
                let mut idx_str = String::new();
1✔
2664
                while let Some(&c) = chars.peek() {
2✔
2665
                    if c == ']' {
1✔
2666
                        break;
2667
                    }
2668
                    idx_str.push(c);
1✔
2669
                    chars.next();
1✔
2670
                }
2671
                if chars.next() != Some(']') {
2✔
2672
                    return Err(SQLRiteError::General(format!(
×
2673
                        "JSON path has unclosed `[` in `{path}`"
2674
                    )));
2675
                }
2676
                let idx: usize = idx_str.trim().parse().map_err(|_| {
2✔
2677
                    SQLRiteError::General(format!(
×
2678
                        "JSON path has non-integer index `[{idx_str}]` in `{path}`"
2679
                    ))
2680
                })?;
2681
                match current.get(idx) {
1✔
2682
                    Some(v) => current = v,
1✔
2683
                    None => return Ok(None),
×
2684
                }
2685
            }
2686
            other => {
×
2687
                return Err(SQLRiteError::General(format!(
×
2688
                    "JSON path has unexpected character `{other}` in `{path}` \
2689
                     (expected `.`, `[`, or end-of-path)"
2690
                )));
2691
            }
2692
        }
2693
    }
2694
    Ok(Some(current))
1✔
2695
}
2696

2697
/// Converts a serde_json scalar to a SQLRite Value. For composite
2698
/// types (object, array) returns the JSON-encoded text — callers
2699
/// pattern-match on shape from the calling json_* function.
2700
fn json_value_to_sql(v: &serde_json::Value) -> Value {
1✔
2701
    match v {
1✔
2702
        serde_json::Value::Null => Value::Null,
×
2703
        serde_json::Value::Bool(b) => Value::Bool(*b),
×
2704
        serde_json::Value::Number(n) => {
1✔
2705
            // Match SQLite: integer if it fits an i64, else f64.
2706
            if let Some(i) = n.as_i64() {
3✔
2707
                Value::Integer(i)
1✔
2708
            } else if let Some(f) = n.as_f64() {
×
2709
                Value::Real(f)
×
2710
            } else {
2711
                Value::Null
×
2712
            }
2713
        }
2714
        serde_json::Value::String(s) => Value::Text(s.clone()),
1✔
2715
        // Objects + arrays come out as JSON-encoded text. Same as
2716
        // SQLite's json_extract: composite results round-trip through
2717
        // text rather than being modeled as a richer Value type.
2718
        composite => Value::Text(composite.to_string()),
×
2719
    }
2720
}
2721

2722
fn json_fn_extract(name: &str, args: &FunctionArguments, scope: &dyn RowScope) -> Result<Value> {
1✔
2723
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
2724
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
2725
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2726
    })?;
2727
    match walk_json_path(&parsed, &path)? {
2✔
2728
        Some(v) => Ok(json_value_to_sql(v)),
2✔
2729
        None => Ok(Value::Null),
1✔
2730
    }
2731
}
2732

2733
fn json_fn_type(name: &str, args: &FunctionArguments, scope: &dyn RowScope) -> Result<Value> {
1✔
2734
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
2735
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
2736
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2737
    })?;
2738
    let resolved = match walk_json_path(&parsed, &path)? {
2✔
2739
        Some(v) => v,
1✔
2740
        None => return Ok(Value::Null),
×
2741
    };
2742
    let ty = match resolved {
2✔
2743
        serde_json::Value::Null => "null",
1✔
2744
        serde_json::Value::Bool(true) => "true",
1✔
2745
        serde_json::Value::Bool(false) => "false",
×
2746
        serde_json::Value::Number(n) => {
1✔
2747
            if n.is_i64() || n.is_u64() {
4✔
2748
                "integer"
1✔
2749
            } else {
2750
                "real"
1✔
2751
            }
2752
        }
2753
        serde_json::Value::String(_) => "text",
1✔
2754
        serde_json::Value::Array(_) => "array",
1✔
2755
        serde_json::Value::Object(_) => "object",
1✔
2756
    };
2757
    Ok(Value::Text(ty.to_string()))
2✔
2758
}
2759

2760
fn json_fn_array_length(
1✔
2761
    name: &str,
2762
    args: &FunctionArguments,
2763
    scope: &dyn RowScope,
2764
) -> Result<Value> {
2765
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
2766
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
2767
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2768
    })?;
2769
    let resolved = match walk_json_path(&parsed, &path)? {
2✔
2770
        Some(v) => v,
1✔
2771
        None => return Ok(Value::Null),
×
2772
    };
2773
    match resolved.as_array() {
2✔
2774
        Some(arr) => Ok(Value::Integer(arr.len() as i64)),
2✔
2775
        None => Err(SQLRiteError::General(format!(
1✔
2776
            "{name}() resolved to a non-array value at path `{path}`"
2777
        ))),
2778
    }
2779
}
2780

2781
fn json_fn_object_keys(
×
2782
    name: &str,
2783
    args: &FunctionArguments,
2784
    scope: &dyn RowScope,
2785
) -> Result<Value> {
2786
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
×
2787
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
×
2788
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2789
    })?;
2790
    let resolved = match walk_json_path(&parsed, &path)? {
×
2791
        Some(v) => v,
×
2792
        None => return Ok(Value::Null),
×
2793
    };
2794
    let obj = resolved.as_object().ok_or_else(|| {
×
2795
        SQLRiteError::General(format!(
×
2796
            "{name}() resolved to a non-object value at path `{path}`"
2797
        ))
2798
    })?;
2799
    // SQLite's json_object_keys is a table-valued function (one row
2800
    // per key). Without set-returning function support we can't
2801
    // reproduce that shape; instead return the keys as a JSON array
2802
    // text. Caller can iterate via json_array_length + json_extract,
2803
    // or just treat it as a serialized list. Document this divergence
2804
    // in supported-sql.md.
2805
    let keys: Vec<serde_json::Value> = obj
2806
        .keys()
2807
        .map(|k| serde_json::Value::String(k.clone()))
×
2808
        .collect();
2809
    Ok(Value::Text(serde_json::Value::Array(keys).to_string()))
×
2810
}
2811

2812
/// Extracts exactly two `Vec<f32>` arguments from a function call,
2813
/// validating arity and that both sides are Vector-typed with matching
2814
/// dimensions. Used by all three vec_distance_* functions.
2815
fn extract_two_vector_args(
1✔
2816
    fn_name: &str,
2817
    args: &FunctionArguments,
2818
    scope: &dyn RowScope,
2819
) -> Result<(Vec<f32>, Vec<f32>)> {
2820
    let arg_list = match args {
1✔
2821
        FunctionArguments::List(l) => &l.args,
1✔
2822
        _ => {
2823
            return Err(SQLRiteError::General(format!(
×
2824
                "{fn_name}() expects exactly two vector arguments"
2825
            )));
2826
        }
2827
    };
2828
    if arg_list.len() != 2 {
1✔
2829
        return Err(SQLRiteError::General(format!(
×
2830
            "{fn_name}() expects exactly 2 arguments, got {}",
2831
            arg_list.len()
×
2832
        )));
2833
    }
2834
    let mut out: Vec<Vec<f32>> = Vec::with_capacity(2);
1✔
2835
    for (i, arg) in arg_list.iter().enumerate() {
3✔
2836
        let expr = match arg {
2✔
2837
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2838
            other => {
×
2839
                return Err(SQLRiteError::NotImplemented(format!(
×
2840
                    "{fn_name}() argument {i} has unsupported shape: {other:?}"
2841
                )));
2842
            }
2843
        };
2844
        let val = eval_expr_scope(expr, scope)?;
1✔
2845
        match val {
1✔
2846
            Value::Vector(v) => out.push(v),
1✔
2847
            other => {
×
2848
                return Err(SQLRiteError::General(format!(
×
2849
                    "{fn_name}() argument {i} is not a vector: got {}",
2850
                    other.to_display_string()
×
2851
                )));
2852
            }
2853
        }
2854
    }
2855
    let b = out.pop().unwrap();
1✔
2856
    let a = out.pop().unwrap();
2✔
2857
    if a.len() != b.len() {
2✔
2858
        return Err(SQLRiteError::General(format!(
1✔
2859
            "{fn_name}(): vector dimensions don't match (lhs={}, rhs={})",
2860
            a.len(),
2✔
2861
            b.len()
1✔
2862
        )));
2863
    }
2864
    Ok((a, b))
1✔
2865
}
2866

2867
/// Euclidean (L2) distance: √Σ(aᵢ − bᵢ)².
2868
/// Smaller-is-closer; identical vectors return 0.0.
2869
pub(crate) fn vec_distance_l2(a: &[f32], b: &[f32]) -> f32 {
1✔
2870
    debug_assert_eq!(a.len(), b.len());
1✔
2871
    let mut sum = 0.0f32;
1✔
2872
    for i in 0..a.len() {
2✔
2873
        let d = a[i] - b[i];
2✔
2874
        sum += d * d;
1✔
2875
    }
2876
    sum.sqrt()
1✔
2877
}
2878

2879
/// Cosine distance: 1 − (a·b) / (‖a‖·‖b‖).
2880
/// Smaller-is-closer; identical (non-zero) vectors return 0.0,
2881
/// orthogonal vectors return 1.0, opposite-direction vectors return 2.0.
2882
///
2883
/// Errors if either vector has zero magnitude — cosine similarity is
2884
/// undefined for the zero vector and silently returning NaN would
2885
/// poison `ORDER BY` ranking. Callers who want the silent-NaN
2886
/// behavior can compute `vec_distance_dot(a, b) / (norm(a) * norm(b))`
2887
/// themselves.
2888
pub(crate) fn vec_distance_cosine(a: &[f32], b: &[f32]) -> Result<f32> {
1✔
2889
    debug_assert_eq!(a.len(), b.len());
1✔
2890
    let mut dot = 0.0f32;
1✔
2891
    let mut norm_a_sq = 0.0f32;
1✔
2892
    let mut norm_b_sq = 0.0f32;
1✔
2893
    for i in 0..a.len() {
2✔
2894
        dot += a[i] * b[i];
2✔
2895
        norm_a_sq += a[i] * a[i];
2✔
2896
        norm_b_sq += b[i] * b[i];
2✔
2897
    }
2898
    let denom = (norm_a_sq * norm_b_sq).sqrt();
1✔
2899
    if denom == 0.0 {
1✔
2900
        return Err(SQLRiteError::General(
1✔
2901
            "vec_distance_cosine() is undefined for zero-magnitude vectors".to_string(),
1✔
2902
        ));
2903
    }
2904
    Ok(1.0 - dot / denom)
1✔
2905
}
2906

2907
/// Negated dot product: −(a·b).
2908
/// pgvector convention — negated so smaller-is-closer like L2 / cosine.
2909
/// For unit-norm vectors `vec_distance_dot(a, b) == vec_distance_cosine(a, b) - 1`.
2910
pub(crate) fn vec_distance_dot(a: &[f32], b: &[f32]) -> f32 {
1✔
2911
    debug_assert_eq!(a.len(), b.len());
1✔
2912
    let mut dot = 0.0f32;
1✔
2913
    for i in 0..a.len() {
2✔
2914
        dot += a[i] * b[i];
2✔
2915
    }
2916
    -dot
1✔
2917
}
2918

2919
/// Evaluates an integer/real arithmetic op. NULL on either side propagates.
2920
/// Mixed Integer/Real promotes to Real. Divide/Modulo by zero → error.
2921
fn eval_arith(op: &BinaryOperator, l: &Value, r: &Value) -> Result<Value> {
1✔
2922
    if matches!(l, Value::Null) || matches!(r, Value::Null) {
1✔
2923
        return Ok(Value::Null);
×
2924
    }
2925
    match (l, r) {
1✔
2926
        (Value::Integer(a), Value::Integer(b)) => match op {
1✔
2927
            BinaryOperator::Plus => Ok(Value::Integer(a.wrapping_add(*b))),
1✔
2928
            BinaryOperator::Minus => Ok(Value::Integer(a.wrapping_sub(*b))),
×
2929
            BinaryOperator::Multiply => Ok(Value::Integer(a.wrapping_mul(*b))),
1✔
2930
            BinaryOperator::Divide => {
2931
                if *b == 0 {
×
2932
                    Err(SQLRiteError::General("division by zero".to_string()))
×
2933
                } else {
2934
                    Ok(Value::Integer(a / b))
×
2935
                }
2936
            }
2937
            BinaryOperator::Modulo => {
2938
                if *b == 0 {
×
2939
                    Err(SQLRiteError::General("modulo by zero".to_string()))
×
2940
                } else {
2941
                    Ok(Value::Integer(a % b))
×
2942
                }
2943
            }
2944
            _ => unreachable!(),
2945
        },
2946
        // Anything involving a Real promotes both sides to f64.
2947
        (a, b) => {
×
2948
            let af = as_number(a)?;
×
2949
            let bf = as_number(b)?;
×
2950
            match op {
×
2951
                BinaryOperator::Plus => Ok(Value::Real(af + bf)),
×
2952
                BinaryOperator::Minus => Ok(Value::Real(af - bf)),
×
2953
                BinaryOperator::Multiply => Ok(Value::Real(af * bf)),
×
2954
                BinaryOperator::Divide => {
2955
                    if bf == 0.0 {
×
2956
                        Err(SQLRiteError::General("division by zero".to_string()))
×
2957
                    } else {
2958
                        Ok(Value::Real(af / bf))
×
2959
                    }
2960
                }
2961
                BinaryOperator::Modulo => {
2962
                    if bf == 0.0 {
×
2963
                        Err(SQLRiteError::General("modulo by zero".to_string()))
×
2964
                    } else {
2965
                        Ok(Value::Real(af % bf))
×
2966
                    }
2967
                }
2968
                _ => unreachable!(),
2969
            }
2970
        }
2971
    }
2972
}
2973

2974
fn as_number(v: &Value) -> Result<f64> {
×
2975
    match v {
×
2976
        Value::Integer(i) => Ok(*i as f64),
×
2977
        Value::Real(f) => Ok(*f),
×
2978
        Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
×
2979
        other => Err(SQLRiteError::General(format!(
×
2980
            "arithmetic on non-numeric value '{}'",
2981
            other.to_display_string()
×
2982
        ))),
2983
    }
2984
}
2985

2986
fn as_bool(v: &Value) -> Result<bool> {
1✔
2987
    match v {
1✔
2988
        Value::Bool(b) => Ok(*b),
1✔
2989
        Value::Null => Ok(false),
2990
        Value::Integer(i) => Ok(*i != 0),
×
2991
        other => Err(SQLRiteError::Internal(format!(
×
2992
            "expected boolean, got {}",
2993
            other.to_display_string()
×
2994
        ))),
2995
    }
2996
}
2997

2998
// -----------------------------------------------------------------
2999
// SQLR-3 — LIKE / IN evaluators
3000
// -----------------------------------------------------------------
3001

3002
#[allow(clippy::too_many_arguments)]
3003
fn eval_like(
1✔
3004
    scope: &dyn RowScope,
3005
    negated: bool,
3006
    any: bool,
3007
    lhs: &Expr,
3008
    pattern: &Expr,
3009
    escape_char: Option<&AstValue>,
3010
    case_insensitive: bool,
3011
) -> Result<Value> {
3012
    if any {
1✔
3013
        return Err(SQLRiteError::NotImplemented(
×
3014
            "LIKE ANY (...) is not supported".to_string(),
×
3015
        ));
3016
    }
3017
    if escape_char.is_some() {
1✔
3018
        return Err(SQLRiteError::NotImplemented(
×
3019
            "LIKE ... ESCAPE '<char>' is not supported (default `\\` escape only)".to_string(),
×
3020
        ));
3021
    }
3022

3023
    let l = eval_expr_scope(lhs, scope)?;
1✔
3024
    let p = eval_expr_scope(pattern, scope)?;
2✔
3025
    if matches!(l, Value::Null) || matches!(p, Value::Null) {
1✔
3026
        return Ok(Value::Null);
×
3027
    }
3028
    let text = match l {
1✔
3029
        Value::Text(s) => s,
1✔
3030
        other => other.to_display_string(),
×
3031
    };
3032
    let pat = match p {
1✔
3033
        Value::Text(s) => s,
1✔
3034
        other => other.to_display_string(),
×
3035
    };
3036
    let m = like_match(&text, &pat, case_insensitive);
2✔
3037
    Ok(Value::Bool(if negated { !m } else { m }))
1✔
3038
}
3039

3040
fn eval_in_list(scope: &dyn RowScope, lhs: &Expr, list: &[Expr], negated: bool) -> Result<Value> {
1✔
3041
    let l = eval_expr_scope(lhs, scope)?;
1✔
3042
    if matches!(l, Value::Null) {
1✔
3043
        return Ok(Value::Null);
×
3044
    }
3045
    let mut saw_null = false;
1✔
3046
    for item in list {
2✔
3047
        let r = eval_expr_scope(item, scope)?;
2✔
3048
        if matches!(r, Value::Null) {
1✔
3049
            saw_null = true;
1✔
3050
            continue;
3051
        }
3052
        if compare_values(Some(&l), Some(&r)) == Ordering::Equal {
2✔
3053
            return Ok(Value::Bool(!negated));
1✔
3054
        }
3055
    }
3056
    if saw_null {
2✔
3057
        // SQLite three-valued IN: unmatched + a NULL on the RHS → NULL.
3058
        // WHERE coerces NULL → false, so the row is excluded either way.
3059
        Ok(Value::Null)
1✔
3060
    } else {
3061
        Ok(Value::Bool(negated))
1✔
3062
    }
3063
}
3064

3065
// -----------------------------------------------------------------
3066
// SQLR-3 — Aggregation phase, DISTINCT, post-projection sort
3067
// -----------------------------------------------------------------
3068

3069
/// Walk `matching` rowids, partition into groups (one synthetic group
3070
/// when `group_by` is empty), update one `AggState` per aggregate
3071
/// projection slot per group, then materialize one output row per
3072
/// group in projection order. Group-key columns surface their original
3073
/// `Value` (captured the first time the group was seen); aggregate
3074
/// slots surface `AggState::finalize()`.
3075
fn aggregate_rows(
1✔
3076
    table: &Table,
3077
    matching: &[i64],
3078
    group_by: &[String],
3079
    proj_items: &[ProjectionItem],
3080
) -> Result<Vec<Vec<Value>>> {
3081
    // Build the per-projection-slot accumulator template once. Each
3082
    // group clones this template on first sight. Non-aggregate slots
3083
    // hold a "captured group-key value" (`None` until set).
3084
    let template: Vec<Option<AggState>> = proj_items
1✔
3085
        .iter()
3086
        .map(|i| match &i.kind {
3✔
3087
            ProjectionKind::Aggregate(call) => Some(AggState::new(call)),
1✔
3088
            ProjectionKind::Column { .. } => None,
1✔
3089
        })
3090
        .collect();
3091

3092
    // Linear-scan group lookup. For typical ad-hoc queries (cardinality
3093
    // ≪ 10k), this is fine; if grouping cardinality grows, swap to a
3094
    // HashMap<Vec<DistinctKey>, usize> keyed by the same DistinctKey
3095
    // wrapper. Order-preserving for readable output (groups appear in
3096
    // first-occurrence order, matching SQLite's typical behavior).
3097
    let mut keys: Vec<Vec<DistinctKey>> = Vec::new();
1✔
3098
    let mut group_states: Vec<Vec<Option<AggState>>> = Vec::new();
1✔
3099
    let mut group_key_values: Vec<Vec<Value>> = Vec::new();
1✔
3100

3101
    for &rowid in matching {
3✔
3102
        let mut key_values: Vec<Value> = Vec::with_capacity(group_by.len());
2✔
3103
        let mut key: Vec<DistinctKey> = Vec::with_capacity(group_by.len());
2✔
3104
        for col in group_by {
3✔
3105
            let v = table.get_value(col, rowid).unwrap_or(Value::Null);
2✔
3106
            key.push(DistinctKey::from_value(&v));
2✔
3107
            key_values.push(v);
1✔
3108
        }
3109
        let idx = match keys.iter().position(|k| k == &key) {
3✔
3110
            Some(i) => i,
1✔
3111
            None => {
3112
                keys.push(key);
1✔
3113
                group_states.push(template.clone());
1✔
3114
                group_key_values.push(key_values);
1✔
3115
                keys.len() - 1
1✔
3116
            }
3117
        };
3118

3119
        for (slot, item) in proj_items.iter().enumerate() {
1✔
3120
            if let ProjectionKind::Aggregate(call) = &item.kind {
2✔
3121
                let v = match &call.arg {
1✔
3122
                    AggregateArg::Star => Value::Null,
1✔
3123
                    AggregateArg::Column(c) => table.get_value(c, rowid).unwrap_or(Value::Null),
2✔
3124
                };
3125
                if let Some(state) = group_states[idx][slot].as_mut() {
2✔
3126
                    state.update(&v)?;
2✔
3127
                }
3128
            }
3129
        }
3130
    }
3131

3132
    // No groups but no aggregate-only "implicit one row" semantic to
3133
    // emit: e.g. `SELECT dept FROM t GROUP BY dept` over an empty
3134
    // matching set should produce zero rows. `SELECT COUNT(*) FROM t`
3135
    // (no GROUP BY) DOES produce one row even on empty input — the
3136
    // single-synthetic-group path below handles it.
3137
    if keys.is_empty() && group_by.is_empty() {
2✔
3138
        // Synthetic single empty group so we still emit one row with
3139
        // initial accumulator finals (e.g. COUNT(*) → 0).
3140
        keys.push(Vec::new());
1✔
3141
        group_states.push(template.clone());
1✔
3142
        group_key_values.push(Vec::new());
1✔
3143
    }
3144

3145
    // Project: one row per group, in projection order.
3146
    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(keys.len());
2✔
3147
    for (group_idx, _) in keys.iter().enumerate() {
3✔
3148
        let mut row: Vec<Value> = Vec::with_capacity(proj_items.len());
2✔
3149
        for (slot, item) in proj_items.iter().enumerate() {
2✔
3150
            match &item.kind {
1✔
3151
                ProjectionKind::Column { name: c, .. } => {
1✔
3152
                    // The validation in execute_select_rows guarantees
3153
                    // bare-column projections are also in `group_by`.
3154
                    let pos = group_by
2✔
3155
                        .iter()
3156
                        .position(|g| g == c)
3✔
3157
                        .expect("validated to be in GROUP BY");
3158
                    row.push(group_key_values[group_idx][pos].clone());
1✔
3159
                }
3160
                ProjectionKind::Aggregate(_) => {
3161
                    let state = group_states[group_idx][slot]
3✔
3162
                        .as_ref()
3163
                        .expect("aggregate slot has state");
3164
                    row.push(state.finalize());
1✔
3165
                }
3166
            }
3167
        }
3168
        rows.push(row);
1✔
3169
    }
3170
    Ok(rows)
1✔
3171
}
3172

3173
/// SELECT DISTINCT post-pass. Walks the rows once with a `HashSet` of
3174
/// row-keys, preserving first-occurrence order. NULL == NULL for
3175
/// dedupe purposes, which matches the SQL DISTINCT semantic.
3176
fn dedupe_rows(rows: Vec<Vec<Value>>) -> Vec<Vec<Value>> {
1✔
3177
    use std::collections::HashSet;
3178
    let mut seen: HashSet<Vec<DistinctKey>> = HashSet::new();
1✔
3179
    let mut out = Vec::with_capacity(rows.len());
2✔
3180
    for row in rows {
4✔
3181
        let key: Vec<DistinctKey> = row.iter().map(DistinctKey::from_value).collect();
2✔
3182
        if seen.insert(key) {
1✔
3183
            out.push(row);
1✔
3184
        }
3185
    }
3186
    out
1✔
3187
}
3188

3189
/// Sort output rows for the aggregating path. ORDER BY can reference
3190
/// either an output column name (alias or bare GROUP BY column) or an
3191
/// aggregate function call by display form (e.g. `COUNT(*)`).
3192
fn sort_output_rows(
1✔
3193
    rows: &mut [Vec<Value>],
3194
    columns: &[String],
3195
    proj_items: &[ProjectionItem],
3196
    order: &OrderByClause,
3197
) -> Result<()> {
3198
    let target_idx = resolve_order_by_index(&order.expr, columns, proj_items)?;
1✔
3199
    rows.sort_by(|a, b| {
2✔
3200
        let va = &a[target_idx];
1✔
3201
        let vb = &b[target_idx];
1✔
3202
        let ord = compare_values(Some(va), Some(vb));
1✔
3203
        if order.ascending { ord } else { ord.reverse() }
1✔
3204
    });
3205
    Ok(())
1✔
3206
}
3207

3208
/// Map an ORDER BY expression to the index of the output column that
3209
/// should drive the sort.
3210
fn resolve_order_by_index(
1✔
3211
    expr: &Expr,
3212
    columns: &[String],
3213
    proj_items: &[ProjectionItem],
3214
) -> Result<usize> {
3215
    // Bare identifier — match against output names (alias-first).
3216
    let target_name: Option<String> = match expr {
1✔
3217
        Expr::Identifier(ident) => Some(ident.value.clone()),
1✔
3218
        Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
×
3219
        Expr::Function(_) => None,
1✔
3220
        Expr::Nested(inner) => return resolve_order_by_index(inner, columns, proj_items),
×
3221
        other => {
×
3222
            return Err(SQLRiteError::NotImplemented(format!(
×
3223
                "ORDER BY expression not supported on aggregating queries: {other:?}"
3224
            )));
3225
        }
3226
    };
3227
    if let Some(name) = target_name {
2✔
3228
        if let Some(i) = columns.iter().position(|c| c.eq_ignore_ascii_case(&name)) {
4✔
3229
            return Ok(i);
1✔
3230
        }
3231
        return Err(SQLRiteError::Internal(format!(
×
3232
            "ORDER BY references unknown column '{name}' in the SELECT output"
3233
        )));
3234
    }
3235
    // Function form: match by display name against any aggregate item
3236
    // whose canonical display equals the user's call. Tolerate case
3237
    // differences in the function name.
3238
    if let Expr::Function(func) = expr {
2✔
3239
        let user_disp = format_function_display(func);
1✔
3240
        for (i, item) in proj_items.iter().enumerate() {
2✔
3241
            if let ProjectionKind::Aggregate(call) = &item.kind
2✔
3242
                && call.display_name().eq_ignore_ascii_case(&user_disp)
1✔
3243
            {
3244
                return Ok(i);
1✔
3245
            }
3246
        }
3247
        return Err(SQLRiteError::Internal(format!(
×
3248
            "ORDER BY references aggregate '{user_disp}' that isn't in the SELECT output"
3249
        )));
3250
    }
3251
    Err(SQLRiteError::Internal(
×
3252
        "ORDER BY expression could not be resolved against the output columns".to_string(),
×
3253
    ))
3254
}
3255

3256
/// Format a sqlparser function call into the same canonical form
3257
/// `AggregateCall::display_name()` uses, so ORDER BY on
3258
/// `COUNT(*)` / `SUM(salary)` matches its projection counterpart.
3259
fn format_function_display(func: &sqlparser::ast::Function) -> String {
1✔
3260
    let name = match func.name.0.as_slice() {
2✔
3261
        [ObjectNamePart::Identifier(ident)] => ident.value.to_uppercase(),
2✔
3262
        _ => format!("{:?}", func.name).to_uppercase(),
×
3263
    };
3264
    let inner = match &func.args {
1✔
3265
        FunctionArguments::List(l) => {
1✔
3266
            let distinct = matches!(
1✔
3267
                l.duplicate_treatment,
1✔
3268
                Some(sqlparser::ast::DuplicateTreatment::Distinct)
3269
            );
3270
            let arg = l.args.first().map(|a| match a {
4✔
3271
                FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => "*".to_string(),
1✔
3272
                FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Identifier(i))) => i.value.clone(),
×
3273
                FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::CompoundIdentifier(parts))) => {
×
3274
                    parts.last().map(|p| p.value.clone()).unwrap_or_default()
×
3275
                }
3276
                _ => String::new(),
×
3277
            });
3278
            match (distinct, arg) {
2✔
3279
                (true, Some(a)) if a != "*" => format!("DISTINCT {a}"),
×
3280
                (_, Some(a)) => a,
1✔
3281
                _ => String::new(),
×
3282
            }
3283
        }
3284
        _ => String::new(),
×
3285
    };
3286
    format!("{name}({inner})")
2✔
3287
}
3288

3289
fn convert_literal(v: &sqlparser::ast::Value) -> Result<Value> {
1✔
3290
    use sqlparser::ast::Value as AstValue;
3291
    match v {
1✔
3292
        AstValue::Number(n, _) => {
1✔
3293
            if let Ok(i) = n.parse::<i64>() {
2✔
3294
                Ok(Value::Integer(i))
1✔
3295
            } else if let Ok(f) = n.parse::<f64>() {
2✔
3296
                Ok(Value::Real(f))
1✔
3297
            } else {
3298
                Err(SQLRiteError::Internal(format!(
×
3299
                    "could not parse numeric literal '{n}'"
3300
                )))
3301
            }
3302
        }
3303
        AstValue::SingleQuotedString(s) => Ok(Value::Text(s.clone())),
1✔
3304
        AstValue::Boolean(b) => Ok(Value::Bool(*b)),
×
3305
        AstValue::Null => Ok(Value::Null),
1✔
3306
        other => Err(SQLRiteError::NotImplemented(format!(
×
3307
            "unsupported literal value: {other:?}"
3308
        ))),
3309
    }
3310
}
3311

3312
#[cfg(test)]
3313
mod tests {
3314
    use super::*;
3315

3316
    // -----------------------------------------------------------------
3317
    // Phase 7b — Vector distance function math
3318
    // -----------------------------------------------------------------
3319

3320
    /// Float comparison helper — distance results need a small epsilon
3321
    /// because we accumulate sums across many f32 multiplies.
3322
    fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
1✔
3323
        (a - b).abs() < eps
1✔
3324
    }
3325

3326
    #[test]
3327
    fn vec_distance_l2_identical_is_zero() {
3✔
3328
        let v = vec![0.1, 0.2, 0.3];
1✔
3329
        assert_eq!(vec_distance_l2(&v, &v), 0.0);
2✔
3330
    }
3331

3332
    #[test]
3333
    fn vec_distance_l2_unit_basis_is_sqrt2() {
3✔
3334
        // [1, 0] vs [0, 1]: distance = √((1-0)² + (0-1)²) = √2 ≈ 1.414
3335
        let a = vec![1.0, 0.0];
1✔
3336
        let b = vec![0.0, 1.0];
2✔
3337
        assert!(approx_eq(vec_distance_l2(&a, &b), 2.0_f32.sqrt(), 1e-6));
2✔
3338
    }
3339

3340
    #[test]
3341
    fn vec_distance_l2_known_value() {
3✔
3342
        // [0, 0, 0] vs [3, 4, 0]: √(9 + 16 + 0) = 5 (the classic 3-4-5 triangle).
3343
        let a = vec![0.0, 0.0, 0.0];
1✔
3344
        let b = vec![3.0, 4.0, 0.0];
2✔
3345
        assert!(approx_eq(vec_distance_l2(&a, &b), 5.0, 1e-6));
2✔
3346
    }
3347

3348
    #[test]
3349
    fn vec_distance_cosine_identical_is_zero() {
3✔
3350
        let v = vec![0.1, 0.2, 0.3];
1✔
3351
        let d = vec_distance_cosine(&v, &v).unwrap();
2✔
3352
        assert!(approx_eq(d, 0.0, 1e-6), "cos(v,v) = {d}, expected ≈ 0");
1✔
3353
    }
3354

3355
    #[test]
3356
    fn vec_distance_cosine_orthogonal_is_one() {
3✔
3357
        // Two orthogonal unit vectors should have cosine distance = 1.0
3358
        // (cosine similarity = 0 → distance = 1 - 0 = 1).
3359
        let a = vec![1.0, 0.0];
1✔
3360
        let b = vec![0.0, 1.0];
2✔
3361
        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 1.0, 1e-6));
2✔
3362
    }
3363

3364
    #[test]
3365
    fn vec_distance_cosine_opposite_is_two() {
3✔
3366
        // a and -a have cosine similarity = -1 → distance = 1 - (-1) = 2.
3367
        let a = vec![1.0, 0.0, 0.0];
1✔
3368
        let b = vec![-1.0, 0.0, 0.0];
2✔
3369
        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 2.0, 1e-6));
2✔
3370
    }
3371

3372
    #[test]
3373
    fn vec_distance_cosine_zero_magnitude_errors() {
3✔
3374
        // Cosine is undefined for the zero vector — error rather than NaN.
3375
        let a = vec![0.0, 0.0];
1✔
3376
        let b = vec![1.0, 0.0];
2✔
3377
        let err = vec_distance_cosine(&a, &b).unwrap_err();
2✔
3378
        assert!(format!("{err}").contains("zero-magnitude"));
2✔
3379
    }
3380

3381
    #[test]
3382
    fn vec_distance_dot_negates() {
3✔
3383
        // a·b = 1*4 + 2*5 + 3*6 = 32. Negated → -32.
3384
        let a = vec![1.0, 2.0, 3.0];
1✔
3385
        let b = vec![4.0, 5.0, 6.0];
2✔
3386
        assert!(approx_eq(vec_distance_dot(&a, &b), -32.0, 1e-6));
2✔
3387
    }
3388

3389
    #[test]
3390
    fn vec_distance_dot_orthogonal_is_zero() {
3✔
3391
        // Orthogonal vectors have dot product 0 → negated is also 0.
3392
        let a = vec![1.0, 0.0];
1✔
3393
        let b = vec![0.0, 1.0];
2✔
3394
        assert_eq!(vec_distance_dot(&a, &b), 0.0);
2✔
3395
    }
3396

3397
    #[test]
3398
    fn vec_distance_dot_unit_norm_matches_cosine_minus_one() {
3✔
3399
        // For unit-norm vectors: dot(a,b) = cos(a,b)
3400
        // → -dot(a,b) = -cos(a,b) = (1 - cos(a,b)) - 1 = vec_distance_cosine(a,b) - 1.
3401
        // Useful sanity check that the two functions agree on unit vectors.
3402
        let a = vec![0.6f32, 0.8]; // unit norm: √(0.36+0.64) = 1
1✔
3403
        let b = vec![0.8f32, 0.6]; // unit norm too
2✔
3404
        let dot = vec_distance_dot(&a, &b);
2✔
3405
        let cos = vec_distance_cosine(&a, &b).unwrap();
1✔
3406
        assert!(approx_eq(dot, cos - 1.0, 1e-5));
1✔
3407
    }
3408

3409
    // -----------------------------------------------------------------
3410
    // Phase 7c — bounded-heap top-k correctness + benchmark
3411
    // -----------------------------------------------------------------
3412

3413
    use crate::sql::db::database::Database;
3414
    use crate::sql::dialect::SqlriteDialect;
3415
    use crate::sql::parser::select::SelectQuery;
3416
    use sqlparser::parser::Parser;
3417

3418
    /// Builds a `docs(id INTEGER PK, score REAL)` table with N rows of
3419
    /// distinct positive scores so top-k tests aren't sensitive to
3420
    /// tie-breaking (heap is unstable; full-sort is stable; we want
3421
    /// both to agree without arguing about equal-score row order).
3422
    ///
3423
    /// **Why positive scores:** the INSERT parser doesn't currently
3424
    /// handle `Expr::UnaryOp(Minus, …)` for negative number literals
3425
    /// (it would parse `-3.14` as a unary expression and the value
3426
    /// extractor would skip it). That's a pre-existing bug, out of
3427
    /// scope for 7c. Using the Knuth multiplicative hash gives us
3428
    /// distinct positive scrambled values without dancing around the
3429
    /// negative-literal limitation.
3430
    fn seed_score_table(n: usize) -> Database {
1✔
3431
        let mut db = Database::new("tempdb".to_string());
1✔
3432
        crate::sql::process_command(
3433
            "CREATE TABLE docs (id INTEGER PRIMARY KEY, score REAL);",
3434
            &mut db,
3435
        )
3436
        .expect("create");
3437
        for i in 0..n {
1✔
3438
            // Knuth multiplicative hash mod 1_000_000 — distinct,
3439
            // dense in [0, 999_999], no collisions for n up to ~tens
3440
            // of thousands.
3441
            let score = ((i as u64).wrapping_mul(2_654_435_761) % 1_000_000) as f64;
2✔
3442
            let sql = format!("INSERT INTO docs (score) VALUES ({score});");
1✔
3443
            crate::sql::process_command(&sql, &mut db).expect("insert");
2✔
3444
        }
3445
        db
1✔
3446
    }
3447

3448
    /// Helper: parses an SQL SELECT into a SelectQuery so we can drive
3449
    /// `select_topk` / `sort_rowids` directly without the rest of the
3450
    /// process_command pipeline.
3451
    fn parse_select(sql: &str) -> SelectQuery {
1✔
3452
        let dialect = SqlriteDialect::new();
1✔
3453
        let mut ast = Parser::parse_sql(&dialect, sql).expect("parse");
1✔
3454
        let stmt = ast.pop().expect("one statement");
2✔
3455
        SelectQuery::new(&stmt).expect("select-query")
2✔
3456
    }
3457

3458
    #[test]
3459
    fn topk_matches_full_sort_asc() {
3✔
3460
        // Build N=200, top-k=10. Bounded heap output must equal
3461
        // full-sort-then-truncate output (both produce ASC order).
3462
        let db = seed_score_table(200);
1✔
3463
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3464
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
1✔
3465
        let order = q.order_by.as_ref().unwrap();
2✔
3466
        let all_rowids = table.rowids();
1✔
3467

3468
        // Full-sort path
3469
        let mut full = all_rowids.clone();
1✔
3470
        sort_rowids(&mut full, table, order).unwrap();
2✔
3471
        full.truncate(10);
1✔
3472

3473
        // Bounded-heap path
3474
        let topk = select_topk(&all_rowids, table, order, 10).unwrap();
1✔
3475

3476
        assert_eq!(topk, full, "top-k via heap should match full-sort+truncate");
2✔
3477
    }
3478

3479
    #[test]
3480
    fn topk_matches_full_sort_desc() {
3✔
3481
        // Same with DESC — verifies the direction-aware Ord wrapper.
3482
        let db = seed_score_table(200);
1✔
3483
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3484
        let q = parse_select("SELECT * FROM docs ORDER BY score DESC LIMIT 10;");
1✔
3485
        let order = q.order_by.as_ref().unwrap();
2✔
3486
        let all_rowids = table.rowids();
1✔
3487

3488
        let mut full = all_rowids.clone();
1✔
3489
        sort_rowids(&mut full, table, order).unwrap();
2✔
3490
        full.truncate(10);
1✔
3491

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

3494
        assert_eq!(
2✔
3495
            topk, full,
3496
            "top-k DESC via heap should match full-sort+truncate"
3497
        );
3498
    }
3499

3500
    #[test]
3501
    fn topk_k_larger_than_n_returns_everything_sorted() {
3✔
3502
        // The executor branches off to the full-sort path when k >= N,
3503
        // but if a caller invokes select_topk directly with k > N, it
3504
        // should still produce all-sorted output (no truncation
3505
        // because we don't have N items to truncate to k).
3506
        let db = seed_score_table(50);
1✔
3507
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3508
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1000;");
1✔
3509
        let order = q.order_by.as_ref().unwrap();
2✔
3510
        let topk = select_topk(&table.rowids(), table, order, 1000).unwrap();
1✔
3511
        assert_eq!(topk.len(), 50);
1✔
3512
        // All scores in ascending order.
3513
        let scores: Vec<f64> = topk
1✔
3514
            .iter()
3515
            .filter_map(|r| match table.get_value("score", *r) {
3✔
3516
                Some(Value::Real(f)) => Some(f),
1✔
3517
                _ => None,
×
3518
            })
3519
            .collect();
3520
        assert!(scores.windows(2).all(|w| w[0] <= w[1]));
4✔
3521
    }
3522

3523
    #[test]
3524
    fn topk_k_zero_returns_empty() {
3✔
3525
        let db = seed_score_table(10);
1✔
3526
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3527
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1;");
1✔
3528
        let order = q.order_by.as_ref().unwrap();
2✔
3529
        let topk = select_topk(&table.rowids(), table, order, 0).unwrap();
1✔
3530
        assert!(topk.is_empty());
1✔
3531
    }
3532

3533
    #[test]
3534
    fn topk_empty_input_returns_empty() {
3✔
3535
        let db = seed_score_table(0);
1✔
3536
        let table = db.get_table("docs".to_string()).unwrap();
2✔
3537
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 5;");
1✔
3538
        let order = q.order_by.as_ref().unwrap();
2✔
3539
        let topk = select_topk(&[], table, order, 5).unwrap();
1✔
3540
        assert!(topk.is_empty());
2✔
3541
    }
3542

3543
    #[test]
3544
    fn topk_works_through_select_executor_with_distance_function() {
4✔
3545
        // Integration check that the executor actually picks the
3546
        // bounded-heap path on a KNN-shaped query and produces the
3547
        // correct top-k.
3548
        let mut db = Database::new("tempdb".to_string());
1✔
3549
        crate::sql::process_command(
3550
            "CREATE TABLE docs (id INTEGER PRIMARY KEY, e VECTOR(2));",
3551
            &mut db,
3552
        )
3553
        .unwrap();
3554
        // Five rows with distinct distances from probe [1.0, 0.0]:
3555
        //   id=1 [1.0, 0.0]   distance=0
3556
        //   id=2 [2.0, 0.0]   distance=1
3557
        //   id=3 [0.0, 3.0]   distance=√(1+9) = √10 ≈ 3.16
3558
        //   id=4 [1.0, 4.0]   distance=4
3559
        //   id=5 [10.0, 10.0] distance=√(81+100) ≈ 13.45
3560
        for v in &[
1✔
3561
            "[1.0, 0.0]",
3562
            "[2.0, 0.0]",
3563
            "[0.0, 3.0]",
3564
            "[1.0, 4.0]",
3565
            "[10.0, 10.0]",
3566
        ] {
3567
            crate::sql::process_command(&format!("INSERT INTO docs (e) VALUES ({v});"), &mut db)
3✔
3568
                .unwrap();
3569
        }
3570
        let resp = crate::sql::process_command(
3571
            "SELECT id FROM docs ORDER BY vec_distance_l2(e, [1.0, 0.0]) ASC LIMIT 3;",
3572
            &mut db,
3573
        )
3574
        .unwrap();
3575
        // Top-3 closest to [1.0, 0.0] are id=1, id=2, id=3 (in that order).
3576
        // The status message tells us how many rows came back.
3577
        assert!(resp.contains("3 rows returned"), "got: {resp}");
2✔
3578
    }
3579

3580
    /// Manual benchmark — not run by default. Recommended invocation:
3581
    ///
3582
    ///     cargo test -p sqlrite-engine --lib topk_benchmark --release \
3583
    ///         -- --ignored --nocapture
3584
    ///
3585
    /// (`--release` matters: Rust's optimized sort gets very fast under
3586
    /// optimization, so the heap's relative advantage is best observed
3587
    /// against a sort that's also been optimized.)
3588
    ///
3589
    /// Measured numbers on an Apple Silicon laptop with N=10_000 + k=10:
3590
    ///   - bounded heap:    ~820µs
3591
    ///   - full sort+trunc: ~1.5ms
3592
    ///   - ratio:           ~1.8×
3593
    ///
3594
    /// The advantage is real but moderate at this size because the sort
3595
    /// key here is a single REAL column read (cheap) and Rust's sort_by
3596
    /// has a very low constant factor. The asymptotic O(N log k) vs
3597
    /// O(N log N) advantage scales with N and with per-row work — KNN
3598
    /// queries where the sort key is `vec_distance_l2(col, [...])` are
3599
    /// where this path really pays off, because each key evaluation is
3600
    /// itself O(dim) and the heap path skips the per-row evaluation
3601
    /// in the comparator (see `sort_rowids` for the contrast).
3602
    #[test]
3603
    #[ignore]
3604
    fn topk_benchmark() {
3605
        use std::time::Instant;
3606
        const N: usize = 10_000;
3607
        const K: usize = 10;
3608

3609
        let db = seed_score_table(N);
3610
        let table = db.get_table("docs".to_string()).unwrap();
3611
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
3612
        let order = q.order_by.as_ref().unwrap();
3613
        let all_rowids = table.rowids();
3614

3615
        // Time bounded heap.
3616
        let t0 = Instant::now();
3617
        let _topk = select_topk(&all_rowids, table, order, K).unwrap();
3618
        let heap_dur = t0.elapsed();
3619

3620
        // Time full sort + truncate.
3621
        let t1 = Instant::now();
3622
        let mut full = all_rowids.clone();
3623
        sort_rowids(&mut full, table, order).unwrap();
3624
        full.truncate(K);
3625
        let sort_dur = t1.elapsed();
3626

3627
        let ratio = sort_dur.as_secs_f64() / heap_dur.as_secs_f64().max(1e-9);
3628
        println!("\n--- topk_benchmark (N={N}, k={K}) ---");
3629
        println!("  bounded heap:   {heap_dur:?}");
3630
        println!("  full sort+trunc: {sort_dur:?}");
3631
        println!("  speedup ratio:  {ratio:.2}×");
3632

3633
        // Soft assertion. Floor is 1.4× because the cheap-key
3634
        // benchmark hovers around 1.8× empirically; setting this too
3635
        // close to the measured value risks flaky CI on slower
3636
        // runners. Floor of 1.4× still catches an actual regression
3637
        // (e.g., if select_topk became O(N²) or stopped using the
3638
        // heap entirely).
3639
        assert!(
3640
            ratio > 1.4,
3641
            "bounded heap should be substantially faster than full sort, but ratio = {ratio:.2}"
3642
        );
3643
    }
3644

3645
    // ---------------------------------------------------------------------
3646
    // SQLR-7 — IS NULL / IS NOT NULL
3647
    // ---------------------------------------------------------------------
3648

3649
    /// Helper for IS NULL tests: run a SELECT through process_command and
3650
    /// return the rendered table as a String so the test can assert on the
3651
    /// row-count line without re-implementing the executor.
3652
    fn run_select(db: &mut Database, sql: &str) -> String {
1✔
3653
        crate::sql::process_command(sql, db).expect("select")
1✔
3654
    }
3655

3656
    #[test]
3657
    fn where_is_null_returns_null_rows() {
3✔
3658
        let mut db = Database::new("t".to_string());
1✔
3659
        crate::sql::process_command(
3660
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
3661
            &mut db,
3662
        )
3663
        .unwrap();
3664
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, 10);", &mut db).unwrap();
1✔
3665
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
3666
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
3667
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (4, NULL);", &mut db).unwrap();
1✔
3668

3669
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NULL;");
1✔
3670
        assert!(
×
3671
            response.contains("2 rows returned"),
2✔
3672
            "IS NULL should return 2 rows, got: {response}"
3673
        );
3674
    }
3675

3676
    #[test]
3677
    fn where_is_not_null_returns_non_null_rows() {
3✔
3678
        let mut db = Database::new("t".to_string());
1✔
3679
        crate::sql::process_command(
3680
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
3681
            &mut db,
3682
        )
3683
        .unwrap();
3684
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, 10);", &mut db).unwrap();
1✔
3685
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
3686
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
3687

3688
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NOT NULL;");
1✔
3689
        assert!(
×
3690
            response.contains("2 rows returned"),
2✔
3691
            "IS NOT NULL should return 2 rows, got: {response}"
3692
        );
3693
    }
3694

3695
    #[test]
3696
    fn where_is_null_on_indexed_column() {
3✔
3697
        // UNIQUE on a TEXT column gets an automatic secondary index.
3698
        // NULLs aren't stored in the index, so IS NULL falls through to
3699
        // a full scan via select_rowids — verify the full-scan path is
3700
        // still correct.
3701
        let mut db = Database::new("t".to_string());
1✔
3702
        crate::sql::process_command(
3703
            "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT UNIQUE);",
3704
            &mut db,
3705
        )
3706
        .unwrap();
3707
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (1, 'alice');", &mut db)
1✔
3708
            .unwrap();
3709
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (2, NULL);", &mut db).unwrap();
1✔
3710
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (3, 'bob');", &mut db)
1✔
3711
            .unwrap();
3712

3713
        let null_rows = run_select(&mut db, "SELECT id FROM t WHERE name IS NULL;");
1✔
3714
        assert!(
×
3715
            null_rows.contains("1 row returned"),
2✔
3716
            "indexed IS NULL should return 1 row, got: {null_rows}"
3717
        );
3718
        let not_null_rows = run_select(&mut db, "SELECT id FROM t WHERE name IS NOT NULL;");
1✔
3719
        assert!(
×
3720
            not_null_rows.contains("2 rows returned"),
2✔
3721
            "indexed IS NOT NULL should return 2 rows, got: {not_null_rows}"
3722
        );
3723
    }
3724

3725
    #[test]
3726
    fn where_is_null_works_on_omitted_column() {
3✔
3727
        // No DEFAULT, column missing from the INSERT column list — the
3728
        // BTreeMap entry never gets written, get_value returns None,
3729
        // eval_expr maps that to Value::Null, and IS NULL matches.
3730
        let mut db = Database::new("t".to_string());
1✔
3731
        crate::sql::process_command(
3732
            "CREATE TABLE t (id INTEGER PRIMARY KEY, qty INTEGER, label TEXT);",
3733
            &mut db,
3734
        )
3735
        .unwrap();
3736
        crate::sql::process_command(
3737
            "INSERT INTO t (id, qty, label) VALUES (1, 7, 'a');",
3738
            &mut db,
3739
        )
3740
        .unwrap();
3741
        // qty omitted on row 2.
3742
        crate::sql::process_command("INSERT INTO t (id, label) VALUES (2, 'b');", &mut db).unwrap();
1✔
3743

3744
        let response = run_select(&mut db, "SELECT id FROM t WHERE qty IS NULL;");
1✔
3745
        assert!(
×
3746
            response.contains("1 row returned"),
2✔
3747
            "IS NULL should match the omitted-column row, got: {response}"
3748
        );
3749
    }
3750

3751
    #[test]
3752
    fn where_is_null_combines_with_and_or() {
3✔
3753
        // Sanity check that the new arms compose with the existing
3754
        // boolean operators in eval_expr — `n IS NULL AND id > 1`
3755
        // should narrow correctly.
3756
        let mut db = Database::new("t".to_string());
1✔
3757
        crate::sql::process_command(
3758
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
3759
            &mut db,
3760
        )
3761
        .unwrap();
3762
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, NULL);", &mut db).unwrap();
1✔
3763
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
3764
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
3765

3766
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NULL AND id > 1;");
1✔
3767
        assert!(
×
3768
            response.contains("1 row returned"),
2✔
3769
            "IS NULL combined with AND should match exactly row 2, got: {response}"
3770
        );
3771
    }
3772

3773
    // ---------------------------------------------------------------------
3774
    // SQLR-3 — LIKE / IN / DISTINCT / GROUP BY / aggregates
3775
    // ---------------------------------------------------------------------
3776

3777
    /// Seed a small employees table the analytical tests share.
3778
    fn seed_employees() -> Database {
1✔
3779
        let mut db = Database::new("t".to_string());
1✔
3780
        crate::sql::process_command(
3781
            "CREATE TABLE emp (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER);",
3782
            &mut db,
3783
        )
3784
        .unwrap();
3785
        let rows = [
1✔
3786
            "INSERT INTO emp (name, dept, salary) VALUES ('Alice', 'eng', 100);",
3787
            "INSERT INTO emp (name, dept, salary) VALUES ('alex',  'eng', 120);",
3788
            "INSERT INTO emp (name, dept, salary) VALUES ('Bob',   'eng', 100);",
3789
            "INSERT INTO emp (name, dept, salary) VALUES ('Carol', 'sales', 90);",
3790
            "INSERT INTO emp (name, dept, salary) VALUES ('Dave',  'sales', NULL);",
3791
            "INSERT INTO emp (name, dept, salary) VALUES ('Eve',   'ops', 80);",
3792
        ];
3793
        for sql in rows {
2✔
3794
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
3795
        }
3796
        db
1✔
3797
    }
3798

3799
    /// Drive `execute_select_rows` directly so tests can assert on typed values.
3800
    fn run_rows(db: &Database, sql: &str) -> SelectResult {
1✔
3801
        let q = parse_select(sql);
1✔
3802
        execute_select_rows(q, db).expect("select")
1✔
3803
    }
3804

3805
    // ----- LIKE -----
3806

3807
    #[test]
3808
    fn like_percent_prefix_case_insensitive() {
3✔
3809
        let db = seed_employees();
1✔
3810
        let r = run_rows(&db, "SELECT name FROM emp WHERE name LIKE 'a%';");
1✔
3811
        // Matches Alice and alex (case-insensitive ASCII).
3812
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
3813
        assert_eq!(names.len(), 2, "expected 2 rows, got {names:?}");
2✔
3814
        assert!(names.contains(&"Alice".to_string()));
2✔
3815
        assert!(names.contains(&"alex".to_string()));
1✔
3816
    }
3817

3818
    #[test]
3819
    fn like_underscore_singlechar() {
3✔
3820
        let db = seed_employees();
1✔
3821
        let r = run_rows(&db, "SELECT name FROM emp WHERE name LIKE '_ve';");
1✔
3822
        // Eve matches; alex does not (3 chars vs 4).
3823
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
3824
        assert_eq!(names, vec!["Eve".to_string()]);
2✔
3825
    }
3826

3827
    #[test]
3828
    fn not_like_excludes_match() {
3✔
3829
        let db = seed_employees();
1✔
3830
        let r = run_rows(&db, "SELECT name FROM emp WHERE name NOT LIKE 'a%';");
1✔
3831
        // Excludes Alice + alex; 4 rows remain.
3832
        assert_eq!(r.rows.len(), 4);
2✔
3833
    }
3834

3835
    #[test]
3836
    fn like_with_null_excludes_row() {
3✔
3837
        let db = seed_employees();
1✔
3838
        // Match 'sales' rows where salary is NULL → just Dave.
3839
        let r = run_rows(
3840
            &db,
3841
            "SELECT name FROM emp WHERE dept LIKE 'sales' AND salary IS NULL;",
3842
        );
3843
        assert_eq!(r.rows.len(), 1);
2✔
3844
        assert_eq!(r.rows[0][0].to_display_string(), "Dave");
1✔
3845
    }
3846

3847
    // ----- IN -----
3848

3849
    #[test]
3850
    fn in_list_positive() {
4✔
3851
        let db = seed_employees();
1✔
3852
        let r = run_rows(&db, "SELECT name FROM emp WHERE id IN (1, 3, 5);");
1✔
3853
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
3854
        assert_eq!(names.len(), 3);
2✔
3855
        assert!(names.contains(&"Alice".to_string()));
1✔
3856
        assert!(names.contains(&"Bob".to_string()));
1✔
3857
        assert!(names.contains(&"Dave".to_string()));
1✔
3858
    }
3859

3860
    #[test]
3861
    fn not_in_excludes_listed() {
3✔
3862
        let db = seed_employees();
1✔
3863
        let r = run_rows(&db, "SELECT name FROM emp WHERE id NOT IN (1, 2);");
1✔
3864
        // 6 rows total - 2 excluded = 4.
3865
        assert_eq!(r.rows.len(), 4);
2✔
3866
    }
3867

3868
    #[test]
3869
    fn in_list_with_null_three_valued() {
3✔
3870
        let db = seed_employees();
1✔
3871
        // x = 1 should match; for other rows the NULL in the list yields
3872
        // unknown → false in WHERE → excluded.
3873
        let r = run_rows(&db, "SELECT name FROM emp WHERE id IN (1, NULL);");
1✔
3874
        assert_eq!(r.rows.len(), 1);
2✔
3875
        assert_eq!(r.rows[0][0].to_display_string(), "Alice");
1✔
3876
    }
3877

3878
    // ----- DISTINCT -----
3879

3880
    #[test]
3881
    fn distinct_single_column() {
3✔
3882
        let db = seed_employees();
1✔
3883
        let r = run_rows(&db, "SELECT DISTINCT dept FROM emp;");
1✔
3884
        // 3 distinct depts: eng, sales, ops.
3885
        assert_eq!(r.rows.len(), 3);
2✔
3886
    }
3887

3888
    #[test]
3889
    fn distinct_multi_column_with_null() {
3✔
3890
        let db = seed_employees();
1✔
3891
        // (dept, salary) tuples — the two 'eng' / 100 rows collapse.
3892
        let r = run_rows(&db, "SELECT DISTINCT dept, salary FROM emp;");
1✔
3893
        // 6 input rows; (eng, 100) appears twice → 5 distinct tuples.
3894
        assert_eq!(r.rows.len(), 5);
2✔
3895
    }
3896

3897
    // ----- Aggregates without GROUP BY -----
3898

3899
    #[test]
3900
    fn count_star_no_groupby() {
3✔
3901
        let db = seed_employees();
1✔
3902
        let r = run_rows(&db, "SELECT COUNT(*) FROM emp;");
1✔
3903
        assert_eq!(r.rows.len(), 1);
2✔
3904
        assert_eq!(r.rows[0][0], Value::Integer(6));
1✔
3905
    }
3906

3907
    #[test]
3908
    fn count_col_skips_nulls() {
3✔
3909
        let db = seed_employees();
1✔
3910
        let r = run_rows(&db, "SELECT COUNT(salary) FROM emp;");
1✔
3911
        // 6 rows, 1 NULL salary → COUNT(salary) = 5.
3912
        assert_eq!(r.rows[0][0], Value::Integer(5));
2✔
3913
    }
3914

3915
    #[test]
3916
    fn count_distinct_dedupes_and_skips_nulls() {
3✔
3917
        let db = seed_employees();
1✔
3918
        let r = run_rows(&db, "SELECT COUNT(DISTINCT salary) FROM emp;");
1✔
3919
        // Distinct non-null salaries: {100, 120, 90, 80} → 4.
3920
        assert_eq!(r.rows[0][0], Value::Integer(4));
2✔
3921
    }
3922

3923
    #[test]
3924
    fn sum_int_stays_integer() {
3✔
3925
        let db = seed_employees();
1✔
3926
        let r = run_rows(&db, "SELECT SUM(salary) FROM emp;");
1✔
3927
        // 100 + 120 + 100 + 90 + 80 = 490 (NULL skipped).
3928
        assert_eq!(r.rows[0][0], Value::Integer(490));
2✔
3929
    }
3930

3931
    #[test]
3932
    fn avg_returns_real() {
3✔
3933
        let db = seed_employees();
1✔
3934
        let r = run_rows(&db, "SELECT AVG(salary) FROM emp;");
1✔
3935
        // 490 / 5 = 98.0
3936
        match &r.rows[0][0] {
2✔
3937
            Value::Real(v) => assert!((v - 98.0).abs() < 1e-9),
2✔
3938
            other => panic!("expected Real, got {other:?}"),
×
3939
        }
3940
    }
3941

3942
    #[test]
3943
    fn min_max_skip_nulls() {
3✔
3944
        let db = seed_employees();
1✔
3945
        let r = run_rows(&db, "SELECT MIN(salary), MAX(salary) FROM emp;");
1✔
3946
        assert_eq!(r.rows[0][0], Value::Integer(80));
2✔
3947
        assert_eq!(r.rows[0][1], Value::Integer(120));
1✔
3948
    }
3949

3950
    #[test]
3951
    fn aggregates_on_empty_table_emit_one_row() {
3✔
3952
        let mut db = Database::new("t".to_string());
1✔
3953
        crate::sql::process_command("CREATE TABLE t (x INTEGER);", &mut db).unwrap();
2✔
3954
        let r = run_rows(
3955
            &db,
3956
            "SELECT COUNT(*), SUM(x), AVG(x), MIN(x), MAX(x) FROM t;",
3957
        );
3958
        assert_eq!(r.rows.len(), 1);
2✔
3959
        assert_eq!(r.rows[0][0], Value::Integer(0));
1✔
3960
        assert_eq!(r.rows[0][1], Value::Null);
1✔
3961
        assert_eq!(r.rows[0][2], Value::Null);
1✔
3962
        assert_eq!(r.rows[0][3], Value::Null);
1✔
3963
        assert_eq!(r.rows[0][4], Value::Null);
1✔
3964
    }
3965

3966
    // ----- GROUP BY -----
3967

3968
    #[test]
3969
    fn group_by_single_col_with_count() {
3✔
3970
        let db = seed_employees();
1✔
3971
        let r = run_rows(&db, "SELECT dept, COUNT(*) FROM emp GROUP BY dept;");
1✔
3972
        assert_eq!(r.rows.len(), 3);
2✔
3973
        // Build a map for a stable assertion regardless of group order.
3974
        let mut by_dept: std::collections::HashMap<String, i64> = Default::default();
1✔
3975
        for row in &r.rows {
3✔
3976
            let d = row[0].to_display_string();
2✔
3977
            let c = match &row[1] {
2✔
3978
                Value::Integer(i) => *i,
1✔
3979
                v => panic!("expected Integer count, got {v:?}"),
×
3980
            };
3981
            by_dept.insert(d, c);
1✔
3982
        }
3983
        assert_eq!(by_dept["eng"], 3);
1✔
3984
        assert_eq!(by_dept["sales"], 2);
1✔
3985
        assert_eq!(by_dept["ops"], 1);
1✔
3986
    }
3987

3988
    #[test]
3989
    fn group_by_with_where_filter() {
4✔
3990
        let db = seed_employees();
1✔
3991
        let r = run_rows(
3992
            &db,
3993
            "SELECT dept, SUM(salary) FROM emp WHERE salary > 80 GROUP BY dept;",
3994
        );
3995
        // After WHERE, ops drops out (Eve = 80 excluded). eng has 3 rows
3996
        // contributing (100+120+100=320); sales has 1 (90; Dave NULL skipped).
3997
        let by: std::collections::HashMap<String, i64> = r
1✔
3998
            .rows
3999
            .iter()
4000
            .map(|row| {
2✔
4001
                (
4002
                    row[0].to_display_string(),
1✔
4003
                    match &row[1] {
2✔
4004
                        Value::Integer(i) => *i,
1✔
4005
                        v => panic!("expected Integer sum, got {v:?}"),
×
4006
                    },
4007
                )
4008
            })
4009
            .collect();
4010
        assert_eq!(by.len(), 2);
2✔
4011
        assert_eq!(by["eng"], 320);
1✔
4012
        assert_eq!(by["sales"], 90);
1✔
4013
    }
4014

4015
    #[test]
4016
    fn group_by_without_aggregates_is_distinct() {
3✔
4017
        let db = seed_employees();
1✔
4018
        let r = run_rows(&db, "SELECT dept FROM emp GROUP BY dept;");
1✔
4019
        assert_eq!(r.rows.len(), 3);
2✔
4020
    }
4021

4022
    #[test]
4023
    fn order_by_count_desc() {
3✔
4024
        let db = seed_employees();
1✔
4025
        let r = run_rows(
4026
            &db,
4027
            "SELECT dept, COUNT(*) AS n FROM emp GROUP BY dept ORDER BY n DESC LIMIT 2;",
4028
        );
4029
        assert_eq!(r.rows.len(), 2);
2✔
4030
        // Top group is 'eng' with 3.
4031
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
4032
        assert_eq!(r.rows[0][1], Value::Integer(3));
1✔
4033
    }
4034

4035
    #[test]
4036
    fn order_by_aggregate_call_form() {
3✔
4037
        let db = seed_employees();
1✔
4038
        // No alias — ORDER BY references the aggregate by its display form.
4039
        let r = run_rows(
4040
            &db,
4041
            "SELECT dept, COUNT(*) FROM emp GROUP BY dept ORDER BY COUNT(*) DESC;",
4042
        );
4043
        assert_eq!(r.rows.len(), 3);
2✔
4044
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
4045
    }
4046

4047
    #[test]
4048
    fn group_by_invalid_bare_column_errors() {
3✔
4049
        // `name` is neither aggregated nor in GROUP BY → must error at parse.
4050
        let mut db = Database::new("t".to_string());
1✔
4051
        crate::sql::process_command(
4052
            "CREATE TABLE t (id INTEGER PRIMARY KEY, dept TEXT, name TEXT);",
4053
            &mut db,
4054
        )
4055
        .unwrap();
4056
        let err = crate::sql::process_command("SELECT dept, name FROM t GROUP BY dept;", &mut db);
1✔
4057
        assert!(err.is_err(), "should reject bare 'name' not in GROUP BY");
2✔
4058
    }
4059

4060
    #[test]
4061
    fn aggregate_in_where_errors_friendly() {
3✔
4062
        let mut db = Database::new("t".to_string());
1✔
4063
        crate::sql::process_command("CREATE TABLE t (x INTEGER);", &mut db).unwrap();
2✔
4064
        crate::sql::process_command("INSERT INTO t (x) VALUES (1);", &mut db).unwrap();
1✔
4065
        let err = crate::sql::process_command("SELECT x FROM t WHERE COUNT(*) > 0;", &mut db);
1✔
4066
        assert!(err.is_err(), "aggregates must not be allowed in WHERE");
2✔
4067
    }
4068

4069
    // ---------------------------------------------------------------------
4070
    // SQLR-5 — JOINs (INNER / LEFT OUTER / RIGHT OUTER / FULL OUTER)
4071
    // ---------------------------------------------------------------------
4072

4073
    /// Two-table fixture used across the join tests. `customers` has
4074
    /// (1: Alice, 2: Bob, 3: Carol). `orders` has (id, customer_id,
4075
    /// amount): (1, 1, 100), (2, 1, 200), (3, 2, 50), (4, 4, 999).
4076
    /// Customer 3 (Carol) has no orders; order 4 has no customer
4077
    /// (dangling foreign key) — together they exercise both sides of
4078
    /// the outer-join NULL-padding.
4079
    fn seed_join_fixture() -> Database {
1✔
4080
        let mut db = Database::new("t".to_string());
1✔
4081
        for sql in [
3✔
4082
            "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);",
4083
            "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, amount INTEGER);",
4084
            "INSERT INTO customers (name) VALUES ('Alice');",
4085
            "INSERT INTO customers (name) VALUES ('Bob');",
4086
            "INSERT INTO customers (name) VALUES ('Carol');",
4087
            "INSERT INTO orders (customer_id, amount) VALUES (1, 100);",
4088
            "INSERT INTO orders (customer_id, amount) VALUES (1, 200);",
4089
            "INSERT INTO orders (customer_id, amount) VALUES (2, 50);",
4090
            "INSERT INTO orders (customer_id, amount) VALUES (4, 999);",
4091
        ] {
4092
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4093
        }
4094
        db
1✔
4095
    }
4096

4097
    #[test]
4098
    fn inner_join_returns_only_matched_rows() {
3✔
4099
        let db = seed_join_fixture();
1✔
4100
        let r = run_rows(
4101
            &db,
4102
            "SELECT customers.name, orders.amount FROM customers \
4103
             INNER JOIN orders ON customers.id = orders.customer_id;",
4104
        );
4105
        assert_eq!(r.columns, vec!["name".to_string(), "amount".to_string()]);
2✔
4106
        // Alice: 100, 200; Bob: 50. Carol drops (no orders), order 4 drops
4107
        // (no customer). 3 rows.
4108
        let pairs: Vec<(String, i64)> = r
1✔
4109
            .rows
4110
            .iter()
4111
            .map(|row| {
2✔
4112
                (
4113
                    row[0].to_display_string(),
1✔
4114
                    match row[1] {
2✔
4115
                        Value::Integer(i) => i,
1✔
4116
                        ref v => panic!("expected integer amount, got {v:?}"),
×
4117
                    },
4118
                )
4119
            })
4120
            .collect();
4121
        assert_eq!(pairs.len(), 3);
2✔
4122
        assert!(pairs.contains(&("Alice".to_string(), 100)));
1✔
4123
        assert!(pairs.contains(&("Alice".to_string(), 200)));
1✔
4124
        assert!(pairs.contains(&("Bob".to_string(), 50)));
1✔
4125
    }
4126

4127
    #[test]
4128
    fn bare_join_defaults_to_inner() {
3✔
4129
        let db = seed_join_fixture();
1✔
4130
        let r = run_rows(
4131
            &db,
4132
            "SELECT customers.name FROM customers \
4133
             JOIN orders ON customers.id = orders.customer_id;",
4134
        );
4135
        assert_eq!(r.rows.len(), 3, "JOIN without prefix should be INNER");
2✔
4136
    }
4137

4138
    #[test]
4139
    fn left_outer_join_preserves_unmatched_left() {
3✔
4140
        let db = seed_join_fixture();
1✔
4141
        let r = run_rows(
4142
            &db,
4143
            "SELECT customers.name, orders.amount FROM customers \
4144
             LEFT OUTER JOIN orders ON customers.id = orders.customer_id;",
4145
        );
4146
        // Alice: two rows. Bob: one row. Carol: one NULL-padded row.
4147
        // Order 4 is dropped (left side has no customer for id=4).
4148
        assert_eq!(r.rows.len(), 4);
2✔
4149
        let carol = r
3✔
4150
            .rows
4151
            .iter()
4152
            .find(|row| row[0].to_display_string() == "Carol")
3✔
4153
            .expect("Carol should appear with a NULL-padded right side");
4154
        assert_eq!(carol[1], Value::Null);
1✔
4155
    }
4156

4157
    #[test]
4158
    fn right_outer_join_preserves_unmatched_right() {
3✔
4159
        let db = seed_join_fixture();
1✔
4160
        let r = run_rows(
4161
            &db,
4162
            "SELECT customers.name, orders.amount FROM customers \
4163
             RIGHT OUTER JOIN orders ON customers.id = orders.customer_id;",
4164
        );
4165
        // 3 matched rows + 1 dangling order (id=4, customer_id=4 with no
4166
        // matching customer). Total 4. Carol drops because the right
4167
        // table has no row pointing at her.
4168
        assert_eq!(r.rows.len(), 4);
2✔
4169
        let dangling = r
3✔
4170
            .rows
4171
            .iter()
4172
            .find(|row| matches!(row[1], Value::Integer(999)))
3✔
4173
            .expect("dangling order 999 should appear with a NULL-padded customer name");
4174
        assert_eq!(dangling[0], Value::Null);
1✔
4175
    }
4176

4177
    #[test]
4178
    fn full_outer_join_preserves_both_sides() {
3✔
4179
        let db = seed_join_fixture();
1✔
4180
        let r = run_rows(
4181
            &db,
4182
            "SELECT customers.name, orders.amount FROM customers \
4183
             FULL OUTER JOIN orders ON customers.id = orders.customer_id;",
4184
        );
4185
        // 3 matched + 1 unmatched left (Carol) + 1 unmatched right
4186
        // (order 999) = 5 rows.
4187
        assert_eq!(r.rows.len(), 5);
2✔
4188
        // Carol with NULL amount.
4189
        assert!(
×
4190
            r.rows
3✔
4191
                .iter()
1✔
4192
                .any(|row| row[0].to_display_string() == "Carol" && matches!(row[1], Value::Null))
3✔
4193
        );
4194
        // 999 with NULL name.
4195
        assert!(
×
4196
            r.rows
3✔
4197
                .iter()
1✔
4198
                .any(|row| matches!(row[1], Value::Integer(999)) && matches!(row[0], Value::Null))
3✔
4199
        );
4200
    }
4201

4202
    #[test]
4203
    fn join_with_table_aliases_resolves_qualifiers() {
3✔
4204
        let db = seed_join_fixture();
1✔
4205
        let r = run_rows(
4206
            &db,
4207
            "SELECT c.name, o.amount FROM customers AS c \
4208
             INNER JOIN orders AS o ON c.id = o.customer_id;",
4209
        );
4210
        assert_eq!(r.rows.len(), 3);
2✔
4211
        assert_eq!(r.columns, vec!["name".to_string(), "amount".to_string()]);
1✔
4212
    }
4213

4214
    #[test]
4215
    fn join_with_where_filter_applies_after_join() {
3✔
4216
        let db = seed_join_fixture();
1✔
4217
        // Filter to only orders >= 100. With INNER JOIN, this drops Bob's
4218
        // 50-amount order, leaving Alice's 100 and 200.
4219
        let r = run_rows(
4220
            &db,
4221
            "SELECT customers.name, orders.amount FROM customers \
4222
             INNER JOIN orders ON customers.id = orders.customer_id \
4223
             WHERE orders.amount >= 100;",
4224
        );
4225
        assert_eq!(r.rows.len(), 2);
2✔
4226
        assert!(
×
4227
            r.rows
3✔
4228
                .iter()
1✔
4229
                .all(|row| row[0].to_display_string() == "Alice")
3✔
4230
        );
4231
    }
4232

4233
    #[test]
4234
    fn left_join_with_where_on_right_side_is_not_inner() {
3✔
4235
        // WHERE on the right side that excludes NULL turns LEFT JOIN
4236
        // back into INNER JOIN semantically. Verify the executor
4237
        // applies the WHERE *after* the join padded NULLs in.
4238
        let db = seed_join_fixture();
1✔
4239
        let r = run_rows(
4240
            &db,
4241
            "SELECT customers.name, orders.amount FROM customers \
4242
             LEFT OUTER JOIN orders ON customers.id = orders.customer_id \
4243
             WHERE orders.amount IS NULL;",
4244
        );
4245
        // Only Carol survives — she's the only customer with no order.
4246
        assert_eq!(r.rows.len(), 1);
2✔
4247
        assert_eq!(r.rows[0][0].to_display_string(), "Carol");
1✔
4248
        assert_eq!(r.rows[0][1], Value::Null);
1✔
4249
    }
4250

4251
    #[test]
4252
    fn select_star_over_join_emits_all_columns_from_both_tables() {
3✔
4253
        let db = seed_join_fixture();
1✔
4254
        let r = run_rows(
4255
            &db,
4256
            "SELECT * FROM customers \
4257
             INNER JOIN orders ON customers.id = orders.customer_id;",
4258
        );
4259
        // customers has 2 cols (id, name), orders has 3 cols
4260
        // (id, customer_id, amount). 5 columns total. Header order
4261
        // follows source order — primary table first.
4262
        assert_eq!(
1✔
4263
            r.columns,
4264
            vec![
3✔
4265
                "id".to_string(),
1✔
4266
                "name".to_string(),
1✔
4267
                "id".to_string(),
1✔
4268
                "customer_id".to_string(),
1✔
4269
                "amount".to_string(),
1✔
4270
            ]
4271
        );
4272
        assert_eq!(r.rows.len(), 3);
1✔
4273
    }
4274

4275
    #[test]
4276
    fn join_order_by_sorts_full_joined_rows() {
3✔
4277
        let db = seed_join_fixture();
1✔
4278
        let r = run_rows(
4279
            &db,
4280
            "SELECT c.name, o.amount FROM customers AS c \
4281
             INNER JOIN orders AS o ON c.id = o.customer_id \
4282
             ORDER BY o.amount;",
4283
        );
4284
        let amounts: Vec<i64> = r
1✔
4285
            .rows
4286
            .iter()
4287
            .map(|row| match row[1] {
3✔
4288
                Value::Integer(i) => i,
1✔
4289
                ref v => panic!("expected integer, got {v:?}"),
×
4290
            })
4291
            .collect();
4292
        assert_eq!(amounts, vec![50, 100, 200]);
2✔
4293
    }
4294

4295
    #[test]
4296
    fn join_limit_truncates_after_join_and_sort() {
3✔
4297
        let db = seed_join_fixture();
1✔
4298
        let r = run_rows(
4299
            &db,
4300
            "SELECT c.name, o.amount FROM customers AS c \
4301
             INNER JOIN orders AS o ON c.id = o.customer_id \
4302
             ORDER BY o.amount DESC LIMIT 2;",
4303
        );
4304
        assert_eq!(r.rows.len(), 2);
2✔
4305
        // Top two by amount DESC: 200 (Alice), 100 (Alice).
4306
        let amounts: Vec<i64> = r
1✔
4307
            .rows
4308
            .iter()
4309
            .map(|row| match row[1] {
3✔
4310
                Value::Integer(i) => i,
1✔
4311
                ref v => panic!("expected integer, got {v:?}"),
×
4312
            })
4313
            .collect();
4314
        assert_eq!(amounts, vec![200, 100]);
2✔
4315
    }
4316

4317
    #[test]
4318
    fn three_table_join_chains_correctly() {
3✔
4319
        let mut db = Database::new("t".to_string());
1✔
4320
        for sql in [
3✔
4321
            "CREATE TABLE a (id INTEGER PRIMARY KEY, label TEXT);",
4322
            "CREATE TABLE b (id INTEGER PRIMARY KEY, a_id INTEGER, tag TEXT);",
4323
            "CREATE TABLE c (id INTEGER PRIMARY KEY, b_id INTEGER, note TEXT);",
4324
            "INSERT INTO a (label) VALUES ('a-one');",
4325
            "INSERT INTO a (label) VALUES ('a-two');",
4326
            "INSERT INTO b (a_id, tag) VALUES (1, 'b1');",
4327
            "INSERT INTO b (a_id, tag) VALUES (2, 'b2');",
4328
            "INSERT INTO c (b_id, note) VALUES (1, 'c1');",
4329
        ] {
4330
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4331
        }
4332
        let r = run_rows(
4333
            &db,
4334
            "SELECT a.label, b.tag, c.note FROM a \
4335
             INNER JOIN b ON a.id = b.a_id \
4336
             INNER JOIN c ON b.id = c.b_id;",
4337
        );
4338
        // Only b1 has a c row. So one combined row.
4339
        assert_eq!(r.rows.len(), 1);
2✔
4340
        assert_eq!(r.rows[0][0].to_display_string(), "a-one");
1✔
4341
        assert_eq!(r.rows[0][1].to_display_string(), "b1");
1✔
4342
        assert_eq!(r.rows[0][2].to_display_string(), "c1");
1✔
4343
    }
4344

4345
    #[test]
4346
    fn ambiguous_unqualified_column_in_join_errors() {
3✔
4347
        // Both customers and orders have a column named `id`. An
4348
        // unqualified `id` in the SELECT must error rather than
4349
        // silently picking one side.
4350
        let db = seed_join_fixture();
1✔
4351
        let q = parse_select(
4352
            "SELECT id FROM customers INNER JOIN orders ON customers.id = orders.customer_id;",
4353
        );
4354
        let res = execute_select_rows(q, &db);
1✔
4355
        assert!(res.is_err(), "unqualified ambiguous 'id' should error");
2✔
4356
    }
4357

4358
    #[test]
4359
    fn join_self_without_alias_is_rejected() {
3✔
4360
        let mut db = Database::new("t".to_string());
1✔
4361
        crate::sql::process_command(
4362
            "CREATE TABLE n (id INTEGER PRIMARY KEY, parent INTEGER);",
4363
            &mut db,
4364
        )
4365
        .unwrap();
4366
        let q = parse_select("SELECT n.id FROM n INNER JOIN n ON n.id = n.parent;");
1✔
4367
        let res = execute_select_rows(q, &db);
1✔
4368
        assert!(
×
4369
            res.is_err(),
2✔
4370
            "self-join without an alias should error on duplicate qualifier"
4371
        );
4372
    }
4373

4374
    #[test]
4375
    fn using_or_natural_join_returns_not_implemented() {
3✔
4376
        let mut db = Database::new("t".to_string());
1✔
4377
        crate::sql::process_command("CREATE TABLE a (id INTEGER PRIMARY KEY);", &mut db).unwrap();
2✔
4378
        crate::sql::process_command("CREATE TABLE b (id INTEGER PRIMARY KEY);", &mut db).unwrap();
1✔
4379
        let err = crate::sql::process_command("SELECT * FROM a INNER JOIN b USING (id);", &mut db);
1✔
4380
        assert!(err.is_err(), "USING is not yet supported");
2✔
4381

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

4386
    #[test]
4387
    fn aggregates_over_join_are_rejected() {
3✔
4388
        let db = seed_join_fixture();
1✔
4389
        let err = crate::sql::process_command(
4390
            "SELECT COUNT(*) FROM customers \
4391
             INNER JOIN orders ON customers.id = orders.customer_id;",
4392
            &mut seed_join_fixture(),
1✔
4393
        );
4394
        assert!(err.is_err(), "aggregates over JOIN are not yet supported");
1✔
4395
        let _ = db; // keep compiler happy if unused
4396
    }
4397

4398
    #[test]
4399
    fn left_join_with_no_matches_pads_every_row() {
3✔
4400
        let mut db = Database::new("t".to_string());
1✔
4401
        for sql in [
3✔
4402
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4403
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
4404
            "INSERT INTO a (x) VALUES (1);",
4405
            "INSERT INTO a (x) VALUES (2);",
4406
            "INSERT INTO b (y) VALUES (10);",
4407
        ] {
4408
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4409
        }
4410
        // ON condition matches nothing.
4411
        let r = run_rows(
4412
            &db,
4413
            "SELECT a.x, b.y FROM a LEFT OUTER JOIN b ON a.x = b.y;",
4414
        );
4415
        assert_eq!(r.rows.len(), 2);
2✔
4416
        for row in &r.rows {
1✔
4417
            assert_eq!(row[1], Value::Null);
2✔
4418
        }
4419
    }
4420

4421
    #[test]
4422
    fn left_outer_join_order_by_places_nulls_first() {
3✔
4423
        // NULL ordering matches the engine-wide rule: NULL is Less
4424
        // than every concrete value (see compare_values). So an
4425
        // ORDER BY of a NULL-padded right column puts the
4426
        // outer-join row at the top under ASC.
4427
        let db = seed_join_fixture();
1✔
4428
        let r = run_rows(
4429
            &db,
4430
            "SELECT c.name, o.amount FROM customers AS c \
4431
             LEFT OUTER JOIN orders AS o ON c.id = o.customer_id \
4432
             ORDER BY o.amount ASC;",
4433
        );
4434
        assert_eq!(r.rows.len(), 4);
2✔
4435
        // Carol's NULL amount sorts first.
4436
        assert_eq!(r.rows[0][0].to_display_string(), "Carol");
1✔
4437
        assert_eq!(r.rows[0][1], Value::Null);
1✔
4438
    }
4439

4440
    #[test]
4441
    fn chained_left_outer_join_preserves_left_through_two_levels() {
4✔
4442
        // A LEFT JOIN B LEFT JOIN C — a row in A with no match in B
4443
        // must survive both joins with NULL padding for both sides.
4444
        let mut db = Database::new("t".to_string());
1✔
4445
        for sql in [
3✔
4446
            "CREATE TABLE a (id INTEGER PRIMARY KEY, label TEXT);",
4447
            "CREATE TABLE b (id INTEGER PRIMARY KEY, a_id INTEGER, tag TEXT);",
4448
            "CREATE TABLE c (id INTEGER PRIMARY KEY, b_id INTEGER, note TEXT);",
4449
            "INSERT INTO a (label) VALUES ('a-one');",
4450
            "INSERT INTO a (label) VALUES ('a-two');",
4451
            // b only matches a-one.
4452
            "INSERT INTO b (a_id, tag) VALUES (1, 'b1');",
4453
            // No c rows at all.
4454
        ] {
4455
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4456
        }
4457
        let r = run_rows(
4458
            &db,
4459
            "SELECT a.label, b.tag, c.note FROM a \
4460
             LEFT OUTER JOIN b ON a.id = b.a_id \
4461
             LEFT OUTER JOIN c ON b.id = c.b_id;",
4462
        );
4463
        // Two rows: a-one + b1 with c=NULL, and a-two with b=NULL+c=NULL.
4464
        assert_eq!(r.rows.len(), 2);
2✔
4465
        let by_label: std::collections::HashMap<String, &Vec<Value>> = r
1✔
4466
            .rows
4467
            .iter()
4468
            .map(|row| (row[0].to_display_string(), row))
3✔
4469
            .collect();
4470
        assert_eq!(by_label["a-one"][1].to_display_string(), "b1");
2✔
4471
        assert_eq!(by_label["a-one"][2], Value::Null);
1✔
4472
        assert_eq!(by_label["a-two"][1], Value::Null);
1✔
4473
        assert_eq!(by_label["a-two"][2], Value::Null);
1✔
4474
    }
4475

4476
    #[test]
4477
    fn on_clause_referencing_not_yet_joined_table_errors_clearly() {
3✔
4478
        // ON should only see tables joined so far. Referencing a
4479
        // table that hasn't joined yet is a clean error rather than
4480
        // silently NULL-coalescing into "ON evaluated false".
4481
        let mut db = Database::new("t".to_string());
1✔
4482
        for sql in [
3✔
4483
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4484
            "CREATE TABLE b (id INTEGER PRIMARY KEY, x INTEGER);",
4485
            "CREATE TABLE c (id INTEGER PRIMARY KEY, x INTEGER);",
4486
            "INSERT INTO a (x) VALUES (1);",
4487
            "INSERT INTO b (x) VALUES (1);",
4488
            "INSERT INTO c (x) VALUES (1);",
4489
        ] {
4490
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4491
        }
4492
        let q =
4493
            parse_select("SELECT a.x FROM a INNER JOIN b ON a.x = c.x INNER JOIN c ON b.x = c.x;");
4494
        let res = execute_select_rows(q, &db);
1✔
4495
        assert!(
×
4496
            res.is_err(),
2✔
4497
            "ON referencing not-yet-joined table 'c' should error"
4498
        );
4499
    }
4500

4501
    #[test]
4502
    fn join_on_truthy_integer_is_accepted() {
3✔
4503
        // ON `1` should be treated as true, like WHERE 1. Verifies
4504
        // the executor reuses eval_predicate_scope's truthiness
4505
        // semantic on JOIN conditions.
4506
        let mut db = Database::new("t".to_string());
1✔
4507
        for sql in [
3✔
4508
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4509
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
4510
            "INSERT INTO a (x) VALUES (1);",
4511
            "INSERT INTO a (x) VALUES (2);",
4512
            "INSERT INTO b (y) VALUES (10);",
4513
            "INSERT INTO b (y) VALUES (20);",
4514
        ] {
4515
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4516
        }
4517
        let r = run_rows(&db, "SELECT a.x, b.y FROM a INNER JOIN b ON 1;");
1✔
4518
        // ON 1 is always true → cross product → 2 × 2 = 4 rows.
4519
        assert_eq!(r.rows.len(), 4);
2✔
4520
    }
4521

4522
    #[test]
4523
    fn full_join_on_empty_tables_returns_empty() {
3✔
4524
        let mut db = Database::new("t".to_string());
1✔
4525
        for sql in [
3✔
4526
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
4527
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
4528
        ] {
4529
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4530
        }
4531
        let r = run_rows(
4532
            &db,
4533
            "SELECT a.x, b.y FROM a FULL OUTER JOIN b ON a.x = b.y;",
4534
        );
4535
        assert!(r.rows.is_empty());
2✔
4536
    }
4537
}
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