1use 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
20pub struct SelectResult {
29 pub columns: Vec<String>,
30 pub rows: Vec<Vec<Value>>,
31}
32
33pub 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 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 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 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 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
142pub 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
165pub 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 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 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
219pub 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 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 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 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 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
331pub 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 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 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 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#[derive(Debug, Clone, Copy)]
482enum IndexMethod {
483 Btree,
484 Hnsw,
485}
486
487fn 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 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
525fn 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 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 let seed = hash_str_to_seed(index_name);
560 let mut idx = HnswIndex::new(DistanceMetric::L2, seed);
561
562 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 _ => 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 needs_rebuild: false,
602 });
603 Ok(index_name.to_string())
604}
605
606fn 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
618fn 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
655enum RowidSource {
657 IndexProbe(Vec<i64>),
661 FullScan,
664}
665
666fn 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 let literal_value = match convert_literal(&literal) {
685 Ok(v) => v,
686 Err(_) => return Ok(RowidSource::FullScan),
687 };
688
689 let mut rowids = idx.lookup(&literal_value);
693 rowids.sort_unstable();
694 Ok(RowidSource::IndexProbe(rowids))
695}
696
697fn try_extract_equality(expr: &Expr) -> Option<(String, sqlparser::ast::Value)> {
701 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
735fn try_hnsw_probe(table: &Table, order_expr: &Expr, k: usize) -> Option<Vec<i64>> {
757 if k == 0 {
758 return None;
759 }
760
761 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 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 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 let entry = table
807 .hnsw_indexes
808 .iter()
809 .find(|e| e.column_name == col_name)?;
810
811 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 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
841fn 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
860struct 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
899fn 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 if entry < *heap.peek().unwrap() {
936 heap.pop();
937 heap.push(entry);
938 }
939 }
940 }
941
942 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 let mut keys: Vec<(i64, Result<Value>)> = rowids
962 .iter()
963 .map(|r| (*r, eval_expr(&order.expr, table, *r)))
964 .collect();
965
966 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 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 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 (x, y) => x.to_display_string().cmp(&y.to_display_string()),
1014 },
1015 }
1016}
1017
1018pub 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), 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 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 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 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 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
1171fn eval_function(func: &sqlparser::ast::Function, table: &Table, rowid: i64) -> Result<Value> {
1176 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 Ok(Value::Real(dist as f64))
1203 }
1204 other => Err(SQLRiteError::NotImplemented(format!(
1205 "unknown function: {other}(...)"
1206 ))),
1207 }
1208}
1209
1210fn 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
1266pub(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
1278pub(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
1306pub(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
1318fn 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 (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 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 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 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 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 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 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 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 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 let a = vec![0.6f32, 0.8]; let b = vec![0.8f32, 0.6]; 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 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 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 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 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 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 let mut full = all_rowids.clone();
1578 sort_rowids(&mut full, table, order).unwrap();
1579 full.truncate(10);
1580
1581 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 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 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 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 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 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 assert!(resp.contains("3 rows returned"), "got: {resp}");
1686 }
1687
1688 #[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 let t0 = Instant::now();
1725 let _topk = select_topk(&all_rowids, table, order, K).unwrap();
1726 let heap_dur = t0.elapsed();
1727
1728 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 assert!(
1748 ratio > 1.4,
1749 "bounded heap should be substantially faster than full sort, but ratio = {ratio:.2}"
1750 );
1751 }
1752}