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

View file

@ -1,3 +1,3 @@
pub mod database;
pub mod history;
pub mod settings;
pub mod settings;

View file

@ -1,8 +1,8 @@
use serde::{Deserialize, Serialize};
use sqlx::SqlitePool;
use serde_json;
use tauri::{Emitter, Manager};
use sqlx::Row;
use sqlx::SqlitePool;
use tauri::{Emitter, Manager};
#[derive(Deserialize, Serialize)]
struct KeybindSetting {
@ -15,12 +15,10 @@ pub async fn initialize_settings(pool: &SqlitePool) -> Result<(), Box<dyn std::e
};
let json = serde_json::to_string(&default_keybind)?;
sqlx::query(
"INSERT INTO settings (key, value) VALUES ('keybind', ?)"
)
.bind(json)
.execute(pool)
.await?;
sqlx::query("INSERT INTO settings (key, value) VALUES ('keybind', ?)")
.bind(json)
.execute(pool)
.await?;
Ok(())
}
@ -50,7 +48,7 @@ pub async fn save_keybind(
#[tauri::command]
pub async fn get_setting(
pool: tauri::State<'_, SqlitePool>,
key: String
key: String,
) -> Result<String, String> {
let row = sqlx::query("SELECT value FROM settings WHERE key = ?")
.bind(key)
@ -65,7 +63,7 @@ pub async fn get_setting(
pub async fn save_setting(
pool: tauri::State<'_, SqlitePool>,
key: String,
value: String
value: String,
) -> Result<(), String> {
sqlx::query("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
.bind(key)
@ -78,23 +76,18 @@ pub async fn save_setting(
}
#[tauri::command]
pub async fn get_keybind(
app_handle: tauri::AppHandle,
) -> Result<Vec<String>, String> {
pub async fn get_keybind(app_handle: tauri::AppHandle) -> Result<Vec<String>, String> {
let pool = app_handle.state::<SqlitePool>();
let row = sqlx::query("SELECT value FROM settings WHERE key = 'keybind'")
.fetch_optional(&*pool)
.await
.map_err(|e| e.to_string())?;
let json = row
.map(|r| r.get::<String, _>("value"))
.unwrap_or_else(|| {
serde_json::to_string(&vec!["Meta".to_string(), "V".to_string()])
.expect("Failed to serialize default keybind")
});
let json = row.map(|r| r.get::<String, _>("value")).unwrap_or_else(|| {
serde_json::to_string(&vec!["Meta".to_string(), "V".to_string()])
.expect("Failed to serialize default keybind")
});
serde_json::from_str::<Vec<String>>(&json)
.map_err(|e| e.to_string())
}
serde_json::from_str::<Vec<String>>(&json).map_err(|e| e.to_string())
}