feat(mint/sqlite): use sql migrations

This commit is contained in:
thesimplekid
2024-06-12 14:26:55 +01:00
parent 9377b71104
commit a07364c5c6
4 changed files with 9 additions and 48 deletions

View File

@@ -17,7 +17,7 @@ nostr = ["cdk/nostr"]
[dependencies]
bitcoin.workspace = true
const_format = "0.2.32"
sqlx = { version = "0.6.3", default-features = false, features = ["runtime-tokio-rustls", "chrono", "sqlite"] }
sqlx = { version = "0.6.3", default-features = false, features = ["runtime-tokio-rustls", "chrono", "sqlite", "macros", "migrate"] }
cdk = { workspace = true, default-features = false }
thiserror.workspace = true
tokio = { workspace = true, features = [

View File

@@ -1,23 +1,3 @@
//! SQLite Mint Migration
use const_format::formatcp;
use sqlx::{Executor, Pool, Sqlite};
use super::error::Error;
/// Latest database version
pub const DB_VERSION: usize = 0;
/// Schema definition
const INIT_SQL: &str = formatcp!(
r#"
-- Database settings
PRAGMA encoding = "UTF-8";
PRAGMA journal_mode = WAL;
PRAGMA auto_vacuum = FULL;
PRAGMA main.synchronous=NORMAL;
PRAGMA foreign_keys = ON;
PRAGMA user_version = {};
-- Proof Table
CREATE TABLE IF NOT EXISTS proof (
@@ -84,25 +64,3 @@ CREATE TABLE IF NOT EXISTS blind_signature (
);
CREATE INDEX IF NOT EXISTS keyset_id_index ON blind_signature(keyset_id);
"#,
DB_VERSION
);
pub(crate) async fn init_migration(pool: &Pool<Sqlite>) -> Result<usize, Error> {
let mut conn = pool.acquire().await?;
match conn.execute(INIT_SQL).await {
Ok(_) => {
tracing::info!(
"database pragma/schema initialized to v{}, and ready",
DB_VERSION
);
}
Err(err) => {
tracing::error!("update (init) failed: {}", err);
return Err(Error::CouldNotInitialize);
}
}
Ok(DB_VERSION)
}

View File

@@ -12,12 +12,10 @@ use cdk::secret::Secret;
use cdk::types::{MeltQuote, MintQuote};
use cdk::Amount;
use error::Error;
use migration::init_migration;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqliteRow};
use sqlx::{ConnectOptions, Row};
pub mod error;
mod migration;
#[derive(Debug, Clone)]
pub struct MintSqliteDatabase {
@@ -36,10 +34,15 @@ impl MintSqliteDatabase {
let pool = SqlitePool::connect(path).await?;
init_migration(&pool).await?;
Ok(Self { pool })
}
pub async fn migrate(&self) {
sqlx::migrate!("./src/mint/migrations")
.run(&self.pool)
.await
.expect("Could not run migrations");
}
}
#[async_trait]

View File

@@ -54,7 +54,7 @@
devShells = flakeboxLib.mkShells {
toolchain = toolchainNative;
packages = [ ];
nativeBuildInputs = with pkgs; [ wasm-pack ];
nativeBuildInputs = with pkgs; [ wasm-pack sqlx-cli ];
};
});
}