Merge pull request #195 from jgallagher/gwenn-query-row

Add Statement.query_row convenient method
This commit is contained in:
John Gallagher 2016-12-31 00:11:41 -05:00 committed by GitHub
commit 2b437cb1ee
3 changed files with 33 additions and 5 deletions

View File

@ -11,6 +11,7 @@
https://github.com/jgallagher/rusqlite/pull/184. https://github.com/jgallagher/rusqlite/pull/184.
* Added `#[deprecated(since = "...", note = "...")]` flags (new in Rust 1.9 for libraries) to * Added `#[deprecated(since = "...", note = "...")]` flags (new in Rust 1.9 for libraries) to
all deprecated APIs. all deprecated APIs.
* Added `query_row` convenience function to `Statement`.
* Fixed a bug where using cached prepared statements resulted in attempting to close a connection * Fixed a bug where using cached prepared statements resulted in attempting to close a connection
failing with `DatabaseBusy`; see https://github.com/jgallagher/rusqlite/issues/186. failing with `DatabaseBusy`; see https://github.com/jgallagher/rusqlite/issues/186.

View File

@ -1,4 +1,4 @@
use {Error, Result, Statement}; use {Error, Result, Row, Statement};
use types::ToSql; use types::ToSql;
impl<'conn> Statement<'conn> { impl<'conn> Statement<'conn> {
@ -34,11 +34,26 @@ impl<'conn> Statement<'conn> {
}; };
Ok(exists) Ok(exists)
} }
/// Convenience method to execute a query that is expected to return a single row.
///
/// If the query returns more than one row, all rows except the first are ignored.
///
/// # Failure
///
/// Will return `Err` if the underlying SQLite call fails.
pub fn query_row<T, F>(&mut self, params: &[&ToSql], f: F) -> Result<T>
where F: FnOnce(&Row) -> T
{
let mut rows = try!(self.query(params));
rows.get_expected_row().map(|r| f(&r))
}
} }
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use {Connection, Error}; use {Connection, Error, Result};
#[test] #[test]
fn test_insert() { fn test_insert() {
@ -88,4 +103,18 @@ mod test {
assert!(stmt.exists(&[&2i32]).unwrap()); assert!(stmt.exists(&[&2i32]).unwrap());
assert!(!stmt.exists(&[&0i32]).unwrap()); assert!(!stmt.exists(&[&0i32]).unwrap());
} }
#[test]
fn test_query_row() {
let db = Connection::open_in_memory().unwrap();
let sql = "BEGIN;
CREATE TABLE foo(x INTEGER, y INTEGER);
INSERT INTO foo VALUES(1, 3);
INSERT INTO foo VALUES(2, 4);
END;";
db.execute_batch(sql).unwrap();
let mut stmt = db.prepare("SELECT y FROM foo WHERE x = ?").unwrap();
let y: Result<i64> = stmt.query_row(&[&1i32], |r| r.get(0));
assert_eq!(3i64, y.unwrap());
}
} }

View File

@ -306,9 +306,7 @@ impl Connection {
where F: FnOnce(&Row) -> T where F: FnOnce(&Row) -> T
{ {
let mut stmt = try!(self.prepare(sql)); let mut stmt = try!(self.prepare(sql));
let mut rows = try!(stmt.query(params)); stmt.query_row(params, f)
rows.get_expected_row().map(|r| f(&r))
} }
/// Convenience method to execute a query that is expected to return a single row, /// Convenience method to execute a query that is expected to return a single row,