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

joaoh82 / rust_sqlite / 27271476638

10 Jun 2026 10:57AM UTC coverage: 69.507% (+0.3%) from 69.256%
27271476638

push

github

web-flow
feat(sql): aggregates / GROUP BY / DISTINCT / HAVING over JOIN results (SQLR-6) (#164)

Generalize the SQLR-3 aggregation pipeline from (table, rowid) to the
RowScope trait, so the joined row stream feeds the same accumulator the
single-table path uses:

- aggregate_rows is now generic over an iterator of RowScopes; group
  keys and aggregate args resolve through scope.lookup, so NULL-padded
  outer-join rows group under NULL and COUNT(col) skips their NULLs.
- GROUP BY keys carry an optional t. qualifier (GROUP BY customers.name)
  via the new GroupByKey struct; AggregateArg::Column keeps its
  qualifier too (SUM(orders.amount)).
- The bare-column-must-be-in-GROUP-BY check stays in the parser for
  single-table queries and moves to the executor for joined ones, where
  qualifier resolution needs the schemas (resolve_scope_column).
- SELECT DISTINCT over a join dedupes the projected output rows, with
  LIMIT deferred past the dedupe (mirrors the single-table path).
- HAVING composes over joins through the shared
  lower_having_into_hidden_slots + run_aggregation_pipeline helpers.
- Bonus fix: SELECT * FROM t GROUP BY c used to panic on the
  'validated to be in GROUP BY' expect (parser validation skips
  Projection::All); it now surfaces the standard 'must appear in
  GROUP BY' error.
- Stale 'HAVING is not yet supported' error message and docs updated.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

217 of 239 new or added lines in 3 files covered. (90.79%)

2 existing lines in 1 file now uncovered.

11762 of 16922 relevant lines covered (69.51%)

1.25 hits per line

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

82.42
/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, Ident, 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, AggregateFn, GroupByKey, JoinConstraintKind, JoinType, OrderByClause, Projection,
25
    ProjectionItem, ProjectionKind, SelectQuery, parse_aggregate_call,
26
};
27

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

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

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

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

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

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

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

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

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

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

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

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

196
    // SQLR-10 — `SELECT … FROM sqlrite_master` introspects the catalog.
197
    // The catalog isn't a live entry in `db.tables` (it's materialized at
198
    // save time), so we synthesize a read-only in-memory snapshot on
199
    // demand and run the normal single-table path against it. WHERE /
200
    // projections / ORDER BY / LIMIT all work unchanged. Writes against
201
    // sqlrite_master remain rejected (it never lands in `db.tables`), and
202
    // joins against it are not supported (the joined path doesn't
203
    // synthesize it).
204
    let master_snapshot;
205
    let table: &Table = if query.table_name == crate::sql::pager::MASTER_TABLE_NAME {
3✔
206
        master_snapshot = crate::sql::pager::build_master_table_snapshot(db)?;
2✔
207
        &master_snapshot
1✔
208
    } else {
209
        db.get_table(query.table_name.clone()).map_err(|_| {
5✔
210
            SQLRiteError::Internal(format!("Table '{}' not found", query.table_name))
2✔
211
        })?
212
    };
213

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

274
    let aggregating = has_aggregates || !query.group_by.is_empty();
3✔
275

276
    // SQLR-3: aggregation path. When the SELECT contains aggregates or a
277
    // GROUP BY, the rowid-shaped optimizations (HNSW / FTS / bounded
278
    // heap) don't compose with grouping — every row contributes to its
279
    // group, so we walk the full filtered rowid set, accumulate, then
280
    // sort/truncate the resulting *output rows*.
281
    if aggregating {
1✔
282
        let (all_items, having_expr) = lower_having_into_hidden_slots(&query, &proj_items)?;
2✔
283

284
        // Validate aggregate column args (visible + HAVING-hidden).
285
        for item in &all_items {
2✔
286
            if let ProjectionKind::Aggregate(call) = &item.kind
2✔
287
                && let AggregateArg::Column { name: c, .. } = &call.arg
1✔
288
                && !table.contains_column(c.clone())
1✔
289
            {
290
                return Err(SQLRiteError::Internal(format!(
×
291
                    "{}({}) references unknown column '{c}' on table '{}'",
292
                    call.func.as_str(),
×
293
                    c,
294
                    query.table_name
295
                )));
296
            }
297
        }
298

299
        let scopes = matching.iter().map(|&r| SingleTableScope::new(table, r));
3✔
300
        return run_aggregation_pipeline(scopes, &query, &proj_items, &all_items, &having_expr);
1✔
301
    }
302

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

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

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

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

388
    if query.distinct {
1✔
389
        rows = dedupe_rows(rows);
1✔
390
        if let Some(k) = query.limit {
1✔
391
            rows.truncate(k);
×
392
        }
393
    }
394

395
    Ok(SelectResult { columns, rows })
1✔
396
}
397

398
/// A join constraint resolved against the live table schemas: the
399
/// concrete `ON` predicate to evaluate, plus the columns that
400
/// `SELECT *` should show once (empty for a plain `ON` join, non-empty
401
/// for `USING` / `NATURAL`).
402
struct ResolvedJoin {
403
    on: Expr,
404
    using_columns: Vec<String>,
405
}
406

