Skip to main content

kanban_persistence_sqlite/sqlite_store/
mod.rs

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