diff options
author | evuez <julien@mulga.net> | 2024-04-03 22:43:16 +0200 |
---|---|---|
committer | evuez <julien@mulga.net> | 2024-04-03 22:43:16 +0200 |
commit | 43e1a12b5bce11b4a28a53acca243e35c2be6d3e (patch) | |
tree | 07d64823718bfee063ab7b3d5721ac1e950ae17c /src/common/sqlite.rs | |
download | carton-43e1a12b5bce11b4a28a53acca243e35c2be6d3e.tar.gz |
Initial commit
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) + } + } +} |