kanban_persistence_sqlite/sqlite_store/mod.rs
1use std::path::{Path, PathBuf};
2use std::time::Duration;
3
4use kanban_domain::{KanbanError, KanbanResult};
5use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
6use sqlx::{Pool, Sqlite};
7use uuid::Uuid;
8
9mod command_log;
10mod conversions;
11mod data_store;
12mod entities;
13mod graph;
14mod helpers;
15mod init;
16mod lists;
17mod metadata;
18mod persistence_store;
19mod prefix_fk;
20mod prefix_repair;
21mod snapshot;
22mod transaction;
23
24#[cfg(test)]
25mod tests;
26
27pub(crate) const SCHEMA: &str = include_str!("../schema.sql");
28
29/// The highest schema_version this binary understands. Used both to
30/// stamp fresh databases and to refuse files written by a future binary.
31///
32/// Also gates [`SqliteStore::write_pre_migration_backup`] (see `open()`
33/// below): the backup only fires when the on-disk `schema_version` is
34/// LOWER than this constant. Any future irreversible/structural change
35/// added to `init::migrate` or a sibling `migrate_*` function MUST be
36/// paired with bumping this constant, or it will run unbacked-up — the two
37/// are intentionally coupled but not enforced by the type system.
38pub const SUPPORTED_SCHEMA_VERSION: u32 = 13;
39
40/// sqlx-sqlite defaults `busy_timeout` to 5s; set to 10s to give a long
41/// command batch more headroom before a concurrently-flushing writer gives up.
42const BUSY_TIMEOUT: Duration = Duration::from_secs(10);
43
44/// (instance_id, saved_at, writer_version, writer_commit, schema_version).
45/// Tuple shape returned by the metadata-singleton SELECT — extracted to a
46/// type alias to keep clippy's type-complexity lint happy.
47type MetadataRow = (String, String, Option<String>, Option<String>, u32);
48
49/// SQLite-backed persistence store using sqlx connection pool.
50pub struct SqliteStore {
51 pub(crate) pool: Pool<Sqlite>,
52 pub(crate) path: PathBuf,
53 pub(crate) instance_id: Uuid,
54 /// Ambient transaction driven by `SqliteBackend::with_transaction`. When
55 /// `Some`, every `db_conn`/`db_conn_local` call joins it instead of
56 /// opening its own local transaction.
57 pub(crate) active_tx: tokio::sync::Mutex<Option<sqlx::Transaction<'static, Sqlite>>>,
58}
59
60impl SqliteStore {
61 pub async fn open(path: impl AsRef<Path>) -> KanbanResult<Self> {
62 let handle = tokio::runtime::Handle::current();
63 if handle.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread {
64 return Err(KanbanError::Database(
65 "SqliteStore requires a multi-threaded Tokio runtime (e.g. #[tokio::main] or \
66 tokio::runtime::Runtime::new()). The current_thread runtime is not supported \
67 because synchronous DataStore methods need to block on async SQLite I/O."
68 .to_string(),
69 ));
70 }
71
72 let path_buf = path.as_ref().to_path_buf();
73
74 let options = SqliteConnectOptions::new()
75 .filename(&path_buf)
76 .create_if_missing(true)
77 .foreign_keys(true)
78 .busy_timeout(BUSY_TIMEOUT)
79 .pragma("journal_mode", "wal");
80
81 let pool = SqlitePoolOptions::new()
82 .max_connections(2)
83 .connect_with(options)
84 .await
85 .map_err(|e| KanbanError::Database(e.to_string()))?;
86
87 // KAN-522: refuse a future-version DB BEFORE any schema-modifying
88 // step runs. Otherwise the legacy-table drops, the SCHEMA's
89 // CREATE TABLE IF NOT EXISTS for tables the file lacks, and
90 // migrate()'s ALTERs would all mutate a file we're about to refuse.
91 //
92 // Why two round-trips rather than one correlated subquery: SQLite
93 // parses the inner SELECT eagerly at prepare time and errors with
94 // "no such table: metadata" on a fresh DB, even when an outer
95 // `WHERE EXISTS` would short-circuit it at runtime. So we split:
96 // first probe `sqlite_master`, then read `schema_version` only if
97 // the table is there. ~µs overhead, executes once per `open()`.
98 let metadata_table_exists: bool = sqlx::query_scalar(
99 "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='metadata'",
100 )
101 .fetch_one(&pool)
102 .await
103 .map_err(|e| KanbanError::Database(e.to_string()))?;
104 if metadata_table_exists {
105 let pre_migrate_version: Option<u32> =
106 sqlx::query_scalar("SELECT schema_version FROM metadata WHERE id = 1")
107 .fetch_optional(&pool)
108 .await
109 .map_err(|e| KanbanError::Database(e.to_string()))?;
110 if let Some(v) = pre_migrate_version {
111 if v > SUPPORTED_SCHEMA_VERSION {
112 return Err(KanbanError::UnsupportedFutureVersion {
113 file_version: v,
114 binary_max: SUPPORTED_SCHEMA_VERSION,
115 });
116 }
117 // KAN-845: snapshot the DB before any irreversible schema
118 // upgrade so a downgraded binary can restore it. Aborts
119 // open() on failure rather than risk an unbacked-up upgrade.
120 if v < SUPPORTED_SCHEMA_VERSION {
121 Self::write_pre_migration_backup(&pool, &path_buf, v).await?;
122 }
123 }
124 }
125
126 // Drop the legacy command_log table (pre-KAN-405 schema with
127 // columns `idx` / `cmd_json`) before SCHEMA runs, so the new
128 // command_log schema (`batch_index` / `commands_json` / `created_at`)
129 // can be created cleanly. Detected by absence of the new
130 // `batch_index` column on an existing command_log table.
131 Self::drop_legacy_command_log_if_present(&pool).await?;
132
133 // schema 2 -> 3: add archived_cards.board_id (+ backfill) and break the
134 // cards -> columns delete cascade so archived cards survive column
135 // deletion. Must run BEFORE SCHEMA: SCHEMA declares
136 // idx_archived_cards_board_id, which fails against the old-shape table.
137 Self::migrate_v2_to_v3_archived_cards(&pool).await?;
138
139 // schema 4 -> 5: add cards.board_id (+ backfill). Must also run BEFORE
140 // SCHEMA: SCHEMA declares idx_cards_board_id, which fails against the
141 // old-shape table.
142 Self::migrate_v4_to_v5_cards_board_id(&pool).await?;
143 // Same reason, same trap: SCHEMA declares idx_cards_prefix_nocase_number, and
144 // `CREATE INDEX IF NOT EXISTS` on a column the old cards table lacks
145 // fails outright rather than skipping. The column must exist first.
146 Self::migrate_v10_to_v11_card_prefix(&pool).await?;
147
148 sqlx::raw_sql(SCHEMA)
149 .execute(&pool)
150 .await
151 .map_err(|e| KanbanError::Database(e.to_string()))?;
152
153 Self::migrate(&pool).await?;
154
155 let instance_id = Self::load_or_create_instance_id(&pool).await?;
156
157 Ok(Self {
158 pool,
159 path: path_buf,
160 instance_id,
161 active_tx: tokio::sync::Mutex::new(None),
162 })
163 }
164
165 /// Raw pool access for tests that need to assert on schema/table shape
166 /// directly. Bypasses the `db_conn` ambient-transaction routing, so it
167 /// must never be reachable from production code.
168 ///
169 /// Gated behind the `test-helpers` feature; see the Cargo.toml doc
170 /// comment for the pattern this mirrors.
171 #[cfg(feature = "test-helpers")]
172 pub fn pool(&self) -> &Pool<Sqlite> {
173 &self.pool
174 }
175}