Skip to main content

semquery_storage/
sqlite.rs

1use std::collections::HashMap;
2use std::mem::transmute;
3use std::path::Path;
4use std::sync::{Arc, Mutex, Once};
5
6use chrono::{DateTime, Utc};
7use rusqlite::ffi::{sqlite3, sqlite3_api_routines, sqlite3_auto_extension};
8use rusqlite::{Connection, OptionalExtension, params, params_from_iter};
9use semquery_core::{Chunk, Collection, Document, ModelRole, ModelSpec, Result, Storage, StorageTx, StoreError};
10use sqlite_vec::sqlite3_vec_init;
11
12use crate::error::map_rusqlite;
13
14static VEC_EXT_LOADED: Once = Once::new();
15
16fn ensure_vec_extension() {
17  VEC_EXT_LOADED.call_once(|| unsafe {
18    sqlite3_auto_extension(Some(transmute::<
19      *const (),
20      unsafe extern "C" fn(*mut sqlite3, *mut *mut i8, *const sqlite3_api_routines) -> i32,
21    >(sqlite3_vec_init as *const ())));
22  });
23}
24
25fn embedding_to_bytes(vec: &[f32]) -> Vec<u8> {
26  let mut bytes = Vec::with_capacity(vec.len() * 4);
27  for &f in vec {
28    bytes.extend_from_slice(&f.to_le_bytes());
29  }
30  bytes
31}
32
33pub struct SqliteStorage {
34  conn: Arc<Mutex<Connection>>,
35}
36
37const DB_FILE_NAME: &str = "semq.db";
38
39impl SqliteStorage {
40  pub fn open(path: impl AsRef<Path>) -> Result<Self> {
41    ensure_vec_extension();
42    let conn = Connection::open(path).map_err(map_rusqlite)?;
43    conn
44      .execute_batch(
45        "PRAGMA busy_timeout = 5000; \
46         PRAGMA foreign_keys = ON; \
47         PRAGMA journal_mode = WAL; \
48         PRAGMA synchronous = NORMAL; \
49         PRAGMA cache_size = -64000;",
50      )
51      .map_err(map_rusqlite)?;
52    Ok(Self {
53      conn: Arc::new(Mutex::new(conn)),
54    })
55  }
56
57  pub fn open_in_memory() -> Result<Self> {
58    ensure_vec_extension();
59    let conn = Connection::open_in_memory().map_err(map_rusqlite)?;
60    conn
61      .execute_batch(
62        "PRAGMA busy_timeout = 5000; \
63       PRAGMA foreign_keys = ON; \
64       PRAGMA synchronous = NORMAL; \
65       PRAGMA cache_size = -64000;",
66      )
67      .map_err(map_rusqlite)?;
68    Ok(Self {
69      conn: Arc::new(Mutex::new(conn)),
70    })
71  }
72
73  /// Open the default SQLite database inside a workspace directory.
74  /// Keeps the concrete filename (`semq.db`) encapsulated in the storage crate
75  /// so callers don't assume SQLite implementation details.
76  pub fn open_workspace(workspace: impl AsRef<Path>) -> Result<Self> {
77    let path = workspace.as_ref().join(DB_FILE_NAME);
78    Self::open(path)
79  }
80
81  fn init_vectors(&self, conn: &Connection, dimension: usize) -> Result<()> {
82    let expected_type = format!("FLOAT[{dimension}]");
83
84    let existing_sql: Option<String> = conn
85      .query_row(
86        "SELECT sql FROM sqlite_master WHERE type='table' AND name='vec_chunks'",
87        [],
88        |r| r.get(0),
89      )
90      .optional()
91      .map_err(map_rusqlite)?;
92
93    if let Some(sql) = existing_sql {
94      if !sql.contains(&expected_type) {
95        return Err(
96          StoreError::SchemaMismatch {
97            expected: expected_type,
98          }
99          .into(),
100        );
101      }
102      return Ok(());
103    }
104
105    let sql = format!(
106      "CREATE VIRTUAL TABLE IF NOT EXISTS vec_chunks USING vec0(
107         chunk_id  TEXT PRIMARY KEY,
108         embedding {expected_type} distance_metric=cosine
109       );"
110    );
111    conn.execute_batch(&sql).map_err(map_rusqlite)?;
112    Ok(())
113  }
114}
115
116fn poisoned() -> StoreError {
117  StoreError::MutexPoisoned
118}
119
120fn insert_document(conn: &Connection, doc: &Document) -> rusqlite::Result<()> {
121  conn.execute(
122    "INSERT OR REPLACE INTO documents
123     (doc_id, content_hash, content_size, indexed_at)
124   VALUES (?1, ?2, ?3, ?4)",
125    params![
126      doc.id,
127      doc.content_hash,
128      doc.content_size as i64,
129      doc.indexed_at.to_rfc3339(),
130    ],
131  )?;
132  Ok(())
133}
134
135fn insert_chunks(conn: &Connection, chunks: &[Chunk]) -> rusqlite::Result<()> {
136  let mut stmt = conn.prepare(
137    "INSERT OR IGNORE INTO chunks (chunk_id, text, start_byte, end_byte)
138     VALUES (?1, ?2, ?3, ?4)",
139  )?;
140  for chunk in chunks {
141    stmt.execute(params![
142      chunk.id,
143      chunk.text,
144      chunk.byte_range.start as i64,
145      chunk.byte_range.end as i64,
146    ])?;
147  }
148  Ok(())
149}
150
151fn insert_chunk_documents(conn: &Connection, chunk_ids: &[String], doc_id: &str) -> rusqlite::Result<()> {
152  let mut stmt = conn.prepare("INSERT OR IGNORE INTO chunk_documents (chunk_id, doc_id) VALUES (?1, ?2)")?;
153  for cid in chunk_ids {
154    stmt.execute(params![cid, doc_id])?;
155  }
156  Ok(())
157}
158
159fn insert_vectors(conn: &Connection, chunk_ids: &[String], embeddings: &[Vec<f32>]) -> rusqlite::Result<()> {
160  // vec0 (sqlite-vec) virtual tables do not honor INSERT OR REPLACE, so an
161  // upsert is expressed as DELETE + INSERT. Idempotent for fresh ids (the
162  // DELETE is a no-op) and correct when re-embedding overwrites stale vectors.
163  let mut del = conn.prepare("DELETE FROM vec_chunks WHERE chunk_id = ?1")?;
164  let mut stmt = conn.prepare("INSERT INTO vec_chunks (chunk_id, embedding) VALUES (?1, ?2)")?;
165  for (id, emb) in chunk_ids.iter().zip(embeddings.iter()) {
166    let bytes = embedding_to_bytes(emb);
167    del.execute(params![id])?;
168    stmt.execute(params![id, bytes])?;
169  }
170  Ok(())
171}
172
173fn insert_fts(conn: &Connection, chunk_ids: &[String], tokenized_texts: &[String]) -> rusqlite::Result<()> {
174  let mut stmt = conn.prepare("INSERT OR REPLACE INTO fts_chunks (chunk_id, text) VALUES (?1, ?2)")?;
175  for (id, text) in chunk_ids.iter().zip(tokenized_texts.iter()) {
176    stmt.execute(params![id, text])?;
177  }
178  Ok(())
179}
180
181fn insert_document_path(conn: &Connection, doc_id: &str, path: &str) -> rusqlite::Result<()> {
182  conn.execute(
183    "INSERT OR REPLACE INTO document_paths (doc_id, file_path) VALUES (?1, ?2)",
184    params![doc_id, path],
185  )?;
186  Ok(())
187}
188
189fn delete_document(conn: &Connection, doc_id: &str) -> rusqlite::Result<()> {
190  conn.execute("DELETE FROM document_paths WHERE doc_id = ?1", params![doc_id])?;
191  conn.execute("DELETE FROM documents WHERE doc_id = ?1", params![doc_id])?;
192  Ok(())
193}
194
195fn delete_chunks_by_doc(conn: &Connection, doc_id: &str) -> rusqlite::Result<()> {
196  conn.execute("DELETE FROM chunk_documents WHERE doc_id = ?1", params![doc_id])?;
197
198  let orphaned = "chunk_id NOT IN (SELECT chunk_id FROM chunk_documents)";
199  conn.execute(
200    &format!("DELETE FROM vec_chunks WHERE chunk_id IN (SELECT chunk_id FROM chunks WHERE {orphaned})"),
201    [],
202  )?;
203  conn.execute(
204    &format!("DELETE FROM fts_chunks WHERE chunk_id IN (SELECT chunk_id FROM chunks WHERE {orphaned})"),
205    [],
206  )?;
207  conn.execute(&format!("DELETE FROM chunks WHERE {orphaned}"), [])?;
208  Ok(())
209}
210
211fn set_model_version(conn: &Connection, role: ModelRole, version: &ModelSpec) -> rusqlite::Result<()> {
212  conn.execute(
213    "INSERT OR REPLACE INTO model_versions (role, repo_id, filename, revision, checksum)
214     VALUES (?1, ?2, ?3, ?4, ?5)",
215    params![
216      role.as_str(),
217      version.repo_id,
218      version.filename,
219      version.revision,
220      version.checksum
221    ],
222  )?;
223  Ok(())
224}
225
226impl Storage for SqliteStorage {
227  fn init(&self, vector_dimension: usize) -> Result<()> {
228    let conn = self.conn.lock().map_err(|_| poisoned())?;
229    conn
230      .execute_batch(
231        "CREATE TABLE IF NOT EXISTS documents (
232         -- Indexed file; one row per .txt/.md added via `semq add`.
233         -- `doc_id` is a stable identifier derived from the file path.
234         doc_id       TEXT PRIMARY KEY,  -- stable document identifier
235         content_hash TEXT NOT NULL,     -- SHA-256 of file bytes; drives incremental reindex
236         content_size INTEGER NOT NULL,  -- byte length of the original file
237         indexed_at   TEXT NOT NULL      -- RFC3339 UTC timestamp of last successful index
238       );
239       CREATE TABLE IF NOT EXISTS document_paths (
240         -- Separates the mutable file system path from the stable document id.
241         doc_id     TEXT PRIMARY KEY,
242         file_path  TEXT NOT NULL UNIQUE,
243         FOREIGN KEY (doc_id) REFERENCES documents(doc_id) ON DELETE CASCADE
244       );
245       CREATE TABLE IF NOT EXISTS chunks (
246          -- Text block produced by the Chunker; `text` is the exact string embedded.
247          -- chunk_id is the SHA-256 of `text`, so identical content is stored once.
248          -- Parallel `vec_chunks` (sqlite-vec) and `fts_chunks` (FTS5) tables
249          -- are keyed by the same chunk_id.
250          -- doc_id is NOT stored here — the many-to-many mapping lives in
251          -- `chunk_documents` so a shared chunk can belong to multiple files
252          -- without one overwriting the other.
253          chunk_id   TEXT PRIMARY KEY,  -- SHA-256 of `text`; content-addressed dedup
254          text       TEXT NOT NULL,     -- full original text actually embedded
255          start_byte INTEGER NOT NULL,  -- byte offset in the source file (inclusive)
256          end_byte   INTEGER NOT NULL  -- byte offset in the source file (exclusive)
257        );
258        CREATE TABLE IF NOT EXISTS chunk_documents (
259          -- Many-to-many junction: a chunk (identified by its text hash) can
260          -- appear in multiple documents. This table records every (chunk, doc)
261          -- pair so that deleting one document does not clobber the doc_id of
262          -- a chunk still referenced by another document.
263          chunk_id  TEXT NOT NULL,
264          doc_id    TEXT NOT NULL,
265          PRIMARY KEY (chunk_id, doc_id),
266          FOREIGN KEY (chunk_id) REFERENCES chunks(chunk_id) ON DELETE CASCADE,
267          FOREIGN KEY (doc_id) REFERENCES documents(doc_id) ON DELETE CASCADE
268        );
269       CREATE TABLE IF NOT EXISTS model_versions (
270         -- Records which model produced the current embeddings / rerank scores / chat answers.
271         -- On embedding-model upgrade the stored vectors become stale; the indexer compares
272         -- the stored spec here against the live one and triggers an explicit reindex
273         -- rather than serving silently-mismatched vectors.
274         role     TEXT PRIMARY KEY,   -- 'embedding' / 'reranker' / 'chat'
275         repo_id  TEXT NOT NULL,      -- HuggingFace repo id, e.g. 'BAAI/bge-small-zh-v1.5'
276         filename TEXT NOT NULL,      -- on-disk artifact filename (.onnx / .gguf)
277         revision TEXT NOT NULL,      -- HuggingFace revision or commit hash
278         checksum TEXT                -- optional content checksum for verifying downloads
279       );
280        CREATE VIRTUAL TABLE IF NOT EXISTS fts_chunks USING fts5(
281          -- FTS5 full-text index over jieba-pre-tokenised text.
282          -- `text` here stores space-separated tokens (jieba output), NOT the raw chunk text.
283          -- Raw text lives in `chunks.text`; this table only serves BM25 ranking.
284          -- `unicode61` splits on the spaces between tokens, treating each jieba word as a term.
285          chunk_id,
286          text,
287          tokenize='unicode61'
288        );
289        CREATE TABLE IF NOT EXISTS collections (
290          name TEXT PRIMARY KEY,
291          path TEXT NOT NULL
292        );
293        CREATE TABLE IF NOT EXISTS meta (
294          key   TEXT PRIMARY KEY,
295          value TEXT NOT NULL
296        );
297        CREATE INDEX IF NOT EXISTS idx_chunk_documents_doc_id ON chunk_documents(doc_id);",
298      )
299      .map_err(map_rusqlite)?;
300    if vector_dimension == 0 {
301      return Ok(());
302    }
303    self.init_vectors(&conn, vector_dimension)
304  }
305
306  fn get_document(&self, doc_id: &str) -> Result<Option<Document>> {
307    let conn = self.conn.lock().map_err(|_| poisoned())?;
308    let row = conn
309      .query_row(
310        "SELECT doc_id, content_hash, content_size, indexed_at
311       FROM documents WHERE doc_id = ?1",
312        params![doc_id],
313        |r| {
314          Ok((
315            r.get::<_, String>(0)?,
316            r.get::<_, String>(1)?,
317            r.get::<_, i64>(2)?,
318            r.get::<_, String>(3)?,
319          ))
320        },
321      )
322      .optional()
323      .map_err(map_rusqlite)?;
324
325    match row {
326      Some((id, content_hash, content_size, ts)) => {
327        let indexed_at = DateTime::parse_from_rfc3339(&ts)
328          .map_err(|e| StoreError::InvalidTimestamp(e.to_string()))?
329          .with_timezone(&Utc);
330        Ok(Some(Document {
331          id,
332          content_hash,
333          content_size: content_size as usize,
334          indexed_at,
335        }))
336      }
337      None => Ok(None),
338    }
339  }
340
341  fn list_documents(&self) -> Result<Vec<Document>> {
342    let conn = self.conn.lock().map_err(|_| poisoned())?;
343    let mut stmt = conn
344      .prepare("SELECT doc_id, content_hash, content_size, indexed_at FROM documents")
345      .map_err(map_rusqlite)?;
346
347    let rows: Vec<(String, String, i64, String)> = stmt
348      .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
349      .map_err(map_rusqlite)?
350      .collect::<rusqlite::Result<Vec<_>>>()
351      .map_err(map_rusqlite)?;
352
353    let docs = rows
354      .into_iter()
355      .map(|(id, content_hash, content_size, ts)| {
356        let indexed_at = DateTime::parse_from_rfc3339(&ts)
357          .map_err(|e| StoreError::InvalidTimestamp(e.to_string()))?
358          .with_timezone(&Utc);
359        Ok(Document {
360          id,
361          content_hash,
362          content_size: content_size as usize,
363          indexed_at,
364        })
365      })
366      .collect::<Result<Vec<_>>>()?;
367    Ok(docs)
368  }
369
370  fn get_document_paths(&self, doc_ids: &[String]) -> Result<HashMap<String, String>> {
371    if doc_ids.is_empty() {
372      return Ok(HashMap::new());
373    }
374    let conn = self.conn.lock().map_err(|_| poisoned())?;
375    let placeholders = (0..doc_ids.len()).map(|_| "?").collect::<Vec<_>>().join(",");
376    let sql = format!(
377      "SELECT doc_id, file_path FROM document_paths WHERE doc_id IN ({})",
378      placeholders
379    );
380    let mut stmt = conn.prepare(&sql).map_err(map_rusqlite)?;
381    let rows = stmt
382      .query_map(params_from_iter(doc_ids.iter()), |r| {
383        Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
384      })
385      .map_err(map_rusqlite)?
386      .collect::<rusqlite::Result<Vec<_>>>()
387      .map_err(map_rusqlite)?;
388    Ok(rows.into_iter().collect())
389  }
390
391  fn get_existing_chunk_ids(&self, chunk_ids: &[String]) -> Result<Vec<String>> {
392    if chunk_ids.is_empty() {
393      return Ok(Vec::new());
394    }
395    let conn = self.conn.lock().map_err(|_| poisoned())?;
396    let placeholders = (0..chunk_ids.len()).map(|_| "?").collect::<Vec<_>>().join(",");
397    let sql = format!("SELECT chunk_id FROM chunks WHERE chunk_id IN ({placeholders})");
398    let mut stmt = conn.prepare(&sql).map_err(map_rusqlite)?;
399    stmt
400      .query_map(params_from_iter(chunk_ids.iter()), |r| r.get::<_, String>(0))
401      .map_err(map_rusqlite)?
402      .collect::<rusqlite::Result<Vec<String>>>()
403      .map_err(map_rusqlite)
404      .map_err(Into::into)
405  }
406
407  fn get_chunks(&self, chunk_ids: &[String]) -> Result<Vec<Chunk>> {
408    if chunk_ids.is_empty() {
409      return Ok(Vec::new());
410    }
411    let conn = self.conn.lock().map_err(|_| poisoned())?;
412    let placeholders = (0..chunk_ids.len()).map(|_| "?").collect::<Vec<_>>().join(",");
413    let sql = format!(
414      "SELECT c.chunk_id, (
415         SELECT cd.doc_id FROM chunk_documents cd
416         WHERE cd.chunk_id = c.chunk_id
417         ORDER BY cd.doc_id LIMIT 1
418       ) AS doc_id, c.text, c.start_byte, c.end_byte
419       FROM chunks c
420       WHERE c.chunk_id IN ({})",
421      placeholders
422    );
423    let mut stmt = conn.prepare(&sql).map_err(map_rusqlite)?;
424    let rows = stmt
425      .query_map(params_from_iter(chunk_ids.iter()), |r| {
426        Ok((
427          r.get::<_, String>(0)?,
428          r.get::<_, Option<String>>(1)?,
429          r.get::<_, String>(2)?,
430          r.get::<_, i64>(3)?,
431          r.get::<_, i64>(4)?,
432        ))
433      })
434      .map_err(map_rusqlite)?
435      .collect::<rusqlite::Result<Vec<_>>>()
436      .map_err(map_rusqlite)?;
437
438    let chunks = rows
439      .into_iter()
440      .map(|(id, doc_id, text, start, end)| Chunk {
441        id,
442        doc_id: doc_id.unwrap_or_default(),
443        text,
444        byte_range: start as usize..end as usize,
445      })
446      .collect();
447    Ok(chunks)
448  }
449
450  fn search_vectors(&self, embedding: &[f32], top_k: usize) -> Result<Vec<(String, f32)>> {
451    let conn = self.conn.lock().map_err(|_| poisoned())?;
452    let bytes = embedding_to_bytes(embedding);
453    let mut stmt = conn
454      .prepare(
455        "SELECT chunk_id, distance
456         FROM vec_chunks
457         WHERE embedding MATCH ?1 AND k = ?2
458         ORDER BY distance",
459      )
460      .map_err(map_rusqlite)?;
461    // sqlite-vec returns cosine distance (0 = identical, 2 = opposite).
462    // Convert to similarity (1.0 = identical, -1.0 = opposite) so all
463    // channels follow the "higher is better" convention uniformly.
464    let rows = stmt
465      .query_map(params![bytes, top_k as i64], |r| {
466        let distance: f32 = r.get(1)?;
467        Ok((r.get::<_, String>(0)?, 1.0 - distance))
468      })
469      .map_err(map_rusqlite)?
470      .collect::<rusqlite::Result<Vec<_>>>()
471      .map_err(map_rusqlite)?;
472    Ok(rows)
473  }
474
475  fn search_text(&self, query: &str, top_k: usize) -> Result<Vec<(String, f32)>> {
476    let conn = self.conn.lock().map_err(|_| poisoned())?;
477    let mut stmt = conn
478      .prepare(
479        "SELECT chunk_id, bm25(fts_chunks) AS score
480         FROM fts_chunks
481         WHERE fts_chunks MATCH ?1
482         ORDER BY rank
483         LIMIT ?2",
484      )
485      .map_err(map_rusqlite)?;
486    // FTS5 bm25() returns negative scores (0 = best, more negative = worse).
487    // Negate so higher = more relevant, matching the convention of all other channels.
488    let rows = stmt
489      .query_map(params![query, top_k as i64], |r| {
490        let raw: f32 = r.get(1)?;
491        Ok((r.get::<_, String>(0)?, -raw))
492      })
493      .map_err(map_rusqlite)?
494      .collect::<rusqlite::Result<Vec<_>>>()
495      .map_err(map_rusqlite)?;
496    Ok(rows)
497  }
498
499  fn get_model_version(&self, role: ModelRole) -> Result<Option<ModelSpec>> {
500    let conn = self.conn.lock().map_err(|_| poisoned())?;
501    let row = conn
502      .query_row(
503        "SELECT repo_id, filename, revision, checksum FROM model_versions WHERE role = ?1",
504        params![role.as_str()],
505        |r| {
506          Ok((
507            r.get::<_, String>(0)?,
508            r.get::<_, String>(1)?,
509            r.get::<_, String>(2)?,
510            r.get::<_, Option<String>>(3)?,
511          ))
512        },
513      )
514      .optional()
515      .map_err(map_rusqlite)?;
516
517    match row {
518      Some((repo_id, filename, revision, checksum)) => Ok(Some(ModelSpec {
519        role,
520        repo_id,
521        filename,
522        revision,
523        checksum,
524      })),
525      None => Ok(None),
526    }
527  }
528
529  fn list_collections(&self) -> Result<Vec<Collection>> {
530    let conn = self.conn.lock().map_err(|_| poisoned())?;
531    let mut stmt = conn.prepare("SELECT name, path FROM collections").map_err(map_rusqlite)?;
532    let rows = stmt
533      .query_map([], |r| {
534        Ok(Collection {
535          name: r.get(0)?,
536          path: r.get::<_, String>(1)?.into(),
537        })
538      })
539      .map_err(map_rusqlite)?
540      .collect::<rusqlite::Result<Vec<_>>>()
541      .map_err(map_rusqlite)?;
542    Ok(rows)
543  }
544
545  fn count_chunks(&self) -> Result<usize> {
546    let conn = self.conn.lock().map_err(|_| poisoned())?;
547    let count: i64 = conn.query_row("SELECT COUNT(*) FROM chunks", [], |r| r.get(0)).map_err(map_rusqlite)?;
548    Ok(count as usize)
549  }
550
551  fn set_model_version_atomic(&self, role: ModelRole, version: &ModelSpec) -> Result<()> {
552    let conn = self.conn.lock().map_err(|_| poisoned())?;
553    set_model_version(&conn, role, version).map_err(map_rusqlite)?;
554    Ok(())
555  }
556
557  fn get_meta(&self, key: &str) -> Result<Option<String>> {
558    let conn = self.conn.lock().map_err(|_| poisoned())?;
559    let value: Option<String> = conn
560      .query_row("SELECT value FROM meta WHERE key = ?1", params![key], |r| r.get(0))
561      .optional()
562      .map_err(map_rusqlite)?;
563    Ok(value)
564  }
565
566  fn set_meta_atomic(&self, key: &str, value: &str) -> Result<()> {
567    let conn = self.conn.lock().map_err(|_| poisoned())?;
568    conn
569      .execute(
570        "INSERT OR REPLACE INTO meta (key, value) VALUES (?1, ?2)",
571        params![key, value],
572      )
573      .map_err(map_rusqlite)?;
574    Ok(())
575  }
576
577  fn begin_tx(&self) -> Result<Box<dyn StorageTx + '_>> {
578    let conn = self.conn.lock().map_err(|_| poisoned())?;
579    conn.execute_batch("BEGIN").map_err(map_rusqlite)?;
580    Ok(Box::new(SqliteTransaction {
581      conn: self.conn.clone(),
582      committed: false,
583    }))
584  }
585}
586
587pub struct SqliteTransaction {
588  conn: Arc<Mutex<Connection>>,
589  committed: bool,
590}
591
592impl StorageTx for SqliteTransaction {
593  fn add_document(&mut self, doc: &Document) -> Result<()> {
594    let conn = self.conn.lock().map_err(|_| poisoned())?;
595    insert_document(&conn, doc).map_err(map_rusqlite)?;
596    Ok(())
597  }
598
599  fn set_document_path(&mut self, doc_id: &str, path: &str) -> Result<()> {
600    let conn = self.conn.lock().map_err(|_| poisoned())?;
601    insert_document_path(&conn, doc_id, path).map_err(map_rusqlite)?;
602    Ok(())
603  }
604
605  fn delete_document(&mut self, doc_id: &str) -> Result<()> {
606    let conn = self.conn.lock().map_err(|_| poisoned())?;
607    delete_document(&conn, doc_id).map_err(map_rusqlite)?;
608    Ok(())
609  }
610
611  fn add_chunks(&mut self, chunks: &[Chunk]) -> Result<()> {
612    let conn = self.conn.lock().map_err(|_| poisoned())?;
613    insert_chunks(&conn, chunks).map_err(map_rusqlite)?;
614    Ok(())
615  }
616
617  fn add_chunk_documents(&mut self, chunk_ids: &[String], doc_id: &str) -> Result<()> {
618    let conn = self.conn.lock().map_err(|_| poisoned())?;
619    insert_chunk_documents(&conn, chunk_ids, doc_id).map_err(map_rusqlite)?;
620    Ok(())
621  }
622
623  fn delete_chunks_by_doc(&mut self, doc_id: &str) -> Result<()> {
624    let conn = self.conn.lock().map_err(|_| poisoned())?;
625    delete_chunks_by_doc(&conn, doc_id).map_err(map_rusqlite)?;
626    Ok(())
627  }
628
629  fn add_vectors(&mut self, chunk_ids: &[String], embeddings: &[Vec<f32>]) -> Result<()> {
630    if chunk_ids.len() != embeddings.len() {
631      return Err(
632        StoreError::ArgumentMismatch {
633          what: "chunk_ids and embeddings".into(),
634          a: chunk_ids.len(),
635          b: embeddings.len(),
636        }
637        .into(),
638      );
639    }
640    let conn = self.conn.lock().map_err(|_| poisoned())?;
641    insert_vectors(&conn, chunk_ids, embeddings).map_err(map_rusqlite)?;
642    Ok(())
643  }
644
645  fn add_fts_chunks(&mut self, chunk_ids: &[String], tokenized_texts: &[String]) -> Result<()> {
646    if chunk_ids.len() != tokenized_texts.len() {
647      return Err(
648        StoreError::ArgumentMismatch {
649          what: "chunk_ids and tokenized_texts".into(),
650          a: chunk_ids.len(),
651          b: tokenized_texts.len(),
652        }
653        .into(),
654      );
655    }
656    let conn = self.conn.lock().map_err(|_| poisoned())?;
657    insert_fts(&conn, chunk_ids, tokenized_texts).map_err(map_rusqlite)?;
658    Ok(())
659  }
660
661  fn set_model_version(&mut self, role: ModelRole, version: &ModelSpec) -> Result<()> {
662    let conn = self.conn.lock().map_err(|_| poisoned())?;
663    set_model_version(&conn, role, version).map_err(map_rusqlite)?;
664    Ok(())
665  }
666
667  fn add_collection(&mut self, name: &str, path: &str) -> Result<()> {
668    let conn = self.conn.lock().map_err(|_| poisoned())?;
669    conn
670      .execute(
671        "INSERT OR REPLACE INTO collections (name, path) VALUES (?1, ?2)",
672        params![name, path],
673      )
674      .map_err(map_rusqlite)?;
675    Ok(())
676  }
677
678  fn delete_collection(&mut self, name: &str) -> Result<()> {
679    let conn = self.conn.lock().map_err(|_| poisoned())?;
680    conn.execute("DELETE FROM collections WHERE name = ?1", params![name]).map_err(map_rusqlite)?;
681    Ok(())
682  }
683
684  fn clear_collections(&mut self) -> Result<()> {
685    let conn = self.conn.lock().map_err(|_| poisoned())?;
686    conn.execute("DELETE FROM collections", []).map_err(map_rusqlite)?;
687    Ok(())
688  }
689
690  fn commit(&mut self) -> Result<()> {
691    if self.committed {
692      return Err(StoreError::TransactionAlreadyCommitted.into());
693    }
694    let conn = self.conn.lock().map_err(|_| poisoned())?;
695    conn.execute_batch("COMMIT").map_err(map_rusqlite)?;
696    self.committed = true;
697    Ok(())
698  }
699}
700
701impl Drop for SqliteTransaction {
702  fn drop(&mut self) {
703    if !self.committed
704      && let Ok(conn) = self.conn.lock()
705    {
706      let _ = conn.execute_batch("ROLLBACK");
707    }
708  }
709}
710
711#[cfg(test)]
712mod tests {
713  use super::*;
714  use chrono::Utc;
715  use semquery_core::{Chunk, Document, Storage, StorageTx};
716  use std::slice::from_ref;
717  use std::thread;
718
719  fn make_doc(id: &str, content: &str) -> Document {
720    Document {
721      id: id.to_string(),
722      content_hash: format!("hash-{content}"),
723      content_size: content.len(),
724      indexed_at: Utc::now(),
725    }
726  }
727
728  fn make_chunk(id: &str, doc_id: &str, text: &str, start: usize, end: usize) -> Chunk {
729    Chunk {
730      id: id.to_string(),
731      doc_id: doc_id.to_string(),
732      text: text.to_string(),
733      byte_range: start..end,
734    }
735  }
736
737  fn commit<F: FnOnce(&mut dyn StorageTx)>(storage: &SqliteStorage, body: F) {
738    let mut tx = storage.begin_tx().unwrap();
739    body(&mut *tx);
740    tx.commit().unwrap();
741  }
742
743  #[test]
744  fn test_init_zero_then_dimension() {
745    // `semq init` / Engine::open use init(0), which must skip
746    // creating the vec table so a later init(512) (lazy model loading)
747    // can create it with the real dimension.
748    let storage = SqliteStorage::open_in_memory().unwrap();
749    storage.init(0).unwrap();
750    storage.init(512).unwrap();
751  }
752
753  #[test]
754  fn test_document_crud() {
755    let storage = SqliteStorage::open_in_memory().unwrap();
756    storage.init(512).unwrap();
757
758    let doc1 = make_doc("doc1.txt", "hello world");
759    let doc2 = make_doc("doc2.txt", "foo bar");
760    commit(&storage, |tx| {
761      tx.add_document(&doc1).unwrap();
762      tx.add_document(&doc2).unwrap();
763    });
764
765    let got = storage.get_document("doc1.txt").unwrap();
766    assert!(got.is_some());
767    assert_eq!(got.unwrap().content_hash, "hash-hello world");
768
769    let list = storage.list_documents().unwrap();
770    assert_eq!(list.len(), 2);
771
772    commit(&storage, |tx| {
773      tx.delete_document("doc1.txt").unwrap();
774    });
775    assert!(storage.get_document("doc1.txt").unwrap().is_none());
776    assert_eq!(storage.list_documents().unwrap().len(), 1);
777  }
778
779  #[test]
780  fn test_chunk_crud() {
781    let storage = SqliteStorage::open_in_memory().unwrap();
782    storage.init(512).unwrap();
783
784    let doc = make_doc("doc1.txt", "hello world");
785    let c1 = make_chunk("c1", "doc1.txt", "hello", 0, 5);
786    let c2 = make_chunk("c2", "doc1.txt", "world", 6, 11);
787    commit(&storage, |tx| {
788      tx.add_document(&doc).unwrap();
789      tx.add_chunks(&[c1, c2]).unwrap();
790      tx.add_chunk_documents(&["c1".to_string(), "c2".to_string()], "doc1.txt").unwrap();
791    });
792
793    let got = storage.get_chunks(&["c1".to_string(), "c2".to_string()]).unwrap();
794    assert_eq!(got.len(), 2);
795
796    commit(&storage, |tx| {
797      tx.delete_chunks_by_doc("doc1.txt").unwrap();
798    });
799    let gone = storage.get_chunks(&["c1".to_string()]).unwrap();
800    assert!(gone.is_empty());
801  }
802
803  #[test]
804  fn test_shared_chunk_survives_deleting_one_doc() {
805    let storage = SqliteStorage::open_in_memory().unwrap();
806    storage.init(512).unwrap();
807
808    let doc_a = make_doc("doc_a.txt", "shared text");
809    let doc_b = make_doc("doc_b.txt", "shared text");
810    let shared_chunk = make_chunk("shared", "doc_a.txt", "shared text", 0, 11);
811
812    commit(&storage, |tx| {
813      tx.add_document(&doc_a).unwrap();
814      tx.add_chunks(&[shared_chunk]).unwrap();
815      tx.add_chunk_documents(&["shared".to_string()], "doc_a.txt").unwrap();
816    });
817    commit(&storage, |tx| {
818      tx.add_document(&doc_b).unwrap();
819      tx.add_chunks(&[make_chunk("shared", "doc_b.txt", "shared text", 0, 11)]).unwrap();
820      tx.add_chunk_documents(&["shared".to_string()], "doc_b.txt").unwrap();
821    });
822
823    let got = storage.get_chunks(&["shared".to_string()]).unwrap();
824    assert_eq!(got.len(), 1);
825    assert!(!got[0].text.is_empty());
826
827    commit(&storage, |tx| {
828      tx.delete_chunks_by_doc("doc_a.txt").unwrap();
829    });
830
831    let got = storage.get_chunks(&["shared".to_string()]).unwrap();
832    assert_eq!(got.len(), 1, "shared chunk must survive when doc_b still references it");
833  }
834
835  #[test]
836  fn test_delete_chunks_cascades_vectors_and_fts() {
837    let storage = SqliteStorage::open_in_memory().unwrap();
838    storage.init(512).unwrap();
839
840    let doc = make_doc("doc1.txt", "content");
841    let chunk = make_chunk("c1", "doc1.txt", "hello", 0, 5);
842    let embedding = vec![0.1_f32; 512];
843    let tokenized = "hello".to_string();
844
845    commit(&storage, |tx| {
846      tx.add_document(&doc).unwrap();
847      tx.add_chunks(&[chunk]).unwrap();
848      tx.add_chunk_documents(&["c1".to_string()], "doc1.txt").unwrap();
849      tx.add_vectors(&["c1".to_string()], &[embedding]).unwrap();
850      tx.add_fts_chunks(&["c1".to_string()], &[tokenized]).unwrap();
851    });
852
853    assert!(!storage.search_vectors(&vec![0.1_f32; 512], 10).unwrap().is_empty());
854    assert!(!storage.search_text("hello", 10).unwrap().is_empty());
855
856    commit(&storage, |tx| {
857      tx.delete_chunks_by_doc("doc1.txt").unwrap();
858    });
859
860    assert!(storage.get_chunks(&["c1".to_string()]).unwrap().is_empty());
861    assert!(storage.search_vectors(&vec![0.1_f32; 512], 10).unwrap().is_empty());
862    assert!(storage.search_text("hello", 10).unwrap().is_empty());
863  }
864
865  #[test]
866  fn test_model_version() {
867    let storage = SqliteStorage::open_in_memory().unwrap();
868    storage.init(512).unwrap();
869
870    assert!(storage.get_model_version(ModelRole::Embedding).unwrap().is_none());
871
872    let spec = ModelSpec {
873      role: ModelRole::Embedding,
874      repo_id: "BAAI/bge-small-zh-v1.5".into(),
875      filename: "model.onnx".into(),
876      revision: "main".into(),
877      checksum: Some("abc123".into()),
878    };
879    commit(&storage, |tx| {
880      tx.set_model_version(ModelRole::Embedding, &spec).unwrap();
881    });
882
883    let got = storage.get_model_version(ModelRole::Embedding).unwrap().unwrap();
884    assert_eq!(got.repo_id, "BAAI/bge-small-zh-v1.5");
885    assert_eq!(got.checksum.as_deref(), Some("abc123"));
886  }
887
888  #[test]
889  fn test_vector_search() {
890    let storage = SqliteStorage::open_in_memory().unwrap();
891    storage.init(512).unwrap();
892
893    let doc = make_doc("doc1.txt", "content");
894    let chunk = make_chunk("c0", "doc1.txt", "text", 0, 4);
895
896    let base = vec![0.0_f32; 512];
897    let mut vectors: Vec<Vec<f32>> = Vec::new();
898    let mut ids: Vec<String> = Vec::new();
899    let mut chunks = vec![chunk];
900    for i in 0..10 {
901      let mut v = base.clone();
902      v[i] = 1.0;
903      vectors.push(v);
904      ids.push(format!("c{i}"));
905      let ch = make_chunk(&format!("c{i}"), "doc1.txt", "text", i, i + 1);
906      chunks.push(ch);
907    }
908    commit(&storage, |tx| {
909      tx.add_document(&doc).unwrap();
910      tx.add_chunks(&chunks).unwrap();
911      tx.add_chunk_documents(&ids, "doc1.txt").unwrap();
912      tx.add_vectors(&ids, &vectors).unwrap();
913    });
914
915    let mut query = vec![0.0_f32; 512];
916    query[3] = 1.0;
917    let hits = storage.search_vectors(&query, 3).unwrap();
918    assert_eq!(hits.len(), 3);
919    assert_eq!(hits[0].0, "c3");
920    assert!(hits[0].1 > hits[1].1);
921  }
922
923  #[test]
924  fn test_text_search() {
925    let storage = SqliteStorage::open_in_memory().unwrap();
926    storage.init(512).unwrap();
927
928    let doc = make_doc("doc1.txt", "content");
929    let chunks = [
930      ("c1", "分布式 共识 算法 解决 多个 节点 达成 一致 的 问题"),
931      ("c2", "Raft 是 一种 易于 理解 的 共识 算法"),
932      ("c3", "今天 天气 不错"),
933    ];
934    let chunk_objs: Vec<Chunk> =
935      chunks.iter().map(|(id, text)| make_chunk(id, "doc1.txt", text, 0, text.len())).collect();
936    let ids: Vec<String> = chunks.iter().map(|(id, _)| id.to_string()).collect();
937    let texts: Vec<String> = chunks.iter().map(|(_, text)| text.to_string()).collect();
938    commit(&storage, |tx| {
939      tx.add_document(&doc).unwrap();
940      tx.add_chunks(&chunk_objs).unwrap();
941      tx.add_chunk_documents(&ids, "doc1.txt").unwrap();
942      tx.add_fts_chunks(&ids, &texts).unwrap();
943    });
944
945    let hits = storage.search_text("共识 算法", 10).unwrap();
946    assert_eq!(hits.len(), 2);
947    let ids: Vec<&str> = hits.iter().map(|(id, _)| id.as_str()).collect();
948    assert!(ids.contains(&"c1"));
949    assert!(ids.contains(&"c2"));
950    assert!(!ids.contains(&"c3"));
951  }
952
953  #[test]
954  fn test_transaction_commit() {
955    let storage = SqliteStorage::open_in_memory().unwrap();
956    storage.init(512).unwrap();
957
958    let doc = make_doc("doc1.txt", "content");
959    let chunk = make_chunk("c1", "doc1.txt", "hello", 0, 5);
960    let tokenized = "hello".to_string();
961    let embedding = vec![0.1_f32; 512];
962
963    {
964      let mut tx = storage.begin_tx().unwrap();
965      tx.add_document(&doc).unwrap();
966      tx.add_chunks(from_ref(&chunk)).unwrap();
967      tx.add_chunk_documents(&["c1".to_string()], "doc1.txt").unwrap();
968      tx.add_vectors(&["c1".to_string()], from_ref(&embedding)).unwrap();
969      tx.add_fts_chunks(&["c1".to_string()], from_ref(&tokenized)).unwrap();
970      tx.commit().unwrap();
971    }
972
973    assert!(storage.get_document("doc1.txt").unwrap().is_some());
974    assert_eq!(storage.get_chunks(&["c1".to_string()]).unwrap().len(), 1);
975    let hits = storage.search_vectors(&embedding, 1).unwrap();
976    assert_eq!(hits.len(), 1);
977    assert_eq!(hits[0].0, "c1");
978    assert_eq!(storage.search_text("hello", 10).unwrap().len(), 1);
979  }
980
981  #[test]
982  fn test_transaction_rollback_on_drop() {
983    let storage = SqliteStorage::open_in_memory().unwrap();
984    storage.init(512).unwrap();
985
986    let doc = make_doc("doc1.txt", "content");
987
988    {
989      let mut tx = storage.begin_tx().unwrap();
990      tx.add_document(&doc).unwrap();
991    }
992
993    assert!(
994      storage.get_document("doc1.txt").unwrap().is_none(),
995      "doc must not persist without commit"
996    );
997  }
998
999  #[test]
1000  fn test_transaction_commit_after_failure() {
1001    let storage = SqliteStorage::open_in_memory().unwrap();
1002    storage.init(512).unwrap();
1003
1004    let doc = make_doc("doc1.txt", "content");
1005    let chunk = make_chunk("c1", "doc1.txt", "hello", 0, 5);
1006
1007    let result = {
1008      let mut tx = storage.begin_tx().unwrap();
1009      tx.add_document(&doc).unwrap();
1010      tx.add_chunks(&[chunk]).unwrap();
1011      tx.add_vectors(&["c1".to_string(), "c2".to_string()], &[vec![0.0_f32; 512]]).unwrap_err();
1012      Err::<(), _>(StoreError::Sqlite("forced".into()))
1013    };
1014    assert!(result.is_err());
1015
1016    assert!(
1017      storage.get_document("doc1.txt").unwrap().is_none(),
1018      "partial writes must be rolled back"
1019    );
1020    assert!(storage.get_chunks(&["c1".to_string()]).unwrap().is_empty());
1021  }
1022
1023  #[test]
1024  fn test_concurrent_reads() {
1025    let storage = Arc::new(SqliteStorage::open_in_memory().unwrap());
1026    storage.init(512).unwrap();
1027
1028    let doc = make_doc("doc1.txt", "concurrent read test");
1029    let chunk = make_chunk("c1", "doc1.txt", "hello world", 0, 11);
1030    commit(&storage, |tx| {
1031      tx.add_document(&doc).unwrap();
1032      tx.add_chunks(&[chunk]).unwrap();
1033      tx.add_chunk_documents(&["c1".to_string()], "doc1.txt").unwrap();
1034      tx.add_vectors(&["c1".to_string()], &[vec![0.1_f32; 512]]).unwrap();
1035      tx.add_fts_chunks(&["c1".to_string()], &["hello world".to_string()]).unwrap();
1036    });
1037
1038    let handles: Vec<_> = (0..8)
1039      .map(|_| {
1040        let s = storage.clone();
1041        thread::spawn(move || {
1042          assert!(s.get_document("doc1.txt").unwrap().is_some());
1043          assert!(!s.get_chunks(&["c1".to_string()]).unwrap().is_empty());
1044          assert!(!s.search_vectors(&vec![0.1_f32; 512], 10).unwrap().is_empty());
1045          assert!(!s.search_text("hello", 10).unwrap().is_empty());
1046          assert_eq!(s.count_chunks().unwrap(), 1);
1047        })
1048      })
1049      .collect();
1050
1051    for h in handles {
1052      h.join().unwrap();
1053    }
1054  }
1055
1056  #[test]
1057  fn test_concurrent_reads_and_writes() {
1058    let storage = Arc::new(SqliteStorage::open_in_memory().unwrap());
1059    storage.init(512).unwrap();
1060
1061    for i in 0..5 {
1062      let doc = make_doc(&format!("doc{i}.txt"), &format!("content {i}"));
1063      let chunk = make_chunk(&format!("c{i}"), &format!("doc{i}.txt"), &format!("text {i}"), 0, 6);
1064      commit(&storage, |tx| {
1065        tx.add_document(&doc).unwrap();
1066        tx.add_chunks(&[chunk]).unwrap();
1067        tx.add_chunk_documents(&[format!("c{i}")], &format!("doc{i}.txt")).unwrap();
1068      });
1069    }
1070
1071    let reader = storage.clone();
1072    let read_handle = thread::spawn(move || {
1073      for _ in 0..50 {
1074        let docs = reader.list_documents().unwrap();
1075        assert!(docs.len() >= 5);
1076        let _ = reader.count_chunks().unwrap();
1077      }
1078    });
1079
1080    let writer = storage.clone();
1081    let write_handle = thread::spawn(move || {
1082      for i in 0..5 {
1083        let doc = make_doc(&format!("extra{i}.txt"), &format!("extra {i}"));
1084        let chunk = make_chunk(
1085          &format!("extra_c{i}"),
1086          &format!("extra{i}.txt"),
1087          &format!("extra {i}"),
1088          0,
1089          7,
1090        );
1091        commit(&writer, |tx| {
1092          tx.add_document(&doc).unwrap();
1093          tx.add_chunks(&[chunk]).unwrap();
1094          tx.add_chunk_documents(&[format!("extra_c{i}")], &format!("extra{i}.txt")).unwrap();
1095        });
1096      }
1097    });
1098
1099    read_handle.join().unwrap();
1100    write_handle.join().unwrap();
1101
1102    let final_count = storage.list_documents().unwrap().len();
1103    assert_eq!(final_count, 10);
1104  }
1105}