From 031bffffa59acb13d4a221ff23577366161092d6 Mon Sep 17 00:00:00 2001 From: gwenn Date: Wed, 12 Jun 2019 19:18:57 +0200 Subject: [PATCH] Add query_row_named for prepared statement. --- src/lib.rs | 4 +--- src/statement.rs | 34 ++++++++++++++++++++++++++++------ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 250635e..7fd98f3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -537,9 +537,7 @@ impl Connection { F: FnOnce(&Row<'_>) -> Result, { let mut stmt = self.prepare(sql)?; - let mut rows = stmt.query_named(params)?; - - rows.get_expected_row().and_then(|r| f(&r)) + stmt.query_row_named(params, f) } /// Convenience method to execute a query that is expected to return a diff --git a/src/statement.rs b/src/statement.rs index c8f0293..d3be4c4 100644 --- a/src/statement.rs +++ b/src/statement.rs @@ -378,6 +378,29 @@ impl Statement<'_> { rows.get_expected_row().and_then(|r| f(&r)) } + /// Convenience method to execute a query with named parameter(s) that is + /// expected to return a single row. + /// + /// If the query returns more than one row, all rows except the first are + /// ignored. + /// + /// Returns `Err(QueryReturnedNoRows)` if no results are returned. If the + /// query truly is optional, you can call `.optional()` on the result of + /// this to get a `Result>`. + /// + /// # Failure + /// + /// Will return `Err` if `sql` cannot be converted to a C-compatible string + /// or if the underlying SQLite call fails. + pub fn query_row_named(&mut self, params: &[(&str, &dyn ToSql)], f: F) -> Result + where + F: FnOnce(&Row<'_>) -> Result, + { + let mut rows = self.query_named(params)?; + + rows.get_expected_row().and_then(|r| f(&r)) + } + /// Consumes the statement. /// /// Functionally equivalent to the `Drop` implementation, but allows @@ -716,14 +739,13 @@ mod test { .unwrap(); stmt.execute_named(&[(":name", &"one")]).unwrap(); + let mut stmt = db + .prepare("SELECT COUNT(*) FROM test WHERE name = :name") + .unwrap(); assert_eq!( 1i32, - db.query_row_named::( - "SELECT COUNT(*) FROM test WHERE name = :name", - &[(":name", &"one")], - |r| r.get(0) - ) - .unwrap() + stmt.query_row_named::(&[(":name", &"one")], |r| r.get(0)) + .unwrap() ); }