407
/// Turn a [`JoinConstraintKind`] into the `ON` predicate the nested-loop
408
/// driver evaluates. `tables[..right_pos]` are the tables in scope on
409
/// the left of this join; `tables[right_pos]` is the table being joined.
410
///
411
/// - `On` passes its predicate through unchanged.
412
/// - `Using(cols)` becomes `left.col = right.col` AND-chained over every
413
///   named column. The left qualifier is the first in-scope table that
414
///   actually has the column, so the rewrite is correct for join chains
415
///   (`A JOIN B USING(x) JOIN C USING(x)` resolves both `x`es against
416
///   `A`). A column missing from either side is an error.
417
/// - `Natural` discovers the shared column names first (right table's
418
///   columns that also appear somewhere on the left), then proceeds
419
///   exactly like `Using`. No shared columns ⇒ an always-true predicate,
420
///   i.e. a cross product, matching SQLite.
421
fn resolve_join_constraint(
1✔
422
    constraint: &JoinConstraintKind,
423
    tables: &[JoinedTableRef<'_>],
424
    right_pos: usize,
425
) -> Result<ResolvedJoin> {
426
    match constraint {
1✔
427
        JoinConstraintKind::On(expr) => Ok(ResolvedJoin {
2✔
428
            on: (**expr).clone(),
2✔
429
            using_columns: Vec::new(),
1✔
430
        }),
431
        JoinConstraintKind::Using(cols) => build_using_join(cols, tables, right_pos),
1✔
432
        JoinConstraintKind::Natural => {
433
            // Shared columns = the right table's columns that also exist
434
            // on some left table, preserving the right table's column
435
            // order for determinism.
436
            let shared: Vec<String> = tables[right_pos]
2✔
437
                .table
438
                .column_names()
439
                .into_iter()
440
                .filter(|c| {
2✔
441
                    tables[..right_pos]
1✔
442
                        .iter()
1✔
443
                        .any(|t| t.table.contains_column(c.clone()))
3✔
444
                })
445
                .collect();
446
            build_using_join(&shared, tables, right_pos)
2✔
447
        }
448
    }
449
}
450

451
/// Shared lowering for `USING` and `NATURAL`: synthesize the AND-chain
452
/// of `left.col = right.col` equalities and report the deduplicated
453
/// columns. An empty `cols` (a `NATURAL` join with nothing in common)
454
/// yields an always-true predicate and no dedup, i.e. a cross product.
455
fn build_using_join(
1✔
456
    cols: &[String],
457
    tables: &[JoinedTableRef<'_>],
458
    right_pos: usize,
459
) -> Result<ResolvedJoin> {
460
    let right = &tables[right_pos];
1✔
461
    let mut predicate: Option<Expr> = None;
1✔
462
    for col in cols {
3✔
463
        // The named column must exist on the right side …
464
        if !right.table.contains_column(col.clone()) {
2✔
465
            return Err(SQLRiteError::Internal(format!(
2✔
466
                "cannot join USING column '{col}' — it is not present on table '{}'",
467
                right.scope_name
468
            )));
469
        }
470
        // … and on at least one left-side table. Qualify the left
471
        // reference with whichever table actually has it.
472
        let left = tables[..right_pos]
3✔
473
            .iter()
1✔
474
            .find(|t| t.table.contains_column(col.clone()))
3✔
475
            .ok_or_else(|| {
1✔
476
                SQLRiteError::Internal(format!(
×
477
                    "cannot join USING column '{col}' — it is not present on any left-side table"
478
                ))
479
            })?;
480
        let eq = col_eq(&left.scope_name, &right.scope_name, col);
1✔
481
        predicate = Some(match predicate {
2✔
482
            None => eq,
1✔
483
            Some(prev) => Expr::BinaryOp {
2✔
484
                left: Box::new(prev),
2✔
485
                op: BinaryOperator::And,
1✔
486
                right: Box::new(eq),
1✔
487
            },
488
        });
489
    }
490
    Ok(ResolvedJoin {
1✔
491
        on: predicate
1✔
492
            .unwrap_or_else(|| Expr::Value(sqlparser::ast::Value::Boolean(true).with_empty_span())),
3✔
493
        using_columns: cols.to_vec(),
1✔
494
    })
495
}
496

497
/// Build the `left_scope.col = right_scope.col` equality used to lower
498
/// `USING` / `NATURAL` joins onto the existing `ON` evaluation path.
499
fn col_eq(left_scope: &str, right_scope: &str, col: &str) -> Expr {
2✔
500
    let col_ref = |scope: &str| {
2✔
501
        Expr::CompoundIdentifier(vec![
2✔
502
            Ident::new(scope.to_string()),
2✔
503
            Ident::new(col.to_string()),
2✔
504
        ])
505
    };
506
    Expr::BinaryOp {
507
        left: Box::new(col_ref(left_scope)),
1✔
508
        op: BinaryOperator::Eq,
509
        right: Box::new(col_ref(right_scope)),
2✔
510
    }
511
}
512

513
// -----------------------------------------------------------------
514
// SQLR-5 — Joined SELECT execution
515
// -----------------------------------------------------------------
516
//
517
// The strategy is a left-folded nested-loop join: start with the
518
// rowids of the leading FROM table, then for each JOIN clause
519
// combine the accumulator (`Vec<Vec<Option<i64>>>`) with the rowids
520
// of the next table. Each join flavor differs only in how it
521
// handles unmatched left / right rows:
522
//
523
//   INNER       — drop unmatched on both sides
524
//   LEFT OUTER  — keep every left row; pad right side with NULL
525
//   RIGHT OUTER — keep every right row; pad left side with NULL
526
//   FULL OUTER  — keep both unmatched sets, NULL-padding the other
527
//
528
// This isn't a hash join — every join is O(N×M) in the size of the
529
// accumulator and the right table. Adequate for SQLRite's "embedded
530
// learning database" niche; a future phase could layer hash / merge
531
// joins on equi-join shapes without changing the surface API.
532
//
533
// SQLR-6 — aggregates / GROUP BY / DISTINCT compose with joins: the
534
// fully-joined row stream feeds the same scope-generic aggregation
535
// pipeline the single-table path uses (Stage 3.5 below), and DISTINCT
536
// dedupes the projected output rows.
537
fn execute_select_rows_joined(query: SelectQuery, db: &Database) -> Result<SelectResult> {
2✔
538
    // Resolve every participating table once and capture its scope
539
    // name (alias if supplied, else table name). Scope names are
540
    // case-sensitive in matching the original identifier text;
541
    // qualifier matches in `JoinedScope::lookup` use
542
    // `eq_ignore_ascii_case` so `T1.c1` works whether the user
543
    // wrote `T1`, `t1`, or `T1` differently than the alias.
544
    let mut joined_tables: Vec<JoinedTableRef<'_>> = Vec::with_capacity(1 + query.joins.len());
2✔
545

546
    let primary = db
1✔
547
        .get_table(query.table_name.clone())
2✔
548
        .map_err(|_| SQLRiteError::Internal(format!("Table '{}' not found", query.table_name)))?;
1✔
549
    joined_tables.push(JoinedTableRef {
1✔
550
        table: primary,
551
        scope_name: query
1✔
552
            .table_alias
553
            .clone()
1✔
554
            .unwrap_or_else(|| query.table_name.clone()),
3✔
555
    });
556
    for j in &query.joins {
1✔
557
        let t = db
1✔
558
            .get_table(j.right_table.clone())
2✔
559
            .map_err(|_| SQLRiteError::Internal(format!("Table '{}' not found", j.right_table)))?;
1✔
560
        joined_tables.push(JoinedTableRef {
1✔
561
            table: t,
562
            scope_name: j
1✔
563
                .right_alias
564
                .clone()
1✔
565
                .unwrap_or_else(|| j.right_table.clone()),
3✔
566
        });
567
    }
568

569
    // Reject duplicate scope names — `FROM t JOIN t ON ...` without
570
    // an alias on one side would silently collapse qualifiers and
571
    // produce confusing results. Forcing the user to alias one side
572
    // keeps `t1.col` / `t2.col` unambiguous.
573
    {
574
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
1✔
575
        for t in &joined_tables {
2✔
576
            let key = t.scope_name.to_ascii_lowercase();
2✔
577
            if !seen.insert(key) {
1✔
578
                return Err(SQLRiteError::Internal(format!(
1✔
579
                    "duplicate table reference '{}' in FROM/JOIN — use AS to alias one side",
580
                    t.scope_name
581
                )));
582
            }
583
        }
584
    }
585

586
    // Resolve each join's match constraint into a concrete ON predicate
587
    // (plus, for USING / NATURAL, the set of columns that `SELECT *`
588
    // shows once). This is done here rather than at parse time because
589
    // USING needs to know which side each named column lives on, and
590
    // NATURAL needs the schemas to discover the shared columns at all —
591
    // neither is available to the parser. `resolved[i]` lines up with
592
    // `query.joins[i]` (i.e. `joined_tables[i + 1]`).
593
    let resolved: Vec<ResolvedJoin> = query
4✔
594
        .joins
595
        .iter()
1✔
596
        .enumerate()
1✔
597
        .map(|(j_idx, join)| resolve_join_constraint(&join.constraint, &joined_tables, j_idx + 1))
3✔
598
        .collect::<Result<Vec<_>>>()?;
2✔
599

600
    // Validate qualified projection column references against the
601
    // table they qualify. Unqualified names are validated by the
602
    // first scope lookup at row materialization — the runtime check
603
    // there gives the same "ambiguous / unknown" message we'd want
604
    // here, so we don't pre-resolve them.
605
    let proj_items: Vec<ProjectionItem> = match &query.projection {
1✔
606
        Projection::All => {
607
            // `SELECT *` over a join expands to every column of every
608
            // in-scope table, in source order. We use the bare column
609
            // name as both the projected identifier and the output
610
            // header — qualified expansion (`t1.col`) would force
611
            // composite headers like `t1.col` which conflict with
612
            // alias-less convention. Duplicate header names are
613
            // permitted (matches SQLite); callers needing
614
            // disambiguation can `SELECT t.col AS t_col`.
615
            //
616
            // USING / NATURAL columns are the exception: SQLite shows a
617
            // joined-on column once, taking the left side's copy and
618
            // omitting the right side's. We honor that by skipping any
619
            // column listed in the right table's `using_columns` when we
620
            // reach that table during expansion. (The left copy was
621
            // already emitted by an earlier table.)
622
            let mut all = Vec::new();
1✔
623
            for (t_idx, t) in joined_tables.iter().enumerate() {
2✔
624
                // `t_idx == 0` is the primary table (no incoming join);
625
                // every later table corresponds to `resolved[t_idx - 1]`.
626
                let dedup: &[String] = t_idx
1✔
627
                    .checked_sub(1)
628
                    .map(|r| resolved[r].using_columns.as_slice())
3✔
629
                    .unwrap_or(&[]);
1✔
630
                for col in t.table.column_names() {
3✔
631
                    if dedup.contains(&col) {
2✔
632
                        continue;
633
                    }
634
                    all.push(ProjectionItem {
1✔
635
                        kind: ProjectionKind::Column {
1✔
636
                            // Qualify the synthetic items so duplicate
637
                            // column names across tables route to the
638
                            // right side at projection time. The output
639
                            // header still uses the bare `name`.
640
                            qualifier: Some(t.scope_name.clone()),
2✔
641
                            name: col,
1✔
642
                        },
643
                        alias: None,
1✔
644
                    });
645
                }
646
            }
647
            all
1✔
648
        }
649
        Projection::Items(items) => items.clone(),
2✔
650
    };
651

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

654
    // Stage 1: enumerate rows of the leading table. The accumulator
655
    // is `Vec<Vec<Option<i64>>>` where each inner `Vec` is a join
656
    // row whose i-th slot is the rowid of `joined_tables[i]` (or
657
    // None for a NULL-padded row from an outer join).
658
    let mut acc: Vec<Vec<Option<i64>>> = primary
659
        .rowids()
660
        .into_iter()
661
        .map(|r| {
3✔
662
            let mut row = Vec::with_capacity(joined_tables.len());
1✔
663
            row.push(Some(r));
1✔
664
            row
1✔
665
        })
666
        .collect();
667

668
    // Stage 2: fold each JOIN clause into the accumulator. After
669
    // join `i`, every row in `acc` has length `i + 2` (primary +
670
    // i+1 right tables joined). Unmatched-side handling depends on
671
    // the join flavor.
672
    for (j_idx, join) in query.joins.iter().enumerate() {
2✔
673
        let right_pos = j_idx + 1;
2✔
674
        let right_table = joined_tables[right_pos].table;
2✔
675
        let right_rowids: Vec<i64> = right_table.rowids();
1✔
676

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

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

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

693
        for left_row in acc.into_iter() {
3✔
694
            // Build a row prefix and extend it with each candidate
695
            // right rowid; record whether any matched (for outer
696
            // padding on the left side).
697
            let mut left_match_count = 0usize;
1✔
698
            for (r_idx, &rrid) in right_rowids.iter().enumerate() {
3✔
699
                let mut on_rowids: Vec<Option<i64>> = left_row.clone();
2✔
700
                on_rowids.push(Some(rrid));
1✔
701
                debug_assert_eq!(on_rowids.len(), on_scope_tables.len());
1✔
702
                let scope = JoinedScope {
703
                    tables: on_scope_tables,
704
                    rowids: &on_rowids,
1✔
705
                };
706
                // Reuse `eval_predicate_scope` so ON shares the same
707
                // truthiness rule WHERE uses — non-zero integers are
708
                // truthy, NULL is false, etc. — instead of rejecting
709
                // anything that isn't a literal bool. `resolved[j_idx].on`
710
                // is the user's ON expr, or the equality we synthesized
711
                // for USING / NATURAL.
712
                if eval_predicate_scope(&resolved[j_idx].on, &scope)? {
1✔
713
                    left_match_count += 1;
1✔
714
                    right_matched[r_idx] = true;
2✔
715
                    // Accumulator entries carry only as many slots
716
                    // as join levels processed so far; the next
717
                    // iteration extends them again. No trailing
718
                    // padding needed here.
719
                    next_acc.push(on_rowids);
1✔
720
                }
721
            }
722

723
            if left_match_count == 0
2✔
724
                && matches!(join.join_type, JoinType::LeftOuter | JoinType::FullOuter)
1✔
725
            {
726
                // Outer-join NULL pad on the right side: keep the
727
                // left row, push None for the right rowid.
728
                let mut padded = left_row;
1✔
729
                padded.push(None);
1✔
730
                next_acc.push(padded);
1✔
731
            }
732
        }
733

734
        // Right-only emission for RIGHT / FULL: any right rowid that
735
        // never matched on the entire accumulator surfaces with all
736
        // left positions NULL-padded.
737
        if matches!(join.join_type, JoinType::RightOuter | JoinType::FullOuter) {
1✔
738
            for (r_idx, matched) in right_matched.iter().enumerate() {
2✔
739
                if *matched {
1✔
740
                    continue;
741
                }
742
                let mut row: Vec<Option<i64>> = vec![None; right_pos];
1✔
743
                row.push(Some(right_rowids[r_idx]));
2✔
744
                next_acc.push(row);
1✔
745
            }
746
        }
747

748
        acc = next_acc;
1✔
749
    }
750

751
    // Stage 3: apply WHERE on each fully-joined row. Outer-join
752
    // NULL-padded rows where WHERE references a NULL'd column will
753
    // (per SQL three-valued logic) be excluded — this is the same
754
    // posture as the single-table path.
755
    let mut filtered: Vec<Vec<Option<i64>>> = if let Some(where_expr) = &query.selection {
2✔
756
        let mut out = Vec::with_capacity(acc.len());
2✔
757
        for row in acc {
4✔
758
            let scope = JoinedScope {
759
                tables: &joined_tables,
1✔
760
                rowids: &row,
1✔
761
            };
762
            if eval_predicate_scope(where_expr, &scope)? {
1✔
763
                out.push(row);
1✔
764
            }
765
        }
766
        out
1✔
767
    } else {
768
        acc
1✔
769
    };
770

771
    // Stage 3.5 — SQLR-6: aggregation over the joined row stream. The
772
    // fully-joined, WHERE-filtered rows are just another row source
773
    // for the shared grouping accumulator: each joined row becomes a
774
    // `JoinedScope` and feeds the same pipeline the single-table path
775
    // uses (grouping, HAVING, DISTINCT, output-row ORDER BY, LIMIT).
776
    // NULL-padded outer-join rows group under a NULL key and are
777
    // skipped by `COUNT(col)` like any other NULL.
778
    let has_aggregates = proj_items
3✔
779
        .iter()
780
        .any(|i| matches!(i.kind, ProjectionKind::Aggregate(_)));
3✔
781
    if has_aggregates || !query.group_by.is_empty() {
2✔
782
        let (all_items, having_expr) = lower_having_into_hidden_slots(&query, &proj_items)?;
2✔
783

784
        // Validate every column reference against the joined scope up
785
        // front: GROUP BY keys and aggregate args must resolve to
786
        // exactly one in-scope table, and every bare projection column
787
        // must resolve to the same table+column as some GROUP BY key
788
        // (the joined-scope equivalent of the parser's single-table
789
        // "must appear in GROUP BY" check).
790
        for g in &query.group_by {
3✔
791
            resolve_scope_column(&joined_tables, g.qualifier.as_deref(), &g.name)?;
3✔
792
        }
793
        for item in &all_items {
1✔
794
            match &item.kind {
1✔
795
                ProjectionKind::Aggregate(call) => {
1✔
796
                    if let AggregateArg::Column { qualifier, name } = &call.arg {
3✔
797
                        resolve_scope_column(&joined_tables, qualifier.as_deref(), name)?;
1✔
798
                    }
799
                }
800
                ProjectionKind::Column { qualifier, name } => {
1✔
801
                    let pos = resolve_scope_column(&joined_tables, qualifier.as_deref(), name)?;
1✔
802
                    let in_group_by = query.group_by.iter().any(|g| {
2✔
803
                        g.name == *name
1✔
804
                            && resolve_scope_column(&joined_tables, g.qualifier.as_deref(), &g.name)
3✔
805
                                == Ok(pos)
2✔
806
                    });
807
                    if !in_group_by {
1✔
808
                        return Err(SQLRiteError::Internal(format!(
1✔
809
                            "column '{name}' must appear in GROUP BY or be used in an \
810
                             aggregate function"
811
                        )));
812
                    }
813
                }
814
            }
815
        }
816

817
        let scopes = filtered.iter().map(|row| JoinedScope {
3✔
818
            tables: &joined_tables,
1✔
819
            rowids: row,
1✔
820
        });
821
        return run_aggregation_pipeline(scopes, &query, &proj_items, &all_items, &having_expr);
1✔
822
    }
823

824
    // Stage 4: ORDER BY across the joined scope. We pre-compute the
825
    // sort key per row (same approach as `sort_rowids`) so the
826
    // comparator runs on Values, not against the expression tree.
827
    if let Some(order) = &query.order_by {
2✔
828
        // Validate up front so a bad ORDER BY surfaces a clear
829
        // error before sort starts.
830
        let mut keys: Vec<(usize, Value)> = Vec::with_capacity(filtered.len());
2✔
831
        for (i, row) in filtered.iter().enumerate() {
3✔
832
            let scope = JoinedScope {
833
                tables: &joined_tables,
1✔
834
                rowids: row,
835
            };
836
            let v = eval_expr_scope(&order.expr, &scope)?;
1✔
837
            keys.push((i, v));
1✔
838
        }
839
        keys.sort_by(|(_, a), (_, b)| {
3✔
840
            let ord = compare_values(Some(a), Some(b));
1✔
841
            if order.ascending { ord } else { ord.reverse() }
1✔
842
        });
843
        let mut sorted = Vec::with_capacity(filtered.len());
1✔
844
        for (i, _) in keys {
3✔
845
            sorted.push(filtered[i].clone());
2✔
846
        }
847
        filtered = sorted;
1✔
848
    }
849

850
    // Stage 5: LIMIT. SQLR-6 — when DISTINCT is on, truncating the
851
    // joined rows here would over-truncate (duplicates collapse later),
852
    // so the limit is deferred past the dedupe step, mirroring the
853
    // single-table path.
854
    if let Some(k) = query.limit
2✔
855
        && !query.distinct
1✔
856
    {
857
        filtered.truncate(k);
1✔
858
    }
859

860
    // Stage 6: project. For each row, evaluate every projection item
861
    // through the joined scope.
862
    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(filtered.len());
2✔
863
    for row in &filtered {
3✔
864
        let scope = JoinedScope {
865
            tables: &joined_tables,
1✔
866
            rowids: row,
867
        };
868
        let mut out_row = Vec::with_capacity(proj_items.len());
1✔
869
        for item in &proj_items {
2✔
870
            let v = match &item.kind {
1✔
871
                ProjectionKind::Column { qualifier, name } => {
1✔
872
                    scope.lookup(qualifier.as_deref(), name)?
2✔
873
                }
874
                ProjectionKind::Aggregate(_) => {
875
                    // Aggregates are handled by the Stage 3.5 pipeline,
876
                    // which returns before reaching this projection —
877
                    // defense in depth keeps the pattern match total.
878
                    return Err(SQLRiteError::Internal(
×
NEW
879
                        "aggregate projection reached the non-aggregating join path".to_string(),
×
880
                    ));
881
                }
882
            };
883
            out_row.push(v);
1✔
884
        }
885
        rows.push(out_row);
1✔
886
    }
887

888
    // SQLR-6 — SELECT DISTINCT over a join: dedupe the projected
889
    // output rows, then apply the LIMIT that Stage 5 deferred.
890
    if query.distinct {
1✔
891
        rows = dedupe_rows(rows);
1✔
892
        if let Some(k) = query.limit {
1✔
893
            rows.truncate(k);
1✔
894
        }
895
    }
896

897
    Ok(SelectResult { columns, rows })
1✔
898
}
899

900
/// Resolve an optionally-qualified column reference to the index of
901
/// the in-scope joined table that owns it. Schema-only counterpart of
902
/// [`JoinedScope::lookup`]: a qualified reference must name a known
903
/// scope and the column must exist there; an unqualified reference
904
/// must exist on exactly one in-scope table (zero → unknown column,
905
/// several → ambiguous).
906
fn resolve_scope_column(
1✔
907
    tables: &[JoinedTableRef<'_>],
908
    qualifier: Option<&str>,
909
    name: &str,
910
) -> Result<usize> {
911
    if let Some(q) = qualifier {
1✔
912
        let pos = tables
1✔
913
            .iter()
1✔
914
            .position(|t| t.scope_name.eq_ignore_ascii_case(q))
3✔
915
            .ok_or_else(|| {
1✔
NEW
916
                SQLRiteError::Internal(format!(
×
917
                    "unknown table qualifier '{q}' in column reference '{q}.{name}'"
918
                ))
919
            })?;
920
        if !tables[pos].table.contains_column(name.to_string()) {
1✔
NEW
921
            return Err(SQLRiteError::Internal(format!(
×
922
                "column '{name}' does not exist on '{}'",
NEW
923
                tables[pos].scope_name
×
924
            )));
925
        }
926
        return Ok(pos);
1✔
927
    }
928
    let mut hit: Option<usize> = None;
1✔
929
    for (i, t) in tables.iter().enumerate() {
2✔
930
        if t.table.contains_column(name.to_string()) {
2✔
931
            if hit.is_some() {
1✔
932
                return Err(SQLRiteError::Internal(format!(
1✔
933
                    "column reference '{name}' is ambiguous — qualify it as <table>.{name}"
934
                )));
935
            }
936
            hit = Some(i);
1✔
937
        }
938
    }
NEW
939
    hit.ok_or_else(|| {
×
NEW
940
        SQLRiteError::Internal(format!(
×
941
            "unknown column '{name}' in joined SELECT (no in-scope table has it)"
942
        ))
943
    })
944
}
945

946
/// Executes a SELECT and returns `(rendered_table, row_count)`. The
947
/// REPL and Tauri app use this to keep the table-printing behaviour
948
/// the engine has always shipped. Structured callers use
949
/// `execute_select_rows` instead.
950
pub fn execute_select(query: SelectQuery, db: &Database) -> Result<(String, usize)> {
1✔
951
    let result = execute_select_rows(query, db)?;
1✔
952
    let row_count = result.rows.len();
2✔
953

954
    let mut print_table = PrintTable::new();
1✔
955
    let header_cells: Vec<PrintCell> = result.columns.iter().map(|c| PrintCell::new(c)).collect();
4✔
956
    print_table.add_row(PrintRow::new(header_cells));
1✔
957

958
    for row in &result.rows {
1✔
959
        let cells: Vec<PrintCell> = row
1✔
960
            .iter()
961
            .map(|v| PrintCell::new(&v.to_display_string()))
3✔
962
            .collect();
963
        print_table.add_row(PrintRow::new(cells));
1✔
964
    }
965

966
    Ok((print_table.to_string(), row_count))
1✔
967
}
968

969
/// Executes a DELETE statement. Returns the number of rows removed.
970
pub fn execute_delete(stmt: &Statement, db: &mut Database) -> Result<usize> {
1✔
971
    let Statement::Delete(Delete {
1✔
972
        from, selection, ..
1✔
973
    }) = stmt
1✔
974
    else {
975
        return Err(SQLRiteError::Internal(
×
976
            "execute_delete called on a non-DELETE statement".to_string(),
×
977
        ));
978
    };
979

980
    let tables = match from {
1✔
981
        FromTable::WithFromKeyword(t) | FromTable::WithoutKeyword(t) => t,
2✔
982
    };
983
    let table_name = extract_single_table_name(tables)?;
1✔
984

985
    // Compute matching rowids with an immutable borrow, then mutate.
986
    let matching: Vec<i64> = {
987
        let table = db
1✔
988
            .get_table(table_name.clone())
2✔
989
            .map_err(|_| SQLRiteError::Internal(format!("Table '{table_name}' not found")))?;
1✔
990
        match select_rowids(table, selection.as_ref())? {
1✔
991
            RowidSource::IndexProbe(rowids) => rowids,
1✔
992
            RowidSource::FullScan => {
993
                let mut out = Vec::new();
1✔
994
                for rowid in table.rowids() {
3✔
995
                    if let Some(expr) = selection {
2✔
996
                        if !eval_predicate(expr, table, rowid)? {
2✔
997
                            continue;
998
                        }
999
                    }
1000
                    out.push(rowid);
2✔
1001
                }
1002
                out
1✔
1003
            }
1004
        }
1005
    };
1006

1007
    let table = db.get_table_mut(table_name)?;
2✔
1008
    for rowid in &matching {
1✔
1009
        table.delete_row(*rowid);
2✔
1010
    }
1011
    // Phase 7d.3 — any DELETE invalidates every HNSW index on this
1012
    // table (the deleted node could still appear in other nodes'
1013
    // neighbor lists, breaking subsequent searches). Mark dirty so
1014
    // the next save rebuilds from current rows before serializing.
1015
    //
1016
    // Phase 8b — same posture for FTS indexes (Q7 — rebuild-on-save
1017
    // mirrors HNSW). The deleted rowid still appears in posting
1018
    // lists; leaving it would surface zombie hits in future queries.
1019
    if !matching.is_empty() {
1✔
1020
        for entry in &mut table.hnsw_indexes {
3✔
1021
            entry.needs_rebuild = true;
1✔
1022
        }
1023
        for entry in &mut table.fts_indexes {
2✔
1024
            entry.needs_rebuild = true;
1✔
1025
        }
1026
    }
1027
    Ok(matching.len())
2✔
1028
}
1029

1030
/// Executes an UPDATE statement. Returns the number of rows updated.
1031
pub fn execute_update(stmt: &Statement, db: &mut Database) -> Result<usize> {
1✔
1032
    let Statement::Update(Update {
1✔
1033
        table,
1✔
1034
        assignments,
1✔
1035
        from,
1✔
1036
        selection,
1✔
1037
        ..
1038
    }) = stmt
1✔
1039
    else {
1040
        return Err(SQLRiteError::Internal(
×
1041
            "execute_update called on a non-UPDATE statement".to_string(),
×
1042
        ));
1043
    };
1044

1045
    if from.is_some() {
1✔
1046
        return Err(SQLRiteError::NotImplemented(
×
1047
            "UPDATE ... FROM is not supported yet".to_string(),
×
1048
        ));
1049
    }
1050

1051
    let table_name = extract_table_name(table)?;
1✔
1052

1053
    // Resolve assignment targets to plain column names and verify they exist.
1054
    let mut parsed_assignments: Vec<(String, Expr)> = Vec::with_capacity(assignments.len());
2✔
1055
    {
1056
        let tbl = db
1✔
1057
            .get_table(table_name.clone())
2✔
1058
            .map_err(|_| SQLRiteError::Internal(format!("Table '{table_name}' not found")))?;
1✔
1059
        for a in assignments {
2✔
1060
            let col = match &a.target {
1✔
1061
                AssignmentTarget::ColumnName(name) => name
2✔
1062
                    .0
1063
                    .last()
1✔
1064
                    .map(|p| p.to_string())
3✔
1065
                    .ok_or_else(|| SQLRiteError::Internal("empty column name".to_string()))?,
1✔
1066
                AssignmentTarget::Tuple(_) => {
1067
                    return Err(SQLRiteError::NotImplemented(
×
1068
                        "tuple assignment targets are not supported".to_string(),
×
1069
                    ));
1070
                }
1071
            };
1072
            if !tbl.contains_column(col.clone()) {
2✔
1073
                return Err(SQLRiteError::Internal(format!(
×
1074
                    "UPDATE references unknown column '{col}'"
1075
                )));
1076
            }
1077
            parsed_assignments.push((col, a.value.clone()));
1✔
1078
        }
1079
    }
1080

1081
    // Gather matching rowids + the new values to write for each assignment, under
1082
    // an immutable borrow. Uses the index-probe fast path when the WHERE is
1083
    // `col = literal` on an indexed column.
1084
    let work: Vec<(i64, Vec<(String, Value)>)> = {
1085
        let tbl = db.get_table(table_name.clone())?;
1✔
1086
        let matched_rowids: Vec<i64> = match select_rowids(tbl, selection.as_ref())? {
1✔
1087
            RowidSource::IndexProbe(rowids) => rowids,
1✔
1088
            RowidSource::FullScan => {
1089
                let mut out = Vec::new();
1✔
1090
                for rowid in tbl.rowids() {
3✔
1091
                    if let Some(expr) = selection {
2✔
1092
                        if !eval_predicate(expr, tbl, rowid)? {
2✔
1093
                            continue;
1094
                        }
1095
                    }
1096
                    out.push(rowid);
2✔
1097
                }
1098
                out
1✔
1099
            }
1100
        };
1101
        let mut rows_to_update = Vec::new();
1✔
1102
        for rowid in matched_rowids {
4✔
1103
            let mut values = Vec::with_capacity(parsed_assignments.len());
2✔
1104
            for (col, expr) in &parsed_assignments {
3✔
1105
                // UPDATE's RHS is evaluated in the context of the row being updated,
1106
                // so column references on the right resolve to the current row's values.
1107
                let v = eval_expr(expr, tbl, rowid)?;
2✔
1108
                values.push((col.clone(), v));
2✔
1109
            }
1110
            rows_to_update.push((rowid, values));
1✔
1111
        }
1112
        rows_to_update
1✔
1113
    };
1114

1115
    let tbl = db.get_table_mut(table_name)?;
2✔
1116
    for (rowid, values) in &work {
1✔
1117
        for (col, v) in values {
2✔
1118
            tbl.set_value(col, *rowid, v.clone())?;
1✔
1119
        }
1120
    }
1121

1122
    // Phase 7d.3 — UPDATE may have changed a vector column that an
1123
    // HNSW index covers. Mark every covering index dirty so save
1124
    // rebuilds from current rows. (Updates that only touched
1125
    // non-vector columns also mark dirty, which is over-conservative
1126
    // but harmless — the rebuild walks rows anyway, and the cost is
1127
    // only paid on save.)
1128
    //
1129
    // Phase 8b — same shape for FTS indexes covering updated TEXT cols.
1130
    if !work.is_empty() {
1✔
1131
        let updated_columns: std::collections::HashSet<&str> = work
1✔
1132
            .iter()
1133
            .flat_map(|(_, values)| values.iter().map(|(c, _)| c.as_str()))
5✔
1134
            .collect();
1135
        for entry in &mut tbl.hnsw_indexes {
2✔
1136
            if updated_columns.contains(entry.column_name.as_str()) {
3✔
1137
                entry.needs_rebuild = true;
1✔
1138
            }
1139
        }
1140
        for entry in &mut tbl.fts_indexes {
1✔
1141
            if updated_columns.contains(entry.column_name.as_str()) {
3✔
1142
                entry.needs_rebuild = true;
1✔
1143
            }
1144
        }
1145
    }
1146
    Ok(work.len())
2✔
1147
}
1148

1149
/// Handles `CREATE INDEX [UNIQUE] <name> ON <table> [USING <method>] (<column>)`.
1150
/// Single-column indexes only.
1151
///
1152
/// Two flavours, branching on the optional `USING <method>` clause:
1153
///   - **No USING, or `USING btree`**: regular B-Tree secondary index
1154
///     (Phase 3e). Indexable types: Integer, Text.
1155
///   - **`USING hnsw`**: HNSW ANN index (Phase 7d.2). Indexable types:
1156
///     Vector(N) only. Distance metric is L2 by default; cosine and
1157
///     dot variants are deferred to Phase 7d.x.
1158
///
1159
/// Returns the (possibly synthesized) index name for the status message.
1160
pub fn execute_create_index(stmt: &Statement, db: &mut Database) -> Result<String> {
1✔
1161
    let Statement::CreateIndex(CreateIndex {
1✔
1162
        name,
1✔
1163
        table_name,
1✔
1164
        columns,
1✔
1165
        using,
1✔
1166
        unique,
1✔
1167
        if_not_exists,
1✔
1168
        predicate,
1✔
1169
        with,
1✔
1170
        ..
1171
    }) = stmt
1✔
1172
    else {
1173
        return Err(SQLRiteError::Internal(
×
1174
            "execute_create_index called on a non-CREATE-INDEX statement".to_string(),
×
1175
        ));
1176
    };
1177

1178
    if predicate.is_some() {
1✔
1179
        return Err(SQLRiteError::NotImplemented(
×
1180
            "partial indexes (CREATE INDEX ... WHERE) are not supported yet".to_string(),
×
1181
        ));
1182
    }
1183

1184
    if columns.len() != 1 {
1✔
1185
        return Err(SQLRiteError::NotImplemented(format!(
×
1186
            "multi-column indexes are not supported yet ({} columns given)",
1187
            columns.len()
×
1188
        )));
1189
    }
1190

1191
    let index_name = name.as_ref().map(|n| n.to_string()).ok_or_else(|| {
3✔
1192
        SQLRiteError::NotImplemented(
×
1193
            "anonymous CREATE INDEX (no name) is not supported — give it a name".to_string(),
×
1194
        )
1195
    })?;
1196

1197
    // Detect USING <method>. The `using` field on CreateIndex covers the
1198
    // pre-column form `CREATE INDEX … USING hnsw (col)`. (sqlparser also
1199
    // accepts a post-column form `… (col) USING hnsw` and parks that in
1200
    // `index_options`; we don't bother with it — the canonical form is
1201
    // pre-column and matches PG/pgvector convention.)
1202
    let method = match using {
1✔
1203
        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("hnsw") => {
2✔
1204
            IndexMethod::Hnsw
1✔
1205
        }
1206
        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("fts") => {
2✔
1207
            IndexMethod::Fts
1✔
1208
        }
1209
        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("btree") => {
×
1210
            IndexMethod::Btree
×
1211
        }
1212
        Some(other) => {
×
1213
            return Err(SQLRiteError::NotImplemented(format!(
×
1214
                "CREATE INDEX … USING {other:?} is not supported \
1215
                 (try `hnsw`, `fts`, or no USING clause)"
1216
            )));
1217
        }
1218
        None => IndexMethod::Btree,
1✔
1219
    };
1220

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

1228
    let table_name_str = table_name.to_string();
1✔
1229
    let column_name = match &columns[0].column.expr {
2✔
1230
        Expr::Identifier(ident) => ident.value.clone(),
2✔
1231
        Expr::CompoundIdentifier(parts) => parts
×
1232
            .last()
×
1233
            .map(|p| p.value.clone())
×
1234
            .ok_or_else(|| SQLRiteError::Internal("empty compound identifier".to_string()))?,
×
1235
        other => {
×
1236
            return Err(SQLRiteError::NotImplemented(format!(
×
1237
                "CREATE INDEX only supports simple column references, got {other:?}"
1238
            )));
1239
        }
1240
    };
1241

1242
    // Validate: table exists, column exists, type matches the index method,
1243
    // name is unique across both index kinds. Snapshot (rowid, value) pairs
1244
    // up front under the immutable borrow so the mutable attach later
1245
    // doesn't fight over `self`.
1246
    let (datatype, existing_rowids_and_values): (DataType, Vec<(i64, Value)>) = {
1✔
1247
        let table = db.get_table(table_name_str.clone()).map_err(|_| {
2✔
1248
            SQLRiteError::General(format!(
×
1249
                "CREATE INDEX references unknown table '{table_name_str}'"
1250
            ))
1251
        })?;
1252
        if !table.contains_column(column_name.clone()) {
1✔
1253
            return Err(SQLRiteError::General(format!(
×
1254
                "CREATE INDEX references unknown column '{column_name}' on table '{table_name_str}'"
1255
            )));
1256
        }
1257
        let col = table
3✔
1258
            .columns
1259
            .iter()
1260
            .find(|c| c.column_name == column_name)
3✔
1261
            .expect("we just verified the column exists");
1262

1263
        // Name uniqueness check spans ALL index kinds — btree, hnsw, and
1264
        // fts share one namespace per table.
1265
        if table.index_by_name(&index_name).is_some()
1✔
1266
            || table.hnsw_indexes.iter().any(|i| i.name == index_name)
4✔
1267
            || table.fts_indexes.iter().any(|i| i.name == index_name)
3✔
1268
        {
1269
            if *if_not_exists {
1✔
1270
                return Ok(index_name);
1✔
1271
            }
1272
            return Err(SQLRiteError::General(format!(
2✔
1273
                "index '{index_name}' already exists"
1274
            )));
1275
        }
1276
        let datatype = clone_datatype(&col.datatype);
1✔
1277

1278
        let mut pairs = Vec::new();
1✔
1279
        for rowid in table.rowids() {
3✔
1280
            if let Some(v) = table.get_value(&column_name, rowid) {
2✔
1281
                pairs.push((rowid, v));
1✔
1282
            }
1283
        }
1284
        (datatype, pairs)
1✔
1285
    };
1286

1287
    match method {
1✔
1288
        IndexMethod::Btree => create_btree_index(
1289
            db,
1290
            &table_name_str,
1✔
1291
            &index_name,
1✔
1292
            &column_name,
1✔
1293
            &datatype,
1294
            *unique,
1✔
1295
            &existing_rowids_and_values,
1✔
1296
        ),
1297
        IndexMethod::Hnsw => create_hnsw_index(
1298
            db,
1299
            &table_name_str,
1✔
1300
            &index_name,
1✔
1301
            &column_name,
1✔
1302
            &datatype,
1303
            *unique,
1✔
1304
            hnsw_metric.unwrap_or(DistanceMetric::L2),
1✔
1305
            &existing_rowids_and_values,
1✔
1306
        ),
1307
        IndexMethod::Fts => create_fts_index(
1308
            db,
1309
            &table_name_str,
1✔
1310
            &index_name,
1✔
1311
            &column_name,
1✔
1312
            &datatype,
1313
            *unique,
1✔
1314
            &existing_rowids_and_values,
1✔
1315
        ),
1316
    }
1317
}
1318

1319
/// Executes `DROP TABLE [IF EXISTS] <name>;`. Mirrors SQLite's single-target
1320
/// shape: sqlparser parses `DROP TABLE a, b` as one statement with
1321
/// `names: vec![a, b]`, but we reject the multi-target form to keep error
1322
/// semantics simple (no partial-failure rollback).
1323
///
1324
/// On success the table — and every index attached to it — disappears from
1325
/// the in-memory `Database`. The next auto-save rebuilds `sqlrite_master`
1326
/// from scratch and simply doesn't write a row for the dropped table or
1327
/// its indexes; pages previously occupied by them become orphans on disk
1328
/// (no free-list yet — file size doesn't shrink until a future VACUUM).
1329
pub fn execute_drop_table(
1✔
1330
    names: &[ObjectName],
1331
    if_exists: bool,
1332
    db: &mut Database,
1333
) -> Result<usize> {
1334
    if names.len() != 1 {
1✔
1335
        return Err(SQLRiteError::NotImplemented(
1✔
1336
            "DROP TABLE supports a single table per statement".to_string(),
1✔
1337
        ));
1338
    }
1339
    let name = names[0].to_string();
2✔
1340

1341
    if name == crate::sql::pager::MASTER_TABLE_NAME {
2✔
1342
        return Err(SQLRiteError::General(format!(
2✔
1343
            "'{}' is a reserved name used by the internal schema catalog",
1344
            crate::sql::pager::MASTER_TABLE_NAME
1345
        )));
1346
    }
1347

1348
    if !db.contains_table(name.clone()) {
2✔
1349
        return if if_exists {
2✔
1350
            Ok(0)
1✔
1351
        } else {
1352
            Err(SQLRiteError::General(format!(
2✔
1353
                "Table '{name}' does not exist"
1354
            )))
1355
        };
1356
    }
1357

1358
    db.tables.remove(&name);
2✔
1359
    Ok(1)
1360
}
1361

1362
/// Executes `DROP INDEX [IF EXISTS] <name>;`. The statement does not name a
1363
/// table, so we walk every table looking for the index across all three
1364
/// index families (B-Tree secondary, HNSW, FTS).
1365
///
1366
/// Refuses to drop auto-indexes (`origin == IndexOrigin::Auto`) — those are
1367
/// invariants of the table's PRIMARY KEY / UNIQUE constraints and should
1368
/// only disappear when the column or table they depend on is dropped.
1369
/// SQLite has the same rule for its `sqlite_autoindex_*` indexes.
1370
pub fn execute_drop_index(
1✔
1371
    names: &[ObjectName],
1372
    if_exists: bool,
1373
    db: &mut Database,
1374
) -> Result<usize> {
1375
    if names.len() != 1 {
1✔
1376
        return Err(SQLRiteError::NotImplemented(
×
1377
            "DROP INDEX supports a single index per statement".to_string(),
×
1378
        ));
1379
    }
1380
    let name = names[0].to_string();
2✔
1381

1382
    for table in db.tables.values_mut() {
2✔
1383
        if let Some(secondary) = table.secondary_indexes.iter().find(|i| i.name == name) {
4✔
1384
            if secondary.origin == IndexOrigin::Auto {
2✔
1385
                return Err(SQLRiteError::General(format!(
2✔
1386
                    "cannot drop auto-created index '{name}' (drop the column or table instead)"
1387
                )));
1388
            }
1389
            table.secondary_indexes.retain(|i| i.name != name);
3✔
1390
            return Ok(1);
1✔
1391
        }
1392
        if table.hnsw_indexes.iter().any(|i| i.name == name) {
×
1393
            table.hnsw_indexes.retain(|i| i.name != name);
×
1394
            return Ok(1);
×
1395
        }
1396
        if table.fts_indexes.iter().any(|i| i.name == name) {
×
1397
            table.fts_indexes.retain(|i| i.name != name);
×
1398
            return Ok(1);
×
1399
        }
1400
    }
1401

1402
    if if_exists {
2✔
1403
        Ok(0)
1404
    } else {
1405
        Err(SQLRiteError::General(format!(
2✔
1406
            "Index '{name}' does not exist"
1407
        )))
1408
    }
1409
}
1410

1411
/// Executes `ALTER TABLE [IF EXISTS] <name> <op>;` for one operation per
1412
/// statement. Supports four sub-operations matching SQLite:
1413
///
1414
///   - `RENAME TO <new>`
1415
///   - `RENAME COLUMN <old> TO <new>`
1416
///   - `ADD COLUMN <coldef>` (NOT NULL requires DEFAULT on a non-empty table;
1417
///     PK / UNIQUE constraints rejected — would need backfill + uniqueness)
1418
///   - `DROP COLUMN <name>` (refuses PK column and only-column)
1419
///
1420
/// Multi-operation ALTER (`ALTER TABLE foo RENAME TO bar, ADD COLUMN x ...`)
1421
/// is rejected; SQLite forbids it too.
1422
pub fn execute_alter_table(alter: AlterTable, db: &mut Database) -> Result<String> {
1✔
1423
    let table_name = alter.name.to_string();
1✔
1424

1425
    if table_name == crate::sql::pager::MASTER_TABLE_NAME {
2✔
1426
        return Err(SQLRiteError::General(format!(
×
1427
            "'{}' is a reserved name used by the internal schema catalog",
1428
            crate::sql::pager::MASTER_TABLE_NAME
1429
        )));
1430
    }
1431

1432
    if !db.contains_table(table_name.clone()) {
2✔
1433
        return if alter.if_exists {
2✔
1434
            Ok("ALTER TABLE: no-op (table does not exist)".to_string())
2✔
1435
        } else {
1436
            Err(SQLRiteError::General(format!(
2✔
1437
                "Table '{table_name}' does not exist"
1438
            )))
1439
        };
1440
    }
1441

1442
    if alter.operations.len() != 1 {
2✔
1443
        return Err(SQLRiteError::NotImplemented(
×
1444
            "ALTER TABLE supports one operation per statement".to_string(),
×
1445
        ));
1446
    }
1447

1448
    match &alter.operations[0] {
2✔
1449
        AlterTableOperation::RenameTable { table_name: kind } => {
1✔
1450
            let new_name = match kind {
1✔
1451
                RenameTableNameKind::To(name) => name.to_string(),
1✔
1452
                RenameTableNameKind::As(_) => {
1453
                    return Err(SQLRiteError::NotImplemented(
×
1454
                        "ALTER TABLE ... RENAME AS (MySQL-only) is not supported; use RENAME TO"
1455
                            .to_string(),
×
1456
                    ));
1457
                }
1458
            };
1459
            alter_rename_table(db, &table_name, &new_name)?;
2✔
1460
            Ok(format!(
1✔
1461
                "ALTER TABLE '{table_name}' RENAME TO '{new_name}' executed."
1462
            ))
1463
        }
1464
        AlterTableOperation::RenameColumn {
1465
            old_column_name,
1✔
1466
            new_column_name,
1✔
1467
        } => {
1468
            let old = old_column_name.value.clone();
1✔
1469
            let new = new_column_name.value.clone();
1✔
1470
            db.get_table_mut(table_name.clone())?
5✔
1471
                .rename_column(&old, &new)?;
2✔
1472
            Ok(format!(
1✔
1473
                "ALTER TABLE '{table_name}' RENAME COLUMN '{old}' TO '{new}' executed."
1474
            ))
1475
        }
1476
        AlterTableOperation::AddColumn {
1477
            column_def,
1✔
1478
            if_not_exists,
1✔
1479
            ..
1480
        } => {
1481
            let parsed = crate::sql::parser::create::parse_one_column(column_def)?;
2✔
1482
            let table = db.get_table_mut(table_name.clone())?;
2✔
1483
            if *if_not_exists && table.contains_column(parsed.name.clone()) {
1✔
1484
                return Ok(format!(
×
1485
                    "ALTER TABLE '{table_name}' ADD COLUMN: no-op (column '{}' already exists)",
1486
                    parsed.name
1487
                ));
1488
            }
1489
            let col_name = parsed.name.clone();
1✔
1490
            table.add_column(parsed)?;
2✔
1491
            Ok(format!(
1✔
1492
                "ALTER TABLE '{table_name}' ADD COLUMN '{col_name}' executed."
1493
            ))
1494
        }
1495
        AlterTableOperation::DropColumn {
1496
            column_names,
1✔
1497
            if_exists,
1✔
1498
            ..
1499
        } => {
1500
            if column_names.len() != 1 {
2✔
1501
                return Err(SQLRiteError::NotImplemented(
×
1502
                    "ALTER TABLE DROP COLUMN supports a single column per statement".to_string(),
×
1503
                ));
1504
            }
1505
            let col_name = column_names[0].value.clone();
2✔
1506
            let table = db.get_table_mut(table_name.clone())?;
2✔
1507
            if *if_exists && !table.contains_column(col_name.clone()) {
1✔
1508
                return Ok(format!(
×
1509
                    "ALTER TABLE '{table_name}' DROP COLUMN: no-op (column '{col_name}' does not exist)"
1510
                ));
1511
            }
1512
            table.drop_column(&col_name)?;
3✔
1513
            Ok(format!(
1✔
1514
                "ALTER TABLE '{table_name}' DROP COLUMN '{col_name}' executed."
1515
            ))
1516
        }
1517
        other => Err(SQLRiteError::NotImplemented(format!(
×
1518
            "ALTER TABLE operation {other:?} is not supported"
1519
        ))),
1520
    }
1521
}
1522

1523
/// Executes `VACUUM;` (SQLR-6). Compacts the database file: rewrites
1524
/// every live table, index, and the catalog contiguously from page 1,
1525
/// drops the freelist, and truncates the tail at the next checkpoint.
1526
///
1527
/// Refuses to run inside a transaction (would publish in-flight writes
1528
/// out of band); refuses on read-only databases (handled upstream by
1529
/// the read-only mutation gate); and is a no-op on in-memory databases
1530
/// (no file to compact). Bare `VACUUM;` only — non-default options
1531
/// (`FULL`, `REINDEX`, table targets, etc.) are rejected.
1532
pub fn execute_vacuum(db: &mut Database) -> Result<String> {
2✔
1533
    if db.in_transaction() {
1✔
1534
        return Err(SQLRiteError::General(
1✔
1535
            "VACUUM cannot run inside a transaction".to_string(),
1✔
1536
        ));
1537
    }
1538
    let path = match db.source_path.clone() {
1✔
1539
        Some(p) => p,
1✔
1540
        None => {
1541
            return Ok("VACUUM is a no-op for in-memory databases".to_string());
1✔
1542
        }
1543
    };
1544
    // Checkpoint before AND after VACUUM so the main-file size we report
1545
    // reflects only what VACUUM actually reclaimed — without the leading
1546
    // checkpoint, `size_before` would be the stale main-file snapshot
1547
    // (typically 2 pages) while WAL holds the live bytes, making the
1548
    // bytes-reclaimed delta meaningless.
1549
    if let Some(pager) = db.pager.as_mut() {
2✔
1550
        let _ = pager.checkpoint();
2✔
1551
    }
1552
    let size_before = std::fs::metadata(&path).ok().map(|m| m.len()).unwrap_or(0);
4✔
1553
    let pages_before = db
2✔
1554
        .pager
1555
        .as_ref()
1556
        .map(|p| p.header().page_count)
3✔
1557
        .unwrap_or(0);
1558
    crate::sql::pager::vacuum_database(db, &path)?;
1✔
1559
    // Second checkpoint so the main file shrinks now — VACUUM's whole
1560
    // purpose is to reclaim bytes, so paying the I/O up front is fair.
1561
    if let Some(pager) = db.pager.as_mut() {
1✔
1562
        let _ = pager.checkpoint();
2✔
1563
    }
1564
    let size_after = std::fs::metadata(&path).ok().map(|m| m.len()).unwrap_or(0);
4✔
1565
    let pages_after = db
2✔
1566
        .pager
1567
        .as_ref()
1568
        .map(|p| p.header().page_count)
3✔
1569
        .unwrap_or(0);
1570
    let pages_reclaimed = pages_before.saturating_sub(pages_after);
1✔
1571
    let bytes_reclaimed = size_before.saturating_sub(size_after);
1✔
1572
    Ok(format!(
1✔
1573
        "VACUUM completed. {pages_reclaimed} pages reclaimed ({bytes_reclaimed} bytes)."
1574
    ))
1575
}
1576

1577
/// Renames a table in `db.tables`. Updates `tb_name`, every secondary
1578
/// index's `table_name` field, and any auto-index whose name embedded
1579
/// the old table name. HNSW / FTS index entries don't carry a
1580
/// `table_name` field — they're addressed implicitly via the `Table`
1581
/// they live inside, so they move with the rename for free.
1582
fn alter_rename_table(db: &mut Database, old: &str, new: &str) -> Result<()> {
1✔
1583
    if new == crate::sql::pager::MASTER_TABLE_NAME {
1✔
1584
        return Err(SQLRiteError::General(format!(
1✔
1585
            "'{}' is a reserved name used by the internal schema catalog",
1586
            crate::sql::pager::MASTER_TABLE_NAME
1587
        )));
1588
    }
1589
    if old == new {
1✔
1590
        return Ok(());
×
1591
    }
1592
    if db.contains_table(new.to_string()) {
1✔
1593
        return Err(SQLRiteError::General(format!(
1✔
1594
            "target table '{new}' already exists"
1595
        )));
1596
    }
1597

1598
    let mut table = db
3✔
1599
        .tables
1600
        .remove(old)
1✔
1601
        .ok_or_else(|| SQLRiteError::General(format!("Table '{old}' does not exist")))?;
1✔
1602
    table.tb_name = new.to_string();
2✔
1603
    for idx in table.secondary_indexes.iter_mut() {
1✔
1604
        idx.table_name = new.to_string();
2✔
1605
        if idx.origin == IndexOrigin::Auto
2✔
1606
            && idx.name == SecondaryIndex::auto_name(old, &idx.column_name)
1✔
1607
        {
1608
            idx.name = SecondaryIndex::auto_name(new, &idx.column_name);
1✔
1609
        }
1610
    }
1611
    db.tables.insert(new.to_string(), table);
1✔
1612
    Ok(())
1✔
1613
}
1614

1615
/// `USING <method>` choices recognized by `execute_create_index`. A
1616
/// missing USING clause defaults to `Btree` so existing CREATE INDEX
1617
/// statements (Phase 3e) keep working unchanged.
1618
#[derive(Debug, Clone, Copy)]
1619
enum IndexMethod {
1620
    Btree,
1621
    Hnsw,
1622
    /// Phase 8b — full-text inverted index over a TEXT column.
1623
    Fts,
1624
}
1625

1626
/// Builds a Phase 3e B-Tree secondary index and attaches it to the table.
1627
fn create_btree_index(
1✔
1628
    db: &mut Database,
1629
    table_name: &str,
1630
    index_name: &str,
1631
    column_name: &str,
1632
    datatype: &DataType,
1633
    unique: bool,
1634
    existing: &[(i64, Value)],
1635
) -> Result<String> {
1636
    let mut idx = SecondaryIndex::new(
3✔
1637
        index_name.to_string(),
1✔
1638
        table_name.to_string(),
2✔
1639
        column_name.to_string(),
1✔
1640
        datatype,
1641
        unique,
1642
        IndexOrigin::Explicit,
1643
    )?;
1644

1645
    // Populate from existing rows. UNIQUE violations here mean the
1646
    // existing data already breaks the new index's constraint — a
1647
    // common source of user confusion, so be explicit.
1648
    for (rowid, v) in existing {
2✔
1649
        if unique && idx.would_violate_unique(v) {
2✔
1650
            return Err(SQLRiteError::General(format!(
1✔
1651
                "cannot create UNIQUE index '{index_name}': column '{column_name}' \
1652
                 already contains the duplicate value {}",
1653
                v.to_display_string()
1✔
1654
            )));
1655
        }
1656
        idx.insert(v, *rowid)?;
2✔
1657
    }
1658

1659
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1660
    table_mut.secondary_indexes.push(idx);
1✔
1661
    Ok(index_name.to_string())
1✔
1662
}
1663

1664
/// Builds a Phase 7d.2 HNSW index and attaches it to the table.
1665
fn create_hnsw_index(
1✔
1666
    db: &mut Database,
1667
    table_name: &str,
1668
    index_name: &str,
1669
    column_name: &str,
1670
    datatype: &DataType,
1671
    unique: bool,
1672
    metric: DistanceMetric,
1673
    existing: &[(i64, Value)],
1674
) -> Result<String> {
1675
    // HNSW only makes sense on VECTOR columns. Reject anything else
1676
    // with a clear message — this is the most likely user error.
1677
    let dim = match datatype {
1✔
1678
        DataType::Vector(d) => *d,
1✔
1679
        other => {
1✔
1680
            return Err(SQLRiteError::General(format!(
1✔
1681
                "USING hnsw requires a VECTOR column; '{column_name}' is {other}"
1682
            )));
1683
        }
1684
    };
1685

1686
    if unique {
1✔
1687
        return Err(SQLRiteError::General(
×
1688
            "UNIQUE has no meaning for HNSW indexes".to_string(),
×
1689
        ));
1690
    }
1691

1692
    // Build the in-memory graph. The distance metric was picked at
1693
    // CREATE INDEX time (defaults to L2 if no `WITH (metric = …)`
1694
    // clause was supplied). The graph topology is metric-specific —
1695
    // L2 neighbour pruning ≠ cosine neighbour pruning — so the
1696
    // optimizer's HNSW shortcut only fires when the query's
1697
    // `vec_distance_*` function matches this value (SQLR-28).
1698
    //
1699
    // Seed: hash the index name so different indexes get different
1700
    // graph topologies, but the same index always gets the same one
1701
    // — useful when debugging recall / index size.
1702
    let seed = hash_str_to_seed(index_name);
1✔
1703
    let mut idx = HnswIndex::new(metric, seed);
1✔
1704

1705
    // Snapshot the (rowid, vector) pairs into a side map so the
1706
    // get_vec closure below can serve them by id without re-borrowing
1707
    // the table (we're already holding `existing` — flatten it).
1708
    let mut vec_map: std::collections::HashMap<i64, Vec<f32>> =
1✔
1709
        std::collections::HashMap::with_capacity(existing.len());
1710
    for (rowid, v) in existing {
2✔
1711
        match v {
1✔
1712
            Value::Vector(vec) => {
1✔
1713
                if vec.len() != dim {
1✔
1714
                    return Err(SQLRiteError::Internal(format!(
×
1715
                        "row {rowid} stores a {}-dim vector in column '{column_name}' \
1716
                         declared as VECTOR({dim}) — schema invariant violated",
1717
                        vec.len()
×
1718
                    )));
1719
                }
1720
                vec_map.insert(*rowid, vec.clone());
2✔
1721
            }
1722
            // Non-vector values (theoretical NULL, type coercion bug)
1723
            // get skipped — they wouldn't have a sensible graph
1724
            // position anyway.
1725
            _ => continue,
1726
        }
1727
    }
1728

1729
    for (rowid, _) in existing {
1✔
1730
        if let Some(v) = vec_map.get(rowid) {
2✔
1731
            let v_clone = v.clone();
1✔
1732
            idx.insert(*rowid, &v_clone, |id| {
3✔
1733
                vec_map.get(&id).cloned().unwrap_or_default()
1✔
1734
            })?;
1735
        }
1736
    }
1737

1738
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1739
    table_mut.hnsw_indexes.push(HnswIndexEntry {
2✔
1740
        name: index_name.to_string(),
1✔
1741
        column_name: column_name.to_string(),
1✔
1742
        metric,
1743
        index: idx,
1✔
1744
        // Freshly built — no DELETE/UPDATE has invalidated it yet.
1745
        needs_rebuild: false,
1746
    });
1747
    Ok(index_name.to_string())
1✔
1748
}
1749

1750
/// Parses the `WITH (metric = '<name>', …)` options bag on a CREATE
1751
/// INDEX statement. Returns the chosen metric (or `None` if no
1752
/// `metric` key was supplied) on HNSW indexes; raises a
1753
/// user-visible error on:
1754
///
1755
///   - WITH options on a non-HNSW index (btree / fts have no knobs we
1756
///     understand here),
1757
///   - unknown option keys,
1758
///   - unknown metric names (typo guard — silently falling back to L2
1759
///     would hide the user's intent and re-introduce the SQLR-28 bug).
1760
fn parse_hnsw_with_options(
1✔
1761
    with: &[Expr],
1762
    index_name: &str,
1763
    method: IndexMethod,
1764
) -> Result<Option<DistanceMetric>> {
1765
    if with.is_empty() {
1✔
1766
        return Ok(None);
1✔
1767
    }
1768
    if !matches!(method, IndexMethod::Hnsw) {
2✔
1769
        return Err(SQLRiteError::General(format!(
1✔
1770
            "CREATE INDEX '{index_name}' has a WITH (...) clause but its index method \
1771
             doesn't support any options — only `USING hnsw` recognises `WITH (metric = ...)`"
1772
        )));
1773
    }
1774

1775
    let mut metric: Option<DistanceMetric> = None;
1✔
1776
    for opt in with {
2✔
1777
        let Expr::BinaryOp { left, op, right } = opt else {
2✔
1778
            return Err(SQLRiteError::General(format!(
×
1779
                "CREATE INDEX '{index_name}': unsupported WITH option {opt:?} \
1780
                 (expected `key = 'value'`)"
1781
            )));
1782
        };
1783
        if !matches!(op, BinaryOperator::Eq) {
2✔
1784
            return Err(SQLRiteError::General(format!(
×
1785
                "CREATE INDEX '{index_name}': WITH options must use `=` (got {op:?})"
1786
            )));
1787
        }
1788
        let key = match left.as_ref() {
1✔
1789
            Expr::Identifier(ident) => ident.value.clone(),
1✔
1790
            other => {
×
1791
                return Err(SQLRiteError::General(format!(
×
1792
                    "CREATE INDEX '{index_name}': WITH option key must be a bare identifier, \
1793
                     got {other:?}"
1794
                )));
1795
            }
1796
        };
1797
        let value = match right.as_ref() {
2✔
1798
            Expr::Value(v) => match &v.value {
1✔
1799
                AstValue::SingleQuotedString(s) => s.clone(),
2✔
1800
                AstValue::DoubleQuotedString(s) => s.clone(),
×
1801
                other => {
×
1802
                    return Err(SQLRiteError::General(format!(
×
1803
                        "CREATE INDEX '{index_name}': WITH option '{key}' value must be \
1804
                         a quoted string, got {other:?}"
1805
                    )));
1806
                }
1807
            },
1808
            Expr::Identifier(ident) => ident.value.clone(),
×
1809
            other => {
×
1810
                return Err(SQLRiteError::General(format!(
×
1811
                    "CREATE INDEX '{index_name}': WITH option '{key}' value must be a \
1812
                     quoted string, got {other:?}"
1813
                )));
1814
            }
1815
        };
1816

1817
        if key.eq_ignore_ascii_case("metric") {
2✔
1818
            let parsed = DistanceMetric::from_sql_name(&value).ok_or_else(|| {
5✔
1819
                SQLRiteError::General(format!(
1✔
1820
                    "CREATE INDEX '{index_name}': unknown HNSW metric '{value}' \
1821
                     (try 'l2', 'cosine', or 'dot')"
1822
                ))
1823
            })?;
1824
            if metric.is_some() {
1✔
1825
                return Err(SQLRiteError::General(format!(
×
1826
                    "CREATE INDEX '{index_name}': metric specified more than once in WITH (...)"
1827
                )));
1828
            }
1829
            metric = Some(parsed);
1✔
1830
        } else {
1831
            return Err(SQLRiteError::General(format!(
×
1832
                "CREATE INDEX '{index_name}': unknown WITH option '{key}' \
1833
                 (only 'metric' is recognised on HNSW indexes)"
1834
            )));
1835
        }
1836
    }
1837

1838
    Ok(metric)
1✔
1839
}
1840

1841
/// Builds a Phase 8b FTS inverted index and attaches it to the table.
1842
/// Mirrors [`create_hnsw_index`] in shape: validate column type,
1843
/// tokenize each existing row's text into the in-memory posting list,
1844
/// push an `FtsIndexEntry`.
1845
fn create_fts_index(
1✔
1846
    db: &mut Database,
1847
    table_name: &str,
1848
    index_name: &str,
1849
    column_name: &str,
1850
    datatype: &DataType,
1851
    unique: bool,
1852
    existing: &[(i64, Value)],
1853
) -> Result<String> {
1854
    // FTS is a TEXT-only feature for the MVP. JSON columns share the
1855
    // Row::Text storage but their content is structured — full-text
1856
    // indexing JSON keys + values would need a different design (and
1857
    // is out of scope per the Phase 8 plan's "Out of scope" section).
1858
    match datatype {
1✔
1859
        DataType::Text => {}
1860
        other => {
1✔
1861
            return Err(SQLRiteError::General(format!(
1✔
1862
                "USING fts requires a TEXT column; '{column_name}' is {other}"
1863
            )));
1864
        }
1865
    }
1866

1867
    if unique {
1✔
1868
        return Err(SQLRiteError::General(
1✔
1869
            "UNIQUE has no meaning for FTS indexes".to_string(),
1✔
1870
        ));
1871
    }
1872

1873
    let mut idx = PostingList::new();
1✔
1874
    for (rowid, v) in existing {
2✔
1875
        if let Value::Text(text) = v {
2✔
1876
            idx.insert(*rowid, text);
1✔
1877
        }
1878
        // Non-text values (Null, type coercion bugs) get skipped — same
1879
        // posture as create_hnsw_index for non-vector values.
1880
    }
1881

1882
    let table_mut = db.get_table_mut(table_name.to_string())?;
1✔
1883
    table_mut.fts_indexes.push(FtsIndexEntry {
2✔
1884
        name: index_name.to_string(),
1✔
1885
        column_name: column_name.to_string(),
1✔
1886
        index: idx,
1✔
1887
        needs_rebuild: false,
1888
    });
1889
    Ok(index_name.to_string())
1✔
1890
}
1891

1892
/// Stable, deterministic hash of a string into a u64 RNG seed. FNV-1a;
1893
/// avoids pulling in `std::hash::DefaultHasher` (which is randomized
1894
/// per process).
1895
fn hash_str_to_seed(s: &str) -> u64 {
1✔
1896
    let mut h: u64 = 0xCBF29CE484222325;
1✔
1897
    for b in s.as_bytes() {
2✔
1898
        h ^= *b as u64;
1✔
1899
        h = h.wrapping_mul(0x100000001B3);
1✔
1900
    }
1901
    h
1✔
1902
}
1903

1904
/// Cheap clone helper — `DataType` intentionally doesn't derive `Clone`
1905
/// because the enum has no ergonomic reason to be cloneable elsewhere.
1906
fn clone_datatype(dt: &DataType) -> DataType {
1✔
1907
    match dt {
1✔
1908
        DataType::Integer => DataType::Integer,
1✔
1909
        DataType::Text => DataType::Text,
1✔
1910
        DataType::Real => DataType::Real,
×
1911
        DataType::Bool => DataType::Bool,
×
1912
        DataType::Vector(dim) => DataType::Vector(*dim),
1✔
1913
        DataType::Json => DataType::Json,
×
1914
        DataType::None => DataType::None,
×
1915
        DataType::Invalid => DataType::Invalid,
×
1916
    }
1917
}
1918

1919
fn extract_single_table_name(tables: &[TableWithJoins]) -> Result<String> {
1✔
1920
    if tables.len() != 1 {
1✔
1921
        return Err(SQLRiteError::NotImplemented(
×
1922
            "multi-table DELETE is not supported yet".to_string(),
×
1923
        ));
1924
    }
1925
    extract_table_name(&tables[0])
2✔
1926
}
1927

1928
fn extract_table_name(twj: &TableWithJoins) -> Result<String> {
1✔
1929
    if !twj.joins.is_empty() {
1✔
1930
        return Err(SQLRiteError::NotImplemented(
×
1931
            "JOIN is not supported yet".to_string(),
×
1932
        ));
1933
    }
1934
    match &twj.relation {
1✔
1935
        TableFactor::Table { name, .. } => Ok(name.to_string()),
1✔
1936
        _ => Err(SQLRiteError::NotImplemented(
×
1937
            "only plain table references are supported".to_string(),
×
1938
        )),
1939
    }
1940
}
1941

1942
/// Tells the executor how to produce its candidate rowid list.
1943
enum RowidSource {
1944
    /// The WHERE was simple enough to probe a secondary index directly.
1945
    /// The `Vec` already contains exactly the rows the index matched;
1946
    /// no further WHERE evaluation is needed (the probe is precise).
1947
    IndexProbe(Vec<i64>),
1948
    /// No applicable index; caller falls back to walking `table.rowids()`
1949
    /// and evaluating the WHERE on each row.
1950
    FullScan,
1951
}
1952

1953
/// Try to satisfy `WHERE` with an index probe. Currently supports the
1954
/// simplest shape: a single `col = literal` (or `literal = col`) where
1955
/// `col` is on a secondary index. AND/OR/range predicates fall back to
1956
/// full scan — those can be layered on later without changing the caller.
1957
fn select_rowids(table: &Table, selection: Option<&Expr>) -> Result<RowidSource> {
1✔
1958
    let Some(expr) = selection else {
1✔
1959
        return Ok(RowidSource::FullScan);
1✔
1960
    };
1961
    let Some((col, literal)) = try_extract_equality(expr) else {
2✔
1962
        return Ok(RowidSource::FullScan);
1✔
1963
    };
1964
    let Some(idx) = table.index_for_column(&col) else {
2✔
1965
        return Ok(RowidSource::FullScan);
1✔
1966
    };
1967

1968
    // Convert the literal into a runtime Value. If the literal type doesn't
1969
    // match the column's index we still need correct semantics — evaluate
1970
    // the WHERE against every row. Fall back to full scan.
1971
    let literal_value = match convert_literal(&literal) {
2✔
1972
        Ok(v) => v,
1✔
1973
        Err(_) => return Ok(RowidSource::FullScan),
×
1974
    };
1975

1976
    // Index lookup returns the full list of rowids matching this equality
1977
    // predicate. For unique indexes that's at most one; for non-unique it
1978
    // can be many.
1979
    let mut rowids = idx.lookup(&literal_value);
1✔
1980
    rowids.sort_unstable();
2✔
1981
    Ok(RowidSource::IndexProbe(rowids))
1✔
1982
}
1983

1984
/// Recognizes `expr` as a simple equality on a column reference against a
1985
/// literal. Returns `(column_name, literal_value)` if the shape matches;
1986
/// `None` otherwise. Accepts both `col = literal` and `literal = col`.
1987
fn try_extract_equality(expr: &Expr) -> Option<(String, sqlparser::ast::Value)> {
1✔
1988
    // Peel off Nested parens so `WHERE (x = 1)` is recognized too.
1989
    let peeled = match expr {
1✔
1990
        Expr::Nested(inner) => inner.as_ref(),
1✔
1991
        other => other,
1✔
1992
    };
1993
    let Expr::BinaryOp { left, op, right } = peeled else {
1✔
1994
        return None;
1✔
1995
    };
1996
    if !matches!(op, BinaryOperator::Eq) {
2✔
1997
        return None;
1✔
1998
    }
1999
    let col_from = |e: &Expr| -> Option<String> {
1✔
2000
        match e {
1✔
2001
            Expr::Identifier(ident) => Some(ident.value.clone()),
1✔
2002
            Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
×
2003
            _ => None,
1✔
2004
        }
2005
    };
2006
    let literal_from = |e: &Expr| -> Option<sqlparser::ast::Value> {
1✔
2007
        if let Expr::Value(v) = e {
2✔
2008
            Some(v.value.clone())
1✔
2009
        } else {
2010
            None
1✔
2011
        }
2012
    };
2013
    if let (Some(c), Some(l)) = (col_from(left), literal_from(right)) {
3✔
2014
        return Some((c, l));
1✔
2015
    }
2016
    if let (Some(l), Some(c)) = (literal_from(left), col_from(right)) {
3✔
2017
        return Some((c, l));
1✔
2018
    }
2019
    None
1✔
2020
}
2021

2022
/// Recognizes the HNSW-probable query pattern and probes the graph
2023
/// if a matching index exists.
2024
///
2025
/// Looks for ORDER BY `vec_distance_<l2|cosine|dot>(<col>, <bracket-
2026
/// array literal>)` where the table has an HNSW index attached to
2027
/// `<col>` *built for that same distance metric*. On a match, returns
2028
/// the top-k rowids straight from the graph (O(log N)). On any miss —
2029
/// different function name, no matching index, query dimension wrong,
2030
/// metric mismatch, etc. — returns `None` and the caller falls through
2031
/// to the bounded-heap brute-force path (7c) or the full sort (7b),
2032
/// preserving correct results regardless of whether the HNSW pathway
2033
/// kicked in.
2034
///
2035
/// Caveats:
2036
/// - The index's metric and the query's `vec_distance_*` function must
2037
///   agree. An L2-built graph silently doesn't help cosine queries
2038
///   (different neighbour pruning policy → potentially different
2039
///   topology), so we don't pretend to.  Pick the metric at CREATE
2040
///   INDEX time via `WITH (metric = '<l2|cosine|dot>')` (SQLR-28).
2041
/// - Only ASCENDING order makes sense for "k nearest" — DESC ORDER BY
2042
///   `vec_distance_*(...) LIMIT k` would mean "k farthest", which isn't
2043
///   what the index is built for. We don't bother to detect
2044
///   `ascending == false` here; the optimizer just skips and the
2045
///   fallback path handles it correctly (slower).
2046
fn try_hnsw_probe(table: &Table, order_expr: &Expr, k: usize) -> Option<Vec<i64>> {
1✔
2047
    if k == 0 {
1✔
2048
        return None;
×
2049
    }
2050

2051
    // Pattern-match: order expr must be a function call
2052
    // vec_distance_<l2|cosine|dot>(a, b).
2053
    let func = match order_expr {
1✔
2054
        Expr::Function(f) => f,
1✔
2055
        _ => return None,
1✔
2056
    };
2057
    let fname = match func.name.0.as_slice() {
2✔
2058
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
2059
        _ => return None,
×
2060
    };
2061
    let query_metric = match fname.as_str() {
2✔
2062
        "vec_distance_l2" => DistanceMetric::L2,
2✔
2063
        "vec_distance_cosine" => DistanceMetric::Cosine,
3✔
2064
        "vec_distance_dot" => DistanceMetric::Dot,
3✔
2065
        _ => return None,
1✔
2066
    };
2067

2068
    // Extract the two args as raw Exprs.
2069
    let arg_list = match &func.args {
1✔
2070
        FunctionArguments::List(l) => &l.args,
1✔
2071
        _ => return None,
×
2072
    };
2073
    if arg_list.len() != 2 {
2✔
2074
        return None;
×
2075
    }
2076
    let exprs: Vec<&Expr> = arg_list
1✔
2077
        .iter()
2078
        .filter_map(|a| match a {
3✔
2079
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Some(e),
1✔
2080
            _ => None,
×
2081
        })
2082
        .collect();
2083
    if exprs.len() != 2 {
2✔
2084
        return None;
×
2085
    }
2086

2087
    // One arg must be a column reference (the indexed col); the other
2088
    // must be a bracket-array literal (the query vector). Try both
2089
    // orderings — pgvector's idiom puts the column on the left, but
2090
    // SQL is commutative for distance.
2091
    let (col_name, query_vec) = match identify_indexed_arg_and_literal(exprs[0], exprs[1]) {
3✔
2092
        Some(v) => v,
1✔
2093
        None => match identify_indexed_arg_and_literal(exprs[1], exprs[0]) {
×
2094
            Some(v) => v,
×
2095
            None => return None,
×
2096
        },
2097
    };
2098

2099
    // Find the HNSW index on this column AND with a matching metric.
2100
    // Multiple indexes on the same column are allowed in principle
2101
    // (cosine-built + L2-built), and a query picks whichever metric
2102
    // its `vec_distance_*` function names.
2103
    let entry = table
4✔
2104
        .hnsw_indexes
2105
        .iter()
1✔
2106
        .find(|e| e.column_name == col_name && e.metric == query_metric)?;
3✔
2107

2108
    // Dimension sanity check — the query vector must match the
2109
    // indexed column's declared dimension. If it doesn't, the brute-
2110
    // force fallback would also error at the vec_distance_l2 dim-check;
2111
    // returning None here lets that path produce the user-visible
2112
    // error message.
2113
    let declared_dim = match table.columns.iter().find(|c| c.column_name == col_name) {
3✔
2114
        Some(c) => match &c.datatype {
1✔
2115
            DataType::Vector(d) => *d,
1✔
2116
            _ => return None,
×
2117
        },
2118
        None => return None,
×
2119
    };
2120
    if query_vec.len() != declared_dim {
2✔
2121
        return None;
×
2122
    }
2123

2124
    // Probe the graph. Vectors are looked up from the table's row
2125
    // storage — a closure rather than a `&Table` so the algorithm
2126
    // module stays decoupled from the SQL types.
2127
    let column_for_closure = col_name.clone();
1✔
2128
    let table_ref = table;
2129
    let result = entry
1✔
2130
        .index
2131
        .search(&query_vec, k, |id| {
3✔
2132
            match table_ref.get_value(&column_for_closure, id) {
1✔
2133
                Some(Value::Vector(v)) => v,
1✔
2134
                _ => Vec::new(),
×
2135
            }
2136
        })
2137
        .ok()?;
1✔
2138
    Some(result)
1✔
2139
}
2140

2141
/// Phase 8b — FTS optimizer hook.
2142
///
2143
/// Recognizes `ORDER BY bm25_score(<col>, '<query>') DESC LIMIT <k>`
2144
/// and serves it from the FTS index instead of full-scanning. Returns
2145
/// `Some(rowids)` already sorted by descending BM25 (with rowid
2146
/// ascending as tie-break), or `None` to fall through to scalar eval.
2147
///
2148
/// **Known limitation (mirrors `try_hnsw_probe`).** This shortcut
2149
/// ignores any `WHERE` clause. The canonical FTS query has a
2150
/// `WHERE fts_match(<col>, '<q>')` predicate, which is implicitly
2151
/// satisfied by the probe results — so dropping it is harmless.
2152
/// Anything *else* in the WHERE (`AND status = 'published'`) gets
2153
/// silently skipped on the optimizer path. Per Phase 8 plan Q6 we
2154
/// match HNSW's posture here; a correctness-preserving multi-index
2155
/// composer is deferred.
2156
fn try_fts_probe(table: &Table, order_expr: &Expr, ascending: bool, k: usize) -> Option<Vec<i64>> {
1✔
2157
    if k == 0 || ascending {
1✔
2158
        // BM25 is "higher = better"; ASC ranking is almost certainly a
2159
        // user mistake. Fall through so the caller gets either an
2160
        // explicit error from scalar eval or the slow correct path.
2161
        return None;
1✔
2162
    }
2163

2164
    let func = match order_expr {
1✔
2165
        Expr::Function(f) => f,
1✔
2166
        _ => return None,
×
2167
    };
2168
    let fname = match func.name.0.as_slice() {
2✔
2169
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
2170
        _ => return None,
×
2171
    };
2172
    if fname != "bm25_score" {
2✔
2173
        return None;
×
2174
    }
2175

2176
    let arg_list = match &func.args {
1✔
2177
        FunctionArguments::List(l) => &l.args,
1✔
2178
        _ => return None,
×
2179
    };
2180
    if arg_list.len() != 2 {
2✔
2181
        return None;
×
2182
    }
2183
    let exprs: Vec<&Expr> = arg_list
1✔
2184
        .iter()
2185
        .filter_map(|a| match a {
3✔
2186
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Some(e),
1✔
2187
            _ => None,
×
2188
        })
2189
        .collect();
2190
    if exprs.len() != 2 {
2✔
2191
        return None;
×
2192
    }
2193

2194
    // Arg 0 must be a bare column identifier.
2195
    let col_name = match exprs[0] {
2✔
2196
        Expr::Identifier(ident) if ident.quote_style.is_none() => ident.value.clone(),
2✔
2197
        _ => return None,
×
2198
    };
2199

2200
    // Arg 1 must be a single-quoted string literal. Anything else
2201
    // (column reference, function call) requires per-row evaluation —
2202
    // we'd lose the whole point of the probe.
2203
    let query = match exprs[1] {
2✔
2204
        Expr::Value(v) => match &v.value {
1✔
2205
            AstValue::SingleQuotedString(s) => s.clone(),
1✔
2206
            _ => return None,
×
2207
        },
2208
        _ => return None,
×
2209
    };
2210

2211
    let entry = table
3✔
2212
        .fts_indexes
2213
        .iter()
1✔
2214
        .find(|e| e.column_name == col_name)?;
3✔
2215

2216
    let scored = entry.index.query(&query, &Bm25Params::default());
1✔
2217
    let mut out: Vec<i64> = scored.into_iter().map(|(id, _)| id).collect();
3✔
2218
    if out.len() > k {
2✔
2219
        out.truncate(k);
1✔
2220
    }
2221
    Some(out)
1✔
2222
}
2223

2224
/// Helper for `try_hnsw_probe`: given two function args, identify which
2225
/// one is a bare column identifier (the indexed column) and which is a
2226
/// bracket-array literal (the query vector). Returns
2227
/// `Some((column_name, query_vec))` on a match, `None` otherwise.
2228
fn identify_indexed_arg_and_literal(a: &Expr, b: &Expr) -> Option<(String, Vec<f32>)> {
1✔
2229
    let col_name = match a {
1✔
2230
        Expr::Identifier(ident) if ident.quote_style.is_none() => ident.value.clone(),
2✔
2231
        _ => return None,
×
2232
    };
2233
    let lit_str = match b {
1✔
2234
        Expr::Identifier(ident) if ident.quote_style == Some('[') => {
2✔
2235
            format!("[{}]", ident.value)
1✔
2236
        }
2237
        _ => return None,
×
2238
    };
2239
    let v = parse_vector_literal(&lit_str).ok()?;
2✔
2240
    Some((col_name, v))
1✔
2241
}
2242

2243
/// One entry in the bounded-heap top-k path. Holds a pre-evaluated
2244
/// sort key + the rowid it came from. The `asc` flag inverts `Ord`
2245
/// so a single `BinaryHeap<HeapEntry>` works for both ASC and DESC
2246
/// without wrapping in `std::cmp::Reverse` at the call site:
2247
///
2248
///   - ASC LIMIT k = "k smallest": natural Ord. Max-heap top is the
2249
///     largest currently kept; new items smaller than top displace.
2250
///   - DESC LIMIT k = "k largest": Ord reversed. Max-heap top is now
2251
///     the smallest currently kept (under reversed Ord, smallest
2252
///     looks largest); new items larger than top displace.
2253
///
2254
/// In both cases the displacement test reduces to "new entry < heap top".
2255
struct HeapEntry {
2256
    key: Value,
2257
    rowid: i64,
2258
    asc: bool,
2259
}
2260

2261
impl PartialEq for HeapEntry {
2262
    fn eq(&self, other: &Self) -> bool {
×
2263
        self.cmp(other) == Ordering::Equal
×
2264
    }
2265
}
2266

2267
impl Eq for HeapEntry {}
2268

2269
impl PartialOrd for HeapEntry {
2270
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1✔
2271
        Some(self.cmp(other))
1✔
2272
    }
2273
}
2274

2275
impl Ord for HeapEntry {
2276
    fn cmp(&self, other: &Self) -> Ordering {
1✔
2277
        let raw = compare_values(Some(&self.key), Some(&other.key));
1✔
2278
        if self.asc { raw } else { raw.reverse() }
1✔
2279
    }
2280
}
2281

2282
/// Bounded-heap top-k selection. Returns at most `k` rowids in the
2283
/// caller's desired order (ascending key for `order.ascending`,
2284
/// descending otherwise).
2285
///
2286
/// O(N log k) where N = `matching.len()`. Caller must check
2287
/// `k < matching.len()` for this to be a win — for k ≥ N the
2288
/// `sort_rowids` full-sort path is the same asymptotic cost without
2289
/// the heap overhead.
2290
fn select_topk(
1✔
2291
    matching: &[i64],
2292
    table: &Table,
2293
    order: &OrderByClause,
2294
    k: usize,
2295
) -> Result<Vec<i64>> {
2296
    use std::collections::BinaryHeap;
2297

2298
    if k == 0 || matching.is_empty() {
1✔
2299
        return Ok(Vec::new());
1✔
2300
    }
2301

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

2304
    for &rowid in matching {
3✔
2305
        let key = eval_expr(&order.expr, table, rowid)?;
2✔
2306
        let entry = HeapEntry {
2307
            key,
2308
            rowid,
2309
            asc: order.ascending,
1✔
2310
        };
2311

2312
        if heap.len() < k {
2✔
2313
            heap.push(entry);
2✔
2314
        } else {
2315
            // peek() returns the largest under our direction-aware Ord
2316
            // — the worst entry currently kept. Displace it iff the
2317
            // new entry is "better" (i.e. compares Less).
2318
            if entry < *heap.peek().unwrap() {
2✔
2319
                heap.pop();
1✔
2320
                heap.push(entry);
1✔
2321
            }
2322
        }
2323
    }
2324

2325
    // `into_sorted_vec` returns ascending under our direction-aware Ord:
2326
    //   ASC: ascending by raw key (what we want)
2327
    //   DESC: ascending under reversed Ord = descending by raw key (what
2328
    //         we want for an ORDER BY DESC LIMIT k result)
2329
    Ok(heap
2✔
2330
        .into_sorted_vec()
1✔
2331
        .into_iter()
1✔
2332
        .map(|e| e.rowid)
3✔
2333
        .collect())
1✔
2334
}
2335

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

2349
    // Surface the FIRST evaluation error if any. We could be lazy
2350
    // and let sort_by encounter it, but `Ord::cmp` can't return a
2351
    // Result and we'd have to swallow errors silently.
2352
    for (_, k) in &keys {
2✔
2353
        if let Err(e) = k {
1✔
2354
            return Err(SQLRiteError::General(format!(
×
2355
                "ORDER BY expression failed: {e}"
2356
            )));
2357
        }
2358
    }
2359

2360
    keys.sort_by(|(_, ka), (_, kb)| {
3✔
2361
        // Both unwrap()s are safe — we just verified above that
2362
        // every key Result is Ok.
2363
        let va = ka.as_ref().unwrap();
1✔
2364
        let vb = kb.as_ref().unwrap();
1✔
2365
        let ord = compare_values(Some(va), Some(vb));
1✔
2366
        if order.ascending { ord } else { ord.reverse() }
1✔
2367
    });
2368

2369
    // Write the sorted rowids back into the caller's slice.
2370
    for (i, (rowid, _)) in keys.into_iter().enumerate() {
2✔
2371
        rowids[i] = rowid;
2✔
2372
    }
2373
    Ok(())
1✔
2374
}
2375

2376
fn compare_values(a: Option<&Value>, b: Option<&Value>) -> Ordering {
1✔
2377
    match (a, b) {
2✔
2378
        (None, None) => Ordering::Equal,
×
2379
        (None, _) => Ordering::Less,
×
2380
        (_, None) => Ordering::Greater,
×
2381
        (Some(a), Some(b)) => match (a, b) {
3✔
2382
            (Value::Null, Value::Null) => Ordering::Equal,
×
2383
            (Value::Null, _) => Ordering::Less,
1✔
2384
            (_, Value::Null) => Ordering::Greater,
×
2385
            (Value::Integer(x), Value::Integer(y)) => x.cmp(y),
1✔
2386
            (Value::Real(x), Value::Real(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
1✔
2387
            (Value::Integer(x), Value::Real(y)) => {
×
2388
                (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal)
×
2389
            }
2390
            (Value::Real(x), Value::Integer(y)) => {
×
2391
                x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal)
×
2392
            }
2393
            (Value::Text(x), Value::Text(y)) => x.cmp(y),
1✔
2394
            (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
×
2395
            // Cross-type fallback: stringify and compare; keeps ORDER BY total.
2396
            (x, y) => x.to_display_string().cmp(&y.to_display_string()),
×
2397
        },
2398
    }
2399
}
2400

2401
/// Returns `true` if the row at `rowid` matches the predicate expression.
2402
pub fn eval_predicate(expr: &Expr, table: &Table, rowid: i64) -> Result<bool> {
1✔
2403
    eval_predicate_scope(expr, &SingleTableScope::new(table, rowid))
1✔
2404
}
2405

2406
/// Scope-aware predicate evaluation. The single-table fast path wraps
2407
/// this with a [`SingleTableScope`]; the join executor wraps it with
2408
/// a [`JoinedScope`].
2409
pub(crate) fn eval_predicate_scope(expr: &Expr, scope: &dyn RowScope) -> Result<bool> {
1✔
2410
    let v = eval_expr_scope(expr, scope)?;
2✔
2411
    match v {
1✔
2412
        Value::Bool(b) => Ok(b),
1✔
2413
        Value::Null => Ok(false), // SQL NULL in a WHERE is treated as false
2414
        Value::Integer(i) => Ok(i != 0),
1✔
2415
        other => Err(SQLRiteError::Internal(format!(
×
2416
            "WHERE clause must evaluate to boolean, got {}",
2417
            other.to_display_string()
×
2418
        ))),
2419
    }
2420
}
2421

2422
/// Single-table convenience wrapper around [`eval_expr_scope`].
2423
fn eval_expr(expr: &Expr, table: &Table, rowid: i64) -> Result<Value> {
1✔
2424
    eval_expr_scope(expr, &SingleTableScope::new(table, rowid))
1✔
2425
}
2426

2427
fn eval_expr_scope(expr: &Expr, scope: &dyn RowScope) -> Result<Value> {
1✔
2428
    match expr {
1✔
2429
        Expr::Nested(inner) => eval_expr_scope(inner, scope),
2✔
2430

2431
        Expr::Identifier(ident) => {
1✔
2432
            // Phase 7b — sqlparser parses bracket-array literals like
2433
            // `[0.1, 0.2, 0.3]` as bracket-quoted identifiers (it inherits
2434
            // MSSQL `[name]` syntax). When we see `quote_style == Some('[')`
2435
            // in expression-evaluation position (SELECT projection, WHERE,
2436
            // ORDER BY, function args), parse the bracketed content as a
2437
            // vector literal so the rest of the executor can compare /
2438
            // distance-compute against it. Same trick the INSERT parser
2439
            // uses; the executor needed its own copy because expression
2440
            // eval runs on a different code path.
2441
            if ident.quote_style == Some('[') {
1✔
2442
                let raw = format!("[{}]", ident.value);
1✔
2443
                let v = parse_vector_literal(&raw)?;
2✔
2444
                return Ok(Value::Vector(v));
1✔
2445
            }
2446
            scope.lookup(None, &ident.value)
1✔
2447
        }
2448

2449
        Expr::CompoundIdentifier(parts) => {
1✔
2450
            // `qualifier.col` — single-table scope ignores the qualifier
2451
            // (legacy behavior). Joined scope dispatches to the table
2452
            // matching `qualifier`. The compound form must have at
2453
            // least two parts; deeper paths (`db.schema.t.col`) are
2454
            // not supported.
2455
            match parts.as_slice() {
1✔
2456
                [only] => scope.lookup(None, &only.value),
1✔
2457
                [q, c] => scope.lookup(Some(&q.value), &c.value),
2✔
2458
                _ => Err(SQLRiteError::NotImplemented(format!(
×
2459
                    "compound identifier with {} parts is not supported",
2460
                    parts.len()
×
2461
                ))),
2462
            }
2463
        }
2464

2465
        Expr::Value(v) => convert_literal(&v.value),
1✔
2466

2467
        Expr::UnaryOp { op, expr } => {
×
2468
            let inner = eval_expr_scope(expr, scope)?;
×
2469
            match op {
×
2470
                UnaryOperator::Not => match inner {
×
2471
                    Value::Bool(b) => Ok(Value::Bool(!b)),
×
2472
                    Value::Null => Ok(Value::Null),
×
2473
                    other => Err(SQLRiteError::Internal(format!(
×
2474
                        "NOT applied to non-boolean value: {}",
2475
                        other.to_display_string()
×
2476
                    ))),
2477
                },
2478
                UnaryOperator::Minus => match inner {
×
2479
                    Value::Integer(i) => Ok(Value::Integer(-i)),
×
2480
                    Value::Real(f) => Ok(Value::Real(-f)),
×
2481
                    Value::Null => Ok(Value::Null),
×
2482
                    other => Err(SQLRiteError::Internal(format!(
×
2483
                        "unary minus on non-numeric value: {}",
2484
                        other.to_display_string()
×
2485
                    ))),
2486
                },
2487
                UnaryOperator::Plus => Ok(inner),
×
2488
                other => Err(SQLRiteError::NotImplemented(format!(
×
2489
                    "unary operator {other:?} is not supported"
2490
                ))),
2491
            }
2492
        }
2493

2494
        Expr::BinaryOp { left, op, right } => match op {
1✔
2495
            BinaryOperator::And => {
2496
                let l = eval_expr_scope(left, scope)?;
2✔
2497
                let r = eval_expr_scope(right, scope)?;
2✔
2498
                Ok(Value::Bool(as_bool(&l)? && as_bool(&r)?))
3✔
2499
            }
2500
            BinaryOperator::Or => {
2501
                let l = eval_expr_scope(left, scope)?;
×
2502
                let r = eval_expr_scope(right, scope)?;
×
2503
                Ok(Value::Bool(as_bool(&l)? || as_bool(&r)?))
×
2504
            }
2505
            cmp @ (BinaryOperator::Eq
2506
            | BinaryOperator::NotEq
2507
            | BinaryOperator::Lt
2508
            | BinaryOperator::LtEq
2509
            | BinaryOperator::Gt
2510
            | BinaryOperator::GtEq) => {
2511
                let l = eval_expr_scope(left, scope)?;
2✔
2512
                let r = eval_expr_scope(right, scope)?;
3✔
2513
                // Any comparison involving NULL is unknown → false in a WHERE.
2514
                if matches!(l, Value::Null) || matches!(r, Value::Null) {
2✔
2515
                    return Ok(Value::Bool(false));
1✔
2516
                }
2517
                let ord = compare_values(Some(&l), Some(&r));
2✔
2518
                let result = match cmp {
1✔
2519
                    BinaryOperator::Eq => ord == Ordering::Equal,
2✔
2520
                    BinaryOperator::NotEq => ord != Ordering::Equal,
×
2521
                    BinaryOperator::Lt => ord == Ordering::Less,
2✔
2522
                    BinaryOperator::LtEq => ord != Ordering::Greater,
×
2523
                    BinaryOperator::Gt => ord == Ordering::Greater,
2✔
2524
                    BinaryOperator::GtEq => ord != Ordering::Less,
2✔
2525
                    _ => unreachable!(),
2526
                };
2527
                Ok(Value::Bool(result))
1✔
2528
            }
2529
            arith @ (BinaryOperator::Plus
2530
            | BinaryOperator::Minus
2531
            | BinaryOperator::Multiply
2532
            | BinaryOperator::Divide
2533
            | BinaryOperator::Modulo) => {
2534
                let l = eval_expr_scope(left, scope)?;
2✔
2535
                let r = eval_expr_scope(right, scope)?;
2✔
2536
                eval_arith(arith, &l, &r)
1✔
2537
            }
2538
            BinaryOperator::StringConcat => {
2539
                let l = eval_expr_scope(left, scope)?;
×
2540
                let r = eval_expr_scope(right, scope)?;
×
2541
                if matches!(l, Value::Null) || matches!(r, Value::Null) {
×
2542
                    return Ok(Value::Null);
×
2543
                }
2544
                Ok(Value::Text(format!(
×
2545
                    "{}{}",
2546
                    l.to_display_string(),
×
2547
                    r.to_display_string()
×
2548
                )))
2549
            }
2550
            other => Err(SQLRiteError::NotImplemented(format!(
×
2551
                "binary operator {other:?} is not supported yet"
2552
            ))),
2553
        },
2554

2555
        // SQLR-7 — `col IS NULL` / `col IS NOT NULL`. Identifier
2556
        // evaluation already maps a missing rowid in the column's
2557
        // BTreeMap to `Value::Null`, so this works uniformly for
2558
        // explicit NULL inserts, omitted columns, and (post-Phase 7e)
2559
        // legacy "Null"-sentinel TEXT cells. NULLs are never inserted
2560
        // into secondary / HNSW / FTS indexes, so an IS NULL probe
2561
        // correctly falls through to a full scan via `select_rowids`.
2562
        Expr::IsNull(inner) => {
1✔
2563
            let v = eval_expr_scope(inner, scope)?;
2✔
2564
            Ok(Value::Bool(matches!(v, Value::Null)))
1✔
2565
        }
2566
        Expr::IsNotNull(inner) => {
1✔
2567
            let v = eval_expr_scope(inner, scope)?;
2✔
2568
            Ok(Value::Bool(!matches!(v, Value::Null)))
1✔
2569
        }
2570

2571
        // SQLR-3 — LIKE / NOT LIKE / ILIKE. Pattern matching uses our
2572
        // own iterative two-pointer matcher (see `agg::like_match`).
2573
        // SQLite's default is case-insensitive ASCII; we follow that.
2574
        // ILIKE is also case-insensitive (a no-op switch here, but we
2575
        // keep the arm explicit so SQLite users typing ILIKE get the
2576
        // expected semantics rather than a NotImplemented).
2577
        Expr::Like {
2578
            negated,
1✔
2579
            any,
1✔
2580
            expr: lhs,
1✔
2581
            pattern,
1✔
2582
            escape_char,
1✔
2583
        } => eval_like(
2584
            scope,
2585
            *negated,
1✔
2586
            *any,
1✔
2587
            lhs,
2✔
2588
            pattern,
2✔
2589
            escape_char.as_ref(),
1✔
2590
            true,
2591
        ),
2592
        Expr::ILike {
2593
            negated,
×
2594
            any,
×
2595
            expr: lhs,
×
2596
            pattern,
×
2597
            escape_char,
×
2598
        } => eval_like(
2599
            scope,
2600
            *negated,
×
2601
            *any,
×
2602
            lhs,
×
2603
            pattern,
×
2604
            escape_char.as_ref(),
×
2605
            true,
2606
        ),
2607

2608
        // SQLR-3 — IN (list) / NOT IN (list). Subquery form is rejected.
2609
        // Three-valued logic: if the LHS is NULL, return NULL; if any
2610
        // list entry is NULL and no match was found, return NULL too.
2611
        // WHERE coerces NULL → false at line ~1494, so the practical
2612
        // effect is "row excluded" — matches SQLite.
2613
        Expr::InList {
2614
            expr: lhs,
1✔
2615
            list,
1✔
2616
            negated,
1✔
2617
        } => eval_in_list(scope, lhs, list, *negated),
2✔
2618
        Expr::InSubquery { .. } => Err(SQLRiteError::NotImplemented(
×
2619
            "IN (subquery) is not supported (only literal lists are)".to_string(),
×
2620
        )),
2621

2622
        // Phase 7b — function-call dispatch. Currently only the three
2623
        // vector-distance functions; this match arm becomes the single
2624
        // place to register more SQL functions later (e.g. abs(),
2625
        // length(), …) without re-touching the rest of the executor.
2626
        //
2627
        // Operator forms (`<->` `<=>` `<#>`) are NOT plumbed here: two
2628
        // of three don't parse natively in sqlparser (we'd need a
2629
        // string-preprocessing pass or a sqlparser fork). Deferred to
2630
        // a follow-up sub-phase; see docs/phase-7-plan.md's "Scope
2631
        // corrections" note.
2632
        Expr::Function(func) => eval_function(func, scope),
1✔
2633

2634
        other => Err(SQLRiteError::NotImplemented(format!(
×
2635
            "unsupported expression in WHERE/projection: {other:?}"
2636
        ))),
2637
    }
2638
}
2639

2640
/// Dispatches an `Expr::Function` to its built-in implementation.
2641
/// Currently only the three vec_distance_* functions; other functions
2642
/// surface as `NotImplemented` errors with the function name in the
2643
/// message so users see what they tried.
2644
fn eval_function(func: &sqlparser::ast::Function, scope: &dyn RowScope) -> Result<Value> {
1✔
2645
    // Function name lives in `name.0[0]` for unqualified calls. Anything
2646
    // qualified (e.g. `pkg.fn(...)`) falls through to NotImplemented.
2647
    let name = match func.name.0.as_slice() {
2✔
2648
        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
2✔
2649
        _ => {
2650
            return Err(SQLRiteError::NotImplemented(format!(
×
2651
                "qualified function names not supported: {:?}",
2652
                func.name
2653
            )));
2654
        }
2655
    };
2656

2657
    match name.as_str() {
2✔
2658
        "vec_distance_l2" | "vec_distance_cosine" | "vec_distance_dot" => {
2✔
2659
            let (a, b) = extract_two_vector_args(&name, &func.args, scope)?;
3✔
2660
            let dist = match name.as_str() {
2✔
2661
                "vec_distance_l2" => vec_distance_l2(&a, &b),
3✔
2662
                "vec_distance_cosine" => vec_distance_cosine(&a, &b)?,
4✔
2663
                "vec_distance_dot" => vec_distance_dot(&a, &b),
3✔
2664
                _ => unreachable!(),
2665
            };
2666
            // Widen f32 → f64 for the runtime Value. Vectors are stored
2667
            // as f32 (consistent with industry convention for embeddings),
2668
            // but the executor's numeric type is f64 so distances slot
2669
            // into Value::Real cleanly and can be compared / ordered with
2670
            // other reals via the existing arithmetic + comparison paths.
2671
            Ok(Value::Real(dist as f64))
1✔
2672
        }
2673
        // Phase 7e — JSON functions. All four parse the JSON text on
2674
        // demand (we don't cache parsed values), then resolve a path
2675
        // (default `$` = root). The path resolver handles `.key` for
2676
        // object access and `[N]` for array index. SQLite-style.
2677
        "json_extract" => json_fn_extract(&name, &func.args, scope),
3✔
2678
        "json_type" => json_fn_type(&name, &func.args, scope),
4✔
2679
        "json_array_length" => json_fn_array_length(&name, &func.args, scope),
4✔
2680
        "json_object_keys" => json_fn_object_keys(&name, &func.args, scope),
2✔
2681
        // Phase 8b — FTS scalars. Both consult an FTS index attached to
2682
        // the named column; both error if no index exists (the index is
2683
        // a hard prerequisite, mirroring SQLite FTS5's MATCH).
2684
        //
2685
        // SQLR-5 — these only work in a single-table scope because they
2686
        // need the owning `Table` to look up an FTS index by name and
2687
        // they key results by the row's rowid. In a joined query the
2688
        // index lookup would be ambiguous (which table's FTS?) and the
2689
        // scoring rowid is per-table. Reject up front rather than
2690
        // silently wrong-result.
2691
        "fts_match" | "bm25_score" => {
3✔
2692
            let Some((table, rowid)) = scope.single_table_view() else {
2✔
2693
                return Err(SQLRiteError::NotImplemented(format!(
×
2694
                    "{name}() is not yet supported inside a JOIN query — \
2695
                     use it on a single-table SELECT or move the FTS lookup into a subquery"
2696
                )));
2697
            };
2698
            let (entry, query) = resolve_fts_args(&name, &func.args, table, scope)?;
3✔
2699
            Ok(match name.as_str() {
3✔
2700
                "fts_match" => Value::Bool(entry.index.matches(rowid, &query)),
3✔
2701
                "bm25_score" => {
2✔
2702
                    Value::Real(entry.index.score(rowid, &query, &Bm25Params::default()))
1✔
2703
                }
2704
                _ => unreachable!(),
×
2705
            })
2706
        }
2707
        // SQLR-3: catch aggregate names used in scalar position (e.g.
2708
        // `WHERE COUNT(*) > 1`) with a clearer message than "unknown
2709
        // function".
2710
        "count" | "sum" | "avg" | "min" | "max" => Err(SQLRiteError::NotImplemented(format!(
2✔
2711
            "aggregate function '{name}' is not allowed in WHERE / projection-scalar position; \
2712
             use it as a top-level projection item or in HAVING"
2713
        ))),
2714
        other => Err(SQLRiteError::NotImplemented(format!(
1✔
2715
            "unknown function: {other}(...)"
2716
        ))),
2717
    }
2718
}
2719

2720
/// Helper for `fts_match` / `bm25_score`: pull the column reference out
2721
/// of arg 0 (a bare identifier — we need the *name*, not the per-row
2722
/// value), evaluate arg 1 as a Text query string, and look up the FTS
2723
/// index attached to that column. Errors if any step fails.
2724
fn resolve_fts_args<'t>(
1✔
2725
    fn_name: &str,
2726
    args: &FunctionArguments,
2727
    table: &'t Table,
2728
    scope: &dyn RowScope,
2729
) -> Result<(&'t FtsIndexEntry, String)> {
2730
    let arg_list = match args {
1✔
2731
        FunctionArguments::List(l) => &l.args,
1✔
2732
        _ => {
2733
            return Err(SQLRiteError::General(format!(
×
2734
                "{fn_name}() expects exactly two arguments: (column, query_text)"
2735
            )));
2736
        }
2737
    };
2738
    if arg_list.len() != 2 {
1✔
2739
        return Err(SQLRiteError::General(format!(
×
2740
            "{fn_name}() expects exactly 2 arguments, got {}",
2741
            arg_list.len()
×
2742
        )));
2743
    }
2744

2745
    // Arg 0: bare column identifier. Must resolve syntactically to a
2746
    // column name (we can't accept arbitrary expressions because we
2747
    // need the column to look up the index, not the column's value).
2748
    let col_expr = match &arg_list[0] {
2✔
2749
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2750
        other => {
×
2751
            return Err(SQLRiteError::NotImplemented(format!(
×
2752
                "{fn_name}() argument 0 must be a column name, got {other:?}"
2753
            )));
2754
        }
2755
    };
2756
    let col_name = match col_expr {
1✔
2757
        Expr::Identifier(ident) => ident.value.clone(),
1✔
2758
        Expr::CompoundIdentifier(parts) => parts
×
2759
            .last()
×
2760
            .map(|p| p.value.clone())
×
2761
            .ok_or_else(|| SQLRiteError::Internal("empty compound identifier".to_string()))?,
×
2762
        other => {
×
2763
            return Err(SQLRiteError::General(format!(
×
2764
                "{fn_name}() argument 0 must be a column reference, got {other:?}"
2765
            )));
2766
        }
2767
    };
2768

2769
    // Arg 1: query string. Evaluated through the normal expression
2770
    // pipeline so callers can pass a literal `'rust db'` or an
2771
    // expression that yields TEXT.
2772
    let q_expr = match &arg_list[1] {
2✔
2773
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2774
        other => {
×
2775
            return Err(SQLRiteError::NotImplemented(format!(
×
2776
                "{fn_name}() argument 1 must be a text expression, got {other:?}"
2777
            )));
2778
        }
2779
    };
2780
    let query = match eval_expr_scope(q_expr, scope)? {
1✔
2781
        Value::Text(s) => s,
1✔
2782
        other => {
×
2783
            return Err(SQLRiteError::General(format!(
×
2784
                "{fn_name}() argument 1 must be TEXT, got {}",
2785
                other.to_display_string()
×
2786
            )));
2787
        }
2788
    };
2789

2790
    let entry = table
4✔
2791
        .fts_indexes
2792
        .iter()
1✔
2793
        .find(|e| e.column_name == col_name)
3✔
2794
        .ok_or_else(|| {
2✔
2795
            SQLRiteError::General(format!(
1✔
2796
                "{fn_name}({col_name}, ...): no FTS index on column '{col_name}' \
2797
                 (run CREATE INDEX <name> ON <table> USING fts({col_name}) first)"
2798
            ))
2799
        })?;
2800
    Ok((entry, query))
1✔
2801
}
2802

2803
// -----------------------------------------------------------------
2804
// Phase 7e — JSON path-extraction functions
2805
// -----------------------------------------------------------------
2806

2807
/// Extracts the JSON-typed text + optional path string out of a
2808
/// function call's args. Used by all four json_* functions.
2809
///
2810
/// Arity rules (matching SQLite JSON1):
2811
///   - 1 arg  → JSON value, path defaults to `$` (root)
2812
///   - 2 args → (JSON value, path text)
2813
///
2814
/// Returns `(json_text, path)` so caller can serde_json::from_str
2815
/// + walk_json_path on it.
2816
fn extract_json_and_path(
1✔
2817
    fn_name: &str,
2818
    args: &FunctionArguments,
2819
    scope: &dyn RowScope,
2820
) -> Result<(String, String)> {
2821
    let arg_list = match args {
1✔
2822
        FunctionArguments::List(l) => &l.args,
1✔
2823
        _ => {
2824
            return Err(SQLRiteError::General(format!(
×
2825
                "{fn_name}() expects 1 or 2 arguments"
2826
            )));
2827
        }
2828
    };
2829
    if !(arg_list.len() == 1 || arg_list.len() == 2) {
2✔
2830
        return Err(SQLRiteError::General(format!(
×
2831
            "{fn_name}() expects 1 or 2 arguments, got {}",
2832
            arg_list.len()
×
2833
        )));
2834
    }
2835
    // Evaluate first arg → must produce text.
2836
    let first_expr = match &arg_list[0] {
2✔
2837
        FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2838
        other => {
×
2839
            return Err(SQLRiteError::NotImplemented(format!(
×
2840
                "{fn_name}() argument 0 has unsupported shape: {other:?}"
2841
            )));
2842
        }
2843
    };
2844
    let json_text = match eval_expr_scope(first_expr, scope)? {
1✔
2845
        Value::Text(s) => s,
1✔
2846
        Value::Null => {
2847
            return Err(SQLRiteError::General(format!(
×
2848
                "{fn_name}() called on NULL — JSON column has no value for this row"
2849
            )));
2850
        }
2851
        other => {
×
2852
            return Err(SQLRiteError::General(format!(
×
2853
                "{fn_name}() argument 0 is not JSON-typed: got {}",
2854
                other.to_display_string()
×
2855
            )));
2856
        }
2857
    };
2858

2859
    // Path defaults to root `$` when omitted.
2860
    let path = if arg_list.len() == 2 {
2✔
2861
        let path_expr = match &arg_list[1] {
2✔
2862
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
2863
            other => {
×
2864
                return Err(SQLRiteError::NotImplemented(format!(
×
2865
                    "{fn_name}() argument 1 has unsupported shape: {other:?}"
2866
                )));
2867
            }
2868
        };
2869
        match eval_expr_scope(path_expr, scope)? {
1✔
2870
            Value::Text(s) => s,
1✔
2871
            other => {
×
2872
                return Err(SQLRiteError::General(format!(
×
2873
                    "{fn_name}() path argument must be a string literal, got {}",
2874
                    other.to_display_string()
×
2875
                )));
2876
            }
2877
        }
2878
    } else {
2879
        "$".to_string()
×
2880
    };
2881

2882
    Ok((json_text, path))
1✔
2883
}
2884

2885
/// Walks a `serde_json::Value` along a JSONPath subset:
2886
///   - `$` is the root
2887
///   - `.key` for object access (key may not contain `.` or `[`)
2888
///   - `[N]` for array index (N a non-negative integer)
2889
///   - chains arbitrarily: `$.foo.bar[0].baz`
2890
///
2891
/// Returns `Ok(None)` for "path didn't match anything" (NULL in SQL),
2892
/// `Err` for malformed paths. Matches SQLite JSON1's semantic
2893
/// distinction: missing-key = NULL, malformed-path = error.
2894
fn walk_json_path<'a>(
1✔
2895
    value: &'a serde_json::Value,
2896
    path: &str,
2897
) -> Result<Option<&'a serde_json::Value>> {
2898
    let mut chars = path.chars().peekable();
1✔
2899
    if chars.next() != Some('$') {
1✔
2900
        return Err(SQLRiteError::General(format!(
1✔
2901
            "JSON path must start with '$', got `{path}`"
2902
        )));
2903
    }
2904
    let mut current = value;
1✔
2905
    while let Some(&c) = chars.peek() {
2✔
2906
        match c {
1✔
2907
            '.' => {
2908
                chars.next();
1✔
2909
                let mut key = String::new();
1✔
2910
                while let Some(&c) = chars.peek() {
2✔
2911
                    if c == '.' || c == '[' {
2✔
2912
                        break;
2913
                    }
2914
                    key.push(c);
1✔
2915
                    chars.next();
1✔
2916
                }
2917
                if key.is_empty() {
2✔
2918
                    return Err(SQLRiteError::General(format!(
×
2919
                        "JSON path has empty key after '.' in `{path}`"
2920
                    )));
2921
                }
2922
                match current.get(&key) {
2✔
2923
                    Some(v) => current = v,
1✔
2924
                    None => return Ok(None),
1✔
2925
                }
2926
            }
2927
            '[' => {
2928
                chars.next();
1✔
2929
                let mut idx_str = String::new();
1✔
2930
                while let Some(&c) = chars.peek() {
2✔
2931
                    if c == ']' {
1✔
2932
                        break;
2933
                    }
2934
                    idx_str.push(c);
1✔
2935
                    chars.next();
1✔
2936
                }
2937
                if chars.next() != Some(']') {
2✔
2938
                    return Err(SQLRiteError::General(format!(
×
2939
                        "JSON path has unclosed `[` in `{path}`"
2940
                    )));
2941
                }
2942
                let idx: usize = idx_str.trim().parse().map_err(|_| {
2✔
2943
                    SQLRiteError::General(format!(
×
2944
                        "JSON path has non-integer index `[{idx_str}]` in `{path}`"
2945
                    ))
2946
                })?;
2947
                match current.get(idx) {
1✔
2948
                    Some(v) => current = v,
1✔
2949
                    None => return Ok(None),
×
2950
                }
2951
            }
2952
            other => {
×
2953
                return Err(SQLRiteError::General(format!(
×
2954
                    "JSON path has unexpected character `{other}` in `{path}` \
2955
                     (expected `.`, `[`, or end-of-path)"
2956
                )));
2957
            }
2958
        }
2959
    }
2960
    Ok(Some(current))
1✔
2961
}
2962

