diff options
Diffstat (limited to 'src/common/sqlite.rs')
-rw-r--r-- | src/common/sqlite.rs | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/src/common/sqlite.rs b/src/common/sqlite.rs new file mode 100644 index 0000000..d373218 --- /dev/null +++ b/src/common/sqlite.rs @@ -0,0 +1,60 @@ +use log::error; +use rusqlite::{Connection, Params, Row}; + +pub fn get<F, P, T>(db: &Connection, query: &str, params: P, row_mapper: F) -> rusqlite::Result<T> +where + F: FnMut(&Row<'_>) -> rusqlite::Result<T>, + P: Params, +{ + let mut stmt = match db.prepare(query) { + Ok(stmt) => stmt, + Err(e) => { + error!("Couldn't prepare get statement: {e:?}"); + return Err(e); + } + }; + + stmt.query_row(params, row_mapper).inspect_err(|e| { + error!("Couldn't read from database: {e:?}"); + }) +} + +pub fn list<F, P, T>( + db: &Connection, + query: &str, + params: P, + row_mapper: F, +) -> rusqlite::Result<Vec<T>> +where + F: FnMut(&Row<'_>) -> rusqlite::Result<T>, + P: Params, +{ + let mut stmt = match db.prepare(query) { + Ok(stmt) => stmt, + Err(e) => { + error!("Couldn't prepare list statement: {e:?}"); + return Err(e); + } + }; + + let result = stmt.query_map(params, row_mapper); + + match result { + Ok(res) => { + let records: rusqlite::Result<Vec<T>> = res.collect(); + + match records { + Ok(records) => Ok(records), + Err(e) => { + error!("Couldn't read from database: {e:?}"); + Err(e) + } + } + } + Err(rusqlite::Error::QueryReturnedNoRows) => Ok(vec![]), + Err(e) => { + error!("Couldn't read from database: {e:?}"); + Err(e) + } + } +} |