Skip to main content

sqlrite/sql/
executor.rs

1//! Query executors — evaluate parsed SQL statements against the in-memory
2//! storage and produce formatted output.
3
4use std::cmp::Ordering;
5
6use prettytable::{Cell as PrintCell, Row as PrintRow, Table as PrintTable};
7use sqlparser::ast::{
8    AssignmentTarget, BinaryOperator, CreateIndex, Delete, Expr, FromTable, FunctionArg,
9    FunctionArgExpr, FunctionArguments, IndexType, ObjectNamePart, Statement, TableFactor,
10    TableWithJoins, UnaryOperator, Update,
11};
12
13use crate::error::{Result, SQLRiteError};
14use crate::sql::db::database::Database;
15use crate::sql::db::secondary_index::{IndexOrigin, SecondaryIndex};
16use crate::sql::db::table::{DataType, HnswIndexEntry, Table, Value, parse_vector_literal};
17use crate::sql::hnsw::{DistanceMetric, HnswIndex};
18use crate::sql::parser::select::{OrderByClause, Projection, SelectQuery};
19
20/// Executes a parsed `SelectQuery` against the database and returns a
21/// human-readable rendering of the result set (prettytable). Also returns
22/// the number of rows produced, for the top-level status message.
23/// Structured result of a SELECT: column names in projection order,
24/// and each matching row as a `Vec<Value>` aligned with the columns.
25/// Phase 5a introduced this so the public `Connection` / `Statement`
26/// API has typed rows to yield; the existing `execute_select` that
27/// returns pre-rendered text is now a thin wrapper on top.
28pub struct SelectResult {
29    pub columns: Vec<String>,
30    pub rows: Vec<Vec<Value>>,
31}
32
33/// Executes a SELECT and returns structured rows. The typed rows are
34/// what the new public API streams to callers; the REPL / Tauri app
35/// pre-render into a prettytable via `execute_select`.
36pub fn execute_select_rows(query: SelectQuery, db: &Database) -> Result<SelectResult> {
37    let table = db
38        .get_table(query.table_name.clone())
39        .map_err(|_| SQLRiteError::Internal(format!("Table '{}' not found", query.table_name)))?;
40
41    // Resolve projection to a concrete ordered column list.
42    let projected_cols: Vec<String> = match &query.projection {
43        Projection::All => table.column_names(),
44        Projection::Columns(cols) => {
45            for c in cols {
46                if !table.contains_column(c.to_string()) {
47                    return Err(SQLRiteError::Internal(format!(
48                        "Column '{c}' does not exist on table '{}'",
49                        query.table_name
50                    )));
51                }
52            }
53            cols.clone()
54        }
55    };
56
57    // Collect matching rowids. If the WHERE is the shape `col = literal`
58    // and `col` has a secondary index, probe the index for an O(log N)
59    // seek; otherwise fall back to the full table scan.
60    let matching = match select_rowids(table, query.selection.as_ref())? {
61        RowidSource::IndexProbe(rowids) => rowids,
62        RowidSource::FullScan => {
63            let mut out = Vec::new();
64            for rowid in table.rowids() {
65                if let Some(expr) = &query.selection {
66                    if !eval_predicate(expr, table, rowid)? {
67                        continue;
68                    }
69                }
70                out.push(rowid);
71            }
72            out
73        }
74    };
75    let mut matching = matching;
76
77    // Phase 7c — bounded-heap top-k optimization.
78    //
79    // The naive "ORDER BY <expr>" path (Phase 7b) sorts every matching
80    // rowid: O(N log N) sort_by + a truncate. For KNN queries
81    //
82    //     SELECT id FROM docs
83    //     ORDER BY vec_distance_l2(embedding, [...])
84    //     LIMIT 10;
85    //
86    // N is the table row count and k is the LIMIT. With a bounded
87    // max-heap of size k we can find the top-k in O(N log k) — same
88    // sort_by-per-row cost on the heap operations, but k is typically
89    // 10-100 while N can be millions.
90    //
91    // Phase 7d.2 — HNSW ANN probe.
92    //
93    // Even better than the bounded heap: if the ORDER BY expression is
94    // exactly `vec_distance_l2(<col>, <bracket-array literal>)` AND
95    // `<col>` has an HNSW index attached, skip the linear scan
96    // entirely and probe the graph in O(log N). Approximate but
97    // typically ≥ 0.95 recall (verified by the recall tests in
98    // src/sql/hnsw.rs).
99    //
100    // We branch in cases:
101    //   1. ORDER BY + LIMIT k matches the HNSW probe pattern  → graph probe.
102    //   2. ORDER BY + LIMIT k where k < |matching|            → bounded heap (7c).
103    //   3. ORDER BY without LIMIT, or LIMIT >= |matching|     → full sort.
104    //   4. LIMIT without ORDER BY                              → just truncate.
105    match (&query.order_by, query.limit) {
106        (Some(order), Some(k)) if try_hnsw_probe(table, &order.expr, k).is_some() => {
107            matching = try_hnsw_probe(table, &order.expr, k).unwrap();
108        }
109        (Some(order), Some(k)) if k < matching.len() => {
110            matching = select_topk(&matching, table, order, k)?;
111        }
112        (Some(order), _) => {
113            sort_rowids(&mut matching, table, order)?;
114            if let Some(k) = query.limit {
115                matching.truncate(k);
116            }
117        }
118        (None, Some(k)) => {
119            matching.truncate(k);
120        }
121        (None, None) => {}
122    }
123
124    // Build typed rows. Missing cells surface as `Value::Null` — that
125    // maps a column-not-present-for-this-rowid case onto the public
126    // `Row::get` → `Option<T>` surface cleanly.
127    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(matching.len());
128    for rowid in &matching {
129        let row: Vec<Value> = projected_cols
130            .iter()
131            .map(|col| table.get_value(col, *rowid).unwrap_or(Value::Null))
132            .collect();
133        rows.push(row);
134    }
135
136    Ok(SelectResult {
137        columns: projected_cols,
138        rows,
139    })
140}
141
142/// Executes a SELECT and returns `(rendered_table, row_count)`. The
143/// REPL and Tauri app use this to keep the table-printing behaviour
144/// the engine has always shipped. Structured callers use
145/// `execute_select_rows` instead.
146pub fn execute_select(query: SelectQuery, db: &Database) -> Result<(String, usize)> {
147    let result = execute_select_rows(query, db)?;
148    let row_count = result.rows.len();
149
150    let mut print_table = PrintTable::new();
151    let header_cells: Vec<PrintCell> = result.columns.iter().map(|c| PrintCell::new(c)).collect();
152    print_table.add_row(PrintRow::new(header_cells));
153
154    for row in &result.rows {
155        let cells: Vec<PrintCell> = row
156            .iter()
157            .map(|v| PrintCell::new(&v.to_display_string()))
158            .collect();
159        print_table.add_row(PrintRow::new(cells));
160    }
161
162    Ok((print_table.to_string(), row_count))
163}
164
165/// Executes a DELETE statement. Returns the number of rows removed.
166pub fn execute_delete(stmt: &Statement, db: &mut Database) -> Result<usize> {
167    let Statement::Delete(Delete {
168        from, selection, ..
169    }) = stmt
170    else {
171        return Err(SQLRiteError::Internal(
172            "execute_delete called on a non-DELETE statement".to_string(),
173        ));
174    };
175
176    let tables = match from {
177        FromTable::WithFromKeyword(t) | FromTable::WithoutKeyword(t) => t,
178    };
179    let table_name = extract_single_table_name(tables)?;
180
181    // Compute matching rowids with an immutable borrow, then mutate.
182    let matching: Vec<i64> = {
183        let table = db
184            .get_table(table_name.clone())
185            .map_err(|_| SQLRiteError::Internal(format!("Table '{table_name}' not found")))?;
186        match select_rowids(table, selection.as_ref())? {
187            RowidSource::IndexProbe(rowids) => rowids,
188            RowidSource::FullScan => {
189                let mut out = Vec::new();
190                for rowid in table.rowids() {
191                    if let Some(expr) = selection {
192                        if !eval_predicate(expr, table, rowid)? {
193                            continue;
194                        }
195                    }
196                    out.push(rowid);
197                }
198                out
199            }
200        }
201    };
202
203    let table = db.get_table_mut(table_name)?;
204    for rowid in &matching {
205        table.delete_row(*rowid);
206    }
207    // Phase 7d.3 — any DELETE invalidates every HNSW index on this
208    // table (the deleted node could still appear in other nodes'
209    // neighbor lists, breaking subsequent searches). Mark dirty so
210    // the next save rebuilds from current rows before serializing.
211    if !matching.is_empty() {
212        for entry in &mut table.hnsw_indexes {
213            entry.needs_rebuild = true;
214        }
215    }
216    Ok(matching.len())
217}
218
219/// Executes an UPDATE statement. Returns the number of rows updated.
220pub fn execute_update(stmt: &Statement, db: &mut Database) -> Result<usize> {
221    let Statement::Update(Update {
222        table,
223        assignments,
224        from,
225        selection,
226        ..
227    }) = stmt
228    else {
229        return Err(SQLRiteError::Internal(
230            "execute_update called on a non-UPDATE statement".to_string(),
231        ));
232    };
233
234    if from.is_some() {
235        return Err(SQLRiteError::NotImplemented(
236            "UPDATE ... FROM is not supported yet".to_string(),
237        ));
238    }
239
240    let table_name = extract_table_name(table)?;
241
242    // Resolve assignment targets to plain column names and verify they exist.
243    let mut parsed_assignments: Vec<(String, Expr)> = Vec::with_capacity(assignments.len());
244    {
245        let tbl = db
246            .get_table(table_name.clone())
247            .map_err(|_| SQLRiteError::Internal(format!("Table '{table_name}' not found")))?;
248        for a in assignments {
249            let col = match &a.target {
250                AssignmentTarget::ColumnName(name) => name
251                    .0
252                    .last()
253                    .map(|p| p.to_string())
254                    .ok_or_else(|| SQLRiteError::Internal("empty column name".to_string()))?,
255                AssignmentTarget::Tuple(_) => {
256                    return Err(SQLRiteError::NotImplemented(
257                        "tuple assignment targets are not supported".to_string(),
258                    ));
259                }
260            };
261            if !tbl.contains_column(col.clone()) {
262                return Err(SQLRiteError::Internal(format!(
263                    "UPDATE references unknown column '{col}'"
264                )));
265            }
266            parsed_assignments.push((col, a.value.clone()));
267        }
268    }
269
270    // Gather matching rowids + the new values to write for each assignment, under
271    // an immutable borrow. Uses the index-probe fast path when the WHERE is
272    // `col = literal` on an indexed column.
273    let work: Vec<(i64, Vec<(String, Value)>)> = {
274        let tbl = db.get_table(table_name.clone())?;
275        let matched_rowids: Vec<i64> = match select_rowids(tbl, selection.as_ref())? {
276            RowidSource::IndexProbe(rowids) => rowids,
277            RowidSource::FullScan => {
278                let mut out = Vec::new();
279                for rowid in tbl.rowids() {
280                    if let Some(expr) = selection {
281                        if !eval_predicate(expr, tbl, rowid)? {
282                            continue;
283                        }
284                    }
285                    out.push(rowid);
286                }
287                out
288            }
289        };
290        let mut rows_to_update = Vec::new();
291        for rowid in matched_rowids {
292            let mut values = Vec::with_capacity(parsed_assignments.len());
293            for (col, expr) in &parsed_assignments {
294                // UPDATE's RHS is evaluated in the context of the row being updated,
295                // so column references on the right resolve to the current row's values.
296                let v = eval_expr(expr, tbl, rowid)?;
297                values.push((col.clone(), v));
298            }
299            rows_to_update.push((rowid, values));
300        }
301        rows_to_update
302    };
303
304    let tbl = db.get_table_mut(table_name)?;
305    for (rowid, values) in &work {
306        for (col, v) in values {
307            tbl.set_value(col, *rowid, v.clone())?;
308        }
309    }
310
311    // Phase 7d.3 — UPDATE may have changed a vector column that an
312    // HNSW index covers. Mark every covering index dirty so save
313    // rebuilds from current rows. (Updates that only touched
314    // non-vector columns also mark dirty, which is over-conservative
315    // but harmless — the rebuild walks rows anyway, and the cost is
316    // only paid on save.)
317    if !work.is_empty() {
318        let updated_columns: std::collections::HashSet<&str> = work
319            .iter()
320            .flat_map(|(_, values)| values.iter().map(|(c, _)| c.as_str()))
321            .collect();
322        for entry in &mut tbl.hnsw_indexes {
323            if updated_columns.contains(entry.column_name.as_str()) {
324                entry.needs_rebuild = true;
325            }
326        }
327    }
328    Ok(work.len())
329}
330
331/// Handles `CREATE INDEX [UNIQUE] <name> ON <table> [USING <method>] (<column>)`.
332/// Single-column indexes only.
333///
334/// Two flavours, branching on the optional `USING <method>` clause:
335///   - **No USING, or `USING btree`**: regular B-Tree secondary index
336///     (Phase 3e). Indexable types: Integer, Text.
337///   - **`USING hnsw`**: HNSW ANN index (Phase 7d.2). Indexable types:
338///     Vector(N) only. Distance metric is L2 by default; cosine and
339///     dot variants are deferred to Phase 7d.x.
340///
341/// Returns the (possibly synthesized) index name for the status message.
342pub fn execute_create_index(stmt: &Statement, db: &mut Database) -> Result<String> {
343    let Statement::CreateIndex(CreateIndex {
344        name,
345        table_name,
346        columns,
347        using,
348        unique,
349        if_not_exists,
350        predicate,
351        ..
352    }) = stmt
353    else {
354        return Err(SQLRiteError::Internal(
355            "execute_create_index called on a non-CREATE-INDEX statement".to_string(),
356        ));
357    };
358
359    if predicate.is_some() {
360        return Err(SQLRiteError::NotImplemented(
361            "partial indexes (CREATE INDEX ... WHERE) are not supported yet".to_string(),
362        ));
363    }
364
365    if columns.len() != 1 {
366        return Err(SQLRiteError::NotImplemented(format!(
367            "multi-column indexes are not supported yet ({} columns given)",
368            columns.len()
369        )));
370    }
371
372    let index_name = name.as_ref().map(|n| n.to_string()).ok_or_else(|| {
373        SQLRiteError::NotImplemented(
374            "anonymous CREATE INDEX (no name) is not supported — give it a name".to_string(),
375        )
376    })?;
377
378    // Detect USING <method>. The `using` field on CreateIndex covers the
379    // pre-column form `CREATE INDEX … USING hnsw (col)`. (sqlparser also
380    // accepts a post-column form `… (col) USING hnsw` and parks that in
381    // `index_options`; we don't bother with it — the canonical form is
382    // pre-column and matches PG/pgvector convention.)
383    let method = match using {
384        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("hnsw") => {
385            IndexMethod::Hnsw
386        }
387        Some(IndexType::Custom(ident)) if ident.value.eq_ignore_ascii_case("btree") => {
388            IndexMethod::Btree
389        }
390        Some(other) => {
391            return Err(SQLRiteError::NotImplemented(format!(
392                "CREATE INDEX … USING {other:?} is not supported (try `hnsw` or no USING clause)"
393            )));
394        }
395        None => IndexMethod::Btree,
396    };
397
398    let table_name_str = table_name.to_string();
399    let column_name = match &columns[0].column.expr {
400        Expr::Identifier(ident) => ident.value.clone(),
401        Expr::CompoundIdentifier(parts) => parts
402            .last()
403            .map(|p| p.value.clone())
404            .ok_or_else(|| SQLRiteError::Internal("empty compound identifier".to_string()))?,
405        other => {
406            return Err(SQLRiteError::NotImplemented(format!(
407                "CREATE INDEX only supports simple column references, got {other:?}"
408            )));
409        }
410    };
411
412    // Validate: table exists, column exists, type matches the index method,
413    // name is unique across both index kinds. Snapshot (rowid, value) pairs
414    // up front under the immutable borrow so the mutable attach later
415    // doesn't fight over `self`.
416    let (datatype, existing_rowids_and_values): (DataType, Vec<(i64, Value)>) = {
417        let table = db.get_table(table_name_str.clone()).map_err(|_| {
418            SQLRiteError::General(format!(
419                "CREATE INDEX references unknown table '{table_name_str}'"
420            ))
421        })?;
422        if !table.contains_column(column_name.clone()) {
423            return Err(SQLRiteError::General(format!(
424                "CREATE INDEX references unknown column '{column_name}' on table '{table_name_str}'"
425            )));
426        }
427        let col = table
428            .columns
429            .iter()
430            .find(|c| c.column_name == column_name)
431            .expect("we just verified the column exists");
432
433        // Name uniqueness check spans BOTH index kinds — a btree and an
434        // hnsw can't share a name.
435        if table.index_by_name(&index_name).is_some()
436            || table.hnsw_indexes.iter().any(|i| i.name == index_name)
437        {
438            if *if_not_exists {
439                return Ok(index_name);
440            }
441            return Err(SQLRiteError::General(format!(
442                "index '{index_name}' already exists"
443            )));
444        }
445        let datatype = clone_datatype(&col.datatype);
446
447        let mut pairs = Vec::new();
448        for rowid in table.rowids() {
449            if let Some(v) = table.get_value(&column_name, rowid) {
450                pairs.push((rowid, v));
451            }
452        }
453        (datatype, pairs)
454    };
455
456    match method {
457        IndexMethod::Btree => create_btree_index(
458            db,
459            &table_name_str,
460            &index_name,
461            &column_name,
462            &datatype,
463            *unique,
464            &existing_rowids_and_values,
465        ),
466        IndexMethod::Hnsw => create_hnsw_index(
467            db,
468            &table_name_str,
469            &index_name,
470            &column_name,
471            &datatype,
472            *unique,
473            &existing_rowids_and_values,
474        ),
475    }
476}
477
478/// `USING <method>` choices recognized by `execute_create_index`. A
479/// missing USING clause defaults to `Btree` so existing CREATE INDEX
480/// statements (Phase 3e) keep working unchanged.
481#[derive(Debug, Clone, Copy)]
482enum IndexMethod {
483    Btree,
484    Hnsw,
485}
486
487/// Builds a Phase 3e B-Tree secondary index and attaches it to the table.
488fn create_btree_index(
489    db: &mut Database,
490    table_name: &str,
491    index_name: &str,
492    column_name: &str,
493    datatype: &DataType,
494    unique: bool,
495    existing: &[(i64, Value)],
496) -> Result<String> {
497    let mut idx = SecondaryIndex::new(
498        index_name.to_string(),
499        table_name.to_string(),
500        column_name.to_string(),
501        datatype,
502        unique,
503        IndexOrigin::Explicit,
504    )?;
505
506    // Populate from existing rows. UNIQUE violations here mean the
507    // existing data already breaks the new index's constraint — a
508    // common source of user confusion, so be explicit.
509    for (rowid, v) in existing {
510        if unique && idx.would_violate_unique(v) {
511            return Err(SQLRiteError::General(format!(
512                "cannot create UNIQUE index '{index_name}': column '{column_name}' \
513                 already contains the duplicate value {}",
514                v.to_display_string()
515            )));
516        }
517        idx.insert(v, *rowid)?;
518    }
519
520    let table_mut = db.get_table_mut(table_name.to_string())?;
521    table_mut.secondary_indexes.push(idx);
522    Ok(index_name.to_string())
523}
524
525/// Builds a Phase 7d.2 HNSW index and attaches it to the table.
526fn create_hnsw_index(
527    db: &mut Database,
528    table_name: &str,
529    index_name: &str,
530    column_name: &str,
531    datatype: &DataType,
532    unique: bool,
533    existing: &[(i64, Value)],
534) -> Result<String> {
535    // HNSW only makes sense on VECTOR columns. Reject anything else
536    // with a clear message — this is the most likely user error.
537    let dim = match datatype {
538        DataType::Vector(d) => *d,
539        other => {
540            return Err(SQLRiteError::General(format!(
541                "USING hnsw requires a VECTOR column; '{column_name}' is {other}"
542            )));
543        }
544    };
545
546    if unique {
547        return Err(SQLRiteError::General(
548            "UNIQUE has no meaning for HNSW indexes".to_string(),
549        ));
550    }
551
552    // Build the in-memory graph. Distance metric is L2 by default
553    // (Phase 7d.2 doesn't yet expose a knob for picking cosine/dot —
554    // see `docs/phase-7-plan.md` for the deferral).
555    //
556    // Seed: hash the index name so different indexes get different
557    // graph topologies, but the same index always gets the same one
558    // — useful when debugging recall / index size.
559    let seed = hash_str_to_seed(index_name);
560    let mut idx = HnswIndex::new(DistanceMetric::L2, seed);
561
562    // Snapshot the (rowid, vector) pairs into a side map so the
563    // get_vec closure below can serve them by id without re-borrowing
564    // the table (we're already holding `existing` — flatten it).
565    let mut vec_map: std::collections::HashMap<i64, Vec<f32>> =
566        std::collections::HashMap::with_capacity(existing.len());
567    for (rowid, v) in existing {
568        match v {
569            Value::Vector(vec) => {
570                if vec.len() != dim {
571                    return Err(SQLRiteError::Internal(format!(
572                        "row {rowid} stores a {}-dim vector in column '{column_name}' \
573                         declared as VECTOR({dim}) — schema invariant violated",
574                        vec.len()
575                    )));
576                }
577                vec_map.insert(*rowid, vec.clone());
578            }
579            // Non-vector values (theoretical NULL, type coercion bug)
580            // get skipped — they wouldn't have a sensible graph
581            // position anyway.
582            _ => continue,
583        }
584    }
585
586    for (rowid, _) in existing {
587        if let Some(v) = vec_map.get(rowid) {
588            let v_clone = v.clone();
589            idx.insert(*rowid, &v_clone, |id| {
590                vec_map.get(&id).cloned().unwrap_or_default()
591            });
592        }
593    }
594
595    let table_mut = db.get_table_mut(table_name.to_string())?;
596    table_mut.hnsw_indexes.push(HnswIndexEntry {
597        name: index_name.to_string(),
598        column_name: column_name.to_string(),
599        index: idx,
600        // Freshly built — no DELETE/UPDATE has invalidated it yet.
601        needs_rebuild: false,
602    });
603    Ok(index_name.to_string())
604}
605
606/// Stable, deterministic hash of a string into a u64 RNG seed. FNV-1a;
607/// avoids pulling in `std::hash::DefaultHasher` (which is randomized
608/// per process).
609fn hash_str_to_seed(s: &str) -> u64 {
610    let mut h: u64 = 0xCBF29CE484222325;
611    for b in s.as_bytes() {
612        h ^= *b as u64;
613        h = h.wrapping_mul(0x100000001B3);
614    }
615    h
616}
617
618/// Cheap clone helper — `DataType` intentionally doesn't derive `Clone`
619/// because the enum has no ergonomic reason to be cloneable elsewhere.
620fn clone_datatype(dt: &DataType) -> DataType {
621    match dt {
622        DataType::Integer => DataType::Integer,
623        DataType::Text => DataType::Text,
624        DataType::Real => DataType::Real,
625        DataType::Bool => DataType::Bool,
626        DataType::Vector(dim) => DataType::Vector(*dim),
627        DataType::None => DataType::None,
628        DataType::Invalid => DataType::Invalid,
629    }
630}
631
632fn extract_single_table_name(tables: &[TableWithJoins]) -> Result<String> {
633    if tables.len() != 1 {
634        return Err(SQLRiteError::NotImplemented(
635            "multi-table DELETE is not supported yet".to_string(),
636        ));
637    }
638    extract_table_name(&tables[0])
639}
640
641fn extract_table_name(twj: &TableWithJoins) -> Result<String> {
642    if !twj.joins.is_empty() {
643        return Err(SQLRiteError::NotImplemented(
644            "JOIN is not supported yet".to_string(),
645        ));
646    }
647    match &twj.relation {
648        TableFactor::Table { name, .. } => Ok(name.to_string()),
649        _ => Err(SQLRiteError::NotImplemented(
650            "only plain table references are supported".to_string(),
651        )),
652    }
653}
654
655/// Tells the executor how to produce its candidate rowid list.
656enum RowidSource {
657    /// The WHERE was simple enough to probe a secondary index directly.
658    /// The `Vec` already contains exactly the rows the index matched;
659    /// no further WHERE evaluation is needed (the probe is precise).
660    IndexProbe(Vec<i64>),
661    /// No applicable index; caller falls back to walking `table.rowids()`
662    /// and evaluating the WHERE on each row.
663    FullScan,
664}
665
666/// Try to satisfy `WHERE` with an index probe. Currently supports the
667/// simplest shape: a single `col = literal` (or `literal = col`) where
668/// `col` is on a secondary index. AND/OR/range predicates fall back to
669/// full scan — those can be layered on later without changing the caller.
670fn select_rowids(table: &Table, selection: Option<&Expr>) -> Result<RowidSource> {
671    let Some(expr) = selection else {
672        return Ok(RowidSource::FullScan);
673    };
674    let Some((col, literal)) = try_extract_equality(expr) else {
675        return Ok(RowidSource::FullScan);
676    };
677    let Some(idx) = table.index_for_column(&col) else {
678        return Ok(RowidSource::FullScan);
679    };
680
681    // Convert the literal into a runtime Value. If the literal type doesn't
682    // match the column's index we still need correct semantics — evaluate
683    // the WHERE against every row. Fall back to full scan.
684    let literal_value = match convert_literal(&literal) {
685        Ok(v) => v,
686        Err(_) => return Ok(RowidSource::FullScan),
687    };
688
689    // Index lookup returns the full list of rowids matching this equality
690    // predicate. For unique indexes that's at most one; for non-unique it
691    // can be many.
692    let mut rowids = idx.lookup(&literal_value);
693    rowids.sort_unstable();
694    Ok(RowidSource::IndexProbe(rowids))
695}
696
697/// Recognizes `expr` as a simple equality on a column reference against a
698/// literal. Returns `(column_name, literal_value)` if the shape matches;
699/// `None` otherwise. Accepts both `col = literal` and `literal = col`.
700fn try_extract_equality(expr: &Expr) -> Option<(String, sqlparser::ast::Value)> {
701    // Peel off Nested parens so `WHERE (x = 1)` is recognized too.
702    let peeled = match expr {
703        Expr::Nested(inner) => inner.as_ref(),
704        other => other,
705    };
706    let Expr::BinaryOp { left, op, right } = peeled else {
707        return None;
708    };
709    if !matches!(op, BinaryOperator::Eq) {
710        return None;
711    }
712    let col_from = |e: &Expr| -> Option<String> {
713        match e {
714            Expr::Identifier(ident) => Some(ident.value.clone()),
715            Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
716            _ => None,
717        }
718    };
719    let literal_from = |e: &Expr| -> Option<sqlparser::ast::Value> {
720        if let Expr::Value(v) = e {
721            Some(v.value.clone())
722        } else {
723            None
724        }
725    };
726    if let (Some(c), Some(l)) = (col_from(left), literal_from(right)) {
727        return Some((c, l));
728    }
729    if let (Some(l), Some(c)) = (literal_from(left), col_from(right)) {
730        return Some((c, l));
731    }
732    None
733}
734
735/// Recognizes the HNSW-probable query pattern and probes the graph
736/// if a matching index exists.
737///
738/// Looks for ORDER BY `vec_distance_l2(<col>, <bracket-array literal>)`
739/// where the table has an HNSW index attached to `<col>`. On a match,
740/// returns the top-k rowids straight from the graph (O(log N)). On
741/// any miss — different function name, no matching index, query
742/// dimension wrong, etc. — returns `None` and the caller falls through
743/// to the bounded-heap brute-force path (7c) or the full sort (7b),
744/// preserving correct results regardless of whether the HNSW pathway
745/// kicked in.
746///
747/// Phase 7d.2 caveats:
748/// - Only `vec_distance_l2` is recognized. Cosine and dot fall through
749///   to brute-force because we don't yet expose a per-index distance
750///   knob (deferred to Phase 7d.x — see `docs/phase-7-plan.md`).
751/// - Only ASCENDING order makes sense for "k nearest" — DESC ORDER BY
752///   `vec_distance_l2(...) LIMIT k` would mean "k farthest", which
753///   isn't what the index is built for. We don't bother to detect
754///   `ascending == false` here; the optimizer just skips and the
755///   fallback path handles it correctly (slower).
756fn try_hnsw_probe(table: &Table, order_expr: &Expr, k: usize) -> Option<Vec<i64>> {
757    if k == 0 {
758        return None;
759    }
760
761    // Pattern-match: order expr must be a function call vec_distance_l2(a, b).
762    let func = match order_expr {
763        Expr::Function(f) => f,
764        _ => return None,
765    };
766    let fname = match func.name.0.as_slice() {
767        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
768        _ => return None,
769    };
770    if fname != "vec_distance_l2" {
771        return None;
772    }
773
774    // Extract the two args as raw Exprs.
775    let arg_list = match &func.args {
776        FunctionArguments::List(l) => &l.args,
777        _ => return None,
778    };
779    if arg_list.len() != 2 {
780        return None;
781    }
782    let exprs: Vec<&Expr> = arg_list
783        .iter()
784        .filter_map(|a| match a {
785            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => Some(e),
786            _ => None,
787        })
788        .collect();
789    if exprs.len() != 2 {
790        return None;
791    }
792
793    // One arg must be a column reference (the indexed col); the other
794    // must be a bracket-array literal (the query vector). Try both
795    // orderings — pgvector's idiom puts the column on the left, but
796    // SQL is commutative for distance.
797    let (col_name, query_vec) = match identify_indexed_arg_and_literal(exprs[0], exprs[1]) {
798        Some(v) => v,
799        None => match identify_indexed_arg_and_literal(exprs[1], exprs[0]) {
800            Some(v) => v,
801            None => return None,
802        },
803    };
804
805    // Find the HNSW index on this column.
806    let entry = table
807        .hnsw_indexes
808        .iter()
809        .find(|e| e.column_name == col_name)?;
810
811    // Dimension sanity check — the query vector must match the
812    // indexed column's declared dimension. If it doesn't, the brute-
813    // force fallback would also error at the vec_distance_l2 dim-check;
814    // returning None here lets that path produce the user-visible
815    // error message.
816    let declared_dim = match table.columns.iter().find(|c| c.column_name == col_name) {
817        Some(c) => match &c.datatype {
818            DataType::Vector(d) => *d,
819            _ => return None,
820        },
821        None => return None,
822    };
823    if query_vec.len() != declared_dim {
824        return None;
825    }
826
827    // Probe the graph. Vectors are looked up from the table's row
828    // storage — a closure rather than a `&Table` so the algorithm
829    // module stays decoupled from the SQL types.
830    let column_for_closure = col_name.clone();
831    let table_ref = table;
832    let result = entry.index.search(&query_vec, k, |id| {
833        match table_ref.get_value(&column_for_closure, id) {
834            Some(Value::Vector(v)) => v,
835            _ => Vec::new(),
836        }
837    });
838    Some(result)
839}
840
841/// Helper for `try_hnsw_probe`: given two function args, identify which
842/// one is a bare column identifier (the indexed column) and which is a
843/// bracket-array literal (the query vector). Returns
844/// `Some((column_name, query_vec))` on a match, `None` otherwise.
845fn identify_indexed_arg_and_literal(a: &Expr, b: &Expr) -> Option<(String, Vec<f32>)> {
846    let col_name = match a {
847        Expr::Identifier(ident) if ident.quote_style.is_none() => ident.value.clone(),
848        _ => return None,
849    };
850    let lit_str = match b {
851        Expr::Identifier(ident) if ident.quote_style == Some('[') => {
852            format!("[{}]", ident.value)
853        }
854        _ => return None,
855    };
856    let v = parse_vector_literal(&lit_str).ok()?;
857    Some((col_name, v))
858}
859
860/// One entry in the bounded-heap top-k path. Holds a pre-evaluated
861/// sort key + the rowid it came from. The `asc` flag inverts `Ord`
862/// so a single `BinaryHeap<HeapEntry>` works for both ASC and DESC
863/// without wrapping in `std::cmp::Reverse` at the call site:
864///
865///   - ASC LIMIT k = "k smallest": natural Ord. Max-heap top is the
866///     largest currently kept; new items smaller than top displace.
867///   - DESC LIMIT k = "k largest": Ord reversed. Max-heap top is now
868///     the smallest currently kept (under reversed Ord, smallest
869///     looks largest); new items larger than top displace.
870///
871/// In both cases the displacement test reduces to "new entry < heap top".
872struct HeapEntry {
873    key: Value,
874    rowid: i64,
875    asc: bool,
876}
877
878impl PartialEq for HeapEntry {
879    fn eq(&self, other: &Self) -> bool {
880        self.cmp(other) == Ordering::Equal
881    }
882}
883
884impl Eq for HeapEntry {}
885
886impl PartialOrd for HeapEntry {
887    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
888        Some(self.cmp(other))
889    }
890}
891
892impl Ord for HeapEntry {
893    fn cmp(&self, other: &Self) -> Ordering {
894        let raw = compare_values(Some(&self.key), Some(&other.key));
895        if self.asc { raw } else { raw.reverse() }
896    }
897}
898
899/// Bounded-heap top-k selection. Returns at most `k` rowids in the
900/// caller's desired order (ascending key for `order.ascending`,
901/// descending otherwise).
902///
903/// O(N log k) where N = `matching.len()`. Caller must check
904/// `k < matching.len()` for this to be a win — for k ≥ N the
905/// `sort_rowids` full-sort path is the same asymptotic cost without
906/// the heap overhead.
907fn select_topk(
908    matching: &[i64],
909    table: &Table,
910    order: &OrderByClause,
911    k: usize,
912) -> Result<Vec<i64>> {
913    use std::collections::BinaryHeap;
914
915    if k == 0 || matching.is_empty() {
916        return Ok(Vec::new());
917    }
918
919    let mut heap: BinaryHeap<HeapEntry> = BinaryHeap::with_capacity(k + 1);
920
921    for &rowid in matching {
922        let key = eval_expr(&order.expr, table, rowid)?;
923        let entry = HeapEntry {
924            key,
925            rowid,
926            asc: order.ascending,
927        };
928
929        if heap.len() < k {
930            heap.push(entry);
931        } else {
932            // peek() returns the largest under our direction-aware Ord
933            // — the worst entry currently kept. Displace it iff the
934            // new entry is "better" (i.e. compares Less).
935            if entry < *heap.peek().unwrap() {
936                heap.pop();
937                heap.push(entry);
938            }
939        }
940    }
941
942    // `into_sorted_vec` returns ascending under our direction-aware Ord:
943    //   ASC: ascending by raw key (what we want)
944    //   DESC: ascending under reversed Ord = descending by raw key (what
945    //         we want for an ORDER BY DESC LIMIT k result)
946    Ok(heap
947        .into_sorted_vec()
948        .into_iter()
949        .map(|e| e.rowid)
950        .collect())
951}
952
953fn sort_rowids(rowids: &mut [i64], table: &Table, order: &OrderByClause) -> Result<()> {
954    // Phase 7b: ORDER BY now accepts any expression (column ref,
955    // arithmetic, function call, …). Pre-compute the sort key for
956    // every rowid up front so the comparator is called O(N log N)
957    // times against pre-evaluated Values rather than re-evaluating
958    // the expression O(N log N) times. Not strictly necessary today,
959    // but vital once 7d's HNSW index lands and this same code path
960    // could be running tens of millions of distance computations.
961    let mut keys: Vec<(i64, Result<Value>)> = rowids
962        .iter()
963        .map(|r| (*r, eval_expr(&order.expr, table, *r)))
964        .collect();
965
966    // Surface the FIRST evaluation error if any. We could be lazy
967    // and let sort_by encounter it, but `Ord::cmp` can't return a
968    // Result and we'd have to swallow errors silently.
969    for (_, k) in &keys {
970        if let Err(e) = k {
971            return Err(SQLRiteError::General(format!(
972                "ORDER BY expression failed: {e}"
973            )));
974        }
975    }
976
977    keys.sort_by(|(_, ka), (_, kb)| {
978        // Both unwrap()s are safe — we just verified above that
979        // every key Result is Ok.
980        let va = ka.as_ref().unwrap();
981        let vb = kb.as_ref().unwrap();
982        let ord = compare_values(Some(va), Some(vb));
983        if order.ascending { ord } else { ord.reverse() }
984    });
985
986    // Write the sorted rowids back into the caller's slice.
987    for (i, (rowid, _)) in keys.into_iter().enumerate() {
988        rowids[i] = rowid;
989    }
990    Ok(())
991}
992
993fn compare_values(a: Option<&Value>, b: Option<&Value>) -> Ordering {
994    match (a, b) {
995        (None, None) => Ordering::Equal,
996        (None, _) => Ordering::Less,
997        (_, None) => Ordering::Greater,
998        (Some(a), Some(b)) => match (a, b) {
999            (Value::Null, Value::Null) => Ordering::Equal,
1000            (Value::Null, _) => Ordering::Less,
1001            (_, Value::Null) => Ordering::Greater,
1002            (Value::Integer(x), Value::Integer(y)) => x.cmp(y),
1003            (Value::Real(x), Value::Real(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
1004            (Value::Integer(x), Value::Real(y)) => {
1005                (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal)
1006            }
1007            (Value::Real(x), Value::Integer(y)) => {
1008                x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal)
1009            }
1010            (Value::Text(x), Value::Text(y)) => x.cmp(y),
1011            (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
1012            // Cross-type fallback: stringify and compare; keeps ORDER BY total.
1013            (x, y) => x.to_display_string().cmp(&y.to_display_string()),
1014        },
1015    }
1016}
1017
1018/// Returns `true` if the row at `rowid` matches the predicate expression.
1019pub fn eval_predicate(expr: &Expr, table: &Table, rowid: i64) -> Result<bool> {
1020    let v = eval_expr(expr, table, rowid)?;
1021    match v {
1022        Value::Bool(b) => Ok(b),
1023        Value::Null => Ok(false), // SQL NULL in a WHERE is treated as false
1024        Value::Integer(i) => Ok(i != 0),
1025        other => Err(SQLRiteError::Internal(format!(
1026            "WHERE clause must evaluate to boolean, got {}",
1027            other.to_display_string()
1028        ))),
1029    }
1030}
1031
1032fn eval_expr(expr: &Expr, table: &Table, rowid: i64) -> Result<Value> {
1033    match expr {
1034        Expr::Nested(inner) => eval_expr(inner, table, rowid),
1035
1036        Expr::Identifier(ident) => {
1037            // Phase 7b — sqlparser parses bracket-array literals like
1038            // `[0.1, 0.2, 0.3]` as bracket-quoted identifiers (it inherits
1039            // MSSQL `[name]` syntax). When we see `quote_style == Some('[')`
1040            // in expression-evaluation position (SELECT projection, WHERE,
1041            // ORDER BY, function args), parse the bracketed content as a
1042            // vector literal so the rest of the executor can compare /
1043            // distance-compute against it. Same trick the INSERT parser
1044            // uses; the executor needed its own copy because expression
1045            // eval runs on a different code path.
1046            if ident.quote_style == Some('[') {
1047                let raw = format!("[{}]", ident.value);
1048                let v = parse_vector_literal(&raw)?;
1049                return Ok(Value::Vector(v));
1050            }
1051            Ok(table.get_value(&ident.value, rowid).unwrap_or(Value::Null))
1052        }
1053
1054        Expr::CompoundIdentifier(parts) => {
1055            // Accept `table.col` — we only have one table in scope, so ignore the qualifier.
1056            let col = parts
1057                .last()
1058                .map(|i| i.value.as_str())
1059                .ok_or_else(|| SQLRiteError::Internal("empty compound identifier".to_string()))?;
1060            Ok(table.get_value(col, rowid).unwrap_or(Value::Null))
1061        }
1062
1063        Expr::Value(v) => convert_literal(&v.value),
1064
1065        Expr::UnaryOp { op, expr } => {
1066            let inner = eval_expr(expr, table, rowid)?;
1067            match op {
1068                UnaryOperator::Not => match inner {
1069                    Value::Bool(b) => Ok(Value::Bool(!b)),
1070                    Value::Null => Ok(Value::Null),
1071                    other => Err(SQLRiteError::Internal(format!(
1072                        "NOT applied to non-boolean value: {}",
1073                        other.to_display_string()
1074                    ))),
1075                },
1076                UnaryOperator::Minus => match inner {
1077                    Value::Integer(i) => Ok(Value::Integer(-i)),
1078                    Value::Real(f) => Ok(Value::Real(-f)),
1079                    Value::Null => Ok(Value::Null),
1080                    other => Err(SQLRiteError::Internal(format!(
1081                        "unary minus on non-numeric value: {}",
1082                        other.to_display_string()
1083                    ))),
1084                },
1085                UnaryOperator::Plus => Ok(inner),
1086                other => Err(SQLRiteError::NotImplemented(format!(
1087                    "unary operator {other:?} is not supported"
1088                ))),
1089            }
1090        }
1091
1092        Expr::BinaryOp { left, op, right } => match op {
1093            BinaryOperator::And => {
1094                let l = eval_expr(left, table, rowid)?;
1095                let r = eval_expr(right, table, rowid)?;
1096                Ok(Value::Bool(as_bool(&l)? && as_bool(&r)?))
1097            }
1098            BinaryOperator::Or => {
1099                let l = eval_expr(left, table, rowid)?;
1100                let r = eval_expr(right, table, rowid)?;
1101                Ok(Value::Bool(as_bool(&l)? || as_bool(&r)?))
1102            }
1103            cmp @ (BinaryOperator::Eq
1104            | BinaryOperator::NotEq
1105            | BinaryOperator::Lt
1106            | BinaryOperator::LtEq
1107            | BinaryOperator::Gt
1108            | BinaryOperator::GtEq) => {
1109                let l = eval_expr(left, table, rowid)?;
1110                let r = eval_expr(right, table, rowid)?;
1111                // Any comparison involving NULL is unknown → false in a WHERE.
1112                if matches!(l, Value::Null) || matches!(r, Value::Null) {
1113                    return Ok(Value::Bool(false));
1114                }
1115                let ord = compare_values(Some(&l), Some(&r));
1116                let result = match cmp {
1117                    BinaryOperator::Eq => ord == Ordering::Equal,
1118                    BinaryOperator::NotEq => ord != Ordering::Equal,
1119                    BinaryOperator::Lt => ord == Ordering::Less,
1120                    BinaryOperator::LtEq => ord != Ordering::Greater,
1121                    BinaryOperator::Gt => ord == Ordering::Greater,
1122                    BinaryOperator::GtEq => ord != Ordering::Less,
1123                    _ => unreachable!(),
1124                };
1125                Ok(Value::Bool(result))
1126            }
1127            arith @ (BinaryOperator::Plus
1128            | BinaryOperator::Minus
1129            | BinaryOperator::Multiply
1130            | BinaryOperator::Divide
1131            | BinaryOperator::Modulo) => {
1132                let l = eval_expr(left, table, rowid)?;
1133                let r = eval_expr(right, table, rowid)?;
1134                eval_arith(arith, &l, &r)
1135            }
1136            BinaryOperator::StringConcat => {
1137                let l = eval_expr(left, table, rowid)?;
1138                let r = eval_expr(right, table, rowid)?;
1139                if matches!(l, Value::Null) || matches!(r, Value::Null) {
1140                    return Ok(Value::Null);
1141                }
1142                Ok(Value::Text(format!(
1143                    "{}{}",
1144                    l.to_display_string(),
1145                    r.to_display_string()
1146                )))
1147            }
1148            other => Err(SQLRiteError::NotImplemented(format!(
1149                "binary operator {other:?} is not supported yet"
1150            ))),
1151        },
1152
1153        // Phase 7b — function-call dispatch. Currently only the three
1154        // vector-distance functions; this match arm becomes the single
1155        // place to register more SQL functions later (e.g. abs(),
1156        // length(), …) without re-touching the rest of the executor.
1157        //
1158        // Operator forms (`<->` `<=>` `<#>`) are NOT plumbed here: two
1159        // of three don't parse natively in sqlparser (we'd need a
1160        // string-preprocessing pass or a sqlparser fork). Deferred to
1161        // a follow-up sub-phase; see docs/phase-7-plan.md's "Scope
1162        // corrections" note.
1163        Expr::Function(func) => eval_function(func, table, rowid),
1164
1165        other => Err(SQLRiteError::NotImplemented(format!(
1166            "unsupported expression in WHERE/projection: {other:?}"
1167        ))),
1168    }
1169}
1170
1171/// Dispatches an `Expr::Function` to its built-in implementation.
1172/// Currently only the three vec_distance_* functions; other functions
1173/// surface as `NotImplemented` errors with the function name in the
1174/// message so users see what they tried.
1175fn eval_function(func: &sqlparser::ast::Function, table: &Table, rowid: i64) -> Result<Value> {
1176    // Function name lives in `name.0[0]` for unqualified calls. Anything
1177    // qualified (e.g. `pkg.fn(...)`) falls through to NotImplemented.
1178    let name = match func.name.0.as_slice() {
1179        [ObjectNamePart::Identifier(ident)] => ident.value.to_lowercase(),
1180        _ => {
1181            return Err(SQLRiteError::NotImplemented(format!(
1182                "qualified function names not supported: {:?}",
1183                func.name
1184            )));
1185        }
1186    };
1187
1188    match name.as_str() {
1189        "vec_distance_l2" | "vec_distance_cosine" | "vec_distance_dot" => {
1190            let (a, b) = extract_two_vector_args(&name, &func.args, table, rowid)?;
1191            let dist = match name.as_str() {
1192                "vec_distance_l2" => vec_distance_l2(&a, &b),
1193                "vec_distance_cosine" => vec_distance_cosine(&a, &b)?,
1194                "vec_distance_dot" => vec_distance_dot(&a, &b),
1195                _ => unreachable!(),
1196            };
1197            // Widen f32 → f64 for the runtime Value. Vectors are stored
1198            // as f32 (consistent with industry convention for embeddings),
1199            // but the executor's numeric type is f64 so distances slot
1200            // into Value::Real cleanly and can be compared / ordered with
1201            // other reals via the existing arithmetic + comparison paths.
1202            Ok(Value::Real(dist as f64))
1203        }
1204        other => Err(SQLRiteError::NotImplemented(format!(
1205            "unknown function: {other}(...)"
1206        ))),
1207    }
1208}
1209
1210/// Extracts exactly two `Vec<f32>` arguments from a function call,
1211/// validating arity and that both sides are Vector-typed with matching
1212/// dimensions. Used by all three vec_distance_* functions.
1213fn extract_two_vector_args(
1214    fn_name: &str,
1215    args: &FunctionArguments,
1216    table: &Table,
1217    rowid: i64,
1218) -> Result<(Vec<f32>, Vec<f32>)> {
1219    let arg_list = match args {
1220        FunctionArguments::List(l) => &l.args,
1221        _ => {
1222            return Err(SQLRiteError::General(format!(
1223                "{fn_name}() expects exactly two vector arguments"
1224            )));
1225        }
1226    };
1227    if arg_list.len() != 2 {
1228        return Err(SQLRiteError::General(format!(
1229            "{fn_name}() expects exactly 2 arguments, got {}",
1230            arg_list.len()
1231        )));
1232    }
1233    let mut out: Vec<Vec<f32>> = Vec::with_capacity(2);
1234    for (i, arg) in arg_list.iter().enumerate() {
1235        let expr = match arg {
1236            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
1237            other => {
1238                return Err(SQLRiteError::NotImplemented(format!(
1239                    "{fn_name}() argument {i} has unsupported shape: {other:?}"
1240                )));
1241            }
1242        };
1243        let val = eval_expr(expr, table, rowid)?;
1244        match val {
1245            Value::Vector(v) => out.push(v),
1246            other => {
1247                return Err(SQLRiteError::General(format!(
1248                    "{fn_name}() argument {i} is not a vector: got {}",
1249                    other.to_display_string()
1250                )));
1251            }
1252        }
1253    }
1254    let b = out.pop().unwrap();
1255    let a = out.pop().unwrap();
1256    if a.len() != b.len() {
1257        return Err(SQLRiteError::General(format!(
1258            "{fn_name}(): vector dimensions don't match (lhs={}, rhs={})",
1259            a.len(),
1260            b.len()
1261        )));
1262    }
1263    Ok((a, b))
1264}
1265
1266/// Euclidean (L2) distance: √Σ(aᵢ − bᵢ)².
1267/// Smaller-is-closer; identical vectors return 0.0.
1268pub(crate) fn vec_distance_l2(a: &[f32], b: &[f32]) -> f32 {
1269    debug_assert_eq!(a.len(), b.len());
1270    let mut sum = 0.0f32;
1271    for i in 0..a.len() {
1272        let d = a[i] - b[i];
1273        sum += d * d;
1274    }
1275    sum.sqrt()
1276}
1277
1278/// Cosine distance: 1 − (a·b) / (‖a‖·‖b‖).
1279/// Smaller-is-closer; identical (non-zero) vectors return 0.0,
1280/// orthogonal vectors return 1.0, opposite-direction vectors return 2.0.
1281///
1282/// Errors if either vector has zero magnitude — cosine similarity is
1283/// undefined for the zero vector and silently returning NaN would
1284/// poison `ORDER BY` ranking. Callers who want the silent-NaN
1285/// behavior can compute `vec_distance_dot(a, b) / (norm(a) * norm(b))`
1286/// themselves.
1287pub(crate) fn vec_distance_cosine(a: &[f32], b: &[f32]) -> Result<f32> {
1288    debug_assert_eq!(a.len(), b.len());
1289    let mut dot = 0.0f32;
1290    let mut norm_a_sq = 0.0f32;
1291    let mut norm_b_sq = 0.0f32;
1292    for i in 0..a.len() {
1293        dot += a[i] * b[i];
1294        norm_a_sq += a[i] * a[i];
1295        norm_b_sq += b[i] * b[i];
1296    }
1297    let denom = (norm_a_sq * norm_b_sq).sqrt();
1298    if denom == 0.0 {
1299        return Err(SQLRiteError::General(
1300            "vec_distance_cosine() is undefined for zero-magnitude vectors".to_string(),
1301        ));
1302    }
1303    Ok(1.0 - dot / denom)
1304}
1305
1306/// Negated dot product: −(a·b).
1307/// pgvector convention — negated so smaller-is-closer like L2 / cosine.
1308/// For unit-norm vectors `vec_distance_dot(a, b) == vec_distance_cosine(a, b) - 1`.
1309pub(crate) fn vec_distance_dot(a: &[f32], b: &[f32]) -> f32 {
1310    debug_assert_eq!(a.len(), b.len());
1311    let mut dot = 0.0f32;
1312    for i in 0..a.len() {
1313        dot += a[i] * b[i];
1314    }
1315    -dot
1316}
1317
1318/// Evaluates an integer/real arithmetic op. NULL on either side propagates.
1319/// Mixed Integer/Real promotes to Real. Divide/Modulo by zero → error.
1320fn eval_arith(op: &BinaryOperator, l: &Value, r: &Value) -> Result<Value> {
1321    if matches!(l, Value::Null) || matches!(r, Value::Null) {
1322        return Ok(Value::Null);
1323    }
1324    match (l, r) {
1325        (Value::Integer(a), Value::Integer(b)) => match op {
1326            BinaryOperator::Plus => Ok(Value::Integer(a.wrapping_add(*b))),
1327            BinaryOperator::Minus => Ok(Value::Integer(a.wrapping_sub(*b))),
1328            BinaryOperator::Multiply => Ok(Value::Integer(a.wrapping_mul(*b))),
1329            BinaryOperator::Divide => {
1330                if *b == 0 {
1331                    Err(SQLRiteError::General("division by zero".to_string()))
1332                } else {
1333                    Ok(Value::Integer(a / b))
1334                }
1335            }
1336            BinaryOperator::Modulo => {
1337                if *b == 0 {
1338                    Err(SQLRiteError::General("modulo by zero".to_string()))
1339                } else {
1340                    Ok(Value::Integer(a % b))
1341                }
1342            }
1343            _ => unreachable!(),
1344        },
1345        // Anything involving a Real promotes both sides to f64.
1346        (a, b) => {
1347            let af = as_number(a)?;
1348            let bf = as_number(b)?;
1349            match op {
1350                BinaryOperator::Plus => Ok(Value::Real(af + bf)),
1351                BinaryOperator::Minus => Ok(Value::Real(af - bf)),
1352                BinaryOperator::Multiply => Ok(Value::Real(af * bf)),
1353                BinaryOperator::Divide => {
1354                    if bf == 0.0 {
1355                        Err(SQLRiteError::General("division by zero".to_string()))
1356                    } else {
1357                        Ok(Value::Real(af / bf))
1358                    }
1359                }
1360                BinaryOperator::Modulo => {
1361                    if bf == 0.0 {
1362                        Err(SQLRiteError::General("modulo by zero".to_string()))
1363                    } else {
1364                        Ok(Value::Real(af % bf))
1365                    }
1366                }
1367                _ => unreachable!(),
1368            }
1369        }
1370    }
1371}
1372
1373fn as_number(v: &Value) -> Result<f64> {
1374    match v {
1375        Value::Integer(i) => Ok(*i as f64),
1376        Value::Real(f) => Ok(*f),
1377        Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
1378        other => Err(SQLRiteError::General(format!(
1379            "arithmetic on non-numeric value '{}'",
1380            other.to_display_string()
1381        ))),
1382    }
1383}
1384
1385fn as_bool(v: &Value) -> Result<bool> {
1386    match v {
1387        Value::Bool(b) => Ok(*b),
1388        Value::Null => Ok(false),
1389        Value::Integer(i) => Ok(*i != 0),
1390        other => Err(SQLRiteError::Internal(format!(
1391            "expected boolean, got {}",
1392            other.to_display_string()
1393        ))),
1394    }
1395}
1396
1397fn convert_literal(v: &sqlparser::ast::Value) -> Result<Value> {
1398    use sqlparser::ast::Value as AstValue;
1399    match v {
1400        AstValue::Number(n, _) => {
1401            if let Ok(i) = n.parse::<i64>() {
1402                Ok(Value::Integer(i))
1403            } else if let Ok(f) = n.parse::<f64>() {
1404                Ok(Value::Real(f))
1405            } else {
1406                Err(SQLRiteError::Internal(format!(
1407                    "could not parse numeric literal '{n}'"
1408                )))
1409            }
1410        }
1411        AstValue::SingleQuotedString(s) => Ok(Value::Text(s.clone())),
1412        AstValue::Boolean(b) => Ok(Value::Bool(*b)),
1413        AstValue::Null => Ok(Value::Null),
1414        other => Err(SQLRiteError::NotImplemented(format!(
1415            "unsupported literal value: {other:?}"
1416        ))),
1417    }
1418}
1419
1420#[cfg(test)]
1421mod tests {
1422    use super::*;
1423
1424    // -----------------------------------------------------------------
1425    // Phase 7b — Vector distance function math
1426    // -----------------------------------------------------------------
1427
1428    /// Float comparison helper — distance results need a small epsilon
1429    /// because we accumulate sums across many f32 multiplies.
1430    fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
1431        (a - b).abs() < eps
1432    }
1433
1434    #[test]
1435    fn vec_distance_l2_identical_is_zero() {
1436        let v = vec![0.1, 0.2, 0.3];
1437        assert_eq!(vec_distance_l2(&v, &v), 0.0);
1438    }
1439
1440    #[test]
1441    fn vec_distance_l2_unit_basis_is_sqrt2() {
1442        // [1, 0] vs [0, 1]: distance = √((1-0)² + (0-1)²) = √2 ≈ 1.414
1443        let a = vec![1.0, 0.0];
1444        let b = vec![0.0, 1.0];
1445        assert!(approx_eq(vec_distance_l2(&a, &b), 2.0_f32.sqrt(), 1e-6));
1446    }
1447
1448    #[test]
1449    fn vec_distance_l2_known_value() {
1450        // [0, 0, 0] vs [3, 4, 0]: √(9 + 16 + 0) = 5 (the classic 3-4-5 triangle).
1451        let a = vec![0.0, 0.0, 0.0];
1452        let b = vec![3.0, 4.0, 0.0];
1453        assert!(approx_eq(vec_distance_l2(&a, &b), 5.0, 1e-6));
1454    }
1455
1456    #[test]
1457    fn vec_distance_cosine_identical_is_zero() {
1458        let v = vec![0.1, 0.2, 0.3];
1459        let d = vec_distance_cosine(&v, &v).unwrap();
1460        assert!(approx_eq(d, 0.0, 1e-6), "cos(v,v) = {d}, expected ≈ 0");
1461    }
1462
1463    #[test]
1464    fn vec_distance_cosine_orthogonal_is_one() {
1465        // Two orthogonal unit vectors should have cosine distance = 1.0
1466        // (cosine similarity = 0 → distance = 1 - 0 = 1).
1467        let a = vec![1.0, 0.0];
1468        let b = vec![0.0, 1.0];
1469        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 1.0, 1e-6));
1470    }
1471
1472    #[test]
1473    fn vec_distance_cosine_opposite_is_two() {
1474        // a and -a have cosine similarity = -1 → distance = 1 - (-1) = 2.
1475        let a = vec![1.0, 0.0, 0.0];
1476        let b = vec![-1.0, 0.0, 0.0];
1477        assert!(approx_eq(vec_distance_cosine(&a, &b).unwrap(), 2.0, 1e-6));
1478    }
1479
1480    #[test]
1481    fn vec_distance_cosine_zero_magnitude_errors() {
1482        // Cosine is undefined for the zero vector — error rather than NaN.
1483        let a = vec![0.0, 0.0];
1484        let b = vec![1.0, 0.0];
1485        let err = vec_distance_cosine(&a, &b).unwrap_err();
1486        assert!(format!("{err}").contains("zero-magnitude"));
1487    }
1488
1489    #[test]
1490    fn vec_distance_dot_negates() {
1491        // a·b = 1*4 + 2*5 + 3*6 = 32. Negated → -32.
1492        let a = vec![1.0, 2.0, 3.0];
1493        let b = vec![4.0, 5.0, 6.0];
1494        assert!(approx_eq(vec_distance_dot(&a, &b), -32.0, 1e-6));
1495    }
1496
1497    #[test]
1498    fn vec_distance_dot_orthogonal_is_zero() {
1499        // Orthogonal vectors have dot product 0 → negated is also 0.
1500        let a = vec![1.0, 0.0];
1501        let b = vec![0.0, 1.0];
1502        assert_eq!(vec_distance_dot(&a, &b), 0.0);
1503    }
1504
1505    #[test]
1506    fn vec_distance_dot_unit_norm_matches_cosine_minus_one() {
1507        // For unit-norm vectors: dot(a,b) = cos(a,b)
1508        // → -dot(a,b) = -cos(a,b) = (1 - cos(a,b)) - 1 = vec_distance_cosine(a,b) - 1.
1509        // Useful sanity check that the two functions agree on unit vectors.
1510        let a = vec![0.6f32, 0.8]; // unit norm: √(0.36+0.64) = 1
1511        let b = vec![0.8f32, 0.6]; // unit norm too
1512        let dot = vec_distance_dot(&a, &b);
1513        let cos = vec_distance_cosine(&a, &b).unwrap();
1514        assert!(approx_eq(dot, cos - 1.0, 1e-5));
1515    }
1516
1517    // -----------------------------------------------------------------
1518    // Phase 7c — bounded-heap top-k correctness + benchmark
1519    // -----------------------------------------------------------------
1520
1521    use crate::sql::db::database::Database;
1522    use crate::sql::parser::select::SelectQuery;
1523    use sqlparser::dialect::SQLiteDialect;
1524    use sqlparser::parser::Parser;
1525
1526    /// Builds a `docs(id INTEGER PK, score REAL)` table with N rows of
1527    /// distinct positive scores so top-k tests aren't sensitive to
1528    /// tie-breaking (heap is unstable; full-sort is stable; we want
1529    /// both to agree without arguing about equal-score row order).
1530    ///
1531    /// **Why positive scores:** the INSERT parser doesn't currently
1532    /// handle `Expr::UnaryOp(Minus, …)` for negative number literals
1533    /// (it would parse `-3.14` as a unary expression and the value
1534    /// extractor would skip it). That's a pre-existing bug, out of
1535    /// scope for 7c. Using the Knuth multiplicative hash gives us
1536    /// distinct positive scrambled values without dancing around the
1537    /// negative-literal limitation.
1538    fn seed_score_table(n: usize) -> Database {
1539        let mut db = Database::new("tempdb".to_string());
1540        crate::sql::process_command(
1541            "CREATE TABLE docs (id INTEGER PRIMARY KEY, score REAL);",
1542            &mut db,
1543        )
1544        .expect("create");
1545        for i in 0..n {
1546            // Knuth multiplicative hash mod 1_000_000 — distinct,
1547            // dense in [0, 999_999], no collisions for n up to ~tens
1548            // of thousands.
1549            let score = ((i as u64).wrapping_mul(2_654_435_761) % 1_000_000) as f64;
1550            let sql = format!("INSERT INTO docs (score) VALUES ({score});");
1551            crate::sql::process_command(&sql, &mut db).expect("insert");
1552        }
1553        db
1554    }
1555
1556    /// Helper: parses an SQL SELECT into a SelectQuery so we can drive
1557    /// `select_topk` / `sort_rowids` directly without the rest of the
1558    /// process_command pipeline.
1559    fn parse_select(sql: &str) -> SelectQuery {
1560        let dialect = SQLiteDialect {};
1561        let mut ast = Parser::parse_sql(&dialect, sql).expect("parse");
1562        let stmt = ast.pop().expect("one statement");
1563        SelectQuery::new(&stmt).expect("select-query")
1564    }
1565
1566    #[test]
1567    fn topk_matches_full_sort_asc() {
1568        // Build N=200, top-k=10. Bounded heap output must equal
1569        // full-sort-then-truncate output (both produce ASC order).
1570        let db = seed_score_table(200);
1571        let table = db.get_table("docs".to_string()).unwrap();
1572        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
1573        let order = q.order_by.as_ref().unwrap();
1574        let all_rowids = table.rowids();
1575
1576        // Full-sort path
1577        let mut full = all_rowids.clone();
1578        sort_rowids(&mut full, table, order).unwrap();
1579        full.truncate(10);
1580
1581        // Bounded-heap path
1582        let topk = select_topk(&all_rowids, table, order, 10).unwrap();
1583
1584        assert_eq!(topk, full, "top-k via heap should match full-sort+truncate");
1585    }
1586
1587    #[test]
1588    fn topk_matches_full_sort_desc() {
1589        // Same with DESC — verifies the direction-aware Ord wrapper.
1590        let db = seed_score_table(200);
1591        let table = db.get_table("docs".to_string()).unwrap();
1592        let q = parse_select("SELECT * FROM docs ORDER BY score DESC LIMIT 10;");
1593        let order = q.order_by.as_ref().unwrap();
1594        let all_rowids = table.rowids();
1595
1596        let mut full = all_rowids.clone();
1597        sort_rowids(&mut full, table, order).unwrap();
1598        full.truncate(10);
1599
1600        let topk = select_topk(&all_rowids, table, order, 10).unwrap();
1601
1602        assert_eq!(
1603            topk, full,
1604            "top-k DESC via heap should match full-sort+truncate"
1605        );
1606    }
1607
1608    #[test]
1609    fn topk_k_larger_than_n_returns_everything_sorted() {
1610        // The executor branches off to the full-sort path when k >= N,
1611        // but if a caller invokes select_topk directly with k > N, it
1612        // should still produce all-sorted output (no truncation
1613        // because we don't have N items to truncate to k).
1614        let db = seed_score_table(50);
1615        let table = db.get_table("docs".to_string()).unwrap();
1616        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1000;");
1617        let order = q.order_by.as_ref().unwrap();
1618        let topk = select_topk(&table.rowids(), table, order, 1000).unwrap();
1619        assert_eq!(topk.len(), 50);
1620        // All scores in ascending order.
1621        let scores: Vec<f64> = topk
1622            .iter()
1623            .filter_map(|r| match table.get_value("score", *r) {
1624                Some(Value::Real(f)) => Some(f),
1625                _ => None,
1626            })
1627            .collect();
1628        assert!(scores.windows(2).all(|w| w[0] <= w[1]));
1629    }
1630
1631    #[test]
1632    fn topk_k_zero_returns_empty() {
1633        let db = seed_score_table(10);
1634        let table = db.get_table("docs".to_string()).unwrap();
1635        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 1;");
1636        let order = q.order_by.as_ref().unwrap();
1637        let topk = select_topk(&table.rowids(), table, order, 0).unwrap();
1638        assert!(topk.is_empty());
1639    }
1640
1641    #[test]
1642    fn topk_empty_input_returns_empty() {
1643        let db = seed_score_table(0);
1644        let table = db.get_table("docs".to_string()).unwrap();
1645        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 5;");
1646        let order = q.order_by.as_ref().unwrap();
1647        let topk = select_topk(&[], table, order, 5).unwrap();
1648        assert!(topk.is_empty());
1649    }
1650
1651    #[test]
1652    fn topk_works_through_select_executor_with_distance_function() {
1653        // Integration check that the executor actually picks the
1654        // bounded-heap path on a KNN-shaped query and produces the
1655        // correct top-k.
1656        let mut db = Database::new("tempdb".to_string());
1657        crate::sql::process_command(
1658            "CREATE TABLE docs (id INTEGER PRIMARY KEY, e VECTOR(2));",
1659            &mut db,
1660        )
1661        .unwrap();
1662        // Five rows with distinct distances from probe [1.0, 0.0]:
1663        //   id=1 [1.0, 0.0]   distance=0
1664        //   id=2 [2.0, 0.0]   distance=1
1665        //   id=3 [0.0, 3.0]   distance=√(1+9) = √10 ≈ 3.16
1666        //   id=4 [1.0, 4.0]   distance=4
1667        //   id=5 [10.0, 10.0] distance=√(81+100) ≈ 13.45
1668        for v in &[
1669            "[1.0, 0.0]",
1670            "[2.0, 0.0]",
1671            "[0.0, 3.0]",
1672            "[1.0, 4.0]",
1673            "[10.0, 10.0]",
1674        ] {
1675            crate::sql::process_command(&format!("INSERT INTO docs (e) VALUES ({v});"), &mut db)
1676                .unwrap();
1677        }
1678        let resp = crate::sql::process_command(
1679            "SELECT id FROM docs ORDER BY vec_distance_l2(e, [1.0, 0.0]) ASC LIMIT 3;",
1680            &mut db,
1681        )
1682        .unwrap();
1683        // Top-3 closest to [1.0, 0.0] are id=1, id=2, id=3 (in that order).
1684        // The status message tells us how many rows came back.
1685        assert!(resp.contains("3 rows returned"), "got: {resp}");
1686    }
1687
1688    /// Manual benchmark — not run by default. Recommended invocation:
1689    ///
1690    ///     cargo test -p sqlrite-engine --lib topk_benchmark --release \
1691    ///         -- --ignored --nocapture
1692    ///
1693    /// (`--release` matters: Rust's optimized sort gets very fast under
1694    /// optimization, so the heap's relative advantage is best observed
1695    /// against a sort that's also been optimized.)
1696    ///
1697    /// Measured numbers on an Apple Silicon laptop with N=10_000 + k=10:
1698    ///   - bounded heap:    ~820µs
1699    ///   - full sort+trunc: ~1.5ms
1700    ///   - ratio:           ~1.8×
1701    ///
1702    /// The advantage is real but moderate at this size because the sort
1703    /// key here is a single REAL column read (cheap) and Rust's sort_by
1704    /// has a very low constant factor. The asymptotic O(N log k) vs
1705    /// O(N log N) advantage scales with N and with per-row work — KNN
1706    /// queries where the sort key is `vec_distance_l2(col, [...])` are
1707    /// where this path really pays off, because each key evaluation is
1708    /// itself O(dim) and the heap path skips the per-row evaluation
1709    /// in the comparator (see `sort_rowids` for the contrast).
1710    #[test]
1711    #[ignore]
1712    fn topk_benchmark() {
1713        use std::time::Instant;
1714        const N: usize = 10_000;
1715        const K: usize = 10;
1716
1717        let db = seed_score_table(N);
1718        let table = db.get_table("docs".to_string()).unwrap();
1719        let q = parse_select("SELECT * FROM docs ORDER BY score ASC LIMIT 10;");
1720        let order = q.order_by.as_ref().unwrap();
1721        let all_rowids = table.rowids();
1722
1723        // Time bounded heap.
1724        let t0 = Instant::now();
1725        let _topk = select_topk(&all_rowids, table, order, K).unwrap();
1726        let heap_dur = t0.elapsed();
1727
1728        // Time full sort + truncate.
1729        let t1 = Instant::now();
1730        let mut full = all_rowids.clone();
1731        sort_rowids(&mut full, table, order).unwrap();
1732        full.truncate(K);
1733        let sort_dur = t1.elapsed();
1734
1735        let ratio = sort_dur.as_secs_f64() / heap_dur.as_secs_f64().max(1e-9);
1736        println!("\n--- topk_benchmark (N={N}, k={K}) ---");
1737        println!("  bounded heap:   {heap_dur:?}");
1738        println!("  full sort+trunc: {sort_dur:?}");
1739        println!("  speedup ratio:  {ratio:.2}×");
1740
1741        // Soft assertion. Floor is 1.4× because the cheap-key
1742        // benchmark hovers around 1.8× empirically; setting this too
1743        // close to the measured value risks flaky CI on slower
1744        // runners. Floor of 1.4× still catches an actual regression
1745        // (e.g., if select_topk became O(N²) or stopped using the
1746        // heap entirely).
1747        assert!(
1748            ratio > 1.4,
1749            "bounded heap should be substantially faster than full sort, but ratio = {ratio:.2}"
1750        );
1751    }
1752}