2963
/// Converts a serde_json scalar to a SQLRite Value. For composite
2964
/// types (object, array) returns the JSON-encoded text — callers
2965
/// pattern-match on shape from the calling json_* function.
2966
fn json_value_to_sql(v: &serde_json::Value) -> Value {
1✔
2967
    match v {
1✔
2968
        serde_json::Value::Null => Value::Null,
×
2969
        serde_json::Value::Bool(b) => Value::Bool(*b),
×
2970
        serde_json::Value::Number(n) => {
1✔
2971
            // Match SQLite: integer if it fits an i64, else f64.
2972
            if let Some(i) = n.as_i64() {
3✔
2973
                Value::Integer(i)
1✔
2974
            } else if let Some(f) = n.as_f64() {
×
2975
                Value::Real(f)
×
2976
            } else {
2977
                Value::Null
×
2978
            }
2979
        }
2980
        serde_json::Value::String(s) => Value::Text(s.clone()),
1✔
2981
        // Objects + arrays come out as JSON-encoded text. Same as
2982
        // SQLite's json_extract: composite results round-trip through
2983
        // text rather than being modeled as a richer Value type.
2984
        composite => Value::Text(composite.to_string()),
×
2985
    }
2986
}
2987

2988
fn json_fn_extract(name: &str, args: &FunctionArguments, scope: &dyn RowScope) -> Result<Value> {
1✔
2989
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
2990
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
2991
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
2992
    })?;
