use std::path::{Path, PathBuf};
use kanban_domain::{KanbanError, KanbanResult};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{Pool, Sqlite};
use uuid::Uuid;
mod command_log;
mod conversions;
mod data_store;
mod entities;
mod graph;
mod helpers;
mod init;
mod lists;
mod metadata;
mod persistence_store;
mod snapshot;
#[cfg(test)]
mod tests;
const SCHEMA: &str = include_str!("../schema.sql");
pub const SUPPORTED_SCHEMA_VERSION: u32 = 5;
type MetadataRow = (String, String, Option<String>, Option<String>, u32);
pub struct SqliteStore {
pub(crate) pool: Pool<Sqlite>,
pub(crate) path: PathBuf,
pub(crate) instance_id: Uuid,
}
impl SqliteStore {
pub async fn open(path: impl AsRef<Path>) -> KanbanResult<Self> {
let handle = tokio::runtime::Handle::current();
if handle.runtime_flavor() != tokio::runtime::RuntimeFlavor::MultiThread {
return Err(KanbanError::Database(
"SqliteStore requires a multi-threaded Tokio runtime (e.g. #[tokio::main] or \
tokio::runtime::Runtime::new()). The current_thread runtime is not supported \
because synchronous DataStore methods need to block on async SQLite I/O."
.to_string(),
));
}
let path_buf = path.as_ref().to_path_buf();
let options = SqliteConnectOptions::new()
.filename(&path_buf)
.create_if_missing(true)
.foreign_keys(true)
.pragma("journal_mode", "wal");
let pool = SqlitePoolOptions::new()
.max_connections(2)
.connect_with(options)
.await
.map_err(|e| KanbanError::Database(e.to_string()))?;
let metadata_table_exists: bool = sqlx::query_scalar(
"SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='metadata'",
)
.fetch_one(&pool)
.await
.map_err(|e| KanbanError::Database(e.to_string()))?;
if metadata_table_exists {
let pre_migrate_version: Option<u32> =
sqlx::query_scalar("SELECT schema_version FROM metadata WHERE id = 1")
.fetch_optional(&pool)
.await
.map_err(|e| KanbanError::Database(e.to_string()))?;
if let Some(v) = pre_migrate_version {
if v > SUPPORTED_SCHEMA_VERSION {
return Err(KanbanError::UnsupportedFutureVersion {
file_version: v,
binary_max: SUPPORTED_SCHEMA_VERSION,
});
}
if v < SUPPORTED_SCHEMA_VERSION {
Self::write_pre_migration_backup(&pool, &path_buf, v).await?;
}
}
}
Self::drop_legacy_command_log_if_present(&pool).await?;
Self::migrate_v2_to_v3_archived_cards(&pool).await?;
Self::migrate_v4_to_v5_cards_board_id(&pool).await?;
sqlx::raw_sql(SCHEMA)
.execute(&pool)
.await
.map_err(|e| KanbanError::Database(e.to_string()))?;
Self::migrate(&pool).await?;
let instance_id = Self::load_or_create_instance_id(&pool).await?;
Ok(Self {
pool,
path: path_buf,
instance_id,
})
}
pub fn pool(&self) -> &Pool<Sqlite> {
&self.pool
}
}