Skip to main content

contextgraph_core/
sqlite.rs

1//! SQLite-backed `CommitStore` + `RefStore`, in WAL mode. Commit blobs and
2//! metadata are stored as JSON text columns; parent/child edges are indexed
3//! in both directions so ancestry walks (`log`, `bisect`) don't need to
4//! deserialize blobs just to traverse the graph.
5
6use crate::commit::{Commit, CommitId};
7use crate::error::{GraphError, Result};
8use crate::store::{CommitStore, RefStore};
9use async_trait::async_trait;
10use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
11use sqlx::{Row, SqlitePool};
12use std::str::FromStr;
13
14/// A single SQLite-backed store implementing both `CommitStore` and
15/// `RefStore`, sharing one connection pool so commit + branch-move
16/// operations can be composed into a single transaction by callers.
17#[derive(Debug, Clone)]
18pub struct SqliteStore {
19    pool: SqlitePool,
20}
21
22impl SqliteStore {
23    /// Opens (creating if needed) a SQLite database at `path` and runs
24    /// migrations. Enables WAL mode for concurrent readers.
25    ///
26    /// Validates the path up front so callers get one clear error message
27    /// (e.g. "parent directory does not exist") instead of an opaque SQLite
28    /// error code, which is otherwise all that surfaces from `open` when
29    /// the containing directory is missing.
30    pub async fn open(path: &str) -> Result<Self> {
31        Self::validate_path(path)?;
32        let options = SqliteConnectOptions::from_str(path)
33            .map_err(|e| GraphError::Storage(e.to_string()))?
34            .create_if_missing(true)
35            .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal);
36        let pool = SqlitePoolOptions::new()
37            .max_connections(8)
38            .connect_with(options)
39            .await
40            .map_err(|e| GraphError::Storage(e.to_string()))?;
41        let store = Self { pool };
42        store.migrate().await?;
43        Ok(store)
44    }
45
46    /// In-memory SQLite, for tests that want SQLite semantics without a
47    /// filesystem temp file.
48    pub async fn open_in_memory() -> Result<Self> {
49        Self::open(":memory:").await
50    }
51
52    pub fn pool(&self) -> &SqlitePool {
53        &self.pool
54    }
55
56    /// Rejects paths whose containing directory doesn't exist, with a
57    /// message naming the exact missing directory. In-memory targets
58    /// (`:memory:` or a `file:...mode=memory...` URI) always pass.
59    fn validate_path(path: &str) -> Result<()> {
60        if path == ":memory:" || (path.starts_with("file:") && path.contains("mode=memory")) {
61            return Ok(());
62        }
63        let parent = std::path::Path::new(path).parent();
64        if let Some(parent) = parent {
65            if !parent.as_os_str().is_empty() && !parent.exists() {
66                return Err(GraphError::Storage(format!(
67                    "cannot open database at '{path}': directory '{}' does not exist",
68                    parent.display()
69                )));
70            }
71        }
72        Ok(())
73    }
74
75    async fn migrate(&self) -> Result<()> {
76        sqlx::query(
77            r#"
78            CREATE TABLE IF NOT EXISTS commits (
79                id TEXT PRIMARY KEY,
80                parent_ids TEXT NOT NULL,
81                author TEXT NOT NULL,
82                delta TEXT NOT NULL,
83                metadata TEXT NOT NULL
84            );
85            "#,
86        )
87        .execute(&self.pool)
88        .await
89        .map_err(|e| GraphError::Storage(e.to_string()))?;
90
91        sqlx::query(
92            r#"
93            CREATE TABLE IF NOT EXISTS edges (
94                parent_id TEXT NOT NULL,
95                child_id TEXT NOT NULL,
96                PRIMARY KEY (parent_id, child_id)
97            );
98            "#,
99        )
100        .execute(&self.pool)
101        .await
102        .map_err(|e| GraphError::Storage(e.to_string()))?;
103
104        sqlx::query("CREATE INDEX IF NOT EXISTS edges_child_idx ON edges(child_id);")
105            .execute(&self.pool)
106            .await
107            .map_err(|e| GraphError::Storage(e.to_string()))?;
108
109        sqlx::query(
110            r#"
111            CREATE TABLE IF NOT EXISTS branches (
112                name TEXT PRIMARY KEY,
113                commit_id TEXT NOT NULL
114            );
115            "#,
116        )
117        .execute(&self.pool)
118        .await
119        .map_err(|e| GraphError::Storage(e.to_string()))?;
120
121        Ok(())
122    }
123
124    fn parent_ids_to_json(ids: &[CommitId]) -> String {
125        let hexes: Vec<String> = ids.iter().map(|i| i.to_hex()).collect();
126        serde_json::to_string(&hexes).expect("hex string vec always serializes")
127    }
128
129    fn parent_ids_from_json(s: &str) -> Result<Vec<CommitId>> {
130        let hexes: Vec<String> = serde_json::from_str(s)?;
131        hexes.into_iter().map(|h| CommitId::from_str(&h)).collect()
132    }
133
134    fn row_to_commit(
135        id: String,
136        parent_ids: String,
137        author: String,
138        delta: String,
139        metadata: String,
140    ) -> Result<Commit> {
141        Ok(Commit {
142            id: CommitId::from_str(&id)?,
143            parent_ids: Self::parent_ids_from_json(&parent_ids)?,
144            author: serde_json::from_str(&author)?,
145            delta: serde_json::from_str(&delta)?,
146            metadata: serde_json::from_str(&metadata)?,
147        })
148    }
149}
150
151#[async_trait]
152impl CommitStore for SqliteStore {
153    async fn put(&self, commit: Commit) -> Result<CommitId> {
154        let mut tx = self
155            .pool
156            .begin()
157            .await
158            .map_err(|e| GraphError::Storage(e.to_string()))?;
159
160        let existing = sqlx::query("SELECT id FROM commits WHERE id = ?")
161            .bind(commit.id.to_hex())
162            .fetch_optional(&mut *tx)
163            .await
164            .map_err(|e| GraphError::Storage(e.to_string()))?;
165        if existing.is_some() {
166            tx.commit()
167                .await
168                .map_err(|e| GraphError::Storage(e.to_string()))?;
169            return Ok(commit.id);
170        }
171
172        for parent in &commit.parent_ids {
173            let found = sqlx::query("SELECT id FROM commits WHERE id = ?")
174                .bind(parent.to_hex())
175                .fetch_optional(&mut *tx)
176                .await
177                .map_err(|e| GraphError::Storage(e.to_string()))?;
178            if found.is_none() {
179                return Err(GraphError::ParentNotFound(*parent));
180            }
181        }
182
183        let author_json = serde_json::to_string(&commit.author)?;
184        let delta_json = serde_json::to_string(&commit.delta)?;
185        let metadata_json = serde_json::to_string(&commit.metadata)?;
186        let parent_ids_json = Self::parent_ids_to_json(&commit.parent_ids);
187
188        sqlx::query(
189            "INSERT INTO commits (id, parent_ids, author, delta, metadata) VALUES (?, ?, ?, ?, ?)",
190        )
191        .bind(commit.id.to_hex())
192        .bind(&parent_ids_json)
193        .bind(&author_json)
194        .bind(&delta_json)
195        .bind(&metadata_json)
196        .execute(&mut *tx)
197        .await
198        .map_err(|e| GraphError::Storage(e.to_string()))?;
199
200        for parent in &commit.parent_ids {
201            sqlx::query("INSERT OR IGNORE INTO edges (parent_id, child_id) VALUES (?, ?)")
202                .bind(parent.to_hex())
203                .bind(commit.id.to_hex())
204                .execute(&mut *tx)
205                .await
206                .map_err(|e| GraphError::Storage(e.to_string()))?;
207        }
208
209        tx.commit()
210            .await
211            .map_err(|e| GraphError::Storage(e.to_string()))?;
212        Ok(commit.id)
213    }
214
215    async fn get(&self, id: &CommitId) -> Result<Option<Commit>> {
216        let row =
217            sqlx::query("SELECT id, parent_ids, author, delta, metadata FROM commits WHERE id = ?")
218                .bind(id.to_hex())
219                .fetch_optional(&self.pool)
220                .await
221                .map_err(|e| GraphError::Storage(e.to_string()))?;
222
223        match row {
224            None => Ok(None),
225            Some(row) => Ok(Some(Self::row_to_commit(
226                row.get("id"),
227                row.get("parent_ids"),
228                row.get("author"),
229                row.get("delta"),
230                row.get("metadata"),
231            )?)),
232        }
233    }
234
235    async fn contains(&self, id: &CommitId) -> Result<bool> {
236        let row = sqlx::query("SELECT 1 FROM commits WHERE id = ?")
237            .bind(id.to_hex())
238            .fetch_optional(&self.pool)
239            .await
240            .map_err(|e| GraphError::Storage(e.to_string()))?;
241        Ok(row.is_some())
242    }
243
244    async fn children(&self, id: &CommitId) -> Result<Vec<CommitId>> {
245        let rows = sqlx::query("SELECT child_id FROM edges WHERE parent_id = ?")
246            .bind(id.to_hex())
247            .fetch_all(&self.pool)
248            .await
249            .map_err(|e| GraphError::Storage(e.to_string()))?;
250        rows.into_iter()
251            .map(|r| CommitId::from_str(r.get::<String, _>("child_id").as_str()))
252            .collect()
253    }
254
255    async fn len(&self) -> Result<usize> {
256        let row = sqlx::query("SELECT COUNT(*) as c FROM commits")
257            .fetch_one(&self.pool)
258            .await
259            .map_err(|e| GraphError::Storage(e.to_string()))?;
260        let c: i64 = row.get("c");
261        Ok(c as usize)
262    }
263
264    async fn all_ids(&self) -> Result<Vec<CommitId>> {
265        let rows = sqlx::query("SELECT id FROM commits")
266            .fetch_all(&self.pool)
267            .await
268            .map_err(|e| GraphError::Storage(e.to_string()))?;
269        rows.into_iter()
270            .map(|r| CommitId::from_str(r.get::<String, _>("id").as_str()))
271            .collect()
272    }
273
274    async fn remove_many(&self, ids: &[CommitId]) -> Result<()> {
275        let mut tx = self
276            .pool
277            .begin()
278            .await
279            .map_err(|e| GraphError::Storage(e.to_string()))?;
280        for id in ids {
281            sqlx::query("DELETE FROM edges WHERE parent_id = ? OR child_id = ?")
282                .bind(id.to_hex())
283                .bind(id.to_hex())
284                .execute(&mut *tx)
285                .await
286                .map_err(|e| GraphError::Storage(e.to_string()))?;
287            sqlx::query("DELETE FROM commits WHERE id = ?")
288                .bind(id.to_hex())
289                .execute(&mut *tx)
290                .await
291                .map_err(|e| GraphError::Storage(e.to_string()))?;
292        }
293        tx.commit()
294            .await
295            .map_err(|e| GraphError::Storage(e.to_string()))?;
296        Ok(())
297    }
298}
299
300#[async_trait]
301impl RefStore for SqliteStore {
302    async fn get_branch(&self, name: &str) -> Result<Option<CommitId>> {
303        let row = sqlx::query("SELECT commit_id FROM branches WHERE name = ?")
304            .bind(name)
305            .fetch_optional(&self.pool)
306            .await
307            .map_err(|e| GraphError::Storage(e.to_string()))?;
308        match row {
309            None => Ok(None),
310            Some(row) => Ok(Some(CommitId::from_str(
311                row.get::<String, _>("commit_id").as_str(),
312            )?)),
313        }
314    }
315
316    async fn set_branch(&self, name: &str, commit_id: CommitId) -> Result<()> {
317        sqlx::query(
318            "INSERT INTO branches (name, commit_id) VALUES (?, ?)
319             ON CONFLICT(name) DO UPDATE SET commit_id = excluded.commit_id",
320        )
321        .bind(name)
322        .bind(commit_id.to_hex())
323        .execute(&self.pool)
324        .await
325        .map_err(|e| GraphError::Storage(e.to_string()))?;
326        Ok(())
327    }
328
329    async fn delete_branch(&self, name: &str) -> Result<()> {
330        let result = sqlx::query("DELETE FROM branches WHERE name = ?")
331            .bind(name)
332            .execute(&self.pool)
333            .await
334            .map_err(|e| GraphError::Storage(e.to_string()))?;
335        if result.rows_affected() == 0 {
336            return Err(GraphError::BranchNotFound(name.to_string()));
337        }
338        Ok(())
339    }
340
341    async fn list_branches(&self) -> Result<Vec<(String, CommitId)>> {
342        let rows = sqlx::query("SELECT name, commit_id FROM branches")
343            .fetch_all(&self.pool)
344            .await
345            .map_err(|e| GraphError::Storage(e.to_string()))?;
346        rows.into_iter()
347            .map(|r| {
348                let id = CommitId::from_str(r.get::<String, _>("commit_id").as_str())?;
349                Ok((r.get::<String, _>("name"), id))
350            })
351            .collect()
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use crate::commit::{Author, Delta, Metadata};
359    use chrono::Utc;
360
361    fn root() -> Commit {
362        Commit::new(
363            vec![],
364            Author::System,
365            Delta::Message {
366                content: "root".into(),
367            },
368            Metadata::new(Utc::now()),
369        )
370    }
371
372    #[tokio::test]
373    async fn sqlite_store_persists_and_retrieves_a_commit() {
374        let store = SqliteStore::open_in_memory().await.unwrap();
375        let r = root();
376        let id = store.put(r.clone()).await.unwrap();
377        let fetched = store.get(&id).await.unwrap().unwrap();
378        assert_eq!(fetched, r);
379    }
380
381    #[tokio::test]
382    async fn sqlite_store_rejects_commit_with_missing_parent() {
383        let store = SqliteStore::open_in_memory().await.unwrap();
384        let orphan = Commit::new(
385            vec![CommitId::from_bytes([7; 32])],
386            Author::User,
387            Delta::Message {
388                content: "x".into(),
389            },
390            Metadata::new(Utc::now()),
391        );
392        let err = store.put(orphan).await.unwrap_err();
393        assert!(matches!(err, GraphError::ParentNotFound(_)));
394    }
395
396    #[tokio::test]
397    async fn sqlite_store_is_idempotent_on_duplicate_put() {
398        let store = SqliteStore::open_in_memory().await.unwrap();
399        let r = root();
400        store.put(r.clone()).await.unwrap();
401        store.put(r.clone()).await.unwrap();
402        assert_eq!(store.len().await.unwrap(), 1);
403    }
404
405    #[tokio::test]
406    async fn sqlite_store_indexes_children_for_traversal() {
407        let store = SqliteStore::open_in_memory().await.unwrap();
408        let r = root();
409        store.put(r.clone()).await.unwrap();
410        let child = Commit::new(
411            vec![r.id],
412            Author::User,
413            Delta::Message {
414                content: "hi".into(),
415            },
416            Metadata::new(Utc::now()),
417        );
418        store.put(child.clone()).await.unwrap();
419        let kids = store.children(&r.id).await.unwrap();
420        assert_eq!(kids, vec![child.id]);
421    }
422
423    #[tokio::test]
424    async fn sqlite_ref_store_round_trips_branch_pointer() {
425        let store = SqliteStore::open_in_memory().await.unwrap();
426        let r = root();
427        store.put(r.clone()).await.unwrap();
428        store.set_branch("main", r.id).await.unwrap();
429        assert_eq!(store.get_branch("main").await.unwrap(), Some(r.id));
430    }
431
432    #[tokio::test]
433    async fn sqlite_ref_store_delete_of_missing_branch_fails() {
434        let store = SqliteStore::open_in_memory().await.unwrap();
435        let err = store.delete_branch("nope").await.unwrap_err();
436        assert!(matches!(err, GraphError::BranchNotFound(_)));
437    }
438
439    #[tokio::test]
440    async fn opening_a_store_in_a_nonexistent_directory_fails_with_a_clear_message() {
441        let err = SqliteStore::open("/no/such/directory/at/all/store.db")
442            .await
443            .unwrap_err();
444        match err {
445            GraphError::Storage(msg) => {
446                assert!(msg.contains("does not exist"), "message was: {msg}");
447                assert!(
448                    msg.contains("/no/such/directory/at/all"),
449                    "message was: {msg}"
450                );
451            }
452            other => panic!("expected Storage error, got {other:?}"),
453        }
454    }
455
456    #[tokio::test]
457    async fn opening_an_in_memory_store_bypasses_path_validation() {
458        // Must not be rejected as "directory does not exist" just because
459        // ":memory:" isn't a real filesystem path.
460        SqliteStore::open_in_memory().await.unwrap();
461    }
462
463    #[tokio::test]
464    async fn opening_a_store_at_an_existing_directory_succeeds() {
465        let dir = tempfile::tempdir().unwrap();
466        let path = dir.path().join("store.db").to_string_lossy().to_string();
467        SqliteStore::open(&path).await.unwrap();
468    }
469}