Browse Source

✨ feat(migration): 删除旧的迁移模块及相关文件

陈雪 2 weeks ago
parent
commit
990c5f036b

File diff suppressed because it is too large
+ 689 - 4
src-tauri/Cargo.lock


+ 5 - 0
src-tauri/Cargo.toml

@@ -18,6 +18,11 @@ crate-type = ["staticlib", "cdylib", "rlib"]
 tauri-build = { version = "2", features = [] }
 
 [dependencies]
+sea-orm = { version = "1.1.0", features = [
+    "sqlx-sqlite",
+    "runtime-tokio-rustls",
+    "macros",
+] }
 tauri = { version = "2", features = [] }
 tauri-plugin-opener = "2"
 serde = { version = "1", features = ["derive"] }

+ 0 - 22
src-tauri/migration/Cargo.toml

@@ -1,22 +0,0 @@
-[package]
-name = "migration"
-version = "0.1.0"
-edition = "2021"
-publish = false
-
-[lib]
-name = "migration"
-path = "src/lib.rs"
-
-[dependencies]
-async-std = { version = "1", features = ["attributes", "tokio1"] }
-
-[dependencies.sea-orm-migration]
-version = "1.1.0"
-features = [
-  # Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
-  # View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
-  # e.g.
-  # "runtime-tokio-rustls",  # `ASYNC_RUNTIME` feature
-  # "sqlx-postgres",         # `DATABASE_DRIVER` feature
-]

+ 0 - 41
src-tauri/migration/README.md

@@ -1,41 +0,0 @@
-# Running Migrator CLI
-
-- Generate a new migration file
-    ```sh
-    cargo run -- generate MIGRATION_NAME
-    ```
-- Apply all pending migrations
-    ```sh
-    cargo run
-    ```
-    ```sh
-    cargo run -- up
-    ```
-- Apply first 10 pending migrations
-    ```sh
-    cargo run -- up -n 10
-    ```
-- Rollback last applied migrations
-    ```sh
-    cargo run -- down
-    ```
-- Rollback last 10 applied migrations
-    ```sh
-    cargo run -- down -n 10
-    ```
-- Drop all tables from the database, then reapply all migrations
-    ```sh
-    cargo run -- fresh
-    ```
-- Rollback all applied migrations, then reapply all migrations
-    ```sh
-    cargo run -- refresh
-    ```
-- Rollback all applied migrations
-    ```sh
-    cargo run -- reset
-    ```
-- Check the status of all migrations
-    ```sh
-    cargo run -- status
-    ```

+ 0 - 12
src-tauri/migration/src/lib.rs

@@ -1,12 +0,0 @@
-pub use sea_orm_migration::prelude::*;
-
-mod m20220101_000001_create_table;
-
-pub struct Migrator;
-
-#[async_trait::async_trait]
-impl MigratorTrait for Migrator {
-    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
-        vec![Box::new(m20220101_000001_create_table::Migration)]
-    }
-}

+ 0 - 37
src-tauri/migration/src/m20220101_000001_create_table.rs

@@ -1,37 +0,0 @@
-use sea_orm_migration::{prelude::*, schema::*};
-
-#[derive(DeriveMigrationName)]
-pub struct Migration;
-
-#[async_trait::async_trait]
-impl MigrationTrait for Migration {
-    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
-        // Replace the sample below with your own migration scripts
-        manager
-            .create_table(
-                Table::create()
-                    .table(Post::Table)
-                    .if_not_exists()
-                    .col(pk_auto(Post::Id))
-                    .col(string(Post::Title))
-                    .col(string(Post::Text))
-                    .to_owned(),
-            )
-            .await
-    }
-
-    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
-        // Replace the sample below with your own migration scripts
-        manager
-            .drop_table(Table::drop().table(Post::Table).to_owned())
-            .await
-    }
-}
-
-#[derive(DeriveIden)]
-enum Post {
-    Table,
-    Id,
-    Title,
-    Text,
-}

