kanban_persistence_sqlite/
lib.rs1pub mod backend_factory;
2pub mod sqlite_backend;
3pub mod sqlite_store;
4
5pub use backend_factory::SqliteBackendFactory;
6pub use sqlite_backend::SqliteBackend;
7
8pub use sqlite_store::SqliteStore;
9pub use sqlite_store::SUPPORTED_SCHEMA_VERSION;
10
11use kanban_domain::KanbanError;
12use kanban_persistence::{PersistenceError, PersistenceStore, StoreFactory};
13use std::sync::Arc;
14
15#[cfg(feature = "test-helpers")]
29pub async fn write_test_metadata_with_schema_version(
30 path: &std::path::Path,
31 version: u32,
32) -> Result<(), PersistenceError> {
33 use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
34 let pool = SqlitePoolOptions::new()
35 .max_connections(1)
36 .connect_with(
37 SqliteConnectOptions::new()
38 .filename(path)
39 .create_if_missing(true),
40 )
41 .await
42 .map_err(|e| PersistenceError::Database(e.to_string()))?;
43 sqlx::raw_sql(&format!(
44 "CREATE TABLE IF NOT EXISTS metadata (
45 id INTEGER PRIMARY KEY CHECK (id = 1),
46 instance_id TEXT NOT NULL,
47 saved_at TEXT NOT NULL,
48 schema_version INTEGER NOT NULL DEFAULT {SUPPORTED_SCHEMA_VERSION},
49 writer_version TEXT,
50 writer_commit TEXT
51 );
52 INSERT OR REPLACE INTO metadata (id, instance_id, saved_at, schema_version)
53 VALUES (1, '550e8400-e29b-41d4-a716-446655440000', '2030-01-01T00:00:00Z', {version});"
54 ))
55 .execute(&pool)
56 .await
57 .map_err(|e| PersistenceError::Database(e.to_string()))?;
58 pool.close().await;
59 Ok(())
60}
61
62#[cfg(feature = "test-helpers")]
70pub async fn read_test_schema_version(
71 path: &std::path::Path,
72) -> Result<Option<u32>, PersistenceError> {
73 use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
74 let pool = SqlitePoolOptions::new()
75 .max_connections(1)
76 .connect_with(SqliteConnectOptions::new().filename(path))
77 .await
78 .map_err(|e| PersistenceError::Database(e.to_string()))?;
79 let version: Option<u32> =
80 sqlx::query_scalar("SELECT schema_version FROM metadata WHERE id = 1")
81 .fetch_optional(&pool)
82 .await
83 .map_err(|e| PersistenceError::Database(e.to_string()))?;
84 pool.close().await;
85 Ok(version)
86}
87
88pub struct SqliteStoreFactory;
89
90impl StoreFactory for SqliteStoreFactory {
91 fn name(&self) -> &str {
92 "sqlite"
93 }
94
95 fn matches_content(&self, header: &[u8]) -> bool {
96 header.starts_with(b"SQLite format 3\0")
97 }
98
99 fn create(
100 &self,
101 locator: &str,
102 ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, PersistenceError> {
103 let handle = tokio::runtime::Handle::current();
104 if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::CurrentThread {
105 return Err(PersistenceError::Database(
106 "SqliteStoreFactory::create requires a multi-thread Tokio runtime; \
107 block_in_place is unavailable on a current_thread runtime. \
108 Use #[tokio::test(flavor = \"multi_thread\")] in tests."
109 .to_string(),
110 ));
111 }
112 let store = tokio::task::block_in_place(|| handle.block_on(SqliteStore::open(locator)))
113 .map_err(|e| match e {
119 KanbanError::UnsupportedFutureVersion {
120 file_version,
121 binary_max,
122 } => PersistenceError::UnsupportedFutureVersion {
123 file_version,
124 binary_max,
125 },
126 other => PersistenceError::Database(other.to_string()),
127 })?;
128 Ok(Arc::new(store))
129 }
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135 use kanban_persistence::StoreFactory;
136
137 #[test]
138 fn test_sqlite_factory_matches_content_sqlite_magic_bytes() {
139 let header = b"SQLite format 3\0extra";
140 assert!(SqliteStoreFactory.matches_content(header));
141 }
142
143 #[test]
144 fn test_sqlite_factory_matches_content_rejects_json() {
145 let header = b"{\"boards\": []}";
146 assert!(!SqliteStoreFactory.matches_content(header));
147 }
148
149 #[test]
150 fn test_sqlite_factory_matches_content_rejects_empty() {
151 assert!(!SqliteStoreFactory.matches_content(b""));
152 }
153
154 #[test]
155 fn test_sqlite_factory_name_is_sqlite() {
156 assert_eq!(SqliteStoreFactory.name(), "sqlite");
157 }
158
159 #[tokio::test(flavor = "multi_thread")]
160 async fn test_sqlite_factory_create_returns_persistence_store() {
161 let dir = tempfile::tempdir().unwrap();
162 let path = dir.path().join("test.db");
163 let store = SqliteStoreFactory.create(path.to_str().unwrap()).unwrap();
164 assert!(store.exists().await);
165 }
166}