Commit f8003dd5
f8003dd54305Merged
Scott Nixon <[email protected]> ยท 9 months ago ยท 2 files ยท +1 added ยท ~1 modified
Description
Add SQLite database layer for multi-project workspace
Implements attractor-86n - Create db.rs with SQLite pool initialization and schema.
Changes:
- Created crates/attractor-web/src/server/db.rs with:
- init_db() for SQLite pool initialization at ~/.attractor/web.db
- Schema creation for projects and documents tables
- CRUD functions: upsert_project, list_open_projects, close_project
- Document persistence: upsert_document, get_documents
- Project and CachedDoc data structures
- Updated crates/attractor-web/src/server/mod.rs to add db module declaration
This is the foundational persistence layer for the multi-project workspace, enabling project data and document content to persist across browser/server restarts.
Details
- Commit
- f8003dd54305
- Parent
- 902ccf52db5a
crates/attractor-web/src/server/db.rsaddedView file
1+
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};2+
use std::path::PathBuf;3+
4+
/// Project stored in the database5+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]6+
pub struct Project {7+
pub id: i64,8+
pub folder_path: String,9+
pub name: String,10+
}11+
12+
/// Cached document content13+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]14+
pub struct CachedDoc {15+
pub doc_type: String,16+
pub content: String,17+
}18+
19+
/// Initialize the SQLite database and return a connection pool.20+
///21+
/// Creates `~/.attractor/web.db` if it doesn't exist, along with the directory.22+
/// Runs schema creation (idempotent).23+
pub async fn init_db() -> Result<SqlitePool, sqlx::Error> {24+
// Determine database path: ~/.attractor/web.db25+
let home_dir = std::env::var("HOME")26+
.expect("HOME environment variable not set");27+
let attractor_dir = PathBuf::from(home_dir).join(".attractor");28+
29+
// Create directory if it doesn't exist30+
std::fs::create_dir_all(&attractor_dir)31+
.expect("Failed to create ~/.attractor directory");32+
33+
let db_path = attractor_dir.join("web.db");34+
let db_url = format!("sqlite:{}", db_path.display());35+
36+
// Create connection pool37+
let pool = SqlitePoolOptions::new()38+
.max_connections(5)39+
.connect(&db_url)40+
.await?;41+
42+
// Create tables (idempotent)43+
sqlx::query(44+
r#"45+
CREATE TABLE IF NOT EXISTS projects (46+
id INTEGER PRIMARY KEY AUTOINCREMENT,47+
folder_path TEXT NOT NULL UNIQUE,48+
name TEXT NOT NULL,49+
is_open INTEGER NOT NULL DEFAULT 1,50+
last_used TEXT NOT NULL DEFAULT (datetime('now')),51+
created_at TEXT NOT NULL DEFAULT (datetime('now'))52+
)53+
"#,54+
)55+
.execute(&pool)56+
.await?;57+
58+
sqlx::query(59+
r#"60+
CREATE TABLE IF NOT EXISTS documents (61+
project_id INTEGER NOT NULL REFERENCES projects(id),62+
doc_type TEXT NOT NULL,63+
content TEXT NOT NULL DEFAULT '',64+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),65+
PRIMARY KEY (project_id, doc_type)66+
)67+
"#,68+
)69+
.execute(&pool)70+
.await?;71+
72+
Ok(pool)73+
}74+
75+
/// Insert or reopen a project. Returns the project record.76+
///77+
/// If the project doesn't exist, it's created with the folder basename as the name.78+
/// If it exists, `is_open` is set to 1 and `last_used` is updated.79+
pub async fn upsert_project(80+
pool: &SqlitePool,81+
folder_path: &str,82+
) -> Result<Project, sqlx::Error> {83+
// Extract project name from folder path84+
let name = PathBuf::from(folder_path)85+
.file_name()86+
.and_then(|n| n.to_str())87+
.unwrap_or("unknown")88+
.to_string();89+
90+
// Insert if not exists91+
sqlx::query(92+
r#"93+
INSERT OR IGNORE INTO projects (folder_path, name)94+
VALUES (?, ?)95+
"#,96+
)97+
.bind(folder_path)98+
.bind(&name)99+
.execute(pool)100+
.await?;101+
102+
// Update last_used and set is_open=1103+
sqlx::query(104+
r#"105+
UPDATE projects106+
SET is_open = 1, last_used = datetime('now')107+
WHERE folder_path = ?108+
"#,109+
)110+
.bind(folder_path)111+
.execute(pool)112+
.await?;113+
114+
// Fetch and return the project115+
let project = sqlx::query_as::<_, (i64, String, String)>(116+
r#"117+
SELECT id, folder_path, name118+
FROM projects119+
WHERE folder_path = ?120+
"#,121+
)122+
.bind(folder_path)123+
.fetch_one(pool)124+
.await?;125+
126+
Ok(Project {127+
id: project.0,128+
folder_path: project.1,129+
name: project.2,130+
})131+
}132+
133+
/// List all open projects, ordered by most recently used first.134+
pub async fn list_open_projects(pool: &SqlitePool) -> Result<Vec<Project>, sqlx::Error> {135+
let rows = sqlx::query_as::<_, (i64, String, String)>(136+
r#"137+
SELECT id, folder_path, name138+
FROM projects139+
WHERE is_open = 1140+
ORDER BY last_used DESC141+
"#,142+
)143+
.fetch_all(pool)144+
.await?;145+
146+
Ok(rows147+
.into_iter()148+
.map(|(id, folder_path, name)| Project {149+
id,150+
folder_path,151+
name,152+
})153+
.collect())154+
}155+
156+
/// Close a project (set is_open=0). Does not delete.157+
pub async fn close_project(pool: &SqlitePool, project_id: i64) -> Result<(), sqlx::Error> {158+
sqlx::query(159+
r#"160+
UPDATE projects161+
SET is_open = 0162+
WHERE id = ?163+
"#,164+
)165+
.bind(project_id)166+
.execute(pool)167+
.await?;168+
169+
Ok(())170+
}171+
172+
/// Store or update document content for a project.173+
pub async fn upsert_document(174+
pool: &SqlitePool,175+
project_id: i64,176+
doc_type: &str,177+
content: &str,178+
) -> Result<(), sqlx::Error> {179+
sqlx::query(180+
r#"181+
INSERT OR REPLACE INTO documents (project_id, doc_type, content, updated_at)182+
VALUES (?, ?, ?, datetime('now'))183+
"#,184+
)185+
.bind(project_id)186+
.bind(doc_type)187+
.bind(content)188+
.execute(pool)189+
.await?;190+
191+
Ok(())192+
}193+
194+
/// Get all cached documents for a project.195+
pub async fn get_documents(196+
pool: &SqlitePool,197+
project_id: i64,198+
) -> Result<Vec<CachedDoc>, sqlx::Error> {199+
let rows = sqlx::query_as::<_, (String, String)>(200+
r#"201+
SELECT doc_type, content202+
FROM documents203+
WHERE project_id = ?204+
"#,205+
)206+
.bind(project_id)207+
.fetch_all(pool)208+
.await?;209+
210+
Ok(rows211+
.into_iter()212+
.map(|(doc_type, content)| CachedDoc { doc_type, content })213+
.collect())214+
}crates/attractor-web/src/server/mod.rsmodifiedView file
Loading diffโฆ