use crate::db; use crate::models::Space; use uuid::Uuid; // ── 空间管理 ──────────────────────────────────────────────── #[tauri::command] pub fn get_spaces() -> Result, String> { let conn = db::pool().get().map_err(|e| e.to_string())?; let mut stmt = conn .prepare("SELECT id, name, is_current, created_at FROM spaces ORDER BY created_at ASC") .map_err(|e| e.to_string())?; let rows = stmt .query_map([], Space::from_row) .map_err(|e| e.to_string())?; rows.map(|r| r.map_err(|e| e.to_string())).collect() } #[tauri::command] pub fn create_space(name: String) -> Result { let conn = db::pool().get().map_err(|e| e.to_string())?; let id = Uuid::new_v4().to_string(); conn.execute_batch("BEGIN").map_err(|e| e.to_string())?; let result = (|| -> Result<(), String> { conn.execute("UPDATE spaces SET is_current = 0", []) .map_err(|e| e.to_string())?; // local_root 保留列但填空字符串(历史 NOT NULL 约束) conn.execute( "INSERT INTO spaces (id, name, local_root, is_current) VALUES (?1, ?2, '', 1)", rusqlite::params![id, name], ) .map_err(|e| e.to_string())?; Ok(()) })(); if let Err(e) = result { let _ = conn.execute_batch("ROLLBACK"); return Err(e); } conn.execute_batch("COMMIT").map_err(|e| e.to_string())?; let space = conn .query_row( "SELECT id, name, is_current, created_at FROM spaces WHERE id = ?1", rusqlite::params![id], Space::from_row, ) .map_err(|e| e.to_string())?; Ok(space) } #[tauri::command] pub fn update_space(id: String, name: String) -> Result<(), String> { let conn = db::pool().get().map_err(|e| e.to_string())?; conn.execute( "UPDATE spaces SET name = ?1 WHERE id = ?2", rusqlite::params![name, id], ) .map_err(|e| e.to_string())?; Ok(()) } #[tauri::command] pub fn delete_space(id: String) -> Result<(), String> { let conn = db::pool().get().map_err(|e| e.to_string())?; conn.execute("DELETE FROM spaces WHERE id = ?1", rusqlite::params![id]) .map_err(|e| e.to_string())?; Ok(()) } #[tauri::command] pub fn set_current_space(id: String) -> Result<(), String> { let conn = db::pool().get().map_err(|e| e.to_string())?; conn.execute("UPDATE spaces SET is_current = 0", []) .map_err(|e| e.to_string())?; conn.execute( "UPDATE spaces SET is_current = 1 WHERE id = ?1", rusqlite::params![id], ) .map_err(|e| e.to_string())?; Ok(()) }