2993
    match walk_json_path(&parsed, &path)? {
2✔
2994
        Some(v) => Ok(json_value_to_sql(v)),
2✔
2995
        None => Ok(Value::Null),
1✔
2996
    }
2997
}
2998

2999
fn json_fn_type(name: &str, args: &FunctionArguments, scope: &dyn RowScope) -> Result<Value> {
1✔
3000
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
3001
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
3002
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
3003
    })?;
3004
    let resolved = match walk_json_path(&parsed, &path)? {
2✔
3005
        Some(v) => v,
1✔
3006
        None => return Ok(Value::Null),
×
3007
    };
3008
    let ty = match resolved {
2✔
3009
        serde_json::Value::Null => "null",
1✔
3010
        serde_json::Value::Bool(true) => "true",
1✔
3011
        serde_json::Value::Bool(false) => "false",
×
3012
        serde_json::Value::Number(n) => {
1✔
3013
            if n.is_i64() || n.is_u64() {
4✔
3014
                "integer"
1✔
3015
            } else {
3016
                "real"
1✔
3017
            }
3018
        }
3019
        serde_json::Value::String(_) => "text",
1✔
3020
        serde_json::Value::Array(_) => "array",
1✔
3021
        serde_json::Value::Object(_) => "object",
1✔
3022
    };
3023
    Ok(Value::Text(ty.to_string()))
2✔
3024
}
3025

3026
fn json_fn_array_length(
1✔
3027
    name: &str,
3028
    args: &FunctionArguments,
3029
    scope: &dyn RowScope,
3030
) -> Result<Value> {
3031
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
1✔
3032
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
2✔
3033
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
3034
    })?;
3035
    let resolved = match walk_json_path(&parsed, &path)? {
2✔
3036
        Some(v) => v,
1✔
3037
        None => return Ok(Value::Null),
×
3038
    };
3039
    match resolved.as_array() {
2✔
3040
        Some(arr) => Ok(Value::Integer(arr.len() as i64)),
2✔
3041
        None => Err(SQLRiteError::General(format!(
1✔
3042
            "{name}() resolved to a non-array value at path `{path}`"
3043
        ))),
3044
    }
3045
}
3046

3047
fn json_fn_object_keys(
×
3048
    name: &str,
3049
    args: &FunctionArguments,
3050
    scope: &dyn RowScope,
3051
) -> Result<Value> {
3052
    let (json_text, path) = extract_json_and_path(name, args, scope)?;
×
3053
    let parsed: serde_json::Value = serde_json::from_str(&json_text).map_err(|e| {
×
3054
        SQLRiteError::General(format!("{name}() got invalid JSON `{json_text}`: {e}"))
×
3055
    })?;
3056
    let resolved = match walk_json_path(&parsed, &path)? {
×
3057
        Some(v) => v,
×
3058
        None => return Ok(Value::Null),
×
3059
    };
3060
    let obj = resolved.as_object().ok_or_else(|| {
×
3061
        SQLRiteError::General(format!(
×
3062
            "{name}() resolved to a non-object value at path `{path}`"
3063
        ))
3064
    })?;
3065
    // SQLite's json_object_keys is a table-valued function (one row
3066
    // per key). Without set-returning function support we can't
3067
    // reproduce that shape; instead return the keys as a JSON array
3068
    // text. Caller can iterate via json_array_length + json_extract,
3069
    // or just treat it as a serialized list. Document this divergence
3070
    // in supported-sql.md.
3071
    let keys: Vec<serde_json::Value> = obj
3072
        .keys()
3073
        .map(|k| serde_json::Value::String(k.clone()))
×
3074
        .collect();
3075
    Ok(Value::Text(serde_json::Value::Array(keys).to_string()))
×
3076
}
3077

