Merge pull request #45 from jgallagher/marcusklaas-query-map

Implement `query_map`
This commit is contained in:
John Gallagher 2015-05-11 20:17:01 -04:00
commit 0ded1a5d2d
2 changed files with 91 additions and 19 deletions

View File

@ -41,14 +41,17 @@ fn main() {
&[&me.name, &me.time_created, &me.data]).unwrap();
let mut stmt = conn.prepare("SELECT id, name, time_created, data FROM person").unwrap();
for row in stmt.query(&[]).unwrap().map(|row| row.unwrap()) {
let person = Person {
let mut person_iter = stmt.query_map(&[], |row| {
Person {
id: row.get(0),
name: row.get(1),
time_created: row.get(2),
data: row.get(3)
};
println!("Found person {:?}", person);
}
}).unwrap();
for person in person_iter {
println!("Found person {:?}", person.unwrap());
}
}
```
@ -87,6 +90,11 @@ fn bad_function_will_panic(conn: &SqliteConnection) -> SqliteResult<i64> {
There are other, less obvious things that may result in a panic as well, such as calling
`collect()` on a `SqliteRows` and then trying to use the collected rows.
Strongly consider using the method `query_map()` instead, if you can.
`query_map()` returns an iterator over rows-mapped-to-some-`'static`-type. This
iterator does not have any of the above issues with panics due to attempting to
access stale rows.
## Author
John Gallagher, johnkgallagher@gmail.com

View File

@ -36,14 +36,17 @@
//! &[&me.name, &me.time_created, &me.data]).unwrap();
//!
//! let mut stmt = conn.prepare("SELECT id, name, time_created, data FROM person").unwrap();
//! for row in stmt.query(&[]).unwrap().map(|row| row.unwrap()) {
//! let person = Person {
//! let mut person_iter = stmt.query_map(&[], |row| {
//! Person {
//! id: row.get(0),
//! name: row.get(1),
//! time_created: row.get(2),
//! data: row.get(3)
//! };
//! println!("Found person {:?}", person);
//! }
//! }).unwrap();
//!
//! for person in person_iter {
//! println!("Found person {:?}", person.unwrap());
//! }
//! }
//! ```
@ -630,6 +633,38 @@ impl<'conn> SqliteStatement<'conn> {
self.reset_if_needed();
unsafe {
try!(self.bind_parameters(params));
}
Ok(SqliteRows::new(self))
}
/// Executes the prepared statement and maps a function over the resulting
/// rows.
///
/// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility
/// for accessing stale rows.
pub fn query_map<'a, T, F>(&'a mut self, params: &[&ToSql], f: F)
-> SqliteResult<MappedRows<'a, F>>
where T: 'static,
F: FnMut(SqliteRow) -> T {
let row_iter = try!(self.query(params));
Ok(MappedRows{
rows: row_iter,
map: f,
})
}
/// Consumes the statement.
///
/// Functionally equivalent to the `Drop` implementation, but allows callers to see any errors
/// that occur.
pub fn finalize(mut self) -> SqliteResult<()> {
self.finalize_()
}
unsafe fn bind_parameters(&mut self, params: &[&ToSql]) -> SqliteResult<()> {
assert!(params.len() as c_int == ffi::sqlite3_bind_parameter_count(self.stmt),
"incorrect number of parameters to query(): expected {}, got {}",
ffi::sqlite3_bind_parameter_count(self.stmt),
@ -640,16 +675,8 @@ impl<'conn> SqliteStatement<'conn> {
}
self.needs_reset = true;
Ok(SqliteRows::new(self))
}
}
/// Consumes the statement.
///
/// Functionally equivalent to the `Drop` implementation, but allows callers to see any errors
/// that occur.
pub fn finalize(mut self) -> SqliteResult<()> {
self.finalize_()
Ok(())
}
fn reset_if_needed(&mut self) {
@ -679,6 +706,22 @@ impl<'conn> Drop for SqliteStatement<'conn> {
}
}
/// An iterator over the mapped resulting rows of a query.
pub struct MappedRows<'stmt, F> {
rows: SqliteRows<'stmt>,
map: F,
}
impl<'stmt, T, F> Iterator for MappedRows<'stmt, F>
where T: 'static,
F: FnMut(SqliteRow) -> T {
type Item = SqliteResult<T>;
fn next(&mut self) -> Option<SqliteResult<T>> {
self.rows.next().map(|row_result| row_result.map(|row| (self.map)(row)))
}
}
/// An iterator over the resulting rows of a query.
///
/// ## Warning
@ -947,6 +990,27 @@ mod test {
}
}
#[test]
fn test_query_map() {
let db = checked_memory_handle();
let sql = "BEGIN;
CREATE TABLE foo(x INTEGER, y TEXT);
INSERT INTO foo VALUES(4, \"hello\");
INSERT INTO foo VALUES(3, \", \");
INSERT INTO foo VALUES(2, \"world\");
INSERT INTO foo VALUES(1, \"!\");
END;";
db.execute_batch(sql).unwrap();
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
let results: SqliteResult<Vec<String>> = query
.query_map(&[], |row| row.get(1))
.unwrap()
.collect();
assert_eq!(results.unwrap().concat(), "hello, world!");
}
#[test]
fn test_query_row() {
let db = checked_memory_handle();