From daaab78f45dee52e6950e21cfd4b653cff778a11 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Tue, 15 Mar 2022 21:08:32 +0100 Subject: select(): Add a test that invokes the function and prints the result It turns out the previous code failed with error: thread 'select::tests::select_extracts_a_database_record_as_yaml' panicked at 'called `Result::unwrap()` on an `Err` value: SqliteFailure(Error { code: Unknown, extended_code: 1 }, Some("near \":table\": syntax error"))', src/select.rs:11:9 Seems that I can't use named parameters to pass the table name to `FROM`. Use string formatting for that instead. Converted the named parameter array to a `rusqlite::named_params!` macro when I read about it, as that seems a bit more concise. --- src/select.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 68 insertions(+), 11 deletions(-) (limited to 'src/select.rs') diff --git a/src/select.rs b/src/select.rs index aa9389f..1e4d81b 100644 --- a/src/select.rs +++ b/src/select.rs @@ -3,19 +3,23 @@ pub fn select( table_name: &str, record_id: &str, ) -> yaml_rust::Yaml { - let mut stmt = dbconn.prepare(r#" - SELECT - x - FROM :table - WHERE :pk_column = :pk; - "#).unwrap(); + let mut stmt = dbconn.prepare( + &format!( + r#" + SELECT + * + FROM {} + WHERE :pk_column = :pk; + "#, + table_name, + ), + ).unwrap(); let rows = stmt.query_map( - &[ - (":table", table_name), - (":pk_column", "id"), - (":pk", record_id), - ], + rusqlite::named_params! { + ":pk_column": "id", + ":pk": record_id, + }, |row| { Ok(()) }, @@ -28,3 +32,56 @@ pub fn select( todo!(); } + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn select_extracts_a_database_record_as_yaml() { + struct TestRecord { + count: i16, + description: String, + } + + let record = TestRecord { + count: 99, + description: "This is a test. + +With multiple paragraphs.".to_owned(), + }; + + let conn = rusqlite::Connection::open_in_memory().unwrap(); + + conn.execute( + r#" + CREATE TABLE "test" ( + id INTEGER PRIMARY KEY, + count INTEGER, + description TEXT + ); + "#, + [] + ).unwrap(); + + { + let mut stmt = conn.prepare(r#" + INSERT INTO "test" + (count, description) + VALUES + (?, ?); + "#).unwrap(); + + stmt.insert( + rusqlite::params![record.count, record.description], + ).unwrap(); + + let got = select(&conn, "test", "1"); + + dbg!(&got); + } + + conn.close().unwrap(); + } +} -- cgit v1.2.3