From bc71c583872b564c1604abb0fb07dfe58311009c Mon Sep 17 00:00:00 2001 From: gwenn Date: Thu, 14 Jul 2016 06:27:46 +0200 Subject: [PATCH 1/2] Add Statement.query_row convenient method (#179) --- src/convenient.rs | 33 +++++++++++++++++++++++++++++++-- src/lib.rs | 4 +--- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/convenient.rs b/src/convenient.rs index 22817a5..4740aa2 100644 --- a/src/convenient.rs +++ b/src/convenient.rs @@ -1,4 +1,4 @@ -use {Error, Result, Statement}; +use {Error, Result, Row, Statement}; use types::ToSql; impl<'conn> Statement<'conn> { @@ -34,11 +34,26 @@ impl<'conn> Statement<'conn> { }; 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(&mut self, params: &[&ToSql], f: F) -> Result + where F: FnOnce(&Row) -> T + { + let mut rows = try!(self.query(params)); + + rows.get_expected_row().map(|r| f(&r)) + } } #[cfg(test)] mod test { - use {Connection, Error}; + use {Connection, Error, Result}; #[test] fn test_insert() { @@ -88,4 +103,18 @@ mod test { assert!(stmt.exists(&[&2i32]).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 = stmt.query_row(&[&1i32], |r| r.get(0)); + assert_eq!(3i64, y.unwrap()); + } } diff --git a/src/lib.rs b/src/lib.rs index ed0f300..ab7a08c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -306,9 +306,7 @@ impl Connection { where F: FnOnce(&Row) -> T { let mut stmt = try!(self.prepare(sql)); - let mut rows = try!(stmt.query(params)); - - rows.get_expected_row().map(|r| f(&r)) + stmt.query_row(params, f) } /// Convenience method to execute a query that is expected to return a single row, From ff311ec29ab26072ebeb29045beaee6e2d3365b1 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sat, 31 Dec 2016 00:04:23 -0500 Subject: [PATCH 2/2] Add Statement::query_row note to Changelog. --- Changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Changelog.md b/Changelog.md index 7e1d231..10a0f3f 100644 --- a/Changelog.md +++ b/Changelog.md @@ -11,6 +11,7 @@ https://github.com/jgallagher/rusqlite/pull/184. * Added `#[deprecated(since = "...", note = "...")]` flags (new in Rust 1.9 for libraries) to 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 failing with `DatabaseBusy`; see https://github.com/jgallagher/rusqlite/issues/186.