Files
jap_learn/src/data_provider/settings.rs
T

81 lines
2.0 KiB
Rust
Raw Normal View History

2026-08-24 18:23:29 +03:00
use crate::notification::NotificationData;
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
2026-08-24 23:10:23 +03:00
use iced::futures::StreamExt;
2026-06-01 15:36:53 +03:00
use rusqlite::Connection;
pub fn get_setting(key: String, connection: &Connection) -> Option<String> {
2026-08-01 19:43:07 +03:00
let mut stmt = connection
.prepare("SELECT value FROM settings WHERE id = ?1")
2026-08-24 23:10:23 +03:00
.expect("Failed to prepare statement.");
let mut iter = stmt.query_map((key,), |row| row.get(0)).ok()?;
2026-06-01 15:36:53 +03:00
2026-08-15 21:32:24 +03:00
if let Some(row) = iter.next()
&& let Ok(value) = row
2026-08-15 13:22:59 +03:00
{
return Some(value);
2026-06-01 15:36:53 +03:00
}
2026-08-15 13:22:59 +03:00
2026-06-01 15:36:53 +03:00
None
}
2026-08-24 18:23:29 +03:00
pub fn set_setting(
key: String,
value: String,
connection: &Connection,
) -> Result<(), NotificationData> {
let current = get_settings_list(connection)?;
2026-06-01 15:36:53 +03:00
if current.contains(&key) {
2026-08-24 18:23:29 +03:00
update_settings(key, value, connection)?;
2026-08-01 19:43:07 +03:00
} else {
2026-08-24 18:23:29 +03:00
create_settings(key, value, connection)?;
2026-06-01 15:36:53 +03:00
}
2026-08-24 18:23:29 +03:00
Ok(())
2026-06-01 15:36:53 +03:00
}
2026-08-24 23:10:23 +03:00
pub fn delete_settings(key: String, connection: &Connection) -> Result<(), NotificationData> {
2026-06-01 15:36:53 +03:00
connection
.execute("DELETE FROM settings WHERE id = ?1", (&key,))
2026-08-24 23:10:23 +03:00
.map_err(|_| DbSaveError)?;
Ok(())
2026-06-01 15:36:53 +03:00
}
2026-08-24 23:10:23 +03:00
fn create_settings(
key: String,
value: String,
connection: &Connection,
) -> Result<(), NotificationData> {
2026-06-01 15:36:53 +03:00
connection
.execute(
"INSERT into settings (id, value) VALUES (?1, ?2)",
(key, value),
)
2026-08-24 18:23:29 +03:00
.map_err(|_| DbSaveError)?;
Ok(())
2026-06-01 15:36:53 +03:00
}
2026-08-24 18:23:29 +03:00
fn update_settings(
key: String,
value: String,
connection: &Connection,
) -> Result<(), NotificationData> {
2026-06-01 15:36:53 +03:00
connection
.execute(
"update settings
set value = ?2
where id = ?1",
(key, value),
)
2026-08-24 18:23:29 +03:00
.map_err(|_| DbSaveError)?;
Ok(())
2026-08-01 19:43:07 +03:00
}
2026-06-01 15:36:53 +03:00
2026-08-24 18:23:29 +03:00
fn get_settings_list(connection: &Connection) -> Result<Vec<String>, NotificationData> {
2026-08-24 23:10:23 +03:00
let mut stmt = connection
.prepare("SELECT id FROM settings")
.expect("prepare stmt failed");
let iter = stmt
.query_map((), |row| row.get(0))
.map_err(|_| DbLoadError)?;
Ok(iter.filter_map(|i| i.ok()).collect())
2026-06-01 15:36:53 +03:00
}