3078
/// Extracts exactly two `Vec<f32>` arguments from a function call,
3079
/// validating arity and that both sides are Vector-typed with matching
3080
/// dimensions. Used by all three vec_distance_* functions.
3081
fn extract_two_vector_args(
1✔
3082
    fn_name: &str,
3083
    args: &FunctionArguments,
3084
    scope: &dyn RowScope,
3085
) -> Result<(Vec<f32>, Vec<f32>)> {
3086
    let arg_list = match args {
1✔
3087
        FunctionArguments::List(l) => &l.args,
1✔
3088
        _ => {
3089
            return Err(SQLRiteError::General(format!(
×
3090
                "{fn_name}() expects exactly two vector arguments"
3091
            )));
3092
        }
3093
    };
3094
    if arg_list.len() != 2 {
1✔
3095
        return Err(SQLRiteError::General(format!(
×
3096
            "{fn_name}() expects exactly 2 arguments, got {}",
3097
            arg_list.len()
×
3098
        )));
3099
    }
3100
    let mut out: Vec<Vec<f32>> = Vec::with_capacity(2);
1✔
3101
    for (i, arg) in arg_list.iter().enumerate() {
3✔
3102
        let expr = match arg {
2✔
3103
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1✔
3104
            other => {
×
3105
                return Err(SQLRiteError::NotImplemented(format!(
×
3106
                    "{fn_name}() argument {i} has unsupported shape: {other:?}"
3107
                )));
3108
            }
3109
        };
3110
        let val = eval_expr_scope(expr, scope)?;
1✔
3111
        match val {
1✔
3112
            Value::Vector(v) => out.push(v),
1✔
3113
            other => {
×
3114
                return Err(SQLRiteError::General(format!(
×
3115
                    "{fn_name}() argument {i} is not a vector: got {}",
3116
                    other.to_display_string()
×
3117
                )));
3118
            }
3119
        }
3120
    }
3121
    let b = out.pop().unwrap();
1✔
3122
    let a = out.pop().unwrap();
2✔
3123
    if a.len() != b.len() {
2✔
3124
        return Err(SQLRiteError::General(format!(
1✔
3125
            "{fn_name}(): vector dimensions don't match (lhs={}, rhs={})",
3126
            a.len(),
2✔
3127
            b.len()
1✔
3128
        )));
3129
    }
3130
    Ok((a, b))
1✔
3131
}
3132

3133
/// Euclidean (L2) distance: √Σ(aᵢ − bᵢ)².
3134
/// Smaller-is-closer; identical vectors return 0.0.
3135
pub(crate) fn vec_distance_l2(a: &[f32], b: &[f32]) -> f32 {
1✔
3136
    debug_assert_eq!(a.len(), b.len());
1✔
3137
    let mut sum = 0.0f32;
1✔
3138
    for i in 0..a.len() {
2✔
3139
        let d = a[i] - b[i];
2✔
3140
        sum += d * d;
1✔
3141
    }
3142
    sum.sqrt()
1✔
3143
}
3144

3145
/// Cosine distance: 1 − (a·b) / (‖a‖·‖b‖).
3146
/// Smaller-is-closer; identical (non-zero) vectors return 0.0,
3147
/// orthogonal vectors return 1.0, opposite-direction vectors return 2.0.
3148
///
3149
/// Errors if either vector has zero magnitude — cosine similarity is
3150
/// undefined for the zero vector and silently returning NaN would
3151
/// poison `ORDER BY` ranking. Callers who want the silent-NaN
3152
/// behavior can compute `vec_distance_dot(a, b) / (norm(a) * norm(b))`
3153
/// themselves.
3154
pub(crate) fn vec_distance_cosine(a: &[f32], b: &[f32]) -> Result<f32> {
1✔
3155
    debug_assert_eq!(a.len(), b.len());
1✔
3156
    let mut dot = 0.0f32;
1✔
3157
    let mut norm_a_sq = 0.0f32;
1✔
3158
    let mut norm_b_sq = 0.0f32;
1✔
3159
    for i in 0..a.len() {
2✔
3160
        dot += a[i] * b[i];
2✔
3161
        norm_a_sq += a[i] * a[i];
2✔
3162
        norm_b_sq += b[i] * b[i];
2✔
3163
    }
3164
    let denom = (norm_a_sq * norm_b_sq).sqrt();
1✔
3165
    if denom == 0.0 {
1✔
3166
        return Err(SQLRiteError::General(
1✔
3167
            "vec_distance_cosine() is undefined for zero-magnitude vectors".to_string(),
1✔
3168
        ));
3169
    }
3170
    Ok(1.0 - dot / denom)
1✔
3171
}
3172

3173
/// Negated dot product: −(a·b).
3174
/// pgvector convention — negated so smaller-is-closer like L2 / cosine.
3175
/// For unit-norm vectors `vec_distance_dot(a, b) == vec_distance_cosine(a, b) - 1`.
3176
pub(crate) fn vec_distance_dot(a: &[f32], b: &[f32]) -> f32 {
1✔
3177
    debug_assert_eq!(a.len(), b.len());
1✔
3178
    let mut dot = 0.0f32;
1✔
3179
    for i in 0..a.len() {
2✔
3180
        dot += a[i] * b[i];
2✔
3181
    }
3182
    -dot
1✔
3183
}
3184

3185
/// Evaluates an integer/real arithmetic op. NULL on either side propagates.
3186
/// Mixed Integer/Real promotes to Real. Divide/Modulo by zero → error.
3187
fn eval_arith(op: &BinaryOperator, l: &Value, r: &Value) -> Result<Value> {
1✔
3188
    if matches!(l, Value::Null) || matches!(r, Value::Null) {
1✔
3189
        return Ok(Value::Null);
×
3190
    }
3191
    match (l, r) {
1✔
3192
        (Value::Integer(a), Value::Integer(b)) => match op {
1✔
3193
            BinaryOperator::Plus => Ok(Value::Integer(a.wrapping_add(*b))),
1✔
3194
            BinaryOperator::Minus => Ok(Value::Integer(a.wrapping_sub(*b))),
×
3195
            BinaryOperator::Multiply => Ok(Value::Integer(a.wrapping_mul(*b))),
1✔
3196
            BinaryOperator::Divide => {
3197
                if *b == 0 {
×
3198
                    Err(SQLRiteError::General("division by zero".to_string()))
×
3199
                } else {
3200
                    Ok(Value::Integer(a / b))
×
3201
                }
3202
            }
3203
            BinaryOperator::Modulo => {
3204
                if *b == 0 {
×
3205
                    Err(SQLRiteError::General("modulo by zero".to_string()))
×
3206
                } else {
3207
                    Ok(Value::Integer(a % b))
×
3208
                }
3209
            }
3210
            _ => unreachable!(),
3211
        },
3212
        // Anything involving a Real promotes both sides to f64.
3213
        (a, b) => {
×
3214
            let af = as_number(a)?;
×
3215
            let bf = as_number(b)?;
×
3216
            match op {
×
3217
                BinaryOperator::Plus => Ok(Value::Real(af + bf)),
×
3218
                BinaryOperator::Minus => Ok(Value::Real(af - bf)),
×
3219
                BinaryOperator::Multiply => Ok(Value::Real(af * bf)),
×
3220
                BinaryOperator::Divide => {
3221
                    if bf == 0.0 {
×
3222
                        Err(SQLRiteError::General("division by zero".to_string()))
×
3223
                    } else {
3224
                        Ok(Value::Real(af / bf))
×
3225
                    }
3226
                }
3227
                BinaryOperator::Modulo => {
3228
                    if bf == 0.0 {
×
3229
                        Err(SQLRiteError::General("modulo by zero".to_string()))
×
3230
                    } else {
3231
                        Ok(Value::Real(af % bf))
×
3232
                    }
3233
                }
3234
                _ => unreachable!(),
3235
            }
3236
        }
3237
    }
3238
}
3239

3240
fn as_number(v: &Value) -> Result<f64> {
×
3241
    match v {
×
3242
        Value::Integer(i) => Ok(*i as f64),
×
3243
        Value::Real(f) => Ok(*f),
×
3244
        Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
×
3245
        other => Err(SQLRiteError::General(format!(
×
3246
            "arithmetic on non-numeric value '{}'",
3247
            other.to_display_string()
×
3248
        ))),
3249
    }
3250
}
3251

3252
fn as_bool(v: &Value) -> Result<bool> {
1✔
3253
    match v {
1✔
3254
        Value::Bool(b) => Ok(*b),
1✔
3255
        Value::Null => Ok(false),
3256
        Value::Integer(i) => Ok(*i != 0),
×
3257
        other => Err(SQLRiteError::Internal(format!(
×
3258
            "expected boolean, got {}",
3259
            other.to_display_string()
×
3260
        ))),
3261
    }
3262
}
3263

3264
// -----------------------------------------------------------------
3265
// SQLR-3 — LIKE / IN evaluators
3266
// -----------------------------------------------------------------
3267

3268
#[allow(clippy::too_many_arguments)]
3269
fn eval_like(
1✔
3270
    scope: &dyn RowScope,
3271
    negated: bool,
3272
    any: bool,
3273
    lhs: &Expr,
3274
    pattern: &Expr,
3275
    escape_char: Option<&AstValue>,
3276
    case_insensitive: bool,
3277
) -> Result<Value> {
3278
    if any {
1✔
3279
        return Err(SQLRiteError::NotImplemented(
×
3280
            "LIKE ANY (...) is not supported".to_string(),
×
3281
        ));
3282
    }
3283
    if escape_char.is_some() {
1✔
3284
        return Err(SQLRiteError::NotImplemented(
×
3285
            "LIKE ... ESCAPE '<char>' is not supported (default `\\` escape only)".to_string(),
×
3286
        ));
3287
    }
3288

3289
    let l = eval_expr_scope(lhs, scope)?;
1✔
3290
    let p = eval_expr_scope(pattern, scope)?;
2✔
3291
    if matches!(l, Value::Null) || matches!(p, Value::Null) {
1✔
3292
        return Ok(Value::Null);
×
3293
    }
3294
    let text = match l {
1✔
3295
        Value::Text(s) => s,
1✔
3296
        other => other.to_display_string(),
×
3297
    };
3298
    let pat = match p {
1✔
3299
        Value::Text(s) => s,
1✔
3300
        other => other.to_display_string(),
×
3301
    };
3302
    let m = like_match(&text, &pat, case_insensitive);
2✔
3303
    Ok(Value::Bool(if negated { !m } else { m }))
1✔
3304
}
3305

3306
fn eval_in_list(scope: &dyn RowScope, lhs: &Expr, list: &[Expr], negated: bool) -> Result<Value> {
2✔
3307
    let l = eval_expr_scope(lhs, scope)?;
1✔
3308
    if matches!(l, Value::Null) {
1✔
3309
        return Ok(Value::Null);
×
3310
    }
3311
    let mut saw_null = false;
1✔
3312
    for item in list {
2✔
3313
        let r = eval_expr_scope(item, scope)?;
2✔
3314
        if matches!(r, Value::Null) {
1✔
3315
            saw_null = true;
1✔
3316
            continue;
3317
        }
3318
        if compare_values(Some(&l), Some(&r)) == Ordering::Equal {
2✔
3319
            return Ok(Value::Bool(!negated));
1✔
3320
        }
3321
    }
3322
    if saw_null {
2✔
3323
        // SQLite three-valued IN: unmatched + a NULL on the RHS → NULL.
3324
        // WHERE coerces NULL → false, so the row is excluded either way.
3325
        Ok(Value::Null)
1✔
3326
    } else {
3327
        Ok(Value::Bool(negated))
1✔
3328
    }
3329
}
3330

3331
// -----------------------------------------------------------------
3332
// SQLR-3 — Aggregation phase, DISTINCT, post-projection sort
3333
// -----------------------------------------------------------------
3334

3335
/// SQLR-52 — HAVING lowering, shared by the single-table and joined
3336
/// aggregation paths. The expression may reference aggregates and
3337
/// GROUP BY keys that aren't in the SELECT output (SQLite allows
3338
/// both: `SELECT dept FROM t GROUP BY dept HAVING COUNT(*) > 1`).
3339
/// We append those as *hidden* trailing projection slots so the
3340
/// `aggregate_rows` accumulator computes them alongside the visible
3341
/// ones; the pipeline strips them after filtering. Aggregate calls in
3342
/// the HAVING tree are lowered to identifiers naming their output slot
3343
/// (`COUNT(*)` → identifier "COUNT(*)") so the shared expression
3344
/// evaluator can resolve them through a `GroupRowScope` like any other
3345
/// column. Returns the widened projection list plus the lowered
3346
/// HAVING expression (`None` when the query has no HAVING).
3347
fn lower_having_into_hidden_slots(
1✔
3348
    query: &SelectQuery,
3349
    proj_items: &[ProjectionItem],
3350
) -> Result<(Vec<ProjectionItem>, Option<Expr>)> {
3351
    let mut all_items = proj_items.to_vec();
1✔
3352
    let having_expr = match &query.having {
1✔
3353
        Some(h) => {
1✔
3354
            for g in &query.group_by {
2✔
3355
                if !all_items
3✔
3356
                    .iter()
1✔
3357
                    .any(|i| i.output_name().eq_ignore_ascii_case(&g.name))
3✔
3358
                {
3359
                    all_items.push(ProjectionItem {
1✔
3360
                        kind: ProjectionKind::Column {
1✔
3361
                            qualifier: g.qualifier.clone(),
1✔
3362
                            name: g.name.clone(),
1✔
3363
                        },
3364
                        alias: None,
1✔
3365
                    });
3366
                }
3367
            }
3368
            Some(lower_having_expr(h, &mut all_items)?)
1✔
3369
        }
3370
        None => None,
1✔
3371
    };
3372
    Ok((all_items, having_expr))
1✔
3373
}
3374

3375
/// The aggregation tail shared by the single-table and joined SELECT
3376
/// paths: accumulate groups over the row scopes, apply HAVING, strip
3377
/// hidden HAVING-only slots, then DISTINCT / ORDER BY / LIMIT on the
3378
/// output rows. Callers validate column references against their own
3379
/// scope (table schema vs. joined-table list) before invoking.
3380
fn run_aggregation_pipeline<S: RowScope>(
2✔
3381
    scopes: impl IntoIterator<Item = S>,
3382
    query: &SelectQuery,
3383
    proj_items: &[ProjectionItem],
3384
    all_items: &[ProjectionItem],
3385
    having_expr: &Option<Expr>,
3386
) -> Result<SelectResult> {
3387
    let columns: Vec<String> = proj_items.iter().map(|i| i.output_name()).collect();
8✔
3388
    let mut rows = aggregate_rows(scopes, &query.group_by, all_items)?;
5✔
3389

3390
    if let Some(h) = having_expr {
2✔
3391
        let all_columns: Vec<String> = all_items.iter().map(|i| i.output_name()).collect();
8✔
3392
        rows = filter_groups_by_having(rows, h, &all_columns)?;
4✔
3393
    }
3394
    // Drop the hidden HAVING-only slots back to the user-visible width.
3395
    if all_items.len() > proj_items.len() {
2✔
3396
        for row in &mut rows {
1✔
3397
            row.truncate(proj_items.len());
2✔
3398
        }
3399
    }
3400

3401
    if query.distinct {
2✔
NEW
3402
        rows = dedupe_rows(rows);
×
3403
    }
3404

3405
    if let Some(order) = &query.order_by {
4✔
3406
        sort_output_rows(&mut rows, &columns, proj_items, order)?;
4✔
3407
    }
3408
    if let Some(k) = query.limit {
3✔
3409
        rows.truncate(k);
2✔
3410
    }
3411

3412
    Ok(SelectResult { columns, rows })
2✔
3413
}
3414

3415
/// Walk the row scopes, partition into groups (one synthetic group
3416
/// when `group_by` is empty), update one `AggState` per aggregate
3417
/// projection slot per group, then materialize one output row per
3418
/// group in projection order. Group-key columns surface their original
3419
/// `Value` (captured the first time the group was seen); aggregate
3420
/// slots surface `AggState::finalize()`.
3421
///
3422
/// SQLR-6 — generic over [`RowScope`] so the same accumulator serves
3423
/// the single-table path (a [`SingleTableScope`] per matching rowid)
3424
/// and the joined path (a [`JoinedScope`] per joined row, where
3425
/// NULL-padded outer-join sides surface as `Value::Null` — grouped
3426
/// together like any other NULL, and skipped by `COUNT(col)` per the
3427
/// usual NULL-skipping aggregate semantics).
3428
fn aggregate_rows<S: RowScope>(
2✔
3429
    scopes: impl IntoIterator<Item = S>,
3430
    group_by: &[GroupByKey],
3431
    proj_items: &[ProjectionItem],
3432
) -> Result<Vec<Vec<Value>>> {
3433
    // Build the per-projection-slot accumulator template once. Each
3434
    // group clones this template on first sight. Non-aggregate slots
3435
    // hold a "captured group-key value" (`None` until set).
3436
    let template: Vec<Option<AggState>> = proj_items
2✔
3437
        .iter()
3438
        .map(|i| match &i.kind {
6✔
3439
            ProjectionKind::Aggregate(call) => Some(AggState::new(call)),
2✔
3440
            ProjectionKind::Column { .. } => None,
2✔
3441
        })
3442
        .collect();
3443

3444
    // Linear-scan group lookup. For typical ad-hoc queries (cardinality
3445
    // ≪ 10k), this is fine; if grouping cardinality grows, swap to a
3446
    // HashMap<Vec<DistinctKey>, usize> keyed by the same DistinctKey
3447
    // wrapper. Order-preserving for readable output (groups appear in
3448
    // first-occurrence order, matching SQLite's typical behavior).
3449
    let mut keys: Vec<Vec<DistinctKey>> = Vec::new();
2✔
3450
    let mut group_states: Vec<Vec<Option<AggState>>> = Vec::new();
2✔
3451
    let mut group_key_values: Vec<Vec<Value>> = Vec::new();
2✔
3452

3453
    for scope in scopes {
6✔
3454
        let mut key_values: Vec<Value> = Vec::with_capacity(group_by.len());
4✔
3455
        let mut key: Vec<DistinctKey> = Vec::with_capacity(group_by.len());
4✔
3456
        for g in group_by {
6✔
3457
            let v = scope.lookup(g.qualifier.as_deref(), &g.name)?;
4✔
3458
            key.push(DistinctKey::from_value(&v));
4✔
3459
            key_values.push(v);
2✔
3460
        }
3461
        let idx = match keys.iter().position(|k| k == &key) {
6✔
3462
            Some(i) => i,
2✔
3463
            None => {
3464
                keys.push(key);
2✔
3465
                group_states.push(template.clone());
2✔
3466
                group_key_values.push(key_values);
2✔
3467
                keys.len() - 1
2✔
3468
            }
3469
        };
3470

3471
        for (slot, item) in proj_items.iter().enumerate() {
2✔
3472
            if let ProjectionKind::Aggregate(call) = &item.kind {
4✔
3473
                let v = match &call.arg {
2✔
3474
                    AggregateArg::Star => Value::Null,
2✔
3475
                    AggregateArg::Column { qualifier, name } => {
2✔
3476
                        scope.lookup(qualifier.as_deref(), name)?
4✔
3477
                    }
3478
                };
3479
                if let Some(state) = group_states[idx][slot].as_mut() {
4✔
3480
                    state.update(&v)?;
4✔
3481
                }
3482
            }
3483
        }
3484
    }
3485

3486
    // No groups but no aggregate-only "implicit one row" semantic to
3487
    // emit: e.g. `SELECT dept FROM t GROUP BY dept` over an empty
3488
    // matching set should produce zero rows. `SELECT COUNT(*) FROM t`
3489
    // (no GROUP BY) DOES produce one row even on empty input — the
3490
    // single-synthetic-group path below handles it.
3491
    if keys.is_empty() && group_by.is_empty() {
3✔
3492
        // Synthetic single empty group so we still emit one row with
3493
        // initial accumulator finals (e.g. COUNT(*) → 0).
3494
        keys.push(Vec::new());
1✔
3495
        group_states.push(template.clone());
1✔
3496
        group_key_values.push(Vec::new());
1✔
3497
    }
3498

3499
    // Project: one row per group, in projection order.
3500
    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(keys.len());
4✔
3501
    for (group_idx, _) in keys.iter().enumerate() {
6✔
3502
        let mut row: Vec<Value> = Vec::with_capacity(proj_items.len());
4✔
3503
        for (slot, item) in proj_items.iter().enumerate() {
4✔
3504
            match &item.kind {
2✔
3505
                ProjectionKind::Column { qualifier, name: c } => {
2✔
3506
                    // Parser / executor validation ties bare-column
3507
                    // projections to GROUP BY entries, but `SELECT *`
3508
                    // expansions reach here unvalidated — surface a
3509
                    // clean error rather than panicking.
3510
                    let pos = group_by
5✔
3511
                        .iter()
2✔
3512
                        .position(|g| g.matches_column(qualifier.as_deref(), c))
6✔
3513
                        .ok_or_else(|| {
3✔
3514
                            SQLRiteError::Internal(format!(
1✔
3515
                                "column '{c}' must appear in GROUP BY or be used in an \
3516
                                 aggregate function"
3517
                            ))
3518
                        })?;
3519
                    row.push(group_key_values[group_idx][pos].clone());
2✔
3520
                }
3521
                ProjectionKind::Aggregate(_) => {
3522
                    let state = group_states[group_idx][slot]
6✔
3523
                        .as_ref()
3524
                        .expect("aggregate slot has state");
3525
                    row.push(state.finalize());
2✔
3526
                }
3527
            }
3528
        }
3529
        rows.push(row);
2✔
3530
    }
3531
    Ok(rows)
2✔
3532
}
3533

3534
// -----------------------------------------------------------------
3535
// SQLR-52 — HAVING (post-aggregation filter)
3536
// -----------------------------------------------------------------
3537

3538
/// Scope for evaluating a HAVING expression against one group's output
3539
/// row. Column references resolve against the output column names —
3540
/// GROUP BY keys, aggregate aliases, aggregate display forms like
3541
/// `COUNT(*)` (the lowered shape `lower_having_expr` produces), and
3542
/// the hidden HAVING-only slots appended by the executor.
3543
struct GroupRowScope<'a> {
3544
    columns: &'a [String],
3545
    values: &'a [Value],
3546
}
3547

3548
impl RowScope for GroupRowScope<'_> {
3549
    fn lookup(&self, qualifier: Option<&str>, col: &str) -> Result<Value> {
1✔
3550
        // Output columns carry no table qualifier — `t.dept` in HAVING
3551
        // resolves by its column part, same as the aggregating ORDER BY.
3552
        let _ = qualifier;
×
3553
        self.columns
1✔
3554
            .iter()
3555
            .position(|c| c.eq_ignore_ascii_case(col))
3✔
3556
            .map(|i| self.values[i].clone())
3✔
3557
            .ok_or_else(|| {
2✔
3558
                SQLRiteError::Internal(format!(
1✔
3559
                    "HAVING references '{col}', which is neither a GROUP BY column nor an \
×
3560
                     aggregate in scope"
×
3561
                ))
3562
            })
3563
    }
3564

3565
    fn single_table_view(&self) -> Option<(&Table, i64)> {
×
3566
        None
×
3567
    }
3568
}
3569

3570
/// Rewrite a HAVING expression for group-row evaluation: every
3571
/// aggregate call in the tree becomes an identifier naming its output
3572
/// slot (`SUM(salary)` → identifier `"SUM(salary)"`), registering a
3573
/// hidden projection slot for any aggregate not already in the SELECT
3574
/// list so `aggregate_rows` computes it. Non-aggregate functions and
3575
/// leaf expressions pass through untouched — the shared evaluator
3576
/// handles (or rejects) them at filter time.
3577
fn lower_having_expr(expr: &Expr, items: &mut Vec<ProjectionItem>) -> Result<Expr> {
1✔
3578
    Ok(match expr {
2✔
3579
        Expr::Function(func) => {
1✔
3580
            let is_aggregate = matches!(
2✔
3581
                func.name.0.as_slice(),
2✔
3582
                [ObjectNamePart::Identifier(ident)] if AggregateFn::from_name(&ident.value).is_some()
2✔
3583
            );
3584
            if !is_aggregate {
1✔
3585
                return Ok(expr.clone());
×
3586
            }
3587
            let call = parse_aggregate_call(func)?;
2✔
3588
            let display = call.display_name();
2✔
3589
            // Resolvable already? Identifier lookup goes by output
3590
            // column name, so an unaliased projection of the same
3591
            // aggregate (output name == display form) suffices. An
3592
            // *aliased* one doesn't — its output name is the alias —
3593
            // so the call still gets a hidden slot of its own.
3594
            let already_known = items
3✔
3595
                .iter()
1✔
3596
                .any(|i| i.output_name().eq_ignore_ascii_case(&display));
3✔
3597
            if !already_known {
1✔
3598
                items.push(ProjectionItem {
2✔
3599
                    kind: ProjectionKind::Aggregate(call),
1✔
3600
                    alias: None,
1✔
3601
                });
3602
            }
3603
            Expr::Identifier(Ident::new(display))
2✔
3604
        }
3605
        Expr::Nested(inner) => Expr::Nested(Box::new(lower_having_expr(inner, items)?)),
×
3606
        Expr::UnaryOp { op, expr: inner } => Expr::UnaryOp {
×
3607
            op: *op,
×
3608
            expr: Box::new(lower_having_expr(inner, items)?),
×
3609
        },
3610
        Expr::BinaryOp { left, op, right } => Expr::BinaryOp {
2✔
3611
            left: Box::new(lower_having_expr(left, items)?),
2✔
3612
            op: op.clone(),
1✔
3613
            right: Box::new(lower_having_expr(right, items)?),
2✔
3614
        },
3615
        Expr::IsNull(inner) => Expr::IsNull(Box::new(lower_having_expr(inner, items)?)),
×
3616
        Expr::IsNotNull(inner) => Expr::IsNotNull(Box::new(lower_having_expr(inner, items)?)),
×
3617
        Expr::InList {
3618
            expr: lhs,
×
3619
            list,
×
3620
            negated,
×
3621
        } => Expr::InList {
×
3622
            expr: Box::new(lower_having_expr(lhs, items)?),
×
3623
            list: list
×
3624
                .iter()
×
3625
                .map(|e| lower_having_expr(e, items))
×
3626
                .collect::<Result<Vec<_>>>()?,
×
3627
            negated: *negated,
×
3628
        },
3629
        Expr::Like {
3630
            negated,
×
3631
            any,
×
3632
            expr: lhs,
×
3633
            pattern,
×
3634
            escape_char,
×
3635
        } => Expr::Like {
×
3636
            negated: *negated,
×
3637
            any: *any,
×
3638
            expr: Box::new(lower_having_expr(lhs, items)?),
×
3639
            pattern: Box::new(lower_having_expr(pattern, items)?),
×
3640
            escape_char: escape_char.clone(),
×
3641
        },
3642
        Expr::ILike {
3643
            negated,
×
3644
            any,
×
3645
            expr: lhs,
×
3646
            pattern,
×
3647
            escape_char,
×
3648
        } => Expr::ILike {
×
3649
            negated: *negated,
×
3650
            any: *any,
×
3651
            expr: Box::new(lower_having_expr(lhs, items)?),
×
3652
            pattern: Box::new(lower_having_expr(pattern, items)?),
×
3653
            escape_char: escape_char.clone(),
×
3654
        },
3655
        // Leaves (identifiers, literals) and unsupported shapes pass
3656
        // through; the evaluator produces its own error for the latter.
3657
        other => other.clone(),
1✔
3658
    })
3659
}
3660

3661
/// Keep only the groups whose HAVING expression evaluates truthy.
3662
/// NULL collapses to false — same three-valued-logic coercion the
3663
/// WHERE path applies.
3664
fn filter_groups_by_having(
1✔
3665
    rows: Vec<Vec<Value>>,
3666
    having: &Expr,
3667
    columns: &[String],
3668
) -> Result<Vec<Vec<Value>>> {
3669
    let mut out = Vec::with_capacity(rows.len());
2✔
3670
    for row in rows {
4✔
3671
        let scope = GroupRowScope {
3672
            columns,
3673
            values: &row,
1✔
3674
        };
3675
        let keep = match eval_expr_scope(having, &scope)? {
2✔
3676
            Value::Bool(b) => b,
1✔
3677
            Value::Null => false,
×
3678
            Value::Integer(i) => i != 0,
×
3679
            other => {
×
3680
                return Err(SQLRiteError::Internal(format!(
×
3681
                    "HAVING clause must evaluate to boolean, got {}",
3682
                    other.to_display_string()
×
3683
                )));
3684
            }
3685
        };
3686
        if keep {
1✔
3687
            out.push(row);
1✔
3688
        }
3689
    }
3690
    Ok(out)
1✔
3691
}
3692

3693
/// SELECT DISTINCT post-pass. Walks the rows once with a `HashSet` of
3694
/// row-keys, preserving first-occurrence order. NULL == NULL for
3695
/// dedupe purposes, which matches the SQL DISTINCT semantic.
3696
fn dedupe_rows(rows: Vec<Vec<Value>>) -> Vec<Vec<Value>> {
1✔
3697
    use std::collections::HashSet;
3698
    let mut seen: HashSet<Vec<DistinctKey>> = HashSet::new();
1✔
3699
    let mut out = Vec::with_capacity(rows.len());
2✔
3700
    for row in rows {
4✔
3701
        let key: Vec<DistinctKey> = row.iter().map(DistinctKey::from_value).collect();
2✔
3702
        if seen.insert(key) {
1✔
3703
            out.push(row);
1✔
3704
        }
3705
    }
3706
    out
1✔
3707
}
3708

3709
/// Sort output rows for the aggregating path. ORDER BY can reference
3710
/// either an output column name (alias or bare GROUP BY column) or an
3711
/// aggregate function call by display form (e.g. `COUNT(*)`).
3712
fn sort_output_rows(
1✔
3713
    rows: &mut [Vec<Value>],
3714
    columns: &[String],
3715
    proj_items: &[ProjectionItem],
3716
    order: &OrderByClause,
3717
) -> Result<()> {
3718
    let target_idx = resolve_order_by_index(&order.expr, columns, proj_items)?;
1✔
3719
    rows.sort_by(|a, b| {
2✔
3720
        let va = &a[target_idx];
1✔
3721
        let vb = &b[target_idx];
1✔
3722
        let ord = compare_values(Some(va), Some(vb));
1✔
3723
        if order.ascending { ord } else { ord.reverse() }
1✔
3724
    });
3725
    Ok(())
1✔
3726
}
3727

