Add query_row_named for prepared statement.

This commit is contained in:
gwenn 2019-06-12 19:18:57 +02:00
parent ec319b32bb
commit 031bffffa5
2 changed files with 29 additions and 9 deletions

View File

@ -537,9 +537,7 @@ impl Connection {
F: FnOnce(&Row<'_>) -> Result<T>, F: FnOnce(&Row<'_>) -> Result<T>,
{ {
let mut stmt = self.prepare(sql)?; let mut stmt = self.prepare(sql)?;
let mut rows = stmt.query_named(params)?; stmt.query_row_named(params, f)
rows.get_expected_row().and_then(|r| f(&r))
} }
/// Convenience method to execute a query that is expected to return a /// Convenience method to execute a query that is expected to return a

View File

@ -378,6 +378,29 @@ impl Statement<'_> {
rows.get_expected_row().and_then(|r| f(&r)) 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<Option<T>>`.
///
/// # 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<T, F>(&mut self, params: &[(&str, &dyn ToSql)], f: F) -> Result<T>
where
F: FnOnce(&Row<'_>) -> Result<T>,
{
let mut rows = self.query_named(params)?;
rows.get_expected_row().and_then(|r| f(&r))
}
/// Consumes the statement. /// Consumes the statement.
/// ///
/// Functionally equivalent to the `Drop` implementation, but allows /// Functionally equivalent to the `Drop` implementation, but allows
@ -716,13 +739,12 @@ mod test {
.unwrap(); .unwrap();
stmt.execute_named(&[(":name", &"one")]).unwrap(); stmt.execute_named(&[(":name", &"one")]).unwrap();
let mut stmt = db
.prepare("SELECT COUNT(*) FROM test WHERE name = :name")
.unwrap();
assert_eq!( assert_eq!(
1i32, 1i32,
db.query_row_named::<i32, _>( stmt.query_row_named::<i32, _>(&[(":name", &"one")], |r| r.get(0))
"SELECT COUNT(*) FROM test WHERE name = :name",
&[(":name", &"one")],
|r| r.get(0)
)
.unwrap() .unwrap()
); );
} }