Merge pull request #485 from gwenn/fix-query-row

Do not panic by default
This commit is contained in:
gwenn 2019-02-21 21:05:02 +01:00 committed by GitHub
commit a0bd73221d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 169 additions and 162 deletions

View File

@ -49,12 +49,12 @@ fn main() -> Result<()> {
let mut stmt = conn let mut stmt = conn
.prepare("SELECT id, name, time_created, data FROM person")?; .prepare("SELECT id, name, time_created, data FROM person")?;
let person_iter = stmt let person_iter = stmt
.query_map(NO_PARAMS, |row| Person { .query_map(NO_PARAMS, |row| Ok(Person {
id: row.get(0), id: row.get(0)?,
name: row.get(1), name: row.get(1)?,
time_created: row.get(2), time_created: row.get(2)?,
data: row.get(3), data: row.get(3)?,
})?; }))?;
for person in person_iter { for person in person_iter {
println!("Found person {:?}", person.unwrap()); println!("Found person {:?}", person.unwrap());

View File

@ -28,8 +28,7 @@
//! )?; //! )?;
//! //!
//! let rowid = db.last_insert_rowid(); //! let rowid = db.last_insert_rowid();
//! let mut blob = db //! let mut blob = db.blob_open(DatabaseName::Main, "test", "content", rowid, false)?;
//! .blob_open(DatabaseName::Main, "test", "content", rowid, false)?;
//! //!
//! // Make sure to test that the number of bytes written matches what you expect; //! // Make sure to test that the number of bytes written matches what you expect;
//! // if you try to write too much, the data will be truncated to the size of the //! // if you try to write too much, the data will be truncated to the size of the

View File

@ -82,7 +82,7 @@ mod test {
use std::time::Duration; use std::time::Duration;
use tempdir; use tempdir;
use crate::{Connection, Error, ErrorCode, TransactionBehavior, NO_PARAMS}; use crate::{Connection, Error, ErrorCode, Result, TransactionBehavior, NO_PARAMS};
#[test] #[test]
fn test_default_busy() { fn test_default_busy() {
@ -94,7 +94,7 @@ mod test {
.transaction_with_behavior(TransactionBehavior::Exclusive) .transaction_with_behavior(TransactionBehavior::Exclusive)
.unwrap(); .unwrap();
let db2 = Connection::open(&path).unwrap(); let db2 = Connection::open(&path).unwrap();
let r = db2.query_row("PRAGMA schema_version", NO_PARAMS, |_| unreachable!()); let r: Result<()> = db2.query_row("PRAGMA schema_version", NO_PARAMS, |_| unreachable!());
match r.unwrap_err() { match r.unwrap_err() {
Error::SqliteFailure(err, _) => { Error::SqliteFailure(err, _) => {
assert_eq!(err.code, ErrorCode::DatabaseBusy); assert_eq!(err.code, ErrorCode::DatabaseBusy);
@ -127,7 +127,7 @@ mod test {
assert_eq!(tx.recv().unwrap(), 1); assert_eq!(tx.recv().unwrap(), 1);
let _ = db2 let _ = db2
.query_row("PRAGMA schema_version", NO_PARAMS, |row| { .query_row("PRAGMA schema_version", NO_PARAMS, |row| {
row.get_checked::<_, i32>(0) row.get::<_, i32>(0)
}) })
.expect("unexpected error"); .expect("unexpected error");
@ -166,7 +166,7 @@ mod test {
assert_eq!(tx.recv().unwrap(), 1); assert_eq!(tx.recv().unwrap(), 1);
let _ = db2 let _ = db2
.query_row("PRAGMA schema_version", NO_PARAMS, |row| { .query_row("PRAGMA schema_version", NO_PARAMS, |row| {
row.get_checked::<_, i32>(0) row.get::<_, i32>(0)
}) })
.expect("unexpected error"); .expect("unexpected error");
assert_eq!(CALLED.load(Ordering::Relaxed), true); assert_eq!(CALLED.load(Ordering::Relaxed), true);

View File

@ -298,7 +298,7 @@ mod test {
let mut stmt = db.prepare_cached(sql).unwrap(); let mut stmt = db.prepare_cached(sql).unwrap();
assert_eq!( assert_eq!(
(1i32, 2i32), (1i32, 2i32),
stmt.query_map(NO_PARAMS, |r| (r.get(0), r.get(1))) stmt.query_map(NO_PARAMS, |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap() .unwrap()
.next() .next()
.unwrap() .unwrap()

View File

@ -25,12 +25,18 @@ pub enum DbConfig {
impl Connection { impl Connection {
/// Returns the current value of a `config`. /// Returns the current value of a `config`.
/// ///
/// - SQLITE_DBCONFIG_ENABLE_FKEY: return `false` or `true` to indicate whether FK enforcement is off or on /// - SQLITE_DBCONFIG_ENABLE_FKEY: return `false` or `true` to indicate
/// - SQLITE_DBCONFIG_ENABLE_TRIGGER: return `false` or `true` to indicate whether triggers are disabled or enabled /// whether FK enforcement is off or on
/// - SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: return `false` or `true` to indicate whether fts3_tokenizer are disabled or enabled /// - SQLITE_DBCONFIG_ENABLE_TRIGGER: return `false` or `true` to indicate
/// - SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: return `false` to indicate checkpoints-on-close are not disabled or `true` if they are /// whether triggers are disabled or enabled
/// - SQLITE_DBCONFIG_ENABLE_QPSG: return `false` or `true` to indicate whether the QPSG is disabled or enabled /// - SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: return `false` or `true` to
/// - SQLITE_DBCONFIG_TRIGGER_EQP: return `false` to indicate output-for-trigger are not disabled or `true` if it is /// indicate whether fts3_tokenizer are disabled or enabled
/// - SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: return `false` to indicate
/// checkpoints-on-close are not disabled or `true` if they are
/// - SQLITE_DBCONFIG_ENABLE_QPSG: return `false` or `true` to indicate
/// whether the QPSG is disabled or enabled
/// - SQLITE_DBCONFIG_TRIGGER_EQP: return `false` to indicate
/// output-for-trigger are not disabled or `true` if it is
pub fn db_config(&self, config: DbConfig) -> Result<bool> { pub fn db_config(&self, config: DbConfig) -> Result<bool> {
let c = self.db.borrow(); let c = self.db.borrow();
unsafe { unsafe {
@ -47,12 +53,18 @@ impl Connection {
/// Make configuration changes to a database connection /// Make configuration changes to a database connection
/// ///
/// - SQLITE_DBCONFIG_ENABLE_FKEY: `false` to disable FK enforcement, `true` to enable FK enforcement /// - SQLITE_DBCONFIG_ENABLE_FKEY: `false` to disable FK enforcement, `true`
/// - SQLITE_DBCONFIG_ENABLE_TRIGGER: `false` to disable triggers, `true` to enable triggers /// to enable FK enforcement
/// - SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: `false` to disable fts3_tokenizer(), `true` to enable fts3_tokenizer() /// - SQLITE_DBCONFIG_ENABLE_TRIGGER: `false` to disable triggers, `true` to
/// - SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: `false` (the default) to enable checkpoints-on-close, `true` to disable them /// enable triggers
/// - SQLITE_DBCONFIG_ENABLE_QPSG: `false` to disable the QPSG, `true` to enable QPSG /// - SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: `false` to disable
/// - SQLITE_DBCONFIG_TRIGGER_EQP: `false` to disable output for trigger programs, `true` to enable it /// fts3_tokenizer(), `true` to enable fts3_tokenizer()
/// - SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: `false` (the default) to enable
/// checkpoints-on-close, `true` to disable them
/// - SQLITE_DBCONFIG_ENABLE_QPSG: `false` to disable the QPSG, `true` to
/// enable QPSG
/// - SQLITE_DBCONFIG_TRIGGER_EQP: `false` to disable output for trigger
/// programs, `true` to enable it
pub fn set_db_config(&self, config: DbConfig, new_val: bool) -> Result<bool> { pub fn set_db_config(&self, config: DbConfig, new_val: bool) -> Result<bool> {
let c = self.db.borrow_mut(); let c = self.db.borrow_mut();
unsafe { unsafe {
@ -78,11 +90,25 @@ mod test {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();
let opposite = !db.db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY).unwrap(); let opposite = !db.db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY).unwrap();
assert_eq!(db.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, opposite), Ok(opposite)); assert_eq!(
assert_eq!(db.db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY), Ok(opposite)); db.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, opposite),
Ok(opposite)
);
assert_eq!(
db.db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY),
Ok(opposite)
);
let opposite = !db.db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER).unwrap(); let opposite = !db
assert_eq!(db.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER, opposite), Ok(opposite)); .db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER)
assert_eq!(db.db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER), Ok(opposite)); .unwrap();
assert_eq!(
db.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER, opposite),
Ok(opposite)
);
assert_eq!(
db.db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_TRIGGER),
Ok(opposite)
);
} }
} }

View File

@ -38,8 +38,7 @@
//! let db = Connection::open_in_memory()?; //! let db = Connection::open_in_memory()?;
//! add_regexp_function(&db)?; //! add_regexp_function(&db)?;
//! //!
//! let is_match: bool = db //! let is_match: bool = db.query_row(
//! .query_row(
//! "SELECT regexp('[aeiou]*', 'aaaaeeeiii')", //! "SELECT regexp('[aeiou]*', 'aaaaeeeiii')",
//! NO_PARAMS, //! NO_PARAMS,
//! |row| row.get(0), //! |row| row.get(0),
@ -771,7 +770,7 @@ mod test {
let dual_sum = "SELECT my_sum(i), my_sum(j) FROM (SELECT 2 AS i, 1 AS j UNION ALL SELECT \ let dual_sum = "SELECT my_sum(i), my_sum(j) FROM (SELECT 2 AS i, 1 AS j UNION ALL SELECT \
2, 1)"; 2, 1)";
let result: (i64, i64) = db let result: (i64, i64) = db
.query_row(dual_sum, NO_PARAMS, |r| (r.get(0), r.get(1))) .query_row(dual_sum, NO_PARAMS, |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap(); .unwrap();
assert_eq!((4, 2), result); assert_eq!((4, 2), result);
} }

View File

@ -38,14 +38,14 @@
//! params![me.name, me.time_created, me.data], //! params![me.name, me.time_created, me.data],
//! )?; //! )?;
//! //!
//! let mut stmt = conn //! let mut stmt = conn.prepare("SELECT id, name, time_created, data FROM person")?;
//! .prepare("SELECT id, name, time_created, data FROM person")?; //! let person_iter = stmt.query_map(params![], |row| {
//! let person_iter = stmt //! Ok(Person {
//! .query_map(params![], |row| Person { //! id: row.get(0)?,
//! id: row.get(0), //! name: row.get(1)?,
//! name: row.get(1), //! time_created: row.get(2)?,
//! time_created: row.get(2), //! data: row.get(3)?,
//! data: row.get(3), //! })
//! })?; //! })?;
//! //!
//! for person in person_iter { //! for person in person_iter {
@ -473,7 +473,7 @@ impl Connection {
where where
P: IntoIterator, P: IntoIterator,
P::Item: ToSql, P::Item: ToSql,
F: FnOnce(&Row<'_, '_>) -> T, F: FnOnce(&Row<'_, '_>) -> Result<T>,
{ {
let mut stmt = self.prepare(sql)?; let mut stmt = self.prepare(sql)?;
stmt.query_row(params, f) stmt.query_row(params, f)
@ -495,12 +495,12 @@ impl Connection {
/// or if the underlying SQLite call fails. /// or if the underlying SQLite call fails.
pub fn query_row_named<T, F>(&self, sql: &str, params: &[(&str, &dyn ToSql)], f: F) -> Result<T> pub fn query_row_named<T, F>(&self, sql: &str, params: &[(&str, &dyn ToSql)], f: F) -> Result<T>
where where
F: FnOnce(&Row<'_, '_>) -> 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)?; let mut rows = stmt.query_named(params)?;
rows.get_expected_row().map(|r| f(&r)) 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
@ -516,7 +516,7 @@ impl Connection {
/// conn.query_row_and_then( /// conn.query_row_and_then(
/// "SELECT value FROM preferences WHERE name='locale'", /// "SELECT value FROM preferences WHERE name='locale'",
/// NO_PARAMS, /// NO_PARAMS,
/// |row| row.get_checked(0), /// |row| row.get(0),
/// ) /// )
/// } /// }
/// ``` /// ```
@ -858,9 +858,9 @@ mod test {
let tx2 = db2.transaction().unwrap(); let tx2 = db2.transaction().unwrap();
// SELECT first makes sqlite lock with a shared lock // SELECT first makes sqlite lock with a shared lock
tx1.query_row("SELECT x FROM foo LIMIT 1", NO_PARAMS, |_| ()) tx1.query_row("SELECT x FROM foo LIMIT 1", NO_PARAMS, |_| Ok(()))
.unwrap(); .unwrap();
tx2.query_row("SELECT x FROM foo LIMIT 1", NO_PARAMS, |_| ()) tx2.query_row("SELECT x FROM foo LIMIT 1", NO_PARAMS, |_| Ok(()))
.unwrap(); .unwrap();
tx1.execute("INSERT INTO foo VALUES(?1)", &[1]).unwrap(); tx1.execute("INSERT INTO foo VALUES(?1)", &[1]).unwrap();
@ -1061,7 +1061,7 @@ mod test {
let mut v = Vec::<i32>::new(); let mut v = Vec::<i32>::new();
while let Some(row) = rows.next() { while let Some(row) = rows.next() {
v.push(row.unwrap().get(0)); v.push(row.unwrap().get(0).unwrap());
} }
assert_eq!(v, [3i32, 2, 1]); assert_eq!(v, [3i32, 2, 1]);
@ -1072,7 +1072,7 @@ mod test {
let mut v = Vec::<i32>::new(); let mut v = Vec::<i32>::new();
while let Some(row) = rows.next() { while let Some(row) = rows.next() {
v.push(row.unwrap().get(0)); v.push(row.unwrap().get(0).unwrap());
} }
assert_eq!(v, [2i32, 1]); assert_eq!(v, [2i32, 1]);
@ -1125,7 +1125,7 @@ mod test {
err => panic!("Unexpected error {}", err), err => panic!("Unexpected error {}", err),
} }
let bad_query_result = db.query_row("NOT A PROPER QUERY; test123", NO_PARAMS, |_| ()); let bad_query_result = db.query_row("NOT A PROPER QUERY; test123", NO_PARAMS, |_| Ok(()));
assert!(bad_query_result.is_err()); assert!(bad_query_result.is_err());
} }
@ -1400,7 +1400,7 @@ mod test {
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
let results: Result<Vec<String>> = query let results: Result<Vec<String>> = query
.query_and_then(NO_PARAMS, |row| row.get_checked(1)) .query_and_then(NO_PARAMS, |row| row.get(1))
.unwrap() .unwrap()
.collect(); .collect();
@ -1421,7 +1421,7 @@ mod test {
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
let bad_type: Result<Vec<f64>> = query let bad_type: Result<Vec<f64>> = query
.query_and_then(NO_PARAMS, |row| row.get_checked(1)) .query_and_then(NO_PARAMS, |row| row.get(1))
.unwrap() .unwrap()
.collect(); .collect();
@ -1431,7 +1431,7 @@ mod test {
} }
let bad_idx: Result<Vec<String>> = query let bad_idx: Result<Vec<String>> = query
.query_and_then(NO_PARAMS, |row| row.get_checked(3)) .query_and_then(NO_PARAMS, |row| row.get(3))
.unwrap() .unwrap()
.collect(); .collect();
@ -1455,9 +1455,7 @@ mod test {
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
let results: CustomResult<Vec<String>> = query let results: CustomResult<Vec<String>> = query
.query_and_then(NO_PARAMS, |row| { .query_and_then(NO_PARAMS, |row| row.get(1).map_err(CustomError::Sqlite))
row.get_checked(1).map_err(CustomError::Sqlite)
})
.unwrap() .unwrap()
.collect(); .collect();
@ -1478,9 +1476,7 @@ mod test {
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
let bad_type: CustomResult<Vec<f64>> = query let bad_type: CustomResult<Vec<f64>> = query
.query_and_then(NO_PARAMS, |row| { .query_and_then(NO_PARAMS, |row| row.get(1).map_err(CustomError::Sqlite))
row.get_checked(1).map_err(CustomError::Sqlite)
})
.unwrap() .unwrap()
.collect(); .collect();
@ -1490,9 +1486,7 @@ mod test {
} }
let bad_idx: CustomResult<Vec<String>> = query let bad_idx: CustomResult<Vec<String>> = query
.query_and_then(NO_PARAMS, |row| { .query_and_then(NO_PARAMS, |row| row.get(3).map_err(CustomError::Sqlite))
row.get_checked(3).map_err(CustomError::Sqlite)
})
.unwrap() .unwrap()
.collect(); .collect();
@ -1523,7 +1517,7 @@ mod test {
let query = "SELECT x, y FROM foo ORDER BY x DESC"; let query = "SELECT x, y FROM foo ORDER BY x DESC";
let results: CustomResult<String> = db.query_row_and_then(query, NO_PARAMS, |row| { let results: CustomResult<String> = db.query_row_and_then(query, NO_PARAMS, |row| {
row.get_checked(1).map_err(CustomError::Sqlite) row.get(1).map_err(CustomError::Sqlite)
}); });
assert_eq!(results.unwrap(), "hello"); assert_eq!(results.unwrap(), "hello");
@ -1540,7 +1534,7 @@ mod test {
let query = "SELECT x, y FROM foo ORDER BY x DESC"; let query = "SELECT x, y FROM foo ORDER BY x DESC";
let bad_type: CustomResult<f64> = db.query_row_and_then(query, NO_PARAMS, |row| { let bad_type: CustomResult<f64> = db.query_row_and_then(query, NO_PARAMS, |row| {
row.get_checked(1).map_err(CustomError::Sqlite) row.get(1).map_err(CustomError::Sqlite)
}); });
match bad_type.unwrap_err() { match bad_type.unwrap_err() {
@ -1549,7 +1543,7 @@ mod test {
} }
let bad_idx: CustomResult<String> = db.query_row_and_then(query, NO_PARAMS, |row| { let bad_idx: CustomResult<String> = db.query_row_and_then(query, NO_PARAMS, |row| {
row.get_checked(3).map_err(CustomError::Sqlite) row.get(3).map_err(CustomError::Sqlite)
}); });
match bad_idx.unwrap_err() { match bad_idx.unwrap_err() {
@ -1576,7 +1570,8 @@ mod test {
db.execute_batch(sql).unwrap(); db.execute_batch(sql).unwrap();
db.query_row("SELECT * FROM foo", params![], |r| { db.query_row("SELECT * FROM foo", params![], |r| {
assert_eq!(2, r.column_count()) assert_eq!(2, r.column_count());
Ok(())
}) })
.unwrap(); .unwrap();
} }

View File

@ -73,7 +73,7 @@ pub struct MappedRows<'stmt, F> {
impl<'stmt, T, F> MappedRows<'stmt, F> impl<'stmt, T, F> MappedRows<'stmt, F>
where where
F: FnMut(&Row<'_, '_>) -> T, F: FnMut(&Row<'_, '_>) -> Result<T>,
{ {
pub(crate) fn new(rows: Rows<'stmt>, f: F) -> MappedRows<'stmt, F> { pub(crate) fn new(rows: Rows<'stmt>, f: F) -> MappedRows<'stmt, F> {
MappedRows { rows, map: f } MappedRows { rows, map: f }
@ -82,7 +82,7 @@ where
impl<T, F> Iterator for MappedRows<'_, F> impl<T, F> Iterator for MappedRows<'_, F>
where where
F: FnMut(&Row<'_, '_>) -> T, F: FnMut(&Row<'_, '_>) -> Result<T>,
{ {
type Item = Result<T>; type Item = Result<T>;
@ -90,7 +90,7 @@ where
let map = &mut self.map; let map = &mut self.map;
self.rows self.rows
.next() .next()
.map(|row_result| row_result.map(|row| (map)(&row))) .map(|row_result| row_result.and_then(|row| (map)(&row)))
} }
} }
@ -136,16 +136,16 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
/// ///
/// ## Failure /// ## Failure
/// ///
/// Panics if calling `row.get_checked(idx)` would return an error, /// Panics if calling `row.get(idx)` would return an error,
/// including: /// including:
/// ///
/// * If the underlying SQLite column type is not a valid type as a /// * If the underlying SQLite column type is not a valid type as a source
/// source for `T` /// for `T`
/// * If the underlying SQLite integral value is outside the range /// * If the underlying SQLite integral value is outside the range
/// representable by `T` /// representable by `T`
/// * If `idx` is outside the range of columns in the returned query /// * If `idx` is outside the range of columns in the returned query
pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> T { pub fn get_unwrap<I: RowIndex, T: FromSql>(&self, idx: I) -> T {
self.get_checked(idx).unwrap() self.get(idx).unwrap()
} }
/// Get the value of a particular column of the result row. /// Get the value of a particular column of the result row.
@ -164,7 +164,7 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
/// If the result type is i128 (which requires the `i128_blob` feature to be /// If the result type is i128 (which requires the `i128_blob` feature to be
/// enabled), and the underlying SQLite column is a blob whose size is not /// enabled), and the underlying SQLite column is a blob whose size is not
/// 16 bytes, `Error::InvalidColumnType` will also be returned. /// 16 bytes, `Error::InvalidColumnType` will also be returned.
pub fn get_checked<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> { pub fn get<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
let idx = idx.idx(self.stmt)?; let idx = idx.idx(self.stmt)?;
let value = self.stmt.value_ref(idx); let value = self.stmt.value_ref(idx);
FromSql::column_result(value).map_err(|err| match err { FromSql::column_result(value).map_err(|err| match err {
@ -184,7 +184,7 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
/// This `ValueRef` is valid only as long as this Row, which is enforced by /// This `ValueRef` is valid only as long as this Row, which is enforced by
/// it's lifetime. This means that while this method is completely safe, /// it's lifetime. This means that while this method is completely safe,
/// it can be somewhat difficult to use, and most callers will be better /// it can be somewhat difficult to use, and most callers will be better
/// served by `get` or `get_checked`. /// served by `get` or `get`.
/// ///
/// ## Failure /// ## Failure
/// ///
@ -208,7 +208,7 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
/// This `ValueRef` is valid only as long as this Row, which is enforced by /// This `ValueRef` is valid only as long as this Row, which is enforced by
/// it's lifetime. This means that while this method is completely safe, /// it's lifetime. This means that while this method is completely safe,
/// it can be difficult to use, and most callers will be better served by /// it can be difficult to use, and most callers will be better served by
/// `get` or `get_checked`. /// `get` or `get`.
/// ///
/// ## Failure /// ## Failure
/// ///

View File

@ -176,7 +176,7 @@ impl Statement<'_> {
/// let mut names = Vec::new(); /// let mut names = Vec::new();
/// while let Some(result_row) = rows.next() { /// while let Some(result_row) = rows.next() {
/// let row = result_row?; /// let row = result_row?;
/// names.push(row.get(0)); /// names.push(row.get(0)?);
/// } /// }
/// ///
/// Ok(names) /// Ok(names)
@ -267,7 +267,7 @@ impl Statement<'_> {
where where
P: IntoIterator, P: IntoIterator,
P::Item: ToSql, P::Item: ToSql,
F: FnMut(&Row<'_, '_>) -> T, F: FnMut(&Row<'_, '_>) -> Result<T>,
{ {
let rows = self.query(params)?; let rows = self.query(params)?;
Ok(MappedRows::new(rows, f)) Ok(MappedRows::new(rows, f))
@ -306,7 +306,7 @@ impl Statement<'_> {
f: F, f: F,
) -> Result<MappedRows<'_, F>> ) -> Result<MappedRows<'_, F>>
where where
F: FnMut(&Row<'_, '_>) -> T, F: FnMut(&Row<'_, '_>) -> Result<T>,
{ {
let rows = self.query_named(params)?; let rows = self.query_named(params)?;
Ok(MappedRows::new(rows, f)) Ok(MappedRows::new(rows, f))
@ -354,7 +354,7 @@ impl Statement<'_> {
/// fn get_names(conn: &Connection) -> Result<Vec<Person>> { /// fn get_names(conn: &Connection) -> Result<Vec<Person>> {
/// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?; /// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
/// let rows = /// let rows =
/// stmt.query_and_then_named(&[(":id", &"one")], |row| name_to_person(row.get(0)))?; /// stmt.query_and_then_named(&[(":id", &"one")], |row| name_to_person(row.get(0)?))?;
/// ///
/// let mut persons = Vec::new(); /// let mut persons = Vec::new();
/// for person_result in rows { /// for person_result in rows {
@ -410,11 +410,11 @@ impl Statement<'_> {
where where
P: IntoIterator, P: IntoIterator,
P::Item: ToSql, P::Item: ToSql,
F: FnOnce(&Row<'_, '_>) -> T, F: FnOnce(&Row<'_, '_>) -> Result<T>,
{ {
let mut rows = self.query(params)?; let mut rows = self.query(params)?;
rows.get_expected_row().map(|r| f(&r)) rows.get_expected_row().and_then(|r| f(&r))
} }
/// Consumes the statement. /// Consumes the statement.
@ -798,8 +798,8 @@ mod test {
.unwrap(); .unwrap();
let mut rows = stmt.query_named(&[(":name", &"one")]).unwrap(); let mut rows = stmt.query_named(&[(":name", &"one")]).unwrap();
let id: i32 = rows.next().unwrap().unwrap().get(0); let id: Result<i32> = rows.next().unwrap().and_then(|row| row.get(0));
assert_eq!(1, id); assert_eq!(Ok(1), id);
} }
#[test] #[test]
@ -816,8 +816,8 @@ mod test {
.unwrap(); .unwrap();
let mut rows = stmt let mut rows = stmt
.query_map_named(&[(":name", &"one")], |row| { .query_map_named(&[(":name", &"one")], |row| {
let id: i32 = row.get(0); let id: Result<i32> = row.get(0);
2 * id id.map(|i| 2 * i)
}) })
.unwrap(); .unwrap();
@ -840,7 +840,7 @@ mod test {
.unwrap(); .unwrap();
let mut rows = stmt let mut rows = stmt
.query_and_then_named(&[(":name", &"one")], |row| { .query_and_then_named(&[(":name", &"one")], |row| {
let id: i32 = row.get(0); let id: i32 = row.get(0)?;
if id == 1 { if id == 1 {
Ok(id) Ok(id)
} else { } else {

View File

@ -140,13 +140,13 @@ mod test {
let mut db = Connection::open_in_memory().unwrap(); let mut db = Connection::open_in_memory().unwrap();
db.trace(Some(tracer)); db.trace(Some(tracer));
{ {
let _ = db.query_row("SELECT ?", &[1i32], |_| {}); let _ = db.query_row("SELECT ?", &[1i32], |_| Ok(()));
let _ = db.query_row("SELECT ?", &["hello"], |_| {}); let _ = db.query_row("SELECT ?", &["hello"], |_| Ok(()));
} }
db.trace(None); db.trace(None);
{ {
let _ = db.query_row("SELECT ?", &[2i32], |_| {}); let _ = db.query_row("SELECT ?", &[2i32], |_| Ok(()));
let _ = db.query_row("SELECT ?", &["goodbye"], |_| {}); let _ = db.query_row("SELECT ?", &["goodbye"], |_| Ok(()));
} }
let traced_stmts = TRACED_STMTS.lock().unwrap(); let traced_stmts = TRACED_STMTS.lock().unwrap();

View File

@ -210,8 +210,7 @@ mod test {
{ {
for n in out_of_range { for n in out_of_range {
let err = db let err = db
.query_row("SELECT ?", &[n], |r| r.get_checked::<_, T>(0)) .query_row("SELECT ?", &[n], |r| r.get::<_, T>(0))
.unwrap()
.unwrap_err(); .unwrap_err();
match err { match err {
Error::IntegralValueOutOfRange(_, value) => assert_eq!(*n, value), Error::IntegralValueOutOfRange(_, value) => assert_eq!(*n, value),

View File

@ -207,16 +207,16 @@ mod test {
{ {
let row1 = rows.next().unwrap().unwrap(); let row1 = rows.next().unwrap().unwrap();
let s1: Option<String> = row1.get(0); let s1: Option<String> = row1.get_unwrap(0);
let b1: Option<Vec<u8>> = row1.get(1); let b1: Option<Vec<u8>> = row1.get_unwrap(1);
assert_eq!(s.unwrap(), s1.unwrap()); assert_eq!(s.unwrap(), s1.unwrap());
assert!(b1.is_none()); assert!(b1.is_none());
} }
{ {
let row2 = rows.next().unwrap().unwrap(); let row2 = rows.next().unwrap().unwrap();
let s2: Option<String> = row2.get(0); let s2: Option<String> = row2.get_unwrap(0);
let b2: Option<Vec<u8>> = row2.get(1); let b2: Option<Vec<u8>> = row2.get_unwrap(1);
assert!(s2.is_none()); assert!(s2.is_none());
assert_eq!(b, b2); assert_eq!(b, b2);
} }
@ -246,102 +246,94 @@ mod test {
let row = rows.next().unwrap().unwrap(); let row = rows.next().unwrap().unwrap();
// check the correct types come back as expected // check the correct types come back as expected
assert_eq!(vec![1, 2], row.get_checked::<_, Vec<u8>>(0).unwrap()); assert_eq!(vec![1, 2], row.get::<_, Vec<u8>>(0).unwrap());
assert_eq!("text", row.get_checked::<_, String>(1).unwrap()); assert_eq!("text", row.get::<_, String>(1).unwrap());
assert_eq!(1, row.get_checked::<_, c_int>(2).unwrap()); assert_eq!(1, row.get::<_, c_int>(2).unwrap());
assert!((1.5 - row.get_checked::<_, c_double>(3).unwrap()).abs() < EPSILON); assert!((1.5 - row.get::<_, c_double>(3).unwrap()).abs() < EPSILON);
assert!(row.get_checked::<_, Option<c_int>>(4).unwrap().is_none()); assert!(row.get::<_, Option<c_int>>(4).unwrap().is_none());
assert!(row.get_checked::<_, Option<c_double>>(4).unwrap().is_none()); assert!(row.get::<_, Option<c_double>>(4).unwrap().is_none());
assert!(row.get_checked::<_, Option<String>>(4).unwrap().is_none()); assert!(row.get::<_, Option<String>>(4).unwrap().is_none());
// check some invalid types // check some invalid types
// 0 is actually a blob (Vec<u8>) // 0 is actually a blob (Vec<u8>)
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_int>(0).err().unwrap() row.get::<_, c_int>(0).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_int>(0).err().unwrap() row.get::<_, c_int>(0).err().unwrap()
));
assert!(is_invalid_column_type(row.get::<_, i64>(0).err().unwrap()));
assert!(is_invalid_column_type(
row.get::<_, c_double>(0).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, i64>(0).err().unwrap() row.get::<_, String>(0).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_double>(0).err().unwrap() row.get::<_, time::Timespec>(0).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, String>(0).err().unwrap() row.get::<_, Option<c_int>>(0).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, time::Timespec>(0).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, Option<c_int>>(0).err().unwrap()
)); ));
// 1 is actually a text (String) // 1 is actually a text (String)
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_int>(1).err().unwrap() row.get::<_, c_int>(1).err().unwrap()
));
assert!(is_invalid_column_type(row.get::<_, i64>(1).err().unwrap()));
assert!(is_invalid_column_type(
row.get::<_, c_double>(1).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, i64>(1).err().unwrap() row.get::<_, Vec<u8>>(1).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_double>(1).err().unwrap() row.get::<_, Option<c_int>>(1).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, Vec<u8>>(1).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, Option<c_int>>(1).err().unwrap()
)); ));
// 2 is actually an integer // 2 is actually an integer
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, String>(2).err().unwrap() row.get::<_, String>(2).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, Vec<u8>>(2).err().unwrap() row.get::<_, Vec<u8>>(2).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, Option<String>>(2).err().unwrap() row.get::<_, Option<String>>(2).err().unwrap()
)); ));
// 3 is actually a float (c_double) // 3 is actually a float (c_double)
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_int>(3).err().unwrap() row.get::<_, c_int>(3).err().unwrap()
));
assert!(is_invalid_column_type(row.get::<_, i64>(3).err().unwrap()));
assert!(is_invalid_column_type(
row.get::<_, String>(3).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, i64>(3).err().unwrap() row.get::<_, Vec<u8>>(3).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, String>(3).err().unwrap() row.get::<_, Option<c_int>>(3).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, Vec<u8>>(3).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, Option<c_int>>(3).err().unwrap()
)); ));
// 4 is actually NULL // 4 is actually NULL
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_int>(4).err().unwrap() row.get::<_, c_int>(4).err().unwrap()
));
assert!(is_invalid_column_type(row.get::<_, i64>(4).err().unwrap()));
assert!(is_invalid_column_type(
row.get::<_, c_double>(4).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, i64>(4).err().unwrap() row.get::<_, String>(4).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, c_double>(4).err().unwrap() row.get::<_, Vec<u8>>(4).err().unwrap()
)); ));
assert!(is_invalid_column_type( assert!(is_invalid_column_type(
row.get_checked::<_, String>(4).err().unwrap() row.get::<_, time::Timespec>(4).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, Vec<u8>>(4).err().unwrap()
));
assert!(is_invalid_column_type(
row.get_checked::<_, time::Timespec>(4).err().unwrap()
)); ));
} }
@ -360,19 +352,16 @@ mod test {
let mut rows = stmt.query(NO_PARAMS).unwrap(); let mut rows = stmt.query(NO_PARAMS).unwrap();
let row = rows.next().unwrap().unwrap(); let row = rows.next().unwrap().unwrap();
assert_eq!( assert_eq!(Value::Blob(vec![1, 2]), row.get::<_, Value>(0).unwrap());
Value::Blob(vec![1, 2]),
row.get_checked::<_, Value>(0).unwrap()
);
assert_eq!( assert_eq!(
Value::Text(String::from("text")), Value::Text(String::from("text")),
row.get_checked::<_, Value>(1).unwrap() row.get::<_, Value>(1).unwrap()
); );
assert_eq!(Value::Integer(1), row.get_checked::<_, Value>(2).unwrap()); assert_eq!(Value::Integer(1), row.get::<_, Value>(2).unwrap());
match row.get_checked::<_, Value>(3).unwrap() { match row.get::<_, Value>(3).unwrap() {
Value::Real(val) => assert!((1.5 - val).abs() < EPSILON), Value::Real(val) => assert!((1.5 - val).abs() < EPSILON),
x => panic!("Invalid Value {:?}", x), x => panic!("Invalid Value {:?}", x),
} }
assert_eq!(Value::Null, row.get_checked::<_, Value>(4).unwrap()); assert_eq!(Value::Null, row.get::<_, Value>(4).unwrap());
} }
} }

View File

@ -229,7 +229,7 @@ mod test {
let res = stmt let res = stmt
.query_map(NO_PARAMS, |row| { .query_map(NO_PARAMS, |row| {
(row.get::<_, i128>(0), row.get::<_, String>(1)) Ok((row.get::<_, i128>(0)?, row.get::<_, String>(1)?))
}) })
.unwrap() .unwrap()
.collect::<Result<Vec<_>, _>>() .collect::<Result<Vec<_>, _>>()

View File

@ -389,7 +389,7 @@ mod test {
let mut rows = s.query(NO_PARAMS).unwrap(); let mut rows = s.query(NO_PARAMS).unwrap();
let row = rows.next().unwrap().unwrap(); let row = rows.next().unwrap().unwrap();
assert_eq!(row.get::<_, i32>(0), 2); assert_eq!(row.get_unwrap::<_, i32>(0), 2);
} }
db.execute_batch("DROP TABLE vtab").unwrap(); db.execute_batch("DROP TABLE vtab").unwrap();
} }