3728
/// Map an ORDER BY expression to the index of the output column that
3729
/// should drive the sort.
3730
fn resolve_order_by_index(
1✔
3731
    expr: &Expr,
3732
    columns: &[String],
3733
    proj_items: &[ProjectionItem],
3734
) -> Result<usize> {
3735
    // Bare identifier — match against output names (alias-first).
3736
    let target_name: Option<String> = match expr {
1✔
3737
        Expr::Identifier(ident) => Some(ident.value.clone()),
1✔
3738
        Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
3✔
3739
        Expr::Function(_) => None,
1✔
3740
        Expr::Nested(inner) => return resolve_order_by_index(inner, columns, proj_items),
×
3741
        other => {
×
3742
            return Err(SQLRiteError::NotImplemented(format!(
×
3743
                "ORDER BY expression not supported on aggregating queries: {other:?}"
3744
            )));
3745
        }
3746
    };
3747
    if let Some(name) = target_name {
2✔
3748
        if let Some(i) = columns.iter().position(|c| c.eq_ignore_ascii_case(&name)) {
4✔
3749
            return Ok(i);
1✔
3750
        }
3751
        return Err(SQLRiteError::Internal(format!(
×
3752
            "ORDER BY references unknown column '{name}' in the SELECT output"
3753
        )));
3754
    }
3755
    // Function form: match by display name against any aggregate item
3756
    // whose canonical display equals the user's call. Tolerate case
3757
    // differences in the function name. SQLR-6 — a second pass with
3758
    // `t.` qualifiers stripped from both sides keeps qualifier
3759
    // spelling differences from blocking the match (`ORDER BY
3760
    // SUM(amount)` finds a `SELECT SUM(o.amount)` slot and vice
3761
    // versa), preserving the pre-qualifier behavior.
3762
    if let Expr::Function(func) = expr {
2✔
3763
        let user_disp = format_function_display(func, true);
1✔
3764
        for (i, item) in proj_items.iter().enumerate() {
2✔
3765
            if let ProjectionKind::Aggregate(call) = &item.kind
2✔
3766
                && call.display_name().eq_ignore_ascii_case(&user_disp)
1✔
3767
            {
3768
                return Ok(i);
1✔
3769
            }
3770
        }
3771
        let user_disp_unqualified = format_function_display(func, false);
1✔
3772
        for (i, item) in proj_items.iter().enumerate() {
2✔
3773
            if let ProjectionKind::Aggregate(call) = &item.kind
2✔
3774
                && call
2✔
3775
                    .display_name_unqualified()
1✔
NEW
3776
                    .eq_ignore_ascii_case(&user_disp_unqualified)
×
3777
            {
3778
                return Ok(i);
1✔
3779
            }
3780
        }
UNCOV
3781
        return Err(SQLRiteError::Internal(format!(
×
3782
            "ORDER BY references aggregate '{user_disp}' that isn't in the SELECT output"
3783
        )));
3784
    }
3785
    Err(SQLRiteError::Internal(
×
3786
        "ORDER BY expression could not be resolved against the output columns".to_string(),
×
3787
    ))
3788
}
3789

3790
/// Format a sqlparser function call into the same canonical form
3791
/// `AggregateCall::display_name()` uses, so ORDER BY on
3792
/// `COUNT(*)` / `SUM(salary)` matches its projection counterpart.
3793
/// `qualified` keeps or strips the argument's `t.` qualifier, matching
3794
/// `display_name()` / `display_name_unqualified()` respectively.
3795
fn format_function_display(func: &sqlparser::ast::Function, qualified: bool) -> String {
1✔
3796
    let name = match func.name.0.as_slice() {
2✔
3797
        [ObjectNamePart::Identifier(ident)] => ident.value.to_uppercase(),
2✔
3798
        _ => format!("{:?}", func.name).to_uppercase(),
×
3799
    };
3800
    let inner = match &func.args {
1✔
3801
        FunctionArguments::List(l) => {
1✔
3802
            let distinct = matches!(
1✔
3803
                l.duplicate_treatment,
1✔
3804
                Some(sqlparser::ast::DuplicateTreatment::Distinct)
3805
            );
3806
            let arg = l.args.first().map(|a| match a {
4✔
3807
                FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => "*".to_string(),
1✔
3808
                FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Identifier(i))) => i.value.clone(),
1✔
3809
                FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::CompoundIdentifier(parts))) => {
1✔
3810
                    if qualified {
1✔
3811
                        parts
2✔
3812
                            .iter()
1✔
3813
                            .map(|p| p.value.clone())
3✔
3814
                            .collect::<Vec<_>>()
1✔
NEW
3815
                            .join(".")
×
3816
                    } else {
NEW
3817
                        parts.last().map(|p| p.value.clone()).unwrap_or_default()
×
3818
                    }
3819
                }
3820
                _ => String::new(),
×
3821
            });
3822
            match (distinct, arg) {
2✔
3823
                (true, Some(a)) if a != "*" => format!("DISTINCT {a}"),
×
3824
                (_, Some(a)) => a,
1✔
3825
                _ => String::new(),
×
3826
            }
3827
        }
3828
        _ => String::new(),
×
3829
    };
3830
    format!("{name}({inner})")
2✔
3831
}
3832

3833
fn convert_literal(v: &sqlparser::ast::Value) -> Result<Value> {
1✔
3834
    use sqlparser::ast::Value as AstValue;
3835
    match v {
1✔
3836
        AstValue::Number(n, _) => {
1✔
3837
            if let Ok(i) = n.parse::<i64>() {
2✔
3838
                Ok(Value::Integer(i))
1✔
3839
            } else if let Ok(f) = n.parse::<f64>() {
2✔
3840
                Ok(Value::Real(f))
1✔
3841
            } else {
3842
                Err(SQLRiteError::Internal(format!(
×
3843
                    "could not parse numeric literal '{n}'"
3844
                )))
3845
            }
3846
        }
3847
        AstValue::SingleQuotedString(s) => Ok(Value::Text(s.clone())),
1✔
3848
        AstValue::Boolean(b) => Ok(Value::Bool(*b)),
1✔
3849
        AstValue::Null => Ok(Value::Null),
1✔
3850
        other => Err(SQLRiteError::NotImplemented(format!(
×
3851
            "unsupported literal value: {other:?}"
3852
        ))),
3853
    }
3854
}
3855

3856
#[cfg(test)]
3857
mod tests {
3858
    use super::*;
3859

3860
    // -----------------------------------------------------------------
3861
    // Phase 7b — Vector distance function math
3862
    // -----------------------------------------------------------------
3863

3864
    /// Float comparison helper — distance results need a small epsilon
3865
    /// because we accumulate sums across many f32 multiplies.
3866
    fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
1✔
3867
        (a - b).abs() < eps
1✔
3868
    }
3869

3870
    #[test]
3871
    fn vec_distance_l2_identical_is_zero() {
3✔
3872
        let v = vec![0.1, 0.2, 0.3];
1✔
3873
        assert_eq!(vec_distance_l2(&v, &v), 0.0);
2✔
3874
    }
3875

3876
    #[test]
3877
    fn vec_distance_l2_unit_basis_is_sqrt2() {
3✔
3878
        // [1, 0] vs [0, 1]: distance = √((1-0)² + (0-1)²) = √2 ≈ 1.414
3879
        let a = vec![1.0, 0.0];
1✔
3880
        let b = vec![0.0, 1.0];
2✔
3881
        assert!(approx_eq(vec_distance_l2(&a, &b), 2.0_f32.sqrt(), 1e-6));
2✔
3882
    }
3883

3884
    #[test]
3885
    fn vec_distance_l2_known_value() {
4✔
3886
        // [0, 0, 0] vs [3, 4, 0]: √(9 + 16 + 0) = 5 (the classic 3-4-5 triangle).
3887
        let a = vec![0.0, 0.0, 0.0];
1✔
3888
        let b = vec![3.0, 4.0, 0.0];
2✔
3889
        assert!(approx_eq(vec_distance_l2(&a, &b), 5.0, 1e-6));
2✔
3890
    }
3891

3892
    #[test]
3893
    fn vec_distance_cosine_identical_is_zero() {
3✔
3894
        let v = vec![0.1, 0.2, 0.3];
1✔
3895
        let d = vec_distance_cosine(&v, &v).unwrap();
2✔
3896
        assert!(approx_eq(d, 0.0, 1e-6), "cos(v,v) = {d}, expected ≈ 0");
1✔
3897
    }
3898

3899
    #[test]
3900
    fn vec_distance_cosine_orthogonal_is_one() {
3✔
3901
        // Two orthogonal unit vectors should have cosine distance = 1.0
3902
        // (cosine similarity = 0 → distance = 1 - 0 = 1).
3903
        let a = vec![1.0, 0.0];
1✔
3904
        let b = vec![0.0, 1.0];
2✔
3905
        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 1.0, 1e-6));
2✔
3906
    }
3907

3908
    #[test]
3909
    fn vec_distance_cosine_opposite_is_two() {
3✔
3910
        // a and -a have cosine similarity = -1 → distance = 1 - (-1) = 2.
3911
        let a = vec![1.0, 0.0, 0.0];
1✔
3912
        let b = vec![-1.0, 0.0, 0.0];
2✔
3913
        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 2.0, 1e-6));
2✔
3914
    }
3915

3916
    #[test]
3917
    fn vec_distance_cosine_zero_magnitude_errors() {
3✔
3918
        // Cosine is undefined for the zero vector — error rather than NaN.
3919
        let a = vec![0.0, 0.0];
1✔
3920
        let b = vec![1.0, 0.0];
2✔
3921
        let err = vec_distance_cosine(&a, &b).unwrap_err();
2✔
3922
        assert!(format!("{err}").contains("zero-magnitude"));
2✔
3923
    }
3924

3925
    #[test]
3926
    fn vec_distance_dot_negates() {
4✔
3927
        // a·b = 1*4 + 2*5 + 3*6 = 32. Negated → -32.
3928
        let a = vec![1.0, 2.0, 3.0];
1✔
3929
        let b = vec![4.0, 5.0, 6.0];
2✔
3930
        assert!(approx_eq(vec_distance_dot(&a, &b), -32.0, 1e-6));
2✔
3931
    }
3932

3933
    #[test]
3934
    fn vec_distance_dot_orthogonal_is_zero() {
3✔
3935
        // Orthogonal vectors have dot product 0 → negated is also 0.
3936
        let a = vec![1.0, 0.0];
1✔
3937
        let b = vec![0.0, 1.0];
2✔
3938
        assert_eq!(vec_distance_dot(&a, &b), 0.0);
2✔
3939
    }
3940

3941
    #[test]
3942
    fn vec_distance_dot_unit_norm_matches_cosine_minus_one() {
3✔
3943
        // For unit-norm vectors: dot(a,b) = cos(a,b)
3944
        // → -dot(a,b) = -cos(a,b) = (1 - cos(a,b)) - 1 = vec_distance_cosine(a,b) - 1.
3945
        // Useful sanity check that the two functions agree on unit vectors.
3946
        let a = vec![0.6f32, 0.8]; // unit norm: √(0.36+0.64) = 1
1✔
3947
        let b = vec![0.8f32, 0.6]; // unit norm too
2✔
3948
        let dot = vec_distance_dot(&a, &b);
2✔
3949
        let cos = vec_distance_cosine(&a, &b).unwrap();
1✔
3950
        assert!(approx_eq(dot, cos - 1.0, 1e-5));
1✔
3951
    }
3952

3953
    // -----------------------------------------------------------------
3954
    // Phase 7c — bounded-heap top-k correctness + benchmark
3955
    // -----------------------------------------------------------------
3956

3957
    use crate::sql::db::database::Database;
3958
    use crate::sql::dialect::SqlriteDialect;
3959
    use crate::sql::parser::select::SelectQuery;
3960
    use sqlparser::parser::Parser;
3961

3962
    /// Builds a `docs(id INTEGER PK, score REAL)` table with N rows of
3963
    /// distinct positive scores so top-k tests aren't sensitive to
3964
    /// tie-breaking (heap is unstable; full-sort is stable; we want
3965
    /// both to agree without arguing about equal-score row order).
3966
    ///
3967
    /// **Why positive scores:** the INSERT parser doesn't currently
3968
    /// handle `Expr::UnaryOp(Minus, …)` for negative number literals
3969
    /// (it would parse `-3.14` as a unary expression and the value
3970
    /// extractor would skip it). That's a pre-existing bug, out of
3971
    /// scope for 7c. Using the Knuth multiplicative hash gives us
3972
    /// distinct positive scrambled values without dancing around the
3973
    /// negative-literal limitation.
3974
    fn seed_score_table(n: usize) -> Database {
1✔
3975
        let mut db = Database::new("tempdb".to_string());
1✔
3976
        crate::sql::process_command(
3977
            "CREATE TABLE docs (id INTEGER PRIMARY KEY, score REAL);",
3978
            &mut db,
3979
        )
3980
        .expect("create");
3981
        for i in 0..n {
1✔
3982
            // Knuth multiplicative hash mod 1_000_000 — distinct,
3983
            // dense in [0, 999_999], no collisions for n up to ~tens
3984
            // of thousands.
3985
            let score = ((i as u64).wrapping_mul(2_654_435_761) % 1_000_000) as f64;
2✔
3986
            let sql = format!("INSERT INTO docs (score) VALUES ({score});");
1✔
3987
            crate::sql::process_command(&sql, &mut db).expect("insert");
2✔
3988
        }
3989
        db
1✔
3990
    }
3991

3992
    /// Helper: parses an SQL SELECT into a SelectQuery so we can drive
3993
    /// `select_topk` / `sort_rowids` directly without the rest of the
3994
    /// process_command pipeline.
3995
    fn parse_select(sql: &str) -> SelectQuery {
1✔
3996
        let dialect = SqlriteDialect::new();
1✔
3997
        let mut ast = Parser::parse_sql(&dialect, sql).expect("parse");
1✔
3998
        let stmt = ast.pop().expect("one statement");
2✔
3999
        SelectQuery::new(&stmt).expect("select-query")
2✔
4000
    }
4001

4002
    #[test]
4003
    fn topk_matches_full_sort_asc() {
3✔
4004
        // Build N=200, top-k=10. Bounded heap output must equal
4005
        // full-sort-then-truncate output (both produce ASC order).
4006
        let db = seed_score_table(200);
1✔
4007
        let table = db.get_table("docs".to_string()).unwrap();
2✔
4008
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
1✔
4009
        let order = q.order_by.as_ref().unwrap();
2✔
4010
        let all_rowids = table.rowids();
1✔
4011

4012
        // Full-sort path
4013
        let mut full = all_rowids.clone();
1✔
4014
        sort_rowids(&mut full, table, order).unwrap();
2✔
4015
        full.truncate(10);
1✔
4016

4017
        // Bounded-heap path
4018
        let topk = select_topk(&all_rowids, table, order, 10).unwrap();
1✔
4019

4020
        assert_eq!(topk, full, "top-k via heap should match full-sort+truncate");
2✔
4021
    }
4022

4023
    #[test]
4024
    fn topk_matches_full_sort_desc() {
3✔
4025
        // Same with DESC — verifies the direction-aware Ord wrapper.
4026
        let db = seed_score_table(200);
1✔
4027
        let table = db.get_table("docs".to_string()).unwrap();
2✔
4028
        let q = parse_select("SELECT * FROM docs ORDER BY score DESC LIMIT 10;");
1✔
4029
        let order = q.order_by.as_ref().unwrap();
2✔
4030
        let all_rowids = table.rowids();
1✔
4031

4032
        let mut full = all_rowids.clone();
1✔
4033
        sort_rowids(&mut full, table, order).unwrap();
2✔
4034
        full.truncate(10);
1✔
4035

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

4038
        assert_eq!(
2✔
4039
            topk, full,
4040
            "top-k DESC via heap should match full-sort+truncate"
4041
        );
4042
    }
4043

4044
    #[test]
4045
    fn topk_k_larger_than_n_returns_everything_sorted() {
3✔
4046
        // The executor branches off to the full-sort path when k >= N,
4047
        // but if a caller invokes select_topk directly with k > N, it
4048
        // should still produce all-sorted output (no truncation
4049
        // because we don't have N items to truncate to k).
4050
        let db = seed_score_table(50);
1✔
4051
        let table = db.get_table("docs".to_string()).unwrap();
2✔
4052
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1000;");
1✔
4053
        let order = q.order_by.as_ref().unwrap();
2✔
4054
        let topk = select_topk(&table.rowids(), table, order, 1000).unwrap();
1✔
4055
        assert_eq!(topk.len(), 50);
1✔
4056
        // All scores in ascending order.
4057
        let scores: Vec<f64> = topk
1✔
4058
            .iter()
4059
            .filter_map(|r| match table.get_value("score", *r) {
3✔
4060
                Some(Value::Real(f)) => Some(f),
1✔
4061
                _ => None,
×
4062
            })
4063
            .collect();
4064
        assert!(scores.windows(2).all(|w| w[0] <= w[1]));
4✔
4065
    }
4066

4067
    #[test]
4068
    fn topk_k_zero_returns_empty() {
3✔
4069
        let db = seed_score_table(10);
1✔
4070
        let table = db.get_table("docs".to_string()).unwrap();
2✔
4071
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1;");
1✔
4072
        let order = q.order_by.as_ref().unwrap();
2✔
4073
        let topk = select_topk(&table.rowids(), table, order, 0).unwrap();
1✔
4074
        assert!(topk.is_empty());
1✔
4075
    }
4076

4077
    #[test]
4078
    fn topk_empty_input_returns_empty() {
3✔
4079
        let db = seed_score_table(0);
1✔
4080
        let table = db.get_table("docs".to_string()).unwrap();
2✔
4081
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 5;");
1✔
4082
        let order = q.order_by.as_ref().unwrap();
2✔
4083
        let topk = select_topk(&[], table, order, 5).unwrap();
1✔
4084
        assert!(topk.is_empty());
2✔
4085
    }
4086

4087
    #[test]
4088
    fn topk_works_through_select_executor_with_distance_function() {
3✔
4089
        // Integration check that the executor actually picks the
4090
        // bounded-heap path on a KNN-shaped query and produces the
4091
        // correct top-k.
4092
        let mut db = Database::new("tempdb".to_string());
1✔
4093
        crate::sql::process_command(
4094
            "CREATE TABLE docs (id INTEGER PRIMARY KEY, e VECTOR(2));",
4095
            &mut db,
4096
        )
4097
        .unwrap();
4098
        // Five rows with distinct distances from probe [1.0, 0.0]:
4099
        //   id=1 [1.0, 0.0]   distance=0
4100
        //   id=2 [2.0, 0.0]   distance=1
4101
        //   id=3 [0.0, 3.0]   distance=√(1+9) = √10 ≈ 3.16
4102
        //   id=4 [1.0, 4.0]   distance=4
4103
        //   id=5 [10.0, 10.0] distance=√(81+100) ≈ 13.45
4104
        for v in &[
1✔
4105
            "[1.0, 0.0]",
4106
            "[2.0, 0.0]",
4107
            "[0.0, 3.0]",
4108
            "[1.0, 4.0]",
4109
            "[10.0, 10.0]",
4110
        ] {
4111
            crate::sql::process_command(&format!("INSERT INTO docs (e) VALUES ({v});"), &mut db)
3✔
4112
                .unwrap();
4113
        }
4114
        let resp = crate::sql::process_command(
4115
            "SELECT id FROM docs ORDER BY vec_distance_l2(e, [1.0, 0.0]) ASC LIMIT 3;",
4116
            &mut db,
4117
        )
4118
        .unwrap();
4119
        // Top-3 closest to [1.0, 0.0] are id=1, id=2, id=3 (in that order).
4120
        // The status message tells us how many rows came back.
4121
        assert!(resp.contains("3 rows returned"), "got: {resp}");
2✔
4122
    }
4123

4124
    /// Manual benchmark — not run by default. Recommended invocation:
4125
    ///
4126
    ///     cargo test -p sqlrite-engine --lib topk_benchmark --release \
4127
    ///         -- --ignored --nocapture
4128
    ///
4129
    /// (`--release` matters: Rust's optimized sort gets very fast under
4130
    /// optimization, so the heap's relative advantage is best observed
4131
    /// against a sort that's also been optimized.)
4132
    ///
4133
    /// Measured numbers on an Apple Silicon laptop with N=10_000 + k=10:
4134
    ///   - bounded heap:    ~820µs
4135
    ///   - full sort+trunc: ~1.5ms
4136
    ///   - ratio:           ~1.8×
4137
    ///
4138
    /// The advantage is real but moderate at this size because the sort
4139
    /// key here is a single REAL column read (cheap) and Rust's sort_by
4140
    /// has a very low constant factor. The asymptotic O(N log k) vs
4141
    /// O(N log N) advantage scales with N and with per-row work — KNN
4142
    /// queries where the sort key is `vec_distance_l2(col, [...])` are
4143
    /// where this path really pays off, because each key evaluation is
4144
    /// itself O(dim) and the heap path skips the per-row evaluation
4145
    /// in the comparator (see `sort_rowids` for the contrast).
4146
    #[test]
4147
    #[ignore]
4148
    fn topk_benchmark() {
4149
        use std::time::Instant;
4150
        const N: usize = 10_000;
4151
        const K: usize = 10;
4152

4153
        let db = seed_score_table(N);
4154
        let table = db.get_table("docs".to_string()).unwrap();
4155
        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
4156
        let order = q.order_by.as_ref().unwrap();
4157
        let all_rowids = table.rowids();
4158

4159
        // Time bounded heap.
4160
        let t0 = Instant::now();
4161
        let _topk = select_topk(&all_rowids, table, order, K).unwrap();
4162
        let heap_dur = t0.elapsed();
4163

4164
        // Time full sort + truncate.
4165
        let t1 = Instant::now();
4166
        let mut full = all_rowids.clone();
4167
        sort_rowids(&mut full, table, order).unwrap();
4168
        full.truncate(K);
4169
        let sort_dur = t1.elapsed();
4170

4171
        let ratio = sort_dur.as_secs_f64() / heap_dur.as_secs_f64().max(1e-9);
4172
        println!("\n--- topk_benchmark (N={N}, k={K}) ---");
4173
        println!("  bounded heap:   {heap_dur:?}");
4174
        println!("  full sort+trunc: {sort_dur:?}");
4175
        println!("  speedup ratio:  {ratio:.2}×");
4176

4177
        // Soft assertion. Floor is 1.4× because the cheap-key
4178
        // benchmark hovers around 1.8× empirically; setting this too
4179
        // close to the measured value risks flaky CI on slower
4180
        // runners. Floor of 1.4× still catches an actual regression
4181
        // (e.g., if select_topk became O(N²) or stopped using the
4182
        // heap entirely).
4183
        assert!(
4184
            ratio > 1.4,
4185
            "bounded heap should be substantially faster than full sort, but ratio = {ratio:.2}"
4186
        );
4187
    }
4188

4189
    // ---------------------------------------------------------------------
4190
    // SQLR-7 — IS NULL / IS NOT NULL
4191
    // ---------------------------------------------------------------------
4192

4193
    /// Helper for IS NULL tests: run a SELECT through process_command and
4194
    /// return the rendered table as a String so the test can assert on the
4195
    /// row-count line without re-implementing the executor.
4196
    fn run_select(db: &mut Database, sql: &str) -> String {
1✔
4197
        crate::sql::process_command(sql, db).expect("select")
1✔
4198
    }
4199

4200
    #[test]
4201
    fn where_is_null_returns_null_rows() {
3✔
4202
        let mut db = Database::new("t".to_string());
1✔
4203
        crate::sql::process_command(
4204
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
4205
            &mut db,
4206
        )
4207
        .unwrap();
4208
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, 10);", &mut db).unwrap();
1✔
4209
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
4210
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
4211
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (4, NULL);", &mut db).unwrap();
1✔
4212

4213
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NULL;");
1✔
4214
        assert!(
×
4215
            response.contains("2 rows returned"),
2✔
4216
            "IS NULL should return 2 rows, got: {response}"
4217
        );
4218
    }
4219

4220
    #[test]
4221
    fn where_is_not_null_returns_non_null_rows() {
3✔
4222
        let mut db = Database::new("t".to_string());
1✔
4223
        crate::sql::process_command(
4224
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
4225
            &mut db,
4226
        )
4227
        .unwrap();
4228
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, 10);", &mut db).unwrap();
1✔
4229
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
4230
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
4231

4232
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NOT NULL;");
1✔
4233
        assert!(
×
4234
            response.contains("2 rows returned"),
2✔
4235
            "IS NOT NULL should return 2 rows, got: {response}"
4236
        );
4237
    }
4238

4239
    #[test]
4240
    fn where_is_null_on_indexed_column() {
3✔
4241
        // UNIQUE on a TEXT column gets an automatic secondary index.
4242
        // NULLs aren't stored in the index, so IS NULL falls through to
4243
        // a full scan via select_rowids — verify the full-scan path is
4244
        // still correct.
4245
        let mut db = Database::new("t".to_string());
1✔
4246
        crate::sql::process_command(
4247
            "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT UNIQUE);",
4248
            &mut db,
4249
        )
4250
        .unwrap();
4251
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (1, 'alice');", &mut db)
1✔
4252
            .unwrap();
4253
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (2, NULL);", &mut db).unwrap();
1✔
4254
        crate::sql::process_command("INSERT INTO t (id, name) VALUES (3, 'bob');", &mut db)
1✔
4255
            .unwrap();
4256

4257
        let null_rows = run_select(&mut db, "SELECT id FROM t WHERE name IS NULL;");
1✔
4258
        assert!(
×
4259
            null_rows.contains("1 row returned"),
2✔
4260
            "indexed IS NULL should return 1 row, got: {null_rows}"
4261
        );
4262
        let not_null_rows = run_select(&mut db, "SELECT id FROM t WHERE name IS NOT NULL;");
1✔
4263
        assert!(
×
4264
            not_null_rows.contains("2 rows returned"),
2✔
4265
            "indexed IS NOT NULL should return 2 rows, got: {not_null_rows}"
4266
        );
4267
    }
4268

4269
    #[test]
4270
    fn where_is_null_works_on_omitted_column() {
3✔
4271
        // No DEFAULT, column missing from the INSERT column list — the
4272
        // BTreeMap entry never gets written, get_value returns None,
4273
        // eval_expr maps that to Value::Null, and IS NULL matches.
4274
        let mut db = Database::new("t".to_string());
1✔
4275
        crate::sql::process_command(
4276
            "CREATE TABLE t (id INTEGER PRIMARY KEY, qty INTEGER, label TEXT);",
4277
            &mut db,
4278
        )
4279
        .unwrap();
4280
        crate::sql::process_command(
4281
            "INSERT INTO t (id, qty, label) VALUES (1, 7, 'a');",
4282
            &mut db,
4283
        )
4284
        .unwrap();
4285
        // qty omitted on row 2.
4286
        crate::sql::process_command("INSERT INTO t (id, label) VALUES (2, 'b');", &mut db).unwrap();
1✔
4287

4288
        let response = run_select(&mut db, "SELECT id FROM t WHERE qty IS NULL;");
1✔
4289
        assert!(
×
4290
            response.contains("1 row returned"),
2✔
4291
            "IS NULL should match the omitted-column row, got: {response}"
4292
        );
4293
    }
4294

4295
    #[test]
4296
    fn where_is_null_combines_with_and_or() {
3✔
4297
        // Sanity check that the new arms compose with the existing
4298
        // boolean operators in eval_expr — `n IS NULL AND id > 1`
4299
        // should narrow correctly.
4300
        let mut db = Database::new("t".to_string());
1✔
4301
        crate::sql::process_command(
4302
            "CREATE TABLE t (id INTEGER PRIMARY KEY, n INTEGER);",
4303
            &mut db,
4304
        )
4305
        .unwrap();
4306
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (1, NULL);", &mut db).unwrap();
1✔
4307
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (2, NULL);", &mut db).unwrap();
1✔
4308
        crate::sql::process_command("INSERT INTO t (id, n) VALUES (3, 30);", &mut db).unwrap();
1✔
4309

4310
        let response = run_select(&mut db, "SELECT id FROM t WHERE n IS NULL AND id > 1;");
1✔
4311
        assert!(
×
4312
            response.contains("1 row returned"),
2✔
4313
            "IS NULL combined with AND should match exactly row 2, got: {response}"
4314
        );
4315
    }
4316

4317
    // ---------------------------------------------------------------------
4318
    // SQLR-3 — LIKE / IN / DISTINCT / GROUP BY / aggregates
4319
    // ---------------------------------------------------------------------
4320

4321
    /// Seed a small employees table the analytical tests share.
4322
    fn seed_employees() -> Database {
1✔
4323
        let mut db = Database::new("t".to_string());
1✔
4324
        crate::sql::process_command(
4325
            "CREATE TABLE emp (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER);",
4326
            &mut db,
4327
        )
4328
        .unwrap();
4329
        let rows = [
1✔
4330
            "INSERT INTO emp (name, dept, salary) VALUES ('Alice', 'eng', 100);",
4331
            "INSERT INTO emp (name, dept, salary) VALUES ('alex',  'eng', 120);",
4332
            "INSERT INTO emp (name, dept, salary) VALUES ('Bob',   'eng', 100);",
4333
            "INSERT INTO emp (name, dept, salary) VALUES ('Carol', 'sales', 90);",
4334
            "INSERT INTO emp (name, dept, salary) VALUES ('Dave',  'sales', NULL);",
4335
            "INSERT INTO emp (name, dept, salary) VALUES ('Eve',   'ops', 80);",
4336
        ];
4337
        for sql in rows {
2✔
4338
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4339
        }
4340
        db
1✔
4341
    }
4342

4343
    /// Drive `execute_select_rows` directly so tests can assert on typed values.
4344
    fn run_rows(db: &Database, sql: &str) -> SelectResult {
1✔
4345
        let q = parse_select(sql);
1✔
4346
        execute_select_rows(q, db).expect("select")
1✔
4347
    }
4348

4349
    // ----- LIKE -----
4350

4351
    #[test]
4352
    fn like_percent_prefix_case_insensitive() {
3✔
4353
        let db = seed_employees();
1✔
4354
        let r = run_rows(&db, "SELECT name FROM emp WHERE name LIKE 'a%';");
1✔
4355
        // Matches Alice and alex (case-insensitive ASCII).
4356
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
4357
        assert_eq!(names.len(), 2, "expected 2 rows, got {names:?}");
2✔
4358
        assert!(names.contains(&"Alice".to_string()));
2✔
4359
        assert!(names.contains(&"alex".to_string()));
1✔
4360
    }
4361

4362
    #[test]
4363
    fn like_underscore_singlechar() {
3✔
4364
        let db = seed_employees();
1✔
4365
        let r = run_rows(&db, "SELECT name FROM emp WHERE name LIKE '_ve';");
1✔
4366
        // Eve matches; alex does not (3 chars vs 4).
4367
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
4368
        assert_eq!(names, vec!["Eve".to_string()]);
2✔
4369
    }
4370

4371
    #[test]
4372
    fn not_like_excludes_match() {
3✔
4373
        let db = seed_employees();
1✔
4374
        let r = run_rows(&db, "SELECT name FROM emp WHERE name NOT LIKE 'a%';");
1✔
4375
        // Excludes Alice + alex; 4 rows remain.
4376
        assert_eq!(r.rows.len(), 4);
2✔
4377
    }
4378

4379
    #[test]
4380
    fn like_with_null_excludes_row() {
3✔
4381
        let db = seed_employees();
1✔
4382
        // Match 'sales' rows where salary is NULL → just Dave.
4383
        let r = run_rows(
4384
            &db,
4385
            "SELECT name FROM emp WHERE dept LIKE 'sales' AND salary IS NULL;",
4386
        );
4387
        assert_eq!(r.rows.len(), 1);
2✔
4388
        assert_eq!(r.rows[0][0].to_display_string(), "Dave");
1✔
4389
    }
4390

4391
    // ----- IN -----
4392

4393
    #[test]
4394
    fn in_list_positive() {
3✔
4395
        let db = seed_employees();
1✔
4396
        let r = run_rows(&db, "SELECT name FROM emp WHERE id IN (1, 3, 5);");
1✔
4397
        let names: Vec<_> = r.rows.iter().map(|r| r[0].to_display_string()).collect();
4✔
4398
        assert_eq!(names.len(), 3);
2✔
4399
        assert!(names.contains(&"Alice".to_string()));
1✔
4400
        assert!(names.contains(&"Bob".to_string()));
1✔
4401
        assert!(names.contains(&"Dave".to_string()));
1✔
4402
    }
