|
| 1 | +//! Read store over the `project` **projection table** — the second entity (after sessions) to prove |
| 2 | +//! the `AppContext → Store → projection table` pattern generalizes. Mirrors the TS `project` schema |
| 3 | +//! (`packages/core/src/project/sql.ts`): the `icon_*` columns fold into one `icon` object and the |
| 4 | +//! `sandboxes`/`commands` columns are JSON. TS owns the schema; reads here are a plain `SELECT`. |
| 5 | +
|
| 6 | +use std::sync::Mutex; |
| 7 | + |
| 8 | +use async_trait::async_trait; |
| 9 | +use serde_json::Value; |
| 10 | +use sqlx::sqlite::SqliteRow; |
| 11 | +use sqlx::{Row, SqlitePool}; |
| 12 | + |
| 13 | +use crate::DbError; |
| 14 | + |
| 15 | +/// `project` projection-table DDL (the columns this store reads). For tests / a future Rust-applies |
| 16 | +/// path; TS owns the real (possibly wider) table. |
| 17 | +pub const PROJECT_DDL: &str = "\ |
| 18 | +CREATE TABLE IF NOT EXISTS project (\ |
| 19 | + id text PRIMARY KEY,\ |
| 20 | + worktree text NOT NULL,\ |
| 21 | + vcs text,\ |
| 22 | + name text,\ |
| 23 | + icon_url text,\ |
| 24 | + icon_url_override text,\ |
| 25 | + icon_color text,\ |
| 26 | + time_created integer NOT NULL,\ |
| 27 | + time_updated integer NOT NULL,\ |
| 28 | + time_initialized integer,\ |
| 29 | + sandboxes text NOT NULL DEFAULT '[]',\ |
| 30 | + commands text\ |
| 31 | +);"; |
| 32 | + |
| 33 | +/// A row of the `project` projection table. |
| 34 | +#[derive(Debug, Clone, PartialEq)] |
| 35 | +pub struct ProjectRecord { |
| 36 | + /// Project id. |
| 37 | + pub id: String, |
| 38 | + /// Absolute worktree path. |
| 39 | + pub worktree: String, |
| 40 | + /// Version-control system (e.g. `"git"`), if known. |
| 41 | + pub vcs: Option<String>, |
| 42 | + /// Display name, if set. |
| 43 | + pub name: Option<String>, |
| 44 | + /// Icon URL, if set. |
| 45 | + pub icon_url: Option<String>, |
| 46 | + /// Icon URL override, if set. |
| 47 | + pub icon_url_override: Option<String>, |
| 48 | + /// Icon color, if set. |
| 49 | + pub icon_color: Option<String>, |
| 50 | + /// Creation time (ms). |
| 51 | + pub time_created: i64, |
| 52 | + /// Last-updated time (ms). |
| 53 | + pub time_updated: i64, |
| 54 | + /// Initialization time (ms), if initialized. |
| 55 | + pub time_initialized: Option<i64>, |
| 56 | + /// Sandbox worktree paths (JSON array column). |
| 57 | + pub sandboxes: Vec<String>, |
| 58 | + /// Project commands JSON (`{ start? }`), if set. |
| 59 | + pub commands: Option<Value>, |
| 60 | +} |
| 61 | + |
| 62 | +const PROJECT_COLS: &str = "id, worktree, vcs, name, icon_url, icon_url_override, icon_color, \ |
| 63 | + time_created, time_updated, time_initialized, sandboxes, commands"; |
| 64 | + |
| 65 | +fn record_from_row(row: &SqliteRow) -> Result<ProjectRecord, DbError> { |
| 66 | + let sandboxes: String = row.try_get("sandboxes")?; |
| 67 | + let sandboxes: Vec<String> = serde_json::from_str(&sandboxes)?; |
| 68 | + let commands: Option<String> = row.try_get("commands")?; |
| 69 | + let commands = commands.map(|s| serde_json::from_str(&s)).transpose()?; |
| 70 | + Ok(ProjectRecord { |
| 71 | + id: row.try_get("id")?, |
| 72 | + worktree: row.try_get("worktree")?, |
| 73 | + vcs: row.try_get("vcs")?, |
| 74 | + name: row.try_get("name")?, |
| 75 | + icon_url: row.try_get("icon_url")?, |
| 76 | + icon_url_override: row.try_get("icon_url_override")?, |
| 77 | + icon_color: row.try_get("icon_color")?, |
| 78 | + time_created: row.try_get("time_created")?, |
| 79 | + time_updated: row.try_get("time_updated")?, |
| 80 | + time_initialized: row.try_get("time_initialized")?, |
| 81 | + sandboxes, |
| 82 | + commands, |
| 83 | + }) |
| 84 | +} |
| 85 | + |
| 86 | +/// Read-only store over the `project` projection table. |
| 87 | +#[async_trait] |
| 88 | +pub trait ProjectStore: Send + Sync { |
| 89 | + /// List all projects, most-recently-created first. |
| 90 | + async fn list(&self) -> Result<Vec<ProjectRecord>, DbError>; |
| 91 | +} |
| 92 | + |
| 93 | +/// SQLite-backed [`ProjectStore`] over the shared pool. |
| 94 | +pub struct SqlxProjectStore { |
| 95 | + pool: SqlitePool, |
| 96 | +} |
| 97 | + |
| 98 | +impl SqlxProjectStore { |
| 99 | + /// Wrap the shared pool. |
| 100 | + pub fn new(pool: SqlitePool) -> Self { |
| 101 | + Self { pool } |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +#[async_trait] |
| 106 | +impl ProjectStore for SqlxProjectStore { |
| 107 | + async fn list(&self) -> Result<Vec<ProjectRecord>, DbError> { |
| 108 | + let rows = sqlx::query(&format!( |
| 109 | + "SELECT {PROJECT_COLS} FROM project ORDER BY time_created DESC, id" |
| 110 | + )) |
| 111 | + .fetch_all(&self.pool) |
| 112 | + .await?; |
| 113 | + rows.iter().map(record_from_row).collect() |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +/// In-memory [`ProjectStore`] — test double / the backing for `AppServices::default()`. |
| 118 | +#[derive(Default)] |
| 119 | +pub struct MemoryProjectStore { |
| 120 | + rows: Mutex<Vec<ProjectRecord>>, |
| 121 | +} |
| 122 | + |
| 123 | +impl MemoryProjectStore { |
| 124 | + /// Create an empty store. |
| 125 | + pub fn new() -> Self { |
| 126 | + Self::default() |
| 127 | + } |
| 128 | + |
| 129 | + /// Insert a project record. |
| 130 | + pub fn insert(&self, record: ProjectRecord) { |
| 131 | + self.rows |
| 132 | + .lock() |
| 133 | + .expect("project store mutex poisoned") |
| 134 | + .push(record); |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +#[async_trait] |
| 139 | +impl ProjectStore for MemoryProjectStore { |
| 140 | + async fn list(&self) -> Result<Vec<ProjectRecord>, DbError> { |
| 141 | + let mut rows = self |
| 142 | + .rows |
| 143 | + .lock() |
| 144 | + .expect("project store mutex poisoned") |
| 145 | + .clone(); |
| 146 | + // Most-recent first, id as a stable tiebreaker (matches the SQL ordering). |
| 147 | + rows.sort_by(|a, b| (b.time_created, b.id.as_str()).cmp(&(a.time_created, a.id.as_str()))); |
| 148 | + Ok(rows) |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +#[cfg(test)] |
| 153 | +mod tests { |
| 154 | + use super::*; |
| 155 | + use crate::Database; |
| 156 | + use serde_json::json; |
| 157 | + |
| 158 | + #[tokio::test] |
| 159 | + async fn sqlx_project_store_reads_ts_written_rows() { |
| 160 | + let dir = tempfile::tempdir().unwrap(); |
| 161 | + let db = Database::connect(dir.path().join("projects.db")) |
| 162 | + .await |
| 163 | + .unwrap(); |
| 164 | + sqlx::query(PROJECT_DDL).execute(db.pool()).await.unwrap(); |
| 165 | + // Two projects (newest by time_created should sort first). |
| 166 | + sqlx::query( |
| 167 | + "INSERT INTO project (id, worktree, vcs, name, icon_url, time_created, time_updated, \ |
| 168 | + time_initialized, sandboxes, commands) \ |
| 169 | + VALUES ('prj_a', '/a', 'git', 'Alpha', 'http://i', 100, 100, 150, \ |
| 170 | + '[\"/a/sb\"]', '{\"start\":\"bun dev\"}')", |
| 171 | + ) |
| 172 | + .execute(db.pool()) |
| 173 | + .await |
| 174 | + .unwrap(); |
| 175 | + sqlx::query( |
| 176 | + "INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) \ |
| 177 | + VALUES ('prj_b', '/b', 300, 300, '[]')", |
| 178 | + ) |
| 179 | + .execute(db.pool()) |
| 180 | + .await |
| 181 | + .unwrap(); |
| 182 | + |
| 183 | + let store = SqlxProjectStore::new(db.pool().clone()); |
| 184 | + let projects = store.list().await.unwrap(); |
| 185 | + assert_eq!(projects.len(), 2); |
| 186 | + // Newest first. |
| 187 | + assert_eq!(projects[0].id, "prj_b"); |
| 188 | + assert_eq!(projects[1].id, "prj_a"); |
| 189 | + let a = &projects[1]; |
| 190 | + assert_eq!(a.worktree, "/a"); |
| 191 | + assert_eq!(a.vcs.as_deref(), Some("git")); |
| 192 | + assert_eq!(a.icon_url.as_deref(), Some("http://i")); |
| 193 | + assert_eq!(a.time_initialized, Some(150)); |
| 194 | + assert_eq!(a.sandboxes, vec!["/a/sb".to_string()]); |
| 195 | + assert_eq!(a.commands, Some(json!({ "start": "bun dev" }))); |
| 196 | + // prj_b: minimal row. |
| 197 | + assert_eq!(projects[0].sandboxes, Vec::<String>::new()); |
| 198 | + assert_eq!(projects[0].commands, None); |
| 199 | + assert_eq!(projects[0].vcs, None); |
| 200 | + } |
| 201 | + |
| 202 | + #[tokio::test] |
| 203 | + async fn memory_project_store_lists_newest_first() { |
| 204 | + let store = MemoryProjectStore::new(); |
| 205 | + let rec = |id: &str, created: i64| ProjectRecord { |
| 206 | + id: id.into(), |
| 207 | + worktree: "/w".into(), |
| 208 | + vcs: None, |
| 209 | + name: None, |
| 210 | + icon_url: None, |
| 211 | + icon_url_override: None, |
| 212 | + icon_color: None, |
| 213 | + time_created: created, |
| 214 | + time_updated: created, |
| 215 | + time_initialized: None, |
| 216 | + sandboxes: vec![], |
| 217 | + commands: None, |
| 218 | + }; |
| 219 | + store.insert(rec("prj_old", 100)); |
| 220 | + store.insert(rec("prj_new", 200)); |
| 221 | + let ids: Vec<String> = store |
| 222 | + .list() |
| 223 | + .await |
| 224 | + .unwrap() |
| 225 | + .into_iter() |
| 226 | + .map(|p| p.id) |
| 227 | + .collect(); |
| 228 | + assert_eq!(ids, ["prj_new", "prj_old"]); |
| 229 | + } |
| 230 | +} |
0 commit comments