Skip to main content

kanban_persistence_sqlite/sqlite_store/
mod.rs

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