Done first draft of strongly typed migrations

This commit is contained in:
Mikayla Maki 2022-11-10 15:29:29 -08:00
parent 4a00f0b062
commit c84201fc9f
18 changed files with 396 additions and 448 deletions

View file

@ -7,18 +7,23 @@ use std::path::Path;
use anyhow::Result;
use indoc::indoc;
use kvp::KVP_MIGRATION;
use sqlez::connection::Connection;
use sqlez::domain::Domain;
use sqlez::thread_safe_connection::ThreadSafeConnection;
use workspace::items::ITEM_MIGRATIONS;
use workspace::pane::PANE_MIGRATIONS;
pub use workspace::*;
#[derive(Clone)]
pub struct Db(ThreadSafeConnection);
const INITIALIZE_QUERY: &'static str = indoc! {"
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA foreign_keys=TRUE;
PRAGMA case_sensitive_like=TRUE;
"};
impl Deref for Db {
#[derive(Clone)]
pub struct Db<D: Domain>(ThreadSafeConnection<D>);
impl<D: Domain> Deref for Db<D> {
type Target = sqlez::connection::Connection;
fn deref(&self) -> &Self::Target {
@ -26,7 +31,7 @@ impl Deref for Db {
}
}
impl Db {
impl<D: Domain> Db<D> {
/// Open or create a database at the given directory path.
pub fn open(db_dir: &Path, channel: &'static str) -> Self {
// Use 0 for now. Will implement incrementing and clearing of old db files soon TM
@ -35,17 +40,15 @@ impl Db {
.expect("Should be able to create the database directory");
let db_path = current_db_dir.join(Path::new("db.sqlite"));
Db(initialize_connection(ThreadSafeConnection::new(
db_path.to_string_lossy().as_ref(),
true,
)))
Db(
ThreadSafeConnection::new(db_path.to_string_lossy().as_ref(), true)
.with_initialize_query(INITIALIZE_QUERY),
)
}
/// Open a in memory database for testing and as a fallback.
pub fn open_in_memory(db_name: &str) -> Self {
Db(initialize_connection(ThreadSafeConnection::new(
db_name, false,
)))
Db(ThreadSafeConnection::new(db_name, false).with_initialize_query(INITIALIZE_QUERY))
}
pub fn persisting(&self) -> bool {
@ -56,19 +59,8 @@ impl Db {
let destination = Connection::open_file(dest.as_ref().to_string_lossy().as_ref());
self.backup_main(&destination)
}
}
fn initialize_connection(conn: ThreadSafeConnection) -> ThreadSafeConnection {
conn.with_initialize_query(indoc! {"
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
PRAGMA foreign_keys=TRUE;
PRAGMA case_sensitive_like=TRUE;
"})
.with_migrations(&[
KVP_MIGRATION,
WORKSPACES_MIGRATION,
PANE_MIGRATIONS,
ITEM_MIGRATIONS,
])
pub fn open_as<D2: Domain>(&self) -> Db<D2> {
Db(self.0.for_domain())
}
}