From 43e1a12b5bce11b4a28a53acca243e35c2be6d3e Mon Sep 17 00:00:00 2001 From: evuez Date: Wed, 3 Apr 2024 22:43:16 +0200 Subject: Initial commit --- src/common/sqlite.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/common/sqlite.rs (limited to 'src/common/sqlite.rs') 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(db: &Connection, query: &str, params: P, row_mapper: F) -> rusqlite::Result +where + F: FnMut(&Row<'_>) -> rusqlite::Result, + 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( + db: &Connection, + query: &str, + params: P, + row_mapper: F, +) -> rusqlite::Result> +where + F: FnMut(&Row<'_>) -> rusqlite::Result, + 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> = 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) + } + } +} -- cgit v1.2.3