4403

4404
    #[test]
4405
    fn not_in_excludes_listed() {
3✔
4406
        let db = seed_employees();
1✔
4407
        let r = run_rows(&db, "SELECT name FROM emp WHERE id NOT IN (1, 2);");
1✔
4408
        // 6 rows total - 2 excluded = 4.
4409
        assert_eq!(r.rows.len(), 4);
2✔
4410
    }
4411

4412
    #[test]
4413
    fn in_list_with_null_three_valued() {
3✔
4414
        let db = seed_employees();
1✔
4415
        // x = 1 should match; for other rows the NULL in the list yields
4416
        // unknown → false in WHERE → excluded.
4417
        let r = run_rows(&db, "SELECT name FROM emp WHERE id IN (1, NULL);");
1✔
4418
        assert_eq!(r.rows.len(), 1);
2✔
4419
        assert_eq!(r.rows[0][0].to_display_string(), "Alice");
1✔
4420
    }
4421

4422
    // ----- DISTINCT -----
4423

4424
    #[test]
4425
    fn distinct_single_column() {
3✔
4426
        let db = seed_employees();
1✔
4427
        let r = run_rows(&db, "SELECT DISTINCT dept FROM emp;");
1✔
4428
        // 3 distinct depts: eng, sales, ops.
4429
        assert_eq!(r.rows.len(), 3);
2✔
4430
    }
4431

4432
    #[test]
4433
    fn distinct_multi_column_with_null() {
3✔
4434
        let db = seed_employees();
1✔
4435
        // (dept, salary) tuples — the two 'eng' / 100 rows collapse.
4436
        let r = run_rows(&db, "SELECT DISTINCT dept, salary FROM emp;");
1✔
4437
        // 6 input rows; (eng, 100) appears twice → 5 distinct tuples.
4438
        assert_eq!(r.rows.len(), 5);
2✔
4439
    }
4440

4441
    // ----- Aggregates without GROUP BY -----
4442

4443
    #[test]
4444
    fn count_star_no_groupby() {
3✔
4445
        let db = seed_employees();
1✔
4446
        let r = run_rows(&db, "SELECT COUNT(*) FROM emp;");
1✔
4447
        assert_eq!(r.rows.len(), 1);
2✔
4448
        assert_eq!(r.rows[0][0], Value::Integer(6));
1✔
4449
    }
4450

4451
    #[test]
4452
    fn count_col_skips_nulls() {
3✔
4453
        let db = seed_employees();
1✔
4454
        let r = run_rows(&db, "SELECT COUNT(salary) FROM emp;");
1✔
4455
        // 6 rows, 1 NULL salary → COUNT(salary) = 5.
4456
        assert_eq!(r.rows[0][0], Value::Integer(5));
2✔
4457
    }
4458

4459
    #[test]
4460
    fn count_distinct_dedupes_and_skips_nulls() {
3✔
4461
        let db = seed_employees();
1✔
4462
        let r = run_rows(&db, "SELECT COUNT(DISTINCT salary) FROM emp;");
1✔
4463
        // Distinct non-null salaries: {100, 120, 90, 80} → 4.
4464
        assert_eq!(r.rows[0][0], Value::Integer(4));
2✔
4465
    }
4466

4467
    #[test]
4468
    fn sum_int_stays_integer() {
3✔
4469
        let db = seed_employees();
1✔
4470
        let r = run_rows(&db, "SELECT SUM(salary) FROM emp;");
1✔
4471
        // 100 + 120 + 100 + 90 + 80 = 490 (NULL skipped).
4472
        assert_eq!(r.rows[0][0], Value::Integer(490));
2✔
4473
    }
4474

4475
    #[test]
4476
    fn avg_returns_real() {
3✔
4477
        let db = seed_employees();
1✔
4478
        let r = run_rows(&db, "SELECT AVG(salary) FROM emp;");
1✔
4479
        // 490 / 5 = 98.0
4480
        match &r.rows[0][0] {
2✔
4481
            Value::Real(v) => assert!((v - 98.0).abs() < 1e-9),
2✔
4482
            other => panic!("expected Real, got {other:?}"),
×
4483
        }
4484
    }
4485

4486
    #[test]
4487
    fn min_max_skip_nulls() {
3✔
4488
        let db = seed_employees();
1✔
4489
        let r = run_rows(&db, "SELECT MIN(salary), MAX(salary) FROM emp;");
1✔
4490
        assert_eq!(r.rows[0][0], Value::Integer(80));
2✔
4491
        assert_eq!(r.rows[0][1], Value::Integer(120));
1✔
4492
    }
4493

4494
    #[test]
4495
    fn aggregates_on_empty_table_emit_one_row() {
3✔
4496
        let mut db = Database::new("t".to_string());
1✔
4497
        crate::sql::process_command("CREATE TABLE t (x INTEGER);", &mut db).unwrap();
2✔
4498
        let r = run_rows(
4499
            &db,
4500
            "SELECT COUNT(*), SUM(x), AVG(x), MIN(x), MAX(x) FROM t;",
4501
        );
4502
        assert_eq!(r.rows.len(), 1);
2✔
4503
        assert_eq!(r.rows[0][0], Value::Integer(0));
1✔
4504
        assert_eq!(r.rows[0][1], Value::Null);
1✔
4505
        assert_eq!(r.rows[0][2], Value::Null);
1✔
4506
        assert_eq!(r.rows[0][3], Value::Null);
1✔
4507
        assert_eq!(r.rows[0][4], Value::Null);
1✔
4508
    }
4509

4510
    // ----- GROUP BY -----
4511

4512
    #[test]
4513
    fn group_by_single_col_with_count() {
3✔
4514
        let db = seed_employees();
1✔
4515
        let r = run_rows(&db, "SELECT dept, COUNT(*) FROM emp GROUP BY dept;");
1✔
4516
        assert_eq!(r.rows.len(), 3);
2✔
4517
        // Build a map for a stable assertion regardless of group order.
4518
        let mut by_dept: std::collections::HashMap<String, i64> = Default::default();
1✔
4519
        for row in &r.rows {
3✔
4520
            let d = row[0].to_display_string();
2✔
4521
            let c = match &row[1] {
2✔
4522
                Value::Integer(i) => *i,
1✔
4523
                v => panic!("expected Integer count, got {v:?}"),
×
4524
            };
4525
            by_dept.insert(d, c);
1✔
4526
        }
4527
        assert_eq!(by_dept["eng"], 3);
1✔
4528
        assert_eq!(by_dept["sales"], 2);
1✔
4529
        assert_eq!(by_dept["ops"], 1);
1✔
4530
    }
4531

4532
    #[test]
4533
    fn group_by_with_where_filter() {
3✔
4534
        let db = seed_employees();
1✔
4535
        let r = run_rows(
4536
            &db,
4537
            "SELECT dept, SUM(salary) FROM emp WHERE salary > 80 GROUP BY dept;",
4538
        );
4539
        // After WHERE, ops drops out (Eve = 80 excluded). eng has 3 rows
4540
        // contributing (100+120+100=320); sales has 1 (90; Dave NULL skipped).
4541
        let by: std::collections::HashMap<String, i64> = r
1✔
4542
            .rows
4543
            .iter()
4544
            .map(|row| {
2✔
4545
                (
4546
                    row[0].to_display_string(),
1✔
4547
                    match &row[1] {
2✔
4548
                        Value::Integer(i) => *i,
1✔
4549
                        v => panic!("expected Integer sum, got {v:?}"),
×
4550
                    },
4551
                )
4552
            })
4553
            .collect();
4554
        assert_eq!(by.len(), 2);
2✔
4555
        assert_eq!(by["eng"], 320);
1✔
4556
        assert_eq!(by["sales"], 90);
1✔
4557
    }
4558

4559
    #[test]
4560
    fn group_by_without_aggregates_is_distinct() {
3✔
4561
        let db = seed_employees();
1✔
4562
        let r = run_rows(&db, "SELECT dept FROM emp GROUP BY dept;");
1✔
4563
        assert_eq!(r.rows.len(), 3);
2✔
4564
    }
4565

4566
    #[test]
4567
    fn order_by_count_desc() {
3✔
4568
        let db = seed_employees();
1✔
4569
        let r = run_rows(
4570
            &db,
4571
            "SELECT dept, COUNT(*) AS n FROM emp GROUP BY dept ORDER BY n DESC LIMIT 2;",
4572
        );
4573
        assert_eq!(r.rows.len(), 2);
2✔
4574
        // Top group is 'eng' with 3.
4575
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
4576
        assert_eq!(r.rows[0][1], Value::Integer(3));
1✔
4577
    }
4578

4579
    #[test]
4580
    fn order_by_aggregate_call_form() {
3✔
4581
        let db = seed_employees();
1✔
4582
        // No alias — ORDER BY references the aggregate by its display form.
4583
        let r = run_rows(
4584
            &db,
4585
            "SELECT dept, COUNT(*) FROM emp GROUP BY dept ORDER BY COUNT(*) DESC;",
4586
        );
4587
        assert_eq!(r.rows.len(), 3);
2✔
4588
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
4589
    }
4590

4591
    #[test]
4592
    fn group_by_invalid_bare_column_errors() {
3✔
4593
        // `name` is neither aggregated nor in GROUP BY → must error at parse.
4594
        let mut db = Database::new("t".to_string());
1✔
4595
        crate::sql::process_command(
4596
            "CREATE TABLE t (id INTEGER PRIMARY KEY, dept TEXT, name TEXT);",
4597
            &mut db,
4598
        )
4599
        .unwrap();
4600
        let err = crate::sql::process_command("SELECT dept, name FROM t GROUP BY dept;", &mut db);
1✔
4601
        assert!(err.is_err(), "should reject bare 'name' not in GROUP BY");
2✔
4602
    }
4603

4604
    #[test]
4605
    fn aggregate_in_where_errors_friendly() {
3✔
4606
        let mut db = Database::new("t".to_string());
1✔
4607
        crate::sql::process_command("CREATE TABLE t (x INTEGER);", &mut db).unwrap();
2✔
4608
        crate::sql::process_command("INSERT INTO t (x) VALUES (1);", &mut db).unwrap();
1✔
4609
        let err = crate::sql::process_command("SELECT x FROM t WHERE COUNT(*) > 0;", &mut db);
1✔
4610
        assert!(err.is_err(), "aggregates must not be allowed in WHERE");
2✔
4611
    }
4612

4613
    // ---------------------------------------------------------------------
4614
    // SQLR-52 — HAVING (post-aggregation filter)
4615
    // ---------------------------------------------------------------------
4616
    //
4617
    // seed_employees groups: eng × 3 (salaries 100, 120, 100 → SUM 320),
4618
    // sales × 2 (90, NULL → SUM 90), ops × 1 (80). Groups materialize in
4619
    // first-occurrence order: eng, sales, ops.
4620

4621
    #[test]
4622
    fn having_count_filters_groups() {
3✔
4623
        let db = seed_employees();
1✔
4624
        let r = run_rows(
4625
            &db,
4626
            "SELECT dept, COUNT(*) FROM emp GROUP BY dept HAVING COUNT(*) > 1;",
4627
        );
4628
        // ops (1 member) drops; hidden HAVING slots must not leak into
4629
        // the output width.
4630
        assert_eq!(r.columns, vec!["dept".to_string(), "COUNT(*)".to_string()]);
2✔
4631
        let got: Vec<(String, i64)> = r
1✔
4632
            .rows
4633
            .iter()
4634
            .map(|row| (row[0].to_display_string(), expect_int(&row[1])))
3✔
4635
            .collect();
4636
        assert_eq!(got, vec![("eng".to_string(), 3), ("sales".to_string(), 2)]);
2✔
4637
    }
4638

4639
    #[test]
4640
    fn having_sum_threshold() {
3✔
4641
        let db = seed_employees();
1✔
4642
        let r = run_rows(
4643
            &db,
4644
            "SELECT dept, SUM(salary) FROM emp GROUP BY dept HAVING SUM(salary) > 100;",
4645
        );
4646
        assert_eq!(r.rows.len(), 1);
2✔
4647
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
4648
        assert_eq!(r.rows[0][1], Value::Integer(320));
1✔
4649
    }
4650

4651
    #[test]
4652
    fn having_references_aggregate_alias() {
3✔
4653
        let db = seed_employees();
1✔
4654
        let r = run_rows(
4655
            &db,
4656
            "SELECT dept, SUM(salary) AS total FROM emp GROUP BY dept HAVING total > 100;",
4657
        );
4658
        assert_eq!(r.columns, vec!["dept".to_string(), "total".to_string()]);
2✔
4659
        assert_eq!(r.rows.len(), 1);
1✔
4660
        assert_eq!(r.rows[0][1], Value::Integer(320));
1✔
4661
    }
4662

4663
    #[test]
4664
    fn having_aggregate_not_in_projection() {
3✔
4665
        let db = seed_employees();
1✔
4666
        // COUNT(*) only exists in HAVING — computed via a hidden slot,
4667
        // stripped before output.
4668
        let r = run_rows(
4669
            &db,
4670
            "SELECT dept FROM emp GROUP BY dept HAVING COUNT(*) > 1;",
4671
        );
4672
        assert_eq!(r.columns, vec!["dept".to_string()]);
2✔
4673
        let depts: Vec<String> = r
1✔
4674
            .rows
4675
            .iter()
4676
            .map(|row| row[0].to_display_string())
3✔
4677
            .collect();
4678
        assert_eq!(depts, vec!["eng".to_string(), "sales".to_string()]);
2✔
4679
    }
4680

4681
    #[test]
4682
    fn having_group_key_not_in_projection() {
3✔
4683
        let db = seed_employees();
1✔
4684
        // dept only exists in GROUP BY + HAVING, not the SELECT list.
4685
        let r = run_rows(
4686
            &db,
4687
            "SELECT COUNT(*) FROM emp GROUP BY dept HAVING dept = 'eng';",
4688
        );
4689
        assert_eq!(r.columns, vec!["COUNT(*)".to_string()]);
2✔
4690
        assert_eq!(r.rows.len(), 1);
1✔
4691
        assert_eq!(r.rows[0][0], Value::Integer(3));
1✔
4692
    }
4693

4694
    #[test]
4695
    fn having_compound_and_predicate() {
3✔
4696
        let db = seed_employees();
1✔
4697
        let r = run_rows(
4698
            &db,
4699
            "SELECT dept FROM emp GROUP BY dept \
4700
             HAVING COUNT(*) > 1 AND SUM(salary) > 100;",
4701
        );
4702
        // eng passes both; sales passes COUNT but fails SUM (90).
4703
        assert_eq!(r.rows.len(), 1);
2✔
4704
        assert_eq!(r.rows[0][0].to_display_string(), "eng");
1✔
4705
    }
4706

4707
    #[test]
4708
    fn having_composes_with_order_by_and_limit() {
4✔
4709
        let db = seed_employees();
1✔
4710
        let r = run_rows(
4711
            &db,
4712
            "SELECT dept, COUNT(*) AS n FROM emp GROUP BY dept \
4713
             HAVING n >= 1 ORDER BY n DESC LIMIT 2;",
4714
        );
4715
        let got: Vec<(String, i64)> = r
1✔
4716
            .rows
4717
            .iter()
4718
            .map(|row| (row[0].to_display_string(), expect_int(&row[1])))
3✔
4719
            .collect();
4720
        assert_eq!(got, vec![("eng".to_string(), 3), ("sales".to_string(), 2)]);
2✔
4721
    }
4722

4723
    #[test]
4724
    fn having_can_exclude_every_group() {
3✔
4725
        let db = seed_employees();
1✔
4726
        let r = run_rows(
4727
            &db,
4728
            "SELECT dept FROM emp GROUP BY dept HAVING COUNT(*) > 99;",
4729
        );
4730
        assert_eq!(r.rows.len(), 0);
2✔
4731
    }
4732

4733
    #[test]
4734
    fn having_null_aggregate_collapses_to_false() {
3✔
4735
        let mut db = seed_employees();
1✔
4736
        // mkt's only salary is NULL → SUM(salary) is NULL → NULL > 0 is
4737
        // unknown → group excluded (NULL-as-false, same as WHERE).
4738
        crate::sql::process_command(
4739
            "INSERT INTO emp (name, dept, salary) VALUES ('Zoe', 'mkt', NULL);",
4740
            &mut db,
4741
        )
4742
        .unwrap();
4743
        let r = run_rows(
4744
            &db,
4745
            "SELECT dept FROM emp GROUP BY dept HAVING SUM(salary) > 0;",
4746
        );
4747
        let depts: Vec<String> = r
1✔
4748
            .rows
4749
            .iter()
4750
            .map(|row| row[0].to_display_string())
3✔
4751
            .collect();
4752
        assert_eq!(
1✔
4753
            depts,
4754
            vec!["eng".to_string(), "sales".to_string(), "ops".to_string()],
2✔
4755
            "mkt (all-NULL salaries) must be filtered out"
4756
        );
4757
    }
4758

4759
    #[test]
4760
    fn having_lowercase_function_form_matches() {
3✔
4761
        let db = seed_employees();
1✔
4762
        let r = run_rows(
4763
            &db,
4764
            "SELECT dept FROM emp GROUP BY dept HAVING count(*) > 1;",
4765
        );
4766
        assert_eq!(r.rows.len(), 2);
2✔
4767
    }
4768

4769
    #[test]
4770
    fn having_without_group_by_is_rejected() {
3✔
4771
        let mut db = seed_employees();
1✔
4772
        let err =
2✔
4773
            crate::sql::process_command("SELECT COUNT(*) FROM emp HAVING COUNT(*) > 0;", &mut db);
4774
        match err {
1✔
4775
            Err(SQLRiteError::NotImplemented(msg)) => assert!(
1✔
4776
                msg.contains("HAVING without GROUP BY"),
2✔
4777
                "unexpected message: {msg}"
4778
            ),
4779
            other => panic!("expected NotImplemented, got {other:?}"),
×
4780
        }
4781
    }
4782

4783
    #[test]
4784
    fn having_unknown_column_is_rejected() {
3✔
4785
        let mut db = seed_employees();
1✔
4786
        // `name` is neither a GROUP BY key nor an aggregate — typed error,
4787
        // not a silent NULL like the legacy single-table WHERE leniency.
4788
        let err = crate::sql::process_command(
4789
            "SELECT dept, COUNT(*) FROM emp GROUP BY dept HAVING name = 'Alice';",
4790
            &mut db,
4791
        );
4792
        match err {
1✔
4793
            Err(e) => {
1✔
4794
                let msg = e.to_string();
1✔
4795
                assert!(
×
4796
                    msg.contains("HAVING references"),
2✔
4797
                    "unexpected message: {msg}"
4798
                );
4799
            }
4800
            Ok(_) => panic!("HAVING on an out-of-scope column must error"),
×
4801
        }
4802
    }
4803

4804
    #[test]
4805
    fn having_over_join_filters_groups_for_all_flavors() {
3✔
4806
        // SQLR-6 — GROUP BY + HAVING compose with every join flavor.
4807
        // Only Alice has more than one order; the dangling order (RIGHT /
4808
        // FULL) groups under a NULL name with count 1 and is filtered.
4809
        for flavor in ["INNER", "LEFT OUTER", "RIGHT OUTER", "FULL OUTER"] {
2✔
4810
            let sql = format!(
2✔
4811
                "SELECT customers.name, COUNT(*) FROM customers \
4812
                 {flavor} JOIN orders ON customers.id = orders.customer_id \
4813
                 GROUP BY customers.name HAVING COUNT(*) > 1;"
4814
            );
4815
            let db = seed_join_fixture();
1✔
4816
            let r = run_rows(&db, &sql);
2✔
4817
            assert_eq!(r.rows.len(), 1, "{flavor}: only Alice has >1 order");
2✔
4818
            assert_eq!(r.rows[0][0].to_display_string(), "Alice", "{flavor}");
2✔
4819
            assert_eq!(expect_int(&r.rows[0][1]), 2, "{flavor}");
1✔
4820
        }
4821
    }
4822

4823
    /// Helper: unwrap an integer `Value` in HAVING tests.
4824
    fn expect_int(v: &Value) -> i64 {
1✔
4825
        match v {
1✔
4826
            Value::Integer(i) => *i,
1✔
4827
            other => panic!("expected integer value, got {other:?}"),
×
4828
        }
4829
    }
4830

4831
    // ---------------------------------------------------------------------
4832
    // SQLR-5 — JOINs (INNER / LEFT OUTER / RIGHT OUTER / FULL OUTER)
4833
    // ---------------------------------------------------------------------
4834

4835
    /// Two-table fixture used across the join tests. `customers` has
4836
    /// (1: Alice, 2: Bob, 3: Carol). `orders` has (id, customer_id,
4837
    /// amount): (1, 1, 100), (2, 1, 200), (3, 2, 50), (4, 4, 999).
4838
    /// Customer 3 (Carol) has no orders; order 4 has no customer
4839
    /// (dangling foreign key) — together they exercise both sides of
4840
    /// the outer-join NULL-padding.
4841
    fn seed_join_fixture() -> Database {
1✔
4842
        let mut db = Database::new("t".to_string());
1✔
4843
        for sql in [
3✔
4844
            "CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);",
4845
            "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, amount INTEGER);",
4846
            "INSERT INTO customers (name) VALUES ('Alice');",
4847
            "INSERT INTO customers (name) VALUES ('Bob');",
4848
            "INSERT INTO customers (name) VALUES ('Carol');",
4849
            "INSERT INTO orders (customer_id, amount) VALUES (1, 100);",
4850
            "INSERT INTO orders (customer_id, amount) VALUES (1, 200);",
4851
            "INSERT INTO orders (customer_id, amount) VALUES (2, 50);",
4852
            "INSERT INTO orders (customer_id, amount) VALUES (4, 999);",
4853
        ] {
4854
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
4855
        }
4856
        db
1✔
4857
    }
4858

4859
    #[test]
4860
    fn inner_join_returns_only_matched_rows() {
3✔
4861
        let db = seed_join_fixture();
1✔
4862
        let r = run_rows(
4863
            &db,
4864
            "SELECT customers.name, orders.amount FROM customers \
4865
             INNER JOIN orders ON customers.id = orders.customer_id;",
4866
        );
4867
        assert_eq!(r.columns, vec!["name".to_string(), "amount".to_string()]);
2✔
4868
        // Alice: 100, 200; Bob: 50. Carol drops (no orders), order 4 drops
4869
        // (no customer). 3 rows.
4870
        let pairs: Vec<(String, i64)> = r
1✔
4871
            .rows
4872
            .iter()
4873
            .map(|row| {
2✔
4874
                (
4875
                    row[0].to_display_string(),
1✔
4876
                    match row[1] {
2✔
4877
                        Value::Integer(i) => i,
1✔
4878
                        ref v => panic!("expected integer amount, got {v:?}"),
×
4879
                    },
4880
                )
4881
            })
4882
            .collect();
4883
        assert_eq!(pairs.len(), 3);
2✔
4884
        assert!(pairs.contains(&("Alice".to_string(), 100)));
1✔
4885
        assert!(pairs.contains(&("Alice".to_string(), 200)));
1✔
4886
        assert!(pairs.contains(&("Bob".to_string(), 50)));
1✔
4887
    }
4888

4889
    #[test]
4890
    fn bare_join_defaults_to_inner() {
3✔
4891
        let db = seed_join_fixture();
1✔
4892
        let r = run_rows(
4893
            &db,
4894
            "SELECT customers.name FROM customers \
4895
             JOIN orders ON customers.id = orders.customer_id;",
4896
        );
4897
        assert_eq!(r.rows.len(), 3, "JOIN without prefix should be INNER");
2✔
4898
    }
4899

4900
    #[test]
4901
    fn left_outer_join_preserves_unmatched_left() {
3✔
4902
        let db = seed_join_fixture();
1✔
4903
        let r = run_rows(
4904
            &db,
4905
            "SELECT customers.name, orders.amount FROM customers \
4906
             LEFT OUTER JOIN orders ON customers.id = orders.customer_id;",
4907
        );
4908
        // Alice: two rows. Bob: one row. Carol: one NULL-padded row.
4909
        // Order 4 is dropped (left side has no customer for id=4).
4910
        assert_eq!(r.rows.len(), 4);
2✔
4911
        let carol = r
3✔
4912
            .rows
4913
            .iter()
4914
            .find(|row| row[0].to_display_string() == "Carol")
3✔
4915
            .expect("Carol should appear with a NULL-padded right side");
4916
        assert_eq!(carol[1], Value::Null);
1✔
4917
    }
4918

4919
    #[test]
4920
    fn right_outer_join_preserves_unmatched_right() {
3✔
4921
        let db = seed_join_fixture();
1✔
4922
        let r = run_rows(
4923
            &db,
4924
            "SELECT customers.name, orders.amount FROM customers \
4925
             RIGHT OUTER JOIN orders ON customers.id = orders.customer_id;",
4926
        );
4927
        // 3 matched rows + 1 dangling order (id=4, customer_id=4 with no
4928
        // matching customer). Total 4. Carol drops because the right
4929
        // table has no row pointing at her.
4930
        assert_eq!(r.rows.len(), 4);
2✔
4931
        let dangling = r
3✔
4932
            .rows
4933
            .iter()
4934
            .find(|row| matches!(row[1], Value::Integer(999)))
3✔
4935
            .expect("dangling order 999 should appear with a NULL-padded customer name");
4936
        assert_eq!(dangling[0], Value::Null);
1✔
4937
    }
4938

4939
    #[test]
4940
    fn full_outer_join_preserves_both_sides() {
3✔
4941
        let db = seed_join_fixture();
1✔
4942
        let r = run_rows(
4943
            &db,
4944
            "SELECT customers.name, orders.amount FROM customers \
4945
             FULL OUTER JOIN orders ON customers.id = orders.customer_id;",
4946
        );
4947
        // 3 matched + 1 unmatched left (Carol) + 1 unmatched right
4948
        // (order 999) = 5 rows.
4949
        assert_eq!(r.rows.len(), 5);
2✔
4950
        // Carol with NULL amount.
4951
        assert!(
×
4952
            r.rows
3✔
4953
                .iter()
1✔
4954
                .any(|row| row[0].to_display_string() == "Carol" && matches!(row[1], Value::Null))
3✔
4955
        );
4956
        // 999 with NULL name.
4957
        assert!(
×
4958
            r.rows
3✔
4959
                .iter()
1✔
4960
                .any(|row| matches!(row[1], Value::Integer(999)) && matches!(row[0], Value::Null))
3✔
4961
        );
4962
    }
4963

4964
    #[test]
4965
    fn join_with_table_aliases_resolves_qualifiers() {
3✔
4966
        let db = seed_join_fixture();
1✔
4967
        let r = run_rows(
4968
            &db,
4969
            "SELECT c.name, o.amount FROM customers AS c \
4970
             INNER JOIN orders AS o ON c.id = o.customer_id;",
4971
        );
4972
        assert_eq!(r.rows.len(), 3);
2✔
4973
        assert_eq!(r.columns, vec!["name".to_string(), "amount".to_string()]);
1✔
4974
    }
4975

4976
    #[test]
4977
    fn join_with_where_filter_applies_after_join() {
3✔
4978
        let db = seed_join_fixture();
1✔
4979
        // Filter to only orders >= 100. With INNER JOIN, this drops Bob's
4980
        // 50-amount order, leaving Alice's 100 and 200.
4981
        let r = run_rows(
4982
            &db,
4983
            "SELECT customers.name, orders.amount FROM customers \
4984
             INNER JOIN orders ON customers.id = orders.customer_id \
4985
             WHERE orders.amount >= 100;",
4986
        );
4987
        assert_eq!(r.rows.len(), 2);
2✔
4988
        assert!(
×
4989
            r.rows
3✔
4990
                .iter()
1✔
4991
                .all(|row| row[0].to_display_string() == "Alice")
3✔
4992
        );
4993
    }
4994

4995
    #[test]
4996
    fn left_join_with_where_on_right_side_is_not_inner() {
3✔
4997
        // WHERE on the right side that excludes NULL turns LEFT JOIN
4998
        // back into INNER JOIN semantically. Verify the executor
4999
        // applies the WHERE *after* the join padded NULLs in.
5000
        let db = seed_join_fixture();
1✔
5001
        let r = run_rows(
5002
            &db,
5003
            "SELECT customers.name, orders.amount FROM customers \
5004
             LEFT OUTER JOIN orders ON customers.id = orders.customer_id \
5005
             WHERE orders.amount IS NULL;",
5006
        );
5007
        // Only Carol survives — she's the only customer with no order.
5008
        assert_eq!(r.rows.len(), 1);
2✔
5009
        assert_eq!(r.rows[0][0].to_display_string(), "Carol");
1✔
5010
        assert_eq!(r.rows[0][1], Value::Null);
1✔
5011
    }
5012

5013
    #[test]
5014
    fn select_star_over_join_emits_all_columns_from_both_tables() {
3✔
5015
        let db = seed_join_fixture();
1✔
5016
        let r = run_rows(
5017
            &db,
5018
            "SELECT * FROM customers \
5019
             INNER JOIN orders ON customers.id = orders.customer_id;",
5020
        );
5021
        // customers has 2 cols (id, name), orders has 3 cols
5022
        // (id, customer_id, amount). 5 columns total. Header order
5023
        // follows source order — primary table first.
5024
        assert_eq!(
1✔
5025
            r.columns,
5026
            vec![
3✔
5027
                "id".to_string(),
1✔
5028
                "name".to_string(),
1✔
5029
                "id".to_string(),
1✔
5030
                "customer_id".to_string(),
1✔
5031
                "amount".to_string(),
1✔
5032
            ]
5033
        );
5034
        assert_eq!(r.rows.len(), 3);
1✔
5035
    }
5036

5037
    #[test]
5038
    fn join_order_by_sorts_full_joined_rows() {
3✔
5039
        let db = seed_join_fixture();
1✔
5040
        let r = run_rows(
5041
            &db,
5042
            "SELECT c.name, o.amount FROM customers AS c \
5043
             INNER JOIN orders AS o ON c.id = o.customer_id \
5044
             ORDER BY o.amount;",
5045
        );
5046
        let amounts: Vec<i64> = r
1✔
5047
            .rows
5048
            .iter()
5049
            .map(|row| match row[1] {
3✔
5050
                Value::Integer(i) => i,
1✔
5051
                ref v => panic!("expected integer, got {v:?}"),
×
5052
            })
5053
            .collect();
5054
        assert_eq!(amounts, vec![50, 100, 200]);
2✔
5055
    }
5056

5057
    #[test]
5058
    fn join_limit_truncates_after_join_and_sort() {
3✔
5059
        let db = seed_join_fixture();
1✔
5060
        let r = run_rows(
5061
            &db,
5062
            "SELECT c.name, o.amount FROM customers AS c \
5063
             INNER JOIN orders AS o ON c.id = o.customer_id \
5064
             ORDER BY o.amount DESC LIMIT 2;",
5065
        );
5066
        assert_eq!(r.rows.len(), 2);
2✔
5067
        // Top two by amount DESC: 200 (Alice), 100 (Alice).
5068
        let amounts: Vec<i64> = r
1✔
5069
            .rows
5070
            .iter()
5071
            .map(|row| match row[1] {
3✔
5072
                Value::Integer(i) => i,
1✔
5073
                ref v => panic!("expected integer, got {v:?}"),
×
5074
            })
5075
            .collect();
5076
        assert_eq!(amounts, vec![200, 100]);
2✔
5077
    }
