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 (
name TEXT NOT NULL,
name TEXT UNIQUE NOT NULL,
data TEXT NOT NULL
);

View File

@ -32,7 +32,8 @@ impl Default for AppConfig {
}
pub async fn load(pool: &SqlitePool) -> Result<AppConfig, SetupError> {
impl AppConfig {
pub async fn load(pool: &SqlitePool) -> Result<AppConfig, SetupError> {
let res = sqlx::query!("SELECT * from config where name = 'main'")
.fetch_optional(pool)
.await?;
@ -43,6 +44,21 @@ pub async fn load(pool: &SqlitePool) -> Result<AppConfig, SetupError> {
};
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(())
}
}

View File

@ -70,7 +70,8 @@ pub fn get_config(app_state: State<'_, AppState>) -> AppConfig {
#[tauri::command]
pub fn save_config(config: AppConfig, app_state: State<'_, AppState>) {
let mut prev_config = app_state.config.write().unwrap();
*prev_config = config;
pub async fn save_config(config: AppConfig, app_state: State<'_, AppState>) -> Result<(), String> {
app_state.update_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?;
sqlx::migrate!().run(&pool).await?;
let creds = Self::load_creds(&pool).await?;
let conf = config::load(&pool).await?;
let conf = AppConfig::load(&pool).await?;
let state = AppState {
config: RwLock::new(conf),
@ -150,6 +150,17 @@ impl AppState {
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 {
let count = {
let mut c = self.request_count.write().unwrap();