diff options
author | Teddy Wing | 2022-03-15 21:08:32 +0100 |
---|---|---|
committer | Teddy Wing | 2022-03-15 21:08:32 +0100 |
commit | daaab78f45dee52e6950e21cfd4b653cff778a11 (patch) | |
tree | 524d4d53c2e3e99b9ba82f2008b92fe047fcbff1 /src/select.rs | |
parent | 5b9fdb3b8917253242875ef30f6b13a064a224ae (diff) | |
download | yaqlite-daaab78f45dee52e6950e21cfd4b653cff778a11.tar.bz2 |
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.
Diffstat (limited to 'src/select.rs')
-rw-r--r-- | src/select.rs | 79 |
1 files changed, 68 insertions, 11 deletions
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(); + } +} |