5078

5079
    #[test]
5080
    fn three_table_join_chains_correctly() {
3✔
5081
        let mut db = Database::new("t".to_string());
1✔
5082
        for sql in [
3✔
5083
            "CREATE TABLE a (id INTEGER PRIMARY KEY, label TEXT);",
5084
            "CREATE TABLE b (id INTEGER PRIMARY KEY, a_id INTEGER, tag TEXT);",
5085
            "CREATE TABLE c (id INTEGER PRIMARY KEY, b_id INTEGER, note TEXT);",
5086
            "INSERT INTO a (label) VALUES ('a-one');",
5087
            "INSERT INTO a (label) VALUES ('a-two');",
5088
            "INSERT INTO b (a_id, tag) VALUES (1, 'b1');",
5089
            "INSERT INTO b (a_id, tag) VALUES (2, 'b2');",
5090
            "INSERT INTO c (b_id, note) VALUES (1, 'c1');",
5091
        ] {
5092
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5093
        }
5094
        let r = run_rows(
5095
            &db,
5096
            "SELECT a.label, b.tag, c.note FROM a \
5097
             INNER JOIN b ON a.id = b.a_id \
5098
             INNER JOIN c ON b.id = c.b_id;",
5099
        );
5100
        // Only b1 has a c row. So one combined row.
5101
        assert_eq!(r.rows.len(), 1);
2✔
5102
        assert_eq!(r.rows[0][0].to_display_string(), "a-one");
1✔
5103
        assert_eq!(r.rows[0][1].to_display_string(), "b1");
1✔
5104
        assert_eq!(r.rows[0][2].to_display_string(), "c1");
1✔
5105
    }
5106

5107
    #[test]
5108
    fn ambiguous_unqualified_column_in_join_errors() {
3✔
5109
        // Both customers and orders have a column named `id`. An
5110
        // unqualified `id` in the SELECT must error rather than
5111
        // silently picking one side.
5112
        let db = seed_join_fixture();
1✔
5113
        let q = parse_select(
5114
            "SELECT id FROM customers INNER JOIN orders ON customers.id = orders.customer_id;",
5115
        );
5116
        let res = execute_select_rows(q, &db);
1✔
5117
        assert!(res.is_err(), "unqualified ambiguous 'id' should error");
2✔
5118
    }
5119

5120
    #[test]
5121
    fn join_self_without_alias_is_rejected() {
3✔
5122
        let mut db = Database::new("t".to_string());
1✔
5123
        crate::sql::process_command(
5124
            "CREATE TABLE n (id INTEGER PRIMARY KEY, parent INTEGER);",
5125
            &mut db,
5126
        )
5127
        .unwrap();
5128
        let q = parse_select("SELECT n.id FROM n INNER JOIN n ON n.id = n.parent;");
1✔
5129
        let res = execute_select_rows(q, &db);
1✔
5130
        assert!(
×
5131
            res.is_err(),
2✔
5132
            "self-join without an alias should error on duplicate qualifier"
5133
        );
5134
    }
5135

5136
    // ----- SQLR-5 follow-up: USING / NATURAL / CROSS joins -----
5137

5138
    /// `customers` and `orders` both have an `id` column. Joining on it
5139
    /// via USING must produce exactly the same rows as the equivalent
5140
    /// explicit `ON customers.id = orders.id`.
5141
    #[test]
5142
    fn join_using_matches_same_rows_as_on() {
3✔
5143
        let db = seed_join_fixture();
1✔
5144
        let using = run_rows(
5145
            &db,
5146
            "SELECT customers.name, orders.amount FROM customers \
5147
             INNER JOIN orders USING (id) ORDER BY orders.amount;",
5148
        );
5149
        let on = run_rows(
5150
            &db,
5151
            "SELECT customers.name, orders.amount FROM customers \
5152
             INNER JOIN orders ON customers.id = orders.id ORDER BY orders.amount;",
5153
        );
5154
        // id matches: cust1↔order1 (100), cust2↔order2 (200), cust3↔order3 (50).
5155
        let pairs: Vec<(String, Value)> = using
1✔
5156
            .rows
5157
            .iter()
5158
            .map(|r| (r[0].to_display_string(), r[1].clone()))
3✔
5159
            .collect();
5160
        assert_eq!(pairs.len(), 3);
2✔
5161
        assert_eq!(
1✔
5162
            using.rows, on.rows,
5163
            "USING must mirror the explicit ON rows"
5164
        );
5165
    }
5166

5167
    /// `SELECT *` over a USING join shows the joined-on column once
5168
    /// (SQLite convention), taking the left side's copy.
5169
    #[test]
5170
    fn select_star_using_dedups_joined_column() {
3✔
5171
        let db = seed_join_fixture();
1✔
5172
        let r = run_rows(&db, "SELECT * FROM customers INNER JOIN orders USING (id);");
1✔
5173
        // Without USING dedup this would be 5 columns (id,name,id,
5174
        // customer_id,amount). USING(id) collapses the duplicate `id`
5175
        // to one, leaving 4 in source order.
5176
        assert_eq!(
1✔
5177
            r.columns,
5178
            vec![
3✔
5179
                "id".to_string(),
1✔
5180
                "name".to_string(),
1✔
5181
                "customer_id".to_string(),
1✔
5182
                "amount".to_string(),
1✔
5183
            ]
5184
        );
5185
        assert_eq!(r.rows.len(), 3);
1✔
5186
        // Each surviving row's single `id` equals both sides' id (they
5187
        // were matched on equality), so the left copy is correct.
5188
        for row in &r.rows {
1✔
5189
            assert!(matches!(row[0], Value::Integer(_)));
2✔
5190
        }
5191
    }
5192

5193
    fn seed_natural_fixture() -> Database {
1✔
5194
        let mut db = Database::new("t".to_string());
1✔
5195
        for sql in [
3✔
5196
            // Distinct PK names (lid / rid) so the *only* shared columns
5197
            // are k1 and k2 — NATURAL must match on both with AND.
5198
            "CREATE TABLE l (lid INTEGER PRIMARY KEY, k1 INTEGER, k2 INTEGER, v1 TEXT);",
5199
            "CREATE TABLE r (rid INTEGER PRIMARY KEY, k1 INTEGER, k2 INTEGER, v2 TEXT);",
5200
            "INSERT INTO l (k1, k2, v1) VALUES (1, 1, 'l-a');",
5201
            "INSERT INTO l (k1, k2, v1) VALUES (1, 2, 'l-b');",
5202
            "INSERT INTO l (k1, k2, v1) VALUES (2, 1, 'l-c');",
5203
            "INSERT INTO r (k1, k2, v2) VALUES (1, 1, 'r-a');",
5204
            "INSERT INTO r (k1, k2, v2) VALUES (1, 2, 'r-b');",
5205
            "INSERT INTO r (k1, k2, v2) VALUES (9, 9, 'r-z');",
5206
        ] {
5207
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5208
        }
5209
        db
1✔
5210
    }
5211

5212
    /// NATURAL JOIN auto-discovers the shared columns (k1, k2) and
5213
    /// matches on both with AND.
5214
    #[test]
5215
    fn natural_join_matches_on_all_shared_columns() {
3✔
5216
        let db = seed_natural_fixture();
1✔
5217
        let natural = run_rows(&db, "SELECT v1, v2 FROM l NATURAL JOIN r ORDER BY v1;");
1✔
5218
        // (1,1)->l-a/r-a and (1,2)->l-b/r-b match. (2,1) and (9,9) don't.
5219
        let pairs: Vec<(String, String)> = natural
1✔
5220
            .rows
5221
            .iter()
5222
            .map(|r| (r[0].to_display_string(), r[1].to_display_string()))
3✔
5223
            .collect();
5224
        assert_eq!(
1✔
5225
            pairs,
5226
            vec![
3✔
5227
                ("l-a".to_string(), "r-a".to_string()),
2✔
5228
                ("l-b".to_string(), "r-b".to_string()),
2✔
5229
            ]
5230
        );
5231
        // Equivalent explicit form yields the same rows.
5232
        let explicit = run_rows(
5233
            &db,
5234
            "SELECT v1, v2 FROM l INNER JOIN r ON l.k1 = r.k1 AND l.k2 = r.k2 ORDER BY v1;",
5235
        );
5236
        assert_eq!(natural.rows, explicit.rows);
2✔
5237
    }
5238

5239
    /// `SELECT *` over a NATURAL join shows each shared column once.
5240
    #[test]
5241
    fn select_star_natural_dedups_shared_columns() {
3✔
5242
        let db = seed_natural_fixture();
1✔
5243
        let r = run_rows(&db, "SELECT * FROM l NATURAL JOIN r;");
1✔
5244
        // Source order with k1,k2 taken from the left only:
5245
        // l: lid, k1, k2, v1 ; r: rid, v2  (k1,k2 dropped from r).
5246
        assert_eq!(
1✔
5247
            r.columns,
5248
            vec![
3✔
5249
                "lid".to_string(),
1✔
5250
                "k1".to_string(),
1✔
5251
                "k2".to_string(),
1✔
5252
                "v1".to_string(),
1✔
5253
                "rid".to_string(),
1✔
5254
                "v2".to_string(),
1✔
5255
            ]
5256
        );
5257
        assert_eq!(r.rows.len(), 2);
1✔
5258
    }
5259

5260
    /// NATURAL JOIN between tables with no shared column names degrades
5261
    /// to a cross product, matching SQLite.
5262
    #[test]
5263
    fn natural_join_without_common_columns_is_cross_product() {
3✔
5264
        let mut db = Database::new("t".to_string());
1✔
5265
        for sql in [
3✔
5266
            "CREATE TABLE p (pid INTEGER PRIMARY KEY, pa TEXT);",
5267
            "CREATE TABLE q (qid INTEGER PRIMARY KEY, qb TEXT);",
5268
            "INSERT INTO p (pa) VALUES ('p1');",
5269
            "INSERT INTO p (pa) VALUES ('p2');",
5270
            "INSERT INTO q (qb) VALUES ('q1');",
5271
            "INSERT INTO q (qb) VALUES ('q2');",
5272
            "INSERT INTO q (qb) VALUES ('q3');",
5273
        ] {
5274
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5275
        }
5276
        let r = run_rows(&db, "SELECT p.pa, q.qb FROM p NATURAL JOIN q;");
1✔
5277
        assert_eq!(r.rows.len(), 2 * 3, "no shared columns ⇒ cross product");
2✔
5278
    }
5279

5280
    /// CROSS JOIN produces the full cartesian product and is equivalent
5281
    /// to `INNER JOIN ... ON 1`.
5282
    #[test]
5283
    fn cross_join_produces_cartesian_product() {
3✔
5284
        let db = seed_join_fixture();
1✔
5285
        let cross = run_rows(
5286
            &db,
5287
            "SELECT customers.name, orders.amount FROM customers CROSS JOIN orders;",
5288
        );
5289
        // 3 customers × 4 orders = 12 rows.
5290
        assert_eq!(cross.rows.len(), 12);
2✔
5291
        let on_true = run_rows(
5292
            &db,
5293
            "SELECT customers.name, orders.amount FROM customers INNER JOIN orders ON 1;",
5294
        );
5295
        assert_eq!(cross.rows.len(), on_true.rows.len());
2✔
5296
        // SELECT * over a cross join keeps every column from both sides.
5297
        let star = run_rows(&db, "SELECT * FROM customers CROSS JOIN orders;");
1✔
5298
        assert_eq!(star.columns.len(), 5);
2✔
5299
        assert_eq!(star.rows.len(), 12);
1✔
5300
    }
5301

5302
    /// A LEFT OUTER join expressed with USING still preserves unmatched
5303
    /// left rows (NULL-padding the right), and the deduplicated column
5304
    /// keeps the left side's value.
5305
    #[test]
5306
    fn left_outer_join_using_preserves_unmatched_left() {
3✔
5307
        let db = seed_join_fixture();
1✔
5308
        let r = run_rows(
5309
            &db,
5310
            "SELECT * FROM customers LEFT OUTER JOIN orders USING (id);",
5311
        );
5312
        // customers ids 1,2,3 each match an order id; none are unmatched
5313
        // here, so confirm the dedup + row count instead. 4 columns,
5314
        // 3 matched rows (orders has no id=customer beyond 1..3 overlap).
5315
        assert_eq!(r.columns.len(), 4, "id is shown once");
2✔
5316
        assert_eq!(r.rows.len(), 3);
2✔
5317
    }
5318

5319
    /// USING a column that doesn't exist on one of the sides is a clean
5320
    /// error, not a silent empty result.
5321
    #[test]
5322
    fn using_unknown_column_errors() {
3✔
5323
        let db = seed_join_fixture();
1✔
5324
        let q = parse_select("SELECT * FROM customers INNER JOIN orders USING (nope);");
1✔
5325
        let res = execute_select_rows(q, &db);
1✔
5326
        assert!(res.is_err(), "USING (nope) must error — column absent");
2✔
5327
    }
5328

5329
    // ---------------------------------------------------------------------
5330
    // SQLR-6 — aggregates / GROUP BY / DISTINCT over JOIN results
5331
    // ---------------------------------------------------------------------
5332

5333
    #[test]
5334
    fn group_by_with_aggregates_over_inner_join() {
3✔
5335
        let db = seed_join_fixture();
1✔
5336
        let r = run_rows(
5337
            &db,
5338
            "SELECT customers.name, COUNT(*), SUM(orders.amount) FROM customers \
5339
             INNER JOIN orders ON customers.id = orders.customer_id \
5340
             GROUP BY customers.name ORDER BY customers.name;",
5341
        );
5342
        assert_eq!(r.columns, vec!["name", "COUNT(*)", "SUM(orders.amount)"]);
2✔
5343
        assert_eq!(r.rows.len(), 2);
1✔
5344
        assert_eq!(r.rows[0][0].to_display_string(), "Alice");
1✔
5345
        assert_eq!(expect_int(&r.rows[0][1]), 2);
1✔
5346
        assert_eq!(expect_int(&r.rows[0][2]), 300);
1✔
5347
        assert_eq!(r.rows[1][0].to_display_string(), "Bob");
1✔
5348
        assert_eq!(expect_int(&r.rows[1][1]), 1);
1✔
5349
        assert_eq!(expect_int(&r.rows[1][2]), 50);
1✔
5350
    }
5351

5352
    #[test]
5353
    fn aggregates_over_join_without_group_by() {
3✔
5354
        let db = seed_join_fixture();
1✔
5355
        let r = run_rows(
5356
            &db,
5357
            "SELECT COUNT(*), SUM(orders.amount) FROM customers \
5358
             INNER JOIN orders ON customers.id = orders.customer_id;",
5359
        );
5360
        assert_eq!(r.rows.len(), 1);
2✔
5361
        assert_eq!(expect_int(&r.rows[0][0]), 3);
1✔
5362
        assert_eq!(expect_int(&r.rows[0][1]), 350);
1✔
5363
    }
5364

5365
    #[test]
5366
    fn count_column_skips_outer_join_null_padding() {
3✔
5367
        // Carol has no orders: her LEFT-JOIN row is NULL-padded on the
5368
        // right. COUNT(*) counts the padded row; COUNT(orders.id) skips
5369
        // its NULL, per the usual NULL-skipping aggregate semantics.
5370
        let db = seed_join_fixture();
1✔
5371
        let r = run_rows(
5372
            &db,
5373
            "SELECT customers.name, COUNT(*), COUNT(orders.id) FROM customers \
5374
             LEFT OUTER JOIN orders ON customers.id = orders.customer_id \
5375
             GROUP BY customers.name ORDER BY customers.name;",
5376
        );
5377
        assert_eq!(r.rows.len(), 3);
2✔
5378
        let carol = &r.rows[2];
1✔
5379
        assert_eq!(carol[0].to_display_string(), "Carol");
1✔
5380
        assert_eq!(expect_int(&carol[1]), 1, "COUNT(*) counts the padded row");
1✔
5381
        assert_eq!(expect_int(&carol[2]), 0, "COUNT(col) skips the NULL");
2✔
5382
    }
5383

5384
    #[test]
5385
    fn outer_join_null_keys_group_together() {
3✔
5386
        // FULL OUTER surfaces the dangling order (customer_id 4) with a
5387
        // NULL customers.name — it must form its own group, not vanish.
5388
        let db = seed_join_fixture();
1✔
5389
        let r = run_rows(
5390
            &db,
5391
            "SELECT customers.name, COUNT(*) FROM customers \
5392
             FULL OUTER JOIN orders ON customers.id = orders.customer_id \
5393
             GROUP BY customers.name;",
5394
        );
5395
        assert_eq!(r.rows.len(), 4, "Alice, Bob, Carol, NULL");
2✔
5396
        let null_group = r
3✔
5397
            .rows
5398
            .iter()
5399
            .find(|row| row[0] == Value::Null)
3✔
5400
            .expect("dangling order groups under NULL");
5401
        assert_eq!(expect_int(&null_group[1]), 1);
1✔
5402
    }
5403

5404
    #[test]
5405
    fn count_distinct_over_join() {
3✔
5406
        let db = seed_join_fixture();
1✔
5407
        let r = run_rows(
5408
            &db,
5409
            "SELECT COUNT(DISTINCT customers.name) FROM customers \
5410
             INNER JOIN orders ON customers.id = orders.customer_id;",
5411
        );
5412
        assert_eq!(expect_int(&r.rows[0][0]), 2);
2✔
5413
    }
5414

5415
    #[test]
5416
    fn group_by_qualified_key_resolves_ambiguous_name() {
3✔
5417
        // `id` exists on both tables — the qualified GROUP BY key picks
5418
        // the customers side.
5419
        let db = seed_join_fixture();
1✔
5420
        let r = run_rows(
5421
            &db,
5422
            "SELECT customers.id, COUNT(*) FROM customers \
5423
             INNER JOIN orders ON customers.id = orders.customer_id \
5424
             GROUP BY customers.id ORDER BY customers.id;",
5425
        );
5426
        assert_eq!(r.rows.len(), 2);
2✔
5427
        assert_eq!(expect_int(&r.rows[0][0]), 1);
1✔
5428
        assert_eq!(expect_int(&r.rows[0][1]), 2);
1✔
5429
    }
5430

5431
    #[test]
5432
    fn group_by_ambiguous_unqualified_key_over_join_errors() {
3✔
5433
        let err = crate::sql::process_command(
5434
            "SELECT COUNT(*) FROM customers \
5435
             INNER JOIN orders ON customers.id = orders.customer_id GROUP BY id;",
5436
            &mut seed_join_fixture(),
1✔
5437
        );
5438
        match err {
1✔
5439
            Err(e) => assert!(
1✔
5440
                e.to_string().contains("ambiguous"),
3✔
5441
                "unexpected message: {e}"
5442
            ),
NEW
5443
            Ok(_) => panic!("ambiguous GROUP BY key must error"),
×
5444
        }
5445
    }
5446

5447
    #[test]
5448
    fn bare_column_not_in_group_by_over_join_errors() {
3✔
5449
        let err = crate::sql::process_command(
5450
            "SELECT orders.amount, COUNT(*) FROM customers \
5451
             INNER JOIN orders ON customers.id = orders.customer_id \
5452
             GROUP BY customers.name;",
5453
            &mut seed_join_fixture(),
1✔
5454
        );
5455
        match err {
1✔
5456
            Err(e) => assert!(
1✔
5457
                e.to_string().contains("must appear in GROUP BY"),
3✔
5458
                "unexpected message: {e}"
5459
            ),
NEW
5460
            Ok(_) => panic!("bare column outside GROUP BY must error"),
×
5461
        }
5462
    }
5463

5464
    #[test]
5465
    fn aggregate_in_where_over_join_errors_cleanly() {
3✔
5466
        // Code-review gap from SQLR-5: aggregate misuse inside WHERE on
5467
        // a joined query must be a typed error, not wrong results.
5468
        let err = crate::sql::process_command(
5469
            "SELECT COUNT(*) FROM customers \
5470
             INNER JOIN orders ON customers.id = orders.customer_id \
5471
             WHERE COUNT(*) > 1;",
5472
            &mut seed_join_fixture(),
1✔
5473
        );
5474
        match err {
1✔
5475
            Err(SQLRiteError::NotImplemented(msg)) => assert!(
1✔
5476
                msg.contains("not allowed in WHERE"),
2✔
5477
                "unexpected message: {msg}"
5478
            ),
NEW
5479
            other => panic!("expected NotImplemented, got {other:?}"),
×
5480
        }
5481
    }
5482

5483
    #[test]
5484
    fn order_by_aggregate_over_join() {
3✔
5485
        let db = seed_join_fixture();
1✔
5486
        let r = run_rows(
5487
            &db,
5488
            "SELECT customers.name, SUM(orders.amount) FROM customers \
5489
             INNER JOIN orders ON customers.id = orders.customer_id \
5490
             GROUP BY customers.name ORDER BY SUM(orders.amount) DESC;",
5491
        );
5492
        assert_eq!(r.rows[0][0].to_display_string(), "Alice");
2✔
5493
        // Qualifier-stripped fallback: ORDER BY SUM(amount) finds the
5494
        // SUM(orders.amount) slot even though the spellings differ.
5495
        let r2 = run_rows(
5496
            &db,
5497
            "SELECT customers.name, SUM(orders.amount) FROM customers \
5498
             INNER JOIN orders ON customers.id = orders.customer_id \
5499
             GROUP BY customers.name ORDER BY SUM(amount) DESC;",
5500
        );
5501
        assert_eq!(r2.rows[0][0].to_display_string(), "Alice");
2✔
5502
    }
5503

5504
    #[test]
5505
    fn distinct_over_join_dedupes_output_rows() {
3✔
5506
        let db = seed_join_fixture();
1✔
5507
        let r = run_rows(
5508
            &db,
5509
            "SELECT DISTINCT customers.name FROM customers \
5510
             INNER JOIN orders ON customers.id = orders.customer_id;",
5511
        );
5512
        assert_eq!(r.rows.len(), 2);
2✔
5513
        let names: Vec<String> = r
1✔
5514
            .rows
5515
            .iter()
5516
            .map(|row| row[0].to_display_string())
3✔
5517
            .collect();
5518
        assert_eq!(names, vec!["Alice".to_string(), "Bob".to_string()]);
2✔
5519
    }
5520

5521
    #[test]
5522
    fn distinct_over_join_defers_limit_past_dedupe() {
3✔
5523
        // Without deferral, LIMIT 2 would truncate the joined rows to
5524
        // Alice's two orders and dedupe to a single row.
5525
        let db = seed_join_fixture();
1✔
5526
        let r = run_rows(
5527
            &db,
5528
            "SELECT DISTINCT customers.name FROM customers \
5529
             INNER JOIN orders ON customers.id = orders.customer_id LIMIT 2;",
5530
        );
5531
        assert_eq!(r.rows.len(), 2, "LIMIT applies after DISTINCT collapses");
2✔
5532
    }
5533

5534
    #[test]
5535
    fn select_star_group_by_errors_instead_of_panicking() {
3✔
5536
        // Single-table regression: the parser's "must appear in GROUP BY"
5537
        // check skips `SELECT *`, so the executor used to hit an
5538
        // `expect()` panic when a non-grouped column reached projection.
5539
        let err = crate::sql::process_command(
5540
            "SELECT * FROM orders GROUP BY customer_id;",
5541
            &mut seed_join_fixture(),
1✔
5542
        );
5543
        match err {
1✔
5544
            Err(e) => assert!(
1✔
5545
                e.to_string().contains("must appear in GROUP BY"),
3✔
5546
                "unexpected message: {e}"
5547
            ),
NEW
5548
            Ok(_) => panic!("SELECT * with GROUP BY must error, not panic"),
×
5549
        }
5550
    }
5551

5552
    #[test]
5553
    fn group_by_qualified_key_single_table_still_works() {
3✔
5554
        // Qualified GROUP BY keys are accepted on the single-table path
5555
        // too (qualifier ignored, same posture as projections).
5556
        let db = seed_employees();
1✔
5557
        let r = run_rows(
5558
            &db,
5559
            "SELECT dept, COUNT(*) FROM emp GROUP BY emp.dept ORDER BY dept;",
5560
        );
5561
        assert_eq!(r.rows.len(), 3, "eng / sales / ops");
2✔
5562
    }
5563

5564
    #[test]
5565
    fn left_join_with_no_matches_pads_every_row() {
3✔
5566
        let mut db = Database::new("t".to_string());
1✔
5567
        for sql in [
3✔
5568
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
5569
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
5570
            "INSERT INTO a (x) VALUES (1);",
5571
            "INSERT INTO a (x) VALUES (2);",
5572
            "INSERT INTO b (y) VALUES (10);",
5573
        ] {
5574
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5575
        }
5576
        // ON condition matches nothing.
5577
        let r = run_rows(
5578
            &db,
5579
            "SELECT a.x, b.y FROM a LEFT OUTER JOIN b ON a.x = b.y;",
5580
        );
5581
        assert_eq!(r.rows.len(), 2);
2✔
5582
        for row in &r.rows {
1✔
5583
            assert_eq!(row[1], Value::Null);
2✔
5584
        }
5585
    }
5586

5587
    #[test]
5588
    fn left_outer_join_order_by_places_nulls_first() {
3✔
5589
        // NULL ordering matches the engine-wide rule: NULL is Less
5590
        // than every concrete value (see compare_values). So an
5591
        // ORDER BY of a NULL-padded right column puts the
5592
        // outer-join row at the top under ASC.
5593
        let db = seed_join_fixture();
1✔
5594
        let r = run_rows(
5595
            &db,
5596
            "SELECT c.name, o.amount FROM customers AS c \
5597
             LEFT OUTER JOIN orders AS o ON c.id = o.customer_id \
5598
             ORDER BY o.amount ASC;",
5599
        );
5600
        assert_eq!(r.rows.len(), 4);
2✔
5601
        // Carol's NULL amount sorts first.
5602
        assert_eq!(r.rows[0][0].to_display_string(), "Carol");
1✔
5603
        assert_eq!(r.rows[0][1], Value::Null);
1✔
5604
    }
5605

5606
    #[test]
5607
    fn chained_left_outer_join_preserves_left_through_two_levels() {
3✔
5608
        // A LEFT JOIN B LEFT JOIN C — a row in A with no match in B
5609
        // must survive both joins with NULL padding for both sides.
5610
        let mut db = Database::new("t".to_string());
1✔
5611
        for sql in [
3✔
5612
            "CREATE TABLE a (id INTEGER PRIMARY KEY, label TEXT);",
5613
            "CREATE TABLE b (id INTEGER PRIMARY KEY, a_id INTEGER, tag TEXT);",
5614
            "CREATE TABLE c (id INTEGER PRIMARY KEY, b_id INTEGER, note TEXT);",
5615
            "INSERT INTO a (label) VALUES ('a-one');",
5616
            "INSERT INTO a (label) VALUES ('a-two');",
5617
            // b only matches a-one.
5618
            "INSERT INTO b (a_id, tag) VALUES (1, 'b1');",
5619
            // No c rows at all.
5620
        ] {
5621
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5622
        }
5623
        let r = run_rows(
5624
            &db,
5625
            "SELECT a.label, b.tag, c.note FROM a \
5626
             LEFT OUTER JOIN b ON a.id = b.a_id \
5627
             LEFT OUTER JOIN c ON b.id = c.b_id;",
5628
        );
5629
        // Two rows: a-one + b1 with c=NULL, and a-two with b=NULL+c=NULL.
5630
        assert_eq!(r.rows.len(), 2);
2✔
5631
        let by_label: std::collections::HashMap<String, &Vec<Value>> = r
1✔
5632
            .rows
5633
            .iter()
5634
            .map(|row| (row[0].to_display_string(), row))
3✔
5635
            .collect();
5636
        assert_eq!(by_label["a-one"][1].to_display_string(), "b1");
2✔
5637
        assert_eq!(by_label["a-one"][2], Value::Null);
1✔
5638
        assert_eq!(by_label["a-two"][1], Value::Null);
1✔
5639
        assert_eq!(by_label["a-two"][2], Value::Null);
1✔
5640
    }
5641

5642
    #[test]
5643
    fn on_clause_referencing_not_yet_joined_table_errors_clearly() {
3✔
5644
        // ON should only see tables joined so far. Referencing a
5645
        // table that hasn't joined yet is a clean error rather than
5646
        // silently NULL-coalescing into "ON evaluated false".
5647
        let mut db = Database::new("t".to_string());
1✔
5648
        for sql in [
3✔
5649
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
5650
            "CREATE TABLE b (id INTEGER PRIMARY KEY, x INTEGER);",
5651
            "CREATE TABLE c (id INTEGER PRIMARY KEY, x INTEGER);",
5652
            "INSERT INTO a (x) VALUES (1);",
5653
            "INSERT INTO b (x) VALUES (1);",
5654
            "INSERT INTO c (x) VALUES (1);",
5655
        ] {
5656
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5657
        }
5658
        let q =
5659
            parse_select("SELECT a.x FROM a INNER JOIN b ON a.x = c.x INNER JOIN c ON b.x = c.x;");
5660
        let res = execute_select_rows(q, &db);
1✔
5661
        assert!(
×
5662
            res.is_err(),
2✔
5663
            "ON referencing not-yet-joined table 'c' should error"
5664
        );
5665
    }
5666

5667
    #[test]
5668
    fn join_on_truthy_integer_is_accepted() {
3✔
5669
        // ON `1` should be treated as true, like WHERE 1. Verifies
5670
        // the executor reuses eval_predicate_scope's truthiness
5671
        // semantic on JOIN conditions.
5672
        let mut db = Database::new("t".to_string());
1✔
5673
        for sql in [
3✔
5674
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
5675
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
5676
            "INSERT INTO a (x) VALUES (1);",
5677
            "INSERT INTO a (x) VALUES (2);",
5678
            "INSERT INTO b (y) VALUES (10);",
5679
            "INSERT INTO b (y) VALUES (20);",
5680
        ] {
5681
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5682
        }
5683
        let r = run_rows(&db, "SELECT a.x, b.y FROM a INNER JOIN b ON 1;");
1✔
5684
        // ON 1 is always true → cross product → 2 × 2 = 4 rows.
5685
        assert_eq!(r.rows.len(), 4);
2✔
5686
    }
5687

5688
    #[test]
5689
    fn full_join_on_empty_tables_returns_empty() {
3✔
5690
        let mut db = Database::new("t".to_string());
1✔
5691
        for sql in [
3✔
5692
            "CREATE TABLE a (id INTEGER PRIMARY KEY, x INTEGER);",
5693
            "CREATE TABLE b (id INTEGER PRIMARY KEY, y INTEGER);",
5694
        ] {
5695
            crate::sql::process_command(sql, &mut db).unwrap();
2✔
5696
        }
5697
        let r = run_rows(
5698
            &db,
5699
            "SELECT a.x, b.y FROM a FULL OUTER JOIN b ON a.x = b.y;",
5700
        );
5701
        assert!(r.rows.is_empty());
2✔
5702
    }
5703
}
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