You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.5 KiB
Rust
57 lines
1.5 KiB
Rust
use rusqlite::Connection;
|
|
use std::error::Error;
|
|
use std::path::PathBuf;
|
|
|
|
static DB_INIT_QUERY: &'static str = include_str!("init.sql");
|
|
|
|
pub struct DbHandle {
|
|
conn: Connection,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct DbProperty {
|
|
name: String,
|
|
value: Option<String>,
|
|
}
|
|
|
|
impl DbHandle {
|
|
pub fn new(db_path: &Option<String>) -> DbHandle {
|
|
let path: PathBuf = db_path
|
|
.as_ref()
|
|
.map(|path: &String| PathBuf::from(path))
|
|
.unwrap_or_else(|| dirs::home_dir().unwrap().join(".foil").to_path_buf());
|
|
let mut conn: Connection = Connection::open(path).unwrap();
|
|
let tx = conn.transaction().unwrap();
|
|
tx.execute_batch(DB_INIT_QUERY).unwrap();
|
|
tx.commit();
|
|
DbHandle { conn: conn }
|
|
}
|
|
|
|
pub fn get_db_property(&self, name: &str) -> Result<Option<String>, Box<dyn Error>> {
|
|
let mut stmt = self
|
|
.conn
|
|
.prepare("SELECT name, value FROM props WHERE name=$1")
|
|
.unwrap();
|
|
let mut props = stmt.query_map(&[&name], |row| {
|
|
Ok(DbProperty {
|
|
name: row.get(0)?,
|
|
value: row.get(1)?,
|
|
})
|
|
})?;
|
|
|
|
match props.next() {
|
|
Some(prop) => Ok(Some(prop.unwrap().value.unwrap())),
|
|
None => Ok(None),
|
|
}
|
|
}
|
|
|
|
pub fn set_db_property(&self, name: &str, value: &str) {
|
|
self.conn
|
|
.execute(
|
|
"INSERT OR REPLACE INTO props (name, value) VALUES ($1, $2)",
|
|
&[&name, &value],
|
|
)
|
|
.unwrap();
|
|
}
|
|
}
|