refactor: cleaning and formatting

This commit is contained in:
PandaDEV 2024-12-16 23:39:37 +10:00
parent e674e0a0ec
commit 00749a9d3a
No known key found for this signature in database
GPG key ID: 13EFF9BAF70EE75C
12 changed files with 479 additions and 120 deletions

View file

@ -1,8 +1,8 @@
use include_dir::{include_dir, Dir};
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
use std::fs;
use tauri::Manager;
use tokio::runtime::Runtime as TokioRuntime;
use include_dir::{include_dir, Dir};
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/src/db/migrations");
@ -49,39 +49,32 @@ pub fn setup(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
}
async fn apply_migrations(pool: &SqlitePool) -> Result<(), Box<dyn std::error::Error>> {
println!("Starting migration process");
// Create schema_version table
sqlx::query(
"CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
);"
);",
)
.execute(pool)
.await?;
let current_version: Option<i64> = sqlx::query_scalar(
"SELECT MAX(version) FROM schema_version"
)
.fetch_one(pool)
.await?;
let current_version: Option<i64> =
sqlx::query_scalar("SELECT MAX(version) FROM schema_version")
.fetch_one(pool)
.await?;
let current_version = current_version.unwrap_or(0);
println!("Current database version: {}", current_version);
let mut migration_files: Vec<(i64, &str)> = MIGRATIONS_DIR
.files()
.filter_map(|file| {
let file_name = file.path().file_name()?.to_str()?;
println!("Processing file: {}", file_name);
if file_name.ends_with(".sql") && file_name.starts_with("migration") {
let version: i64 = file_name
.trim_start_matches("migration")
.trim_end_matches(".sql")
.parse()
.ok()?;
println!("Found migration version: {}", version);
Some((version, file.contents_utf8()?))
} else {
None
@ -93,8 +86,6 @@ async fn apply_migrations(pool: &SqlitePool) -> Result<(), Box<dyn std::error::E
for (version, content) in migration_files {
if version > current_version {
println!("Applying migration {}", version);
let statements: Vec<&str> = content
.split(';')
.map(|s| s.trim())
@ -102,7 +93,6 @@ async fn apply_migrations(pool: &SqlitePool) -> Result<(), Box<dyn std::error::E
.collect();
for statement in statements {
println!("Executing statement: {}", statement);
sqlx::query(statement)
.execute(pool)
.await