save settings to db

This commit is contained in:
Joseph Montanaro 2023-04-26 15:49:08 -07:00
parent 12d9d733a5
commit 4aab08e6f0
4 changed files with 42 additions and 14 deletions

View File

@ -8,7 +8,7 @@ CREATE TABLE credentials (
); );
CREATE TABLE config ( CREATE TABLE config (
name TEXT NOT NULL, name TEXT UNIQUE NOT NULL,
data TEXT NOT NULL data TEXT NOT NULL
); );

View File

@ -32,6 +32,7 @@ impl Default for AppConfig {
} }
impl AppConfig {
pub async fn load(pool: &SqlitePool) -> Result<AppConfig, SetupError> { pub async fn load(pool: &SqlitePool) -> Result<AppConfig, SetupError> {
let res = sqlx::query!("SELECT * from config where name = 'main'") let res = sqlx::query!("SELECT * from config where name = 'main'")
.fetch_optional(pool) .fetch_optional(pool)
@ -45,6 +46,21 @@ pub async fn load(pool: &SqlitePool) -> Result<AppConfig, SetupError> {
Ok(serde_json::from_str(&row.data)?) Ok(serde_json::from_str(&row.data)?)
} }
pub async fn save(&self, pool: &SqlitePool) -> Result<(), sqlx::error::Error> {
let data = serde_json::to_string(self).unwrap();
sqlx::query(
"INSERT INTO config (name, data) VALUES ('main', ?)
ON CONFLICT (name) DO UPDATE SET data = ?"
)
.bind(&data)
.bind(&data)
.execute(pool)
.await?;
Ok(())
}
}
pub fn get_or_create_db_path() -> PathBuf { pub fn get_or_create_db_path() -> PathBuf {
if cfg!(debug_assertions) { if cfg!(debug_assertions) {

View File

@ -70,7 +70,8 @@ pub fn get_config(app_state: State<'_, AppState>) -> AppConfig {
#[tauri::command] #[tauri::command]
pub fn save_config(config: AppConfig, app_state: State<'_, AppState>) { pub async fn save_config(config: AppConfig, app_state: State<'_, AppState>) -> Result<(), String> {
let mut prev_config = app_state.config.write().unwrap(); app_state.update_config(config)
*prev_config = config; .await
.map_err(|e| format!("Error saving config to database: {e}"))
} }

View File

@ -76,7 +76,7 @@ impl AppState {
let pool: SqlitePool = pool_opts.connect_with(conn_opts).await?; let pool: SqlitePool = pool_opts.connect_with(conn_opts).await?;
sqlx::migrate!().run(&pool).await?; sqlx::migrate!().run(&pool).await?;
let creds = Self::load_creds(&pool).await?; let creds = Self::load_creds(&pool).await?;
let conf = config::load(&pool).await?; let conf = AppConfig::load(&pool).await?;
let state = AppState { let state = AppState {
config: RwLock::new(conf), config: RwLock::new(conf),
@ -150,6 +150,17 @@ impl AppState {
Ok(()) Ok(())
} }
pub async fn update_config(&self, new_config: AppConfig) -> Result<(), sqlx::error::Error> {
let config = {
let mut live_config = self.config.write().unwrap();
*live_config = new_config;
live_config.clone()
};
config.save(&self.pool).await?;
Ok(())
}
pub fn register_request(&self, chan: Sender<ipc::Approval>) -> u64 { pub fn register_request(&self, chan: Sender<ipc::Approval>) -> u64 {
let count = { let count = {
let mut c = self.request_count.write().unwrap(); let mut c = self.request_count.write().unwrap();