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.

69 lines
2.0 KiB
Rust

use rusqlite::Connection;
use rustc_serialize::base64;
use rustc_serialize::base64::{FromBase64, ToBase64};
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();
}
pub fn get_db_property_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, Box<dyn Error>> {
self.get_db_property(name)
.map(|option| option.map(|prop| prop.from_base64().unwrap()))
}
pub fn set_db_property_bytes(&self, name: &str, value: &Vec<u8>) {
let b64value: String = value.to_base64(base64::STANDARD);
self.set_db_property(name, &b64value);
}
}