+ 0 - 6
src-tauri/migration/src/main.rs

@@ -1,6 +0,0 @@
-use sea_orm_migration::prelude::*;
-
-#[async_std::main]
-async fn main() {
-    cli::run_cli(migration::Migrator).await;
-}

+ 78 - 2
src-tauri/src/lib.rs

@@ -2,13 +2,42 @@ mod commands;
 mod models;
 mod service;
 
-use std::vec;
+use sea_orm::{ConnectionTrait, DatabaseConnection, Statement, TransactionTrait};
+use std::fs::{self, File};
+use std::sync::Arc;
+use tauri::{AppHandle, Manager, path::BaseDirectory};
 
-use tauri::{AppHandle, Manager};
+// 添加 AppState 结构体
+#[derive(Default)]
+pub struct AppState {
+    pub conn: Arc<DatabaseConnection>,
+}
 
 #[cfg_attr(mobile, tauri::mobile_entry_point)]
 pub fn run() {
     tauri::Builder::default()
+        .setup(|app| {
+            tauri::async_runtime::block_on(async {
+                let app_dir = app.handle().path().app_data_dir()?;
+                std::fs::create_dir_all(&app_dir)?;
+                let db_path = app_dir.join("store.sqlite");
+                if !db_path.exists() {
+                    File::create(&db_path)?;
+                }
+                let db_url = format!("sqlite:{}", db_path.display());
+                let conn = sea_orm::Database::connect(&db_url)
+                    .await
+                    .map_err(|e| anyhow::anyhow!("Database connection error: {}", e))?;
+                conn.execute_unprepared("PRAGMA journal_mode=WAL;")
+                    .await
+                    .map_err(|e| anyhow::anyhow!("Failed to set WAL mode: {}", e))?;
+                migration_db(app, &conn).await?;
+                app.manage(AppState {
+                    conn: Arc::new(conn),
+                });
+                Ok(())
+            })
+        })
         .plugin(tauri_plugin_os::init())
         .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
             let _ = show_window(app);
@@ -31,3 +60,50 @@ fn show_window(app: &AppHandle) {
         .set_focus()
         .expect("Can't Bring Window to Focus");
 }
+
+async fn migration_db(app: &tauri::App, conn: &DatabaseConnection) -> anyhow::Result<()> {
+    let sql_path = app
+        .path()
+        .resolve("resources/init.sql", BaseDirectory::Resource)?;
+    conn.execute(Statement::from_string(
+        conn.get_database_backend(),
+        "CREATE TABLE IF NOT EXISTS seaql_migrations (
+            version VARCHAR(255) PRIMARY KEY,
+            applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+        )"
+        .to_owned(),
+    ))
+    .await?;
+    let applied: Vec<String> = conn
+        .query_all(Statement::from_string(
+            conn.get_database_backend(),
+            "SELECT version FROM seaql_migrations".to_owned(),
+        ))
+        .await?
+        .into_iter()
+        .filter_map(|row| row.try_get("", "version").ok())
+        .collect();
+
+    if let Some(sql_path_stem) = sql_path.file_stem() {
+        if let Some(version) = sql_path_stem.to_str() {
+            if !applied.contains(&version.to_string()) {
+                let sql_str = fs::read_to_string(&sql_path)?;
+                let tx = conn.begin().await?;
+                tx.execute(Statement::from_string(conn.get_database_backend(), sql_str))
+                    .await?;
+                tx.execute(Statement::from_string(
+                    conn.get_database_backend(),
+                    format!(
+                        "INSERT INTO seaql_migrations (version) VALUES ('{}')",
+                        version
+                    ),
+                ))
+                .await?;
+                tx.commit().await?;
+                println!("✅ Applied migration: {}", version);
+            }
+        }
+    }
+
+    Ok(())
+}

Some files were not shown because too many files changed in this diff