refactor: Clean up code formatting in utils module

This commit is contained in:
PandaDEV 2025-01-04 11:58:52 +10:00
parent 60b670c7a7
commit 22fcd84b8d
No known key found for this signature in database
GPG key ID: 13EFF9BAF70EE75C
14 changed files with 485 additions and 394 deletions

View file

@ -1,5 +1,5 @@
use include_dir::{include_dir, Dir};
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
use include_dir::{ include_dir, Dir };
use sqlx::sqlite::{ SqlitePool, SqlitePoolOptions };
use std::fs;
use tauri::Manager;
use tokio::runtime::Runtime as TokioRuntime;
@ -25,8 +25,7 @@ pub fn setup(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let pool = rt.block_on(async {
SqlitePoolOptions::new()
.max_connections(5)
.connect(&db_url)
.await
.connect(&db_url).await
.expect("Failed to create pool")
});
@ -49,24 +48,22 @@ 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>> {
sqlx::query(
"CREATE TABLE IF NOT EXISTS schema_version (
sqlx
::query(
"CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
);",
)
.execute(pool)
.await?;
);"
)
.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);
let mut migration_files: Vec<(i64, &str)> = MIGRATIONS_DIR
.files()
let mut migration_files: Vec<(i64, &str)> = MIGRATIONS_DIR.files()
.filter_map(|file| {
let file_name = file.path().file_name()?.to_str()?;
if file_name.ends_with(".sql") && file_name.starts_with("v") {
@ -93,16 +90,16 @@ async fn apply_migrations(pool: &SqlitePool) -> Result<(), Box<dyn std::error::E
.collect();
for statement in statements {
sqlx::query(statement)
.execute(pool)
.await
sqlx
::query(statement)
.execute(pool).await
.map_err(|e| format!("Failed to execute migration {}: {}", version, e))?;
}
sqlx::query("INSERT INTO schema_version (version) VALUES (?)")
sqlx
::query("INSERT INTO schema_version (version) VALUES (?)")
.bind(version)
.execute(pool)
.await?;
.execute(pool).await?;
}
}

View file

@ -1,39 +1,35 @@
use crate::utils::types::{ContentType, HistoryItem};
use base64::{engine::general_purpose::STANDARD, Engine};
use crate::utils::types::{ ContentType, HistoryItem };
use base64::{ engine::general_purpose::STANDARD, Engine };
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use sqlx::{Row, SqlitePool};
use rand::{ thread_rng, Rng };
use sqlx::{ Row, SqlitePool };
use std::fs;
use tauri_plugin_aptabase::EventTracker;
pub async fn initialize_history(pool: &SqlitePool) -> Result<(), Box<dyn std::error::Error>> {
let id: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(16)
.map(char::from)
.collect();
let id: String = thread_rng().sample_iter(&Alphanumeric).take(16).map(char::from).collect();
sqlx::query(
"INSERT INTO history (id, source, content_type, content, timestamp) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)"
)
.bind(id)
.bind("System")
.bind("text")
.bind("Welcome to your clipboard history!")
.execute(pool)
.await?;
sqlx
::query(
"INSERT INTO history (id, source, content_type, content, timestamp) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)"
)
.bind(id)
.bind("System")
.bind("text")
.bind("Welcome to your clipboard history!")
.execute(pool).await?;
Ok(())
}
#[tauri::command]
pub async fn get_history(pool: tauri::State<'_, SqlitePool>) -> Result<Vec<HistoryItem>, String> {
let rows = sqlx::query(
"SELECT id, source, source_icon, content_type, content, favicon, timestamp, language FROM history ORDER BY timestamp DESC",
)
.fetch_all(&*pool)
.await
.map_err(|e| e.to_string())?;
let rows = sqlx
::query(
"SELECT id, source, source_icon, content_type, content, favicon, timestamp, language FROM history ORDER BY timestamp DESC"
)
.fetch_all(&*pool).await
.map_err(|e| e.to_string())?;
let items = rows
.iter()
@ -56,50 +52,53 @@ pub async fn get_history(pool: tauri::State<'_, SqlitePool>) -> Result<Vec<Histo
pub async fn add_history_item(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>,
item: HistoryItem,
item: HistoryItem
) -> Result<(), String> {
let (id, source, source_icon, content_type, content, favicon, timestamp, language) =
item.to_row();
let existing = sqlx::query("SELECT id FROM history WHERE content = ? AND content_type = ?")
let existing = sqlx
::query("SELECT id FROM history WHERE content = ? AND content_type = ?")
.bind(&content)
.bind(&content_type)
.fetch_optional(&*pool)
.await
.fetch_optional(&*pool).await
.map_err(|e| e.to_string())?;
match existing {
Some(_) => {
sqlx::query(
"UPDATE history SET timestamp = strftime('%Y-%m-%dT%H:%M:%f+00:00', 'now') WHERE content = ? AND content_type = ?"
)
.bind(&content)
.bind(&content_type)
.execute(&*pool)
.await
.map_err(|e| e.to_string())?;
sqlx
::query(
"UPDATE history SET timestamp = strftime('%Y-%m-%dT%H:%M:%f+00:00', 'now') WHERE content = ? AND content_type = ?"
)
.bind(&content)
.bind(&content_type)
.execute(&*pool).await
.map_err(|e| e.to_string())?;
}
None => {
sqlx::query(
"INSERT INTO history (id, source, source_icon, content_type, content, favicon, timestamp, language) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
)
.bind(id)
.bind(source)
.bind(source_icon)
.bind(content_type)
.bind(content)
.bind(favicon)
.bind(timestamp)
.bind(language)
.execute(&*pool)
.await
.map_err(|e| e.to_string())?;
sqlx
::query(
"INSERT INTO history (id, source, source_icon, content_type, content, favicon, timestamp, language) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
)
.bind(id)
.bind(source)
.bind(source_icon)
.bind(content_type)
.bind(content)
.bind(favicon)
.bind(timestamp)
.bind(language)
.execute(&*pool).await
.map_err(|e| e.to_string())?;
}
}
let _ = app_handle.track_event("history_item_added", Some(serde_json::json!({
let _ = app_handle.track_event(
"history_item_added",
Some(serde_json::json!({
"content_type": item.content_type.to_string()
})));
}))
);
Ok(())
}
@ -107,16 +106,16 @@ pub async fn add_history_item(
#[tauri::command]
pub async fn search_history(
pool: tauri::State<'_, SqlitePool>,
query: String,
query: String
) -> Result<Vec<HistoryItem>, String> {
let query = format!("%{}%", query);
let rows = sqlx::query(
"SELECT id, source, source_icon, content_type, content, favicon, timestamp, language FROM history WHERE content LIKE ? ORDER BY timestamp DESC"
)
.bind(query)
.fetch_all(&*pool)
.await
.map_err(|e| e.to_string())?;
let rows = sqlx
::query(
"SELECT id, source, source_icon, content_type, content, favicon, timestamp, language FROM history WHERE content LIKE ? ORDER BY timestamp DESC"
)
.bind(query)
.fetch_all(&*pool).await
.map_err(|e| e.to_string())?;
let items = rows
.iter()
@ -139,16 +138,16 @@ pub async fn search_history(
pub async fn load_history_chunk(
pool: tauri::State<'_, SqlitePool>,
offset: i64,
limit: i64,
limit: i64
) -> Result<Vec<HistoryItem>, String> {
let rows = sqlx::query(
"SELECT id, source, source_icon, content_type, content, favicon, timestamp, language FROM history ORDER BY timestamp DESC LIMIT ? OFFSET ?"
)
.bind(limit)
.bind(offset)
.fetch_all(&*pool)
.await
.map_err(|e| e.to_string())?;
let rows = sqlx
::query(
"SELECT id, source, source_icon, content_type, content, favicon, timestamp, language FROM history ORDER BY timestamp DESC LIMIT ? OFFSET ?"
)
.bind(limit)
.bind(offset)
.fetch_all(&*pool).await
.map_err(|e| e.to_string())?;
let items = rows
.iter()
@ -171,12 +170,12 @@ pub async fn load_history_chunk(
pub async fn delete_history_item(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>,
id: String,
id: String
) -> Result<(), String> {
sqlx::query("DELETE FROM history WHERE id = ?")
sqlx
::query("DELETE FROM history WHERE id = ?")
.bind(id)
.execute(&*pool)
.await
.execute(&*pool).await
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("history_item_deleted", None);
@ -189,9 +188,9 @@ pub async fn clear_history(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>
) -> Result<(), String> {
sqlx::query("DELETE FROM history")
.execute(&*pool)
.await
sqlx
::query("DELETE FROM history")
.execute(&*pool).await
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("history_cleared", None);

View file

@ -1,8 +1,8 @@
use serde::{Deserialize, Serialize};
use serde::{ Deserialize, Serialize };
use serde_json;
use sqlx::Row;
use sqlx::SqlitePool;
use tauri::{Emitter, Manager};
use tauri::{ Emitter, Manager };
use tauri_plugin_aptabase::EventTracker;
#[derive(Deserialize, Serialize)]
@ -16,10 +16,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', ?)")
sqlx
::query("INSERT INTO settings (key, value) VALUES ('keybind', ?)")
.bind(json)
.execute(pool)
.await?;
.execute(pool).await?;
Ok(())
}
@ -28,23 +28,24 @@ pub async fn initialize_settings(pool: &SqlitePool) -> Result<(), Box<dyn std::e
pub async fn save_keybind(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>,
keybind: Vec<String>,
keybind: Vec<String>
) -> Result<(), String> {
app_handle
.emit("update-shortcut", &keybind)
.map_err(|e| e.to_string())?;
app_handle.emit("update-shortcut", &keybind).map_err(|e| e.to_string())?;
let json = serde_json::to_string(&keybind).map_err(|e| e.to_string())?;
sqlx::query("INSERT OR REPLACE INTO settings (key, value) VALUES ('keybind', ?)")
sqlx
::query("INSERT OR REPLACE INTO settings (key, value) VALUES ('keybind', ?)")
.bind(json)
.execute(&*pool)
.await
.execute(&*pool).await
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("keybind_saved", Some(serde_json::json!({
let _ = app_handle.track_event(
"keybind_saved",
Some(serde_json::json!({
"keybind": keybind
})));
}))
);
Ok(())
}
@ -52,12 +53,12 @@ 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 = ?")
let row = sqlx
::query("SELECT value FROM settings WHERE key = ?")
.bind(key)
.fetch_optional(&*pool)
.await
.fetch_optional(&*pool).await
.map_err(|e| e.to_string())?;
Ok(row.map(|r| r.get("value")).unwrap_or_default())
@ -68,18 +69,21 @@ pub async fn save_setting(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>,
key: String,
value: String,
value: String
) -> Result<(), String> {
sqlx::query("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
sqlx
::query("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
.bind(key.clone())
.bind(value)
.execute(&*pool)
.await
.execute(&*pool).await
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("setting_saved", Some(serde_json::json!({
let _ = app_handle.track_event(
"setting_saved",
Some(serde_json::json!({
"key": key
})));
}))
);
Ok(())
}
@ -88,15 +92,18 @@ pub async fn save_setting(
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
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!["MetaLeft".to_string(), "KeyV".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!["MetaLeft".to_string(), "KeyV".to_string()])
.expect("Failed to serialize default keybind")
});
serde_json::from_str::<Vec<String>>(&json).map_err(|e| e.to_string())
}