mirror of
https://github.com/isar/rusqlite.git
synced 2024-11-26 03:11:36 +08:00
Merge pull request #530 from gwenn/query_row_named
Add query_row_named for prepared statement.
This commit is contained in:
commit
6e7d94dffd
@ -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
|
||||||
|
@ -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,14 +739,13 @@ 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",
|
.unwrap()
|
||||||
&[(":name", &"one")],
|
|
||||||
|r| r.get(0)
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user