瀏覽代碼

feat(wallet/sqlite): use sqlx migration

thesimplekid 10 月之前
父節點
當前提交
971fd30d8d
共有 2 個文件被更改,包括 7 次插入48 次删除
  1. 0 43
      crates/cdk-sqlite/src/wallet/migrations/20240612132920_init.sql
  2. 7 5
      crates/cdk-sqlite/src/wallet/mod.rs

+ 0 - 43
crates/cdk-sqlite/src/wallet/migration.rs → crates/cdk-sqlite/src/wallet/migrations/20240612132920_init.sql

@@ -1,24 +1,3 @@
-//! SQLite Wallet 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 = {};
-
 -- Mints
 CREATE TABLE IF NOT EXISTS mint (
     mint_url TEXT PRIMARY KEY,
@@ -100,25 +79,3 @@ CREATE TABLE IF NOT EXISTS nostr_last_checked (
     key BLOB PRIMARY KEY,
     last_check INTEGER NOT NULL
 );
-
-    "#,
-    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)
-}

+ 7 - 5
crates/cdk-sqlite/src/wallet/mod.rs

@@ -17,10 +17,7 @@ use error::Error;
 use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqliteRow};
 use sqlx::{ConnectOptions, Row};
 
-use self::migration::init_migration;
-
 pub mod error;
-mod migration;
 
 #[derive(Debug, Clone)]
 pub struct WalletSQLiteDatabase {
@@ -39,10 +36,15 @@ impl WalletSQLiteDatabase {
 
         let pool = SqlitePool::connect(path).await?;
 
-        init_migration(&pool).await?;
-
         Ok(Self { pool })
     }
+
+    pub async fn migrate(&self) {
+        sqlx::migrate!("./src/wallet/migrations")
+            .run(&self.pool)
+            .await
+            .expect("Could not run migrations");
+    }
 }
 
 #[async_trait]