diff --git a/src/backup.rs b/src/backup.rs index 16f6561..6ea4502 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -309,7 +309,7 @@ impl<'a, 'b> Drop for Backup<'a, 'b> { mod test { use super::Backup; use std::time::Duration; - use {Connection, DatabaseName}; + use {Connection, DatabaseName, NO_PARAMS}; #[test] fn test_backup() { @@ -328,7 +328,7 @@ mod test { } let the_answer: i64 = dst - .query_row("SELECT x FROM foo", &[], |r| r.get(0)) + .query_row("SELECT x FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(42, the_answer); @@ -342,7 +342,7 @@ mod test { } let the_answer: i64 = dst - .query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + .query_row("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(42 + 43, the_answer); } @@ -366,7 +366,7 @@ mod test { } let the_answer: i64 = dst - .query_row("SELECT x FROM foo", &[], |r| r.get(0)) + .query_row("SELECT x FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(42, the_answer); @@ -382,7 +382,7 @@ mod test { } let the_answer: i64 = dst - .query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + .query_row("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(42 + 43, the_answer); } @@ -410,7 +410,7 @@ mod test { } let the_answer: i64 = dst - .query_row("SELECT x FROM foo", &[], |r| r.get(0)) + .query_row("SELECT x FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(42, the_answer); @@ -429,7 +429,7 @@ mod test { } let the_answer: i64 = dst - .query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + .query_row("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(42 + 43, the_answer); } diff --git a/src/blob.rs b/src/blob.rs index c44211a..ef80546 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -18,15 +18,17 @@ //! extern crate rusqlite; //! //! use rusqlite::blob::ZeroBlob; -//! use rusqlite::{Connection, DatabaseName}; +//! use rusqlite::{Connection, DatabaseName, NO_PARAMS}; //! use std::io::{Read, Seek, SeekFrom, Write}; //! //! fn main() { //! let db = Connection::open_in_memory().unwrap(); //! db.execute_batch("CREATE TABLE test (content BLOB);") //! .unwrap(); -//! db.execute("INSERT INTO test (content) VALUES (ZEROBLOB(10))", &[]) -//! .unwrap(); +//! db.execute( +//! "INSERT INTO test (content) VALUES (ZEROBLOB(10))", +//! NO_PARAMS, +//! ).unwrap(); //! //! let rowid = db.last_insert_rowid(); //! let mut blob = db @@ -44,7 +46,7 @@ //! let bytes_read = blob.read(&mut buf[..]).unwrap(); //! assert_eq!(bytes_read, 10); // note we read 10 bytes because the blob has size 10 //! -//! db.execute("INSERT INTO test (content) VALUES (?)", &[&ZeroBlob(64)]) +//! db.execute("INSERT INTO test (content) VALUES (?)", &[ZeroBlob(64)]) //! .unwrap(); //! //! // given a new row ID, we can reopen the blob on that row diff --git a/src/busy.rs b/src/busy.rs index 6156caf..2d15bbf 100644 --- a/src/busy.rs +++ b/src/busy.rs @@ -14,7 +14,7 @@ impl Connection { /// /// Calling this routine with an argument equal to zero turns off all busy /// handlers. - // + /// /// There can only be a single busy handler for a particular database /// connection at any given moment. If another busy handler was defined /// (using `busy_handler`) prior to calling this routine, that other @@ -81,7 +81,7 @@ mod test { use std::thread; use std::time::Duration; - use {Connection, Error, ErrorCode, TransactionBehavior}; + use {Connection, Error, ErrorCode, TransactionBehavior, NO_PARAMS}; #[test] fn test_default_busy() { @@ -93,7 +93,7 @@ mod test { .transaction_with_behavior(TransactionBehavior::Exclusive) .unwrap(); let db2 = Connection::open(&path).unwrap(); - let r = db2.query_row("PRAGMA schema_version", &[], |_| unreachable!()); + let r = db2.query_row("PRAGMA schema_version", NO_PARAMS, |_| unreachable!()); match r.unwrap_err() { Error::SqliteFailure(err, _) => { assert_eq!(err.code, ErrorCode::DatabaseBusy); @@ -125,7 +125,7 @@ mod test { assert_eq!(tx.recv().unwrap(), 1); let _ = db2 - .query_row("PRAGMA schema_version", &[], |row| { + .query_row("PRAGMA schema_version", NO_PARAMS, |row| { row.get_checked::<_, i32>(0) }).expect("unexpected error"); @@ -163,7 +163,7 @@ mod test { assert_eq!(tx.recv().unwrap(), 1); let _ = db2 - .query_row("PRAGMA schema_version", &[], |row| { + .query_row("PRAGMA schema_version", NO_PARAMS, |row| { row.get_checked::<_, i32>(0) }).expect("unexpected error"); assert_eq!(CALLED.load(Ordering::Relaxed), true); diff --git a/src/cache.rs b/src/cache.rs index bd31b39..46e4331 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -17,13 +17,13 @@ impl Connection { /// fn insert_new_people(conn: &Connection) -> Result<()> { /// { /// let mut stmt = try!(conn.prepare_cached("INSERT INTO People (name) VALUES (?)")); - /// try!(stmt.execute(&[&"Joe Smith"])); + /// try!(stmt.execute(&["Joe Smith"])); /// } /// { /// // This will return the same underlying SQLite statement handle without /// // having to prepare it again. /// let mut stmt = try!(conn.prepare_cached("INSERT INTO People (name) VALUES (?)")); - /// try!(stmt.execute(&[&"Bob Jones"])); + /// try!(stmt.execute(&["Bob Jones"])); /// } /// Ok(()) /// } @@ -152,7 +152,7 @@ impl StatementCache { #[cfg(test)] mod test { use super::StatementCache; - use Connection; + use {Connection, NO_PARAMS}; impl StatementCache { fn clear(&self) { @@ -180,14 +180,20 @@ mod test { { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); } assert_eq!(1, cache.len()); { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); } assert_eq!(1, cache.len()); @@ -205,7 +211,10 @@ mod test { { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); } assert_eq!(1, cache.len()); @@ -215,7 +224,10 @@ mod test { { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); } assert_eq!(0, cache.len()); @@ -223,7 +235,10 @@ mod test { { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); } assert_eq!(1, cache.len()); } @@ -237,7 +252,10 @@ mod test { { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); stmt.discard(); } assert_eq!(0, cache.len()); @@ -259,7 +277,7 @@ mod test { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!( 1i32, - stmt.query_map::(&[], |r| r.get(0)) + stmt.query_map::(NO_PARAMS, |r| r.get(0)) .unwrap() .next() .unwrap() @@ -278,7 +296,7 @@ mod test { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!( (1i32, 2i32), - stmt.query_map(&[], |r| (r.get(0), r.get(1))) + stmt.query_map(NO_PARAMS, |r| (r.get(0), r.get(1))) .unwrap() .next() .unwrap() @@ -306,14 +324,20 @@ mod test { { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); } assert_eq!(1, cache.len()); { let mut stmt = db.prepare_cached(sql).unwrap(); assert_eq!(0, cache.len()); - assert_eq!(0, stmt.query_row(&[], |r| r.get::<_, i64>(0)).unwrap()); + assert_eq!( + 0, + stmt.query_row(NO_PARAMS, |r| r.get::<_, i64>(0)).unwrap() + ); } assert_eq!(1, cache.len()); } diff --git a/src/functions.rs b/src/functions.rs index 7137c0d..92cee25 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -14,7 +14,7 @@ //! extern crate regex; //! //! use regex::Regex; -//! use rusqlite::{Connection, Error, Result}; +//! use rusqlite::{Connection, Error, Result, NO_PARAMS}; //! use std::collections::HashMap; //! //! fn add_regexp_function(db: &Connection) -> Result<()> { @@ -43,9 +43,11 @@ //! add_regexp_function(&db).unwrap(); //! //! let is_match: bool = db -//! .query_row("SELECT regexp('[aeiou]*', 'aaaaeeeiii')", &[], |row| { -//! row.get(0) -//! }).unwrap(); +//! .query_row( +//! "SELECT regexp('[aeiou]*', 'aaaaeeeiii')", +//! NO_PARAMS, +//! |row| row.get(0), +//! ).unwrap(); //! //! assert!(is_match); //! } @@ -209,14 +211,14 @@ impl Connection { /// # Example /// /// ```rust - /// # use rusqlite::{Connection, Result}; + /// # use rusqlite::{Connection, Result, NO_PARAMS}; /// fn scalar_function_example(db: Connection) -> Result<()> { /// try!(db.create_scalar_function("halve", 1, true, |ctx| { /// let value = try!(ctx.get::(0)); /// Ok(value / 2f64) /// })); /// - /// let six_halved: f64 = try!(db.query_row("SELECT halve(6)", &[], |r| r.get(0))); + /// let six_halved: f64 = try!(db.query_row("SELECT halve(6)", NO_PARAMS, |r| r.get(0))); /// assert_eq!(six_halved, 3f64); /// Ok(()) /// } @@ -478,7 +480,7 @@ mod test { use std::os::raw::c_double; use functions::{Aggregate, Context}; - use {Connection, Error, Result}; + use {Connection, Error, Result, NO_PARAMS}; fn half(ctx: &Context) -> Result { assert!(ctx.len() == 1, "called with unexpected number of arguments"); @@ -490,7 +492,7 @@ mod test { fn test_function_half() { let db = Connection::open_in_memory().unwrap(); db.create_scalar_function("half", 1, true, half).unwrap(); - let result: Result = db.query_row("SELECT half(6)", &[], |r| r.get(0)); + let result: Result = db.query_row("SELECT half(6)", NO_PARAMS, |r| r.get(0)); assert!((3f64 - result.unwrap()).abs() < EPSILON); } @@ -499,11 +501,11 @@ mod test { fn test_remove_function() { let db = Connection::open_in_memory().unwrap(); db.create_scalar_function("half", 1, true, half).unwrap(); - let result: Result = db.query_row("SELECT half(6)", &[], |r| r.get(0)); + let result: Result = db.query_row("SELECT half(6)", NO_PARAMS, |r| r.get(0)); assert!((3f64 - result.unwrap()).abs() < EPSILON); db.remove_function("half", 1).unwrap(); - let result: Result = db.query_row("SELECT half(6)", &[], |r| r.get(0)); + let result: Result = db.query_row("SELECT half(6)", NO_PARAMS, |r| r.get(0)); assert!(result.is_err()); } @@ -554,13 +556,15 @@ mod test { .unwrap(); let result: Result = - db.query_row("SELECT regexp('l.s[aeiouy]', 'lisa')", &[], |r| r.get(0)); + db.query_row("SELECT regexp('l.s[aeiouy]', 'lisa')", NO_PARAMS, |r| { + r.get(0) + }); assert_eq!(true, result.unwrap()); let result: Result = db.query_row( "SELECT COUNT(*) FROM foo WHERE regexp('l.s[aeiouy]', x) == 1", - &[], + NO_PARAMS, |r| r.get(0), ); @@ -604,13 +608,15 @@ mod test { }).unwrap(); let result: Result = - db.query_row("SELECT regexp('l.s[aeiouy]', 'lisa')", &[], |r| r.get(0)); + db.query_row("SELECT regexp('l.s[aeiouy]', 'lisa')", NO_PARAMS, |r| { + r.get(0) + }); assert_eq!(true, result.unwrap()); let result: Result = db.query_row( "SELECT COUNT(*) FROM foo WHERE regexp('l.s[aeiouy]', x) == 1", - &[], + NO_PARAMS, |r| r.get(0), ); @@ -636,7 +642,7 @@ mod test { ("onetwo", "SELECT my_concat('one', 'two')"), ("abc", "SELECT my_concat('a', 'b', 'c')"), ] { - let result: String = db.query_row(query, &[], |r| r.get(0)).unwrap(); + let result: String = db.query_row(query, NO_PARAMS, |r| r.get(0)).unwrap(); assert_eq!(expected, result); } } @@ -682,17 +688,17 @@ mod test { // sum should return NULL when given no columns (contrast with count below) let no_result = "SELECT my_sum(i) FROM (SELECT 2 AS i WHERE 1 <> 1)"; - let result: Option = db.query_row(no_result, &[], |r| r.get(0)).unwrap(); + let result: Option = db.query_row(no_result, NO_PARAMS, |r| r.get(0)).unwrap(); assert!(result.is_none()); let single_sum = "SELECT my_sum(i) FROM (SELECT 2 AS i UNION ALL SELECT 2)"; - let result: i64 = db.query_row(single_sum, &[], |r| r.get(0)).unwrap(); + let result: i64 = db.query_row(single_sum, NO_PARAMS, |r| r.get(0)).unwrap(); assert_eq!(4, result); let dual_sum = "SELECT my_sum(i), my_sum(j) FROM (SELECT 2 AS i, 1 AS j UNION ALL SELECT \ 2, 1)"; let result: (i64, i64) = db - .query_row(dual_sum, &[], |r| (r.get(0), r.get(1))) + .query_row(dual_sum, NO_PARAMS, |r| (r.get(0), r.get(1))) .unwrap(); assert_eq!((4, 2), result); } @@ -705,11 +711,11 @@ mod test { // count should return 0 when given no columns (contrast with sum above) let no_result = "SELECT my_count(i) FROM (SELECT 2 AS i WHERE 1 <> 1)"; - let result: i64 = db.query_row(no_result, &[], |r| r.get(0)).unwrap(); + let result: i64 = db.query_row(no_result, NO_PARAMS, |r| r.get(0)).unwrap(); assert_eq!(result, 0); let single_sum = "SELECT my_count(i) FROM (SELECT 2 AS i UNION ALL SELECT 2)"; - let result: i64 = db.query_row(single_sum, &[], |r| r.get(0)).unwrap(); + let result: i64 = db.query_row(single_sum, NO_PARAMS, |r| r.get(0)).unwrap(); assert_eq!(2, result); } } diff --git a/src/lib.rs b/src/lib.rs index d23d86b..d44a823 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,7 +5,8 @@ //! extern crate rusqlite; //! extern crate time; //! -//! use rusqlite::Connection; +//! use rusqlite::types::ToSql; +//! use rusqlite::{Connection, NO_PARAMS}; //! use time::Timespec; //! //! #[derive(Debug)] @@ -26,7 +27,7 @@ //! time_created TEXT NOT NULL, //! data BLOB //! )", -//! &[], +//! NO_PARAMS, //! ).unwrap(); //! let me = Person { //! id: 0, @@ -37,14 +38,14 @@ //! conn.execute( //! "INSERT INTO person (name, time_created, data) //! VALUES (?1, ?2, ?3)", -//! &[&me.name, &me.time_created, &me.data], +//! &[&me.name as &ToSql, &me.time_created, &me.data], //! ).unwrap(); //! //! let mut stmt = conn //! .prepare("SELECT id, name, time_created, data FROM person") //! .unwrap(); //! let person_iter = stmt -//! .query_map(&[], |row| Person { +//! .query_map(NO_PARAMS, |row| Person { //! id: row.get(0), //! name: row.get(1), //! time_created: row.get(2), @@ -139,6 +140,8 @@ pub mod vtab; // Number of cached prepared statements we'll hold on to. const STATEMENT_CACHE_DEFAULT_CAPACITY: usize = 16; +/// To be used when your statement has no [parameter](https://sqlite.org/lang_expr.html#varparam). +pub const NO_PARAMS: &'static [&'static ToSql] = &[]; /// Old name for `Result`. `SqliteResult` is deprecated. #[deprecated(since = "0.6.0", note = "Use Result instead")] @@ -306,7 +309,7 @@ impl Connection { /// ```rust,no_run /// # use rusqlite::{Connection}; /// fn update_rows(conn: &Connection) { - /// match conn.execute("UPDATE foo SET bar = 'baz' WHERE qux = ?", &[&1i32]) { + /// match conn.execute("UPDATE foo SET bar = 'baz' WHERE qux = ?", &[1i32]) { /// Ok(updated) => println!("{} rows were updated", updated), /// Err(err) => println!("update failed: {}", err), /// } @@ -317,7 +320,11 @@ impl Connection { /// /// Will return `Err` if `sql` cannot be converted to a C-compatible string /// or if the underlying SQLite call fails. - pub fn execute(&self, sql: &str, params: &[&ToSql]) -> Result { + pub fn execute

(&self, sql: &str, params: P) -> Result + where + P: IntoIterator, + P::Item: ToSql, + { self.prepare(sql).and_then(|mut stmt| stmt.execute(params)) } @@ -362,11 +369,11 @@ impl Connection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{Result,Connection}; + /// # use rusqlite::{Result,Connection, NO_PARAMS}; /// fn preferred_locale(conn: &Connection) -> Result { /// conn.query_row( /// "SELECT value FROM preferences WHERE name='locale'", - /// &[], + /// NO_PARAMS, /// |row| row.get(0), /// ) /// } @@ -379,8 +386,10 @@ impl Connection { /// /// Will return `Err` if `sql` cannot be converted to a C-compatible string /// or if the underlying SQLite call fails. - pub fn query_row(&self, sql: &str, params: &[&ToSql], f: F) -> Result + pub fn query_row(&self, sql: &str, params: P, f: F) -> Result where + P: IntoIterator, + P::Item: ToSql, F: FnOnce(&Row) -> T, { let mut stmt = try!(self.prepare(sql)); @@ -415,11 +424,11 @@ impl Connection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{Result,Connection}; + /// # use rusqlite::{Result,Connection, NO_PARAMS}; /// fn preferred_locale(conn: &Connection) -> Result { /// conn.query_row_and_then( /// "SELECT value FROM preferences WHERE name='locale'", - /// &[], + /// NO_PARAMS, /// |row| row.get_checked(0), /// ) /// } @@ -432,13 +441,10 @@ impl Connection { /// /// Will return `Err` if `sql` cannot be converted to a C-compatible string /// or if the underlying SQLite call fails. - pub fn query_row_and_then( - &self, - sql: &str, - params: &[&ToSql], - f: F, - ) -> result::Result + pub fn query_row_and_then(&self, sql: &str, params: P, f: F) -> result::Result where + P: IntoIterator, + P::Item: ToSql, F: FnOnce(&Row) -> result::Result, E: convert::From, { @@ -448,37 +454,6 @@ impl Connection { rows.get_expected_row().map_err(E::from).and_then(|r| f(&r)) } - /// Convenience method to execute a query that is expected to return a - /// single row. - /// - /// ## Example - /// - /// ```rust,no_run - /// # use rusqlite::{Result,Connection}; - /// fn preferred_locale(conn: &Connection) -> Result { - /// conn.query_row_safe( - /// "SELECT value FROM preferences WHERE name='locale'", - /// &[], - /// |row| row.get(0), - /// ) - /// } - /// ``` - /// - /// If the query returns more than one row, all rows except the first are - /// ignored. - /// - /// ## Deprecated - /// - /// This method should be considered deprecated. Use `query_row` instead, - /// which now does exactly the same thing. - #[deprecated(since = "0.1.0", note = "Use query_row instead")] - pub fn query_row_safe(&self, sql: &str, params: &[&ToSql], f: F) -> Result - where - F: FnOnce(&Row) -> T, - { - self.query_row(sql, params, f) - } - /// Prepare a SQL statement for execution. /// /// ## Example @@ -487,8 +462,8 @@ impl Connection { /// # use rusqlite::{Connection, Result}; /// fn insert_new_people(conn: &Connection) -> Result<()> { /// let mut stmt = try!(conn.prepare("INSERT INTO People (name) VALUES (?)")); - /// try!(stmt.execute(&[&"Joe Smith"])); - /// try!(stmt.execute(&[&"Bob Jones"])); + /// try!(stmt.execute(&["Joe Smith"])); + /// try!(stmt.execute(&["Bob Jones"])); /// Ok(()) /// } /// ``` @@ -1089,14 +1064,14 @@ mod test { // SELECT first makes sqlite lock with a shared lock let _ = tx1 - .query_row("SELECT x FROM foo LIMIT 1", &[], |_| ()) + .query_row("SELECT x FROM foo LIMIT 1", NO_PARAMS, |_| ()) .unwrap(); let _ = tx2 - .query_row("SELECT x FROM foo LIMIT 1", &[], |_| ()) + .query_row("SELECT x FROM foo LIMIT 1", NO_PARAMS, |_| ()) .unwrap(); - tx1.execute("INSERT INTO foo VALUES(?1)", &[&1]).unwrap(); - let _ = tx2.execute("INSERT INTO foo VALUES(?1)", &[&2]); + tx1.execute("INSERT INTO foo VALUES(?1)", &[1]).unwrap(); + let _ = tx2.execute("INSERT INTO foo VALUES(?1)", &[2]); let _ = tx1.commit(); let _ = tx2.commit(); @@ -1126,7 +1101,7 @@ mod test { let path_string = path.to_str().unwrap(); let db = Connection::open(&path_string).unwrap(); - let the_answer: Result = db.query_row("SELECT x FROM foo", &[], |r| r.get(0)); + let the_answer: Result = db.query_row("SELECT x FROM foo", NO_PARAMS, |r| r.get(0)); assert_eq!(42i64, the_answer.unwrap()); } @@ -1216,18 +1191,18 @@ mod test { assert_eq!( 1, - db.execute("INSERT INTO foo(x) VALUES (?)", &[&1i32]) + db.execute("INSERT INTO foo(x) VALUES (?)", &[1i32]) .unwrap() ); assert_eq!( 1, - db.execute("INSERT INTO foo(x) VALUES (?)", &[&2i32]) + db.execute("INSERT INTO foo(x) VALUES (?)", &[2i32]) .unwrap() ); assert_eq!( 3i32, - db.query_row::("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + db.query_row::("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap() ); } @@ -1235,7 +1210,7 @@ mod test { #[test] fn test_execute_select() { let db = checked_memory_handle(); - let err = db.execute("SELECT 1 WHERE 1 < ?", &[&1i32]).unwrap_err(); + let err = db.execute("SELECT 1 WHERE 1 < ?", &[1i32]).unwrap_err(); match err { Error::ExecuteReturnedResults => (), _ => panic!("Unexpected error: {}", err), @@ -1262,18 +1237,18 @@ mod test { db.execute_batch("CREATE TABLE foo(x INTEGER);").unwrap(); let mut insert_stmt = db.prepare("INSERT INTO foo(x) VALUES(?)").unwrap(); - assert_eq!(insert_stmt.execute(&[&1i32]).unwrap(), 1); - assert_eq!(insert_stmt.execute(&[&2i32]).unwrap(), 1); - assert_eq!(insert_stmt.execute(&[&3i32]).unwrap(), 1); + assert_eq!(insert_stmt.execute(&[1i32]).unwrap(), 1); + assert_eq!(insert_stmt.execute(&[2i32]).unwrap(), 1); + assert_eq!(insert_stmt.execute(&[3i32]).unwrap(), 1); - assert_eq!(insert_stmt.execute(&[&"hello".to_string()]).unwrap(), 1); - assert_eq!(insert_stmt.execute(&[&"goodbye".to_string()]).unwrap(), 1); - assert_eq!(insert_stmt.execute(&[&types::Null]).unwrap(), 1); + assert_eq!(insert_stmt.execute(&["hello".to_string()]).unwrap(), 1); + assert_eq!(insert_stmt.execute(&["goodbye".to_string()]).unwrap(), 1); + assert_eq!(insert_stmt.execute(&[types::Null]).unwrap(), 1); let mut update_stmt = db.prepare("UPDATE foo SET x=? WHERE x::new(); while let Some(row) = rows.next() { @@ -1301,7 +1276,7 @@ mod test { } { - let mut rows = query.query(&[&3i32]).unwrap(); + let mut rows = query.query(&[3i32]).unwrap(); let mut v = Vec::::new(); while let Some(row) = rows.next() { @@ -1325,8 +1300,10 @@ mod test { db.execute_batch(sql).unwrap(); let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); - let results: Result> = - query.query_map(&[], |row| row.get(1)).unwrap().collect(); + let results: Result> = query + .query_map(NO_PARAMS, |row| row.get(1)) + .unwrap() + .collect(); assert_eq!(results.unwrap().concat(), "hello, world!"); } @@ -1345,17 +1322,18 @@ mod test { assert_eq!( 10i64, - db.query_row::("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + db.query_row::("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap() ); - let result: Result = db.query_row("SELECT x FROM foo WHERE x > 5", &[], |r| r.get(0)); + let result: Result = + db.query_row("SELECT x FROM foo WHERE x > 5", NO_PARAMS, |r| r.get(0)); match result.unwrap_err() { Error::QueryReturnedNoRows => (), err => panic!("Unexpected error {}", err), } - let bad_query_result = db.query_row("NOT A PROPER QUERY; test123", &[], |_| ()); + let bad_query_result = db.query_row("NOT A PROPER QUERY; test123", NO_PARAMS, |_| ()); assert!(bad_query_result.is_err()); } @@ -1366,12 +1344,12 @@ mod test { assert_eq!( "memory", - db.query_row::("PRAGMA journal_mode", &[], |r| r.get(0)) + db.query_row::("PRAGMA journal_mode", NO_PARAMS, |r| r.get(0)) .unwrap() ); assert_eq!( "off", - db.query_row::("PRAGMA journal_mode=off", &[], |r| r.get(0)) + db.query_row::("PRAGMA journal_mode=off", NO_PARAMS, |r| r.get(0)) .unwrap() ); } @@ -1396,7 +1374,7 @@ mod test { let mut stmt = db.prepare("INSERT INTO foo DEFAULT VALUES").unwrap(); for _ in 0i32..9 { - stmt.execute(&[]).unwrap(); + stmt.execute(NO_PARAMS).unwrap(); } assert_eq!(db.last_insert_rowid(), 10); } @@ -1418,7 +1396,7 @@ mod test { let mut stmt = db.prepare("PRAGMA schema_version").unwrap(); assert!(!db.is_busy()); { - let mut rows = stmt.query(&[]).unwrap(); + let mut rows = stmt.query(NO_PARAMS).unwrap(); assert!(!db.is_busy()); let row = rows.next(); assert!(db.is_busy()); @@ -1450,7 +1428,7 @@ mod test { let db = checked_memory_handle(); db.execute_batch("CREATE TABLE foo(x NOT NULL)").unwrap(); - let result = db.execute("INSERT INTO foo (x) VALUES (NULL)", &[]); + let result = db.execute("INSERT INTO foo (x) VALUES (NULL)", NO_PARAMS); assert!(result.is_err()); match result.unwrap_err() { @@ -1526,7 +1504,7 @@ mod test { let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let results: Result> = query - .query_and_then(&[], |row| row.get_checked(1)) + .query_and_then(NO_PARAMS, |row| row.get_checked(1)) .unwrap() .collect(); @@ -1547,7 +1525,7 @@ mod test { let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let bad_type: Result> = query - .query_and_then(&[], |row| row.get_checked(1)) + .query_and_then(NO_PARAMS, |row| row.get_checked(1)) .unwrap() .collect(); @@ -1557,7 +1535,7 @@ mod test { } let bad_idx: Result> = query - .query_and_then(&[], |row| row.get_checked(3)) + .query_and_then(NO_PARAMS, |row| row.get_checked(3)) .unwrap() .collect(); @@ -1581,8 +1559,9 @@ mod test { let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let results: CustomResult> = query - .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) - .unwrap() + .query_and_then(NO_PARAMS, |row| { + row.get_checked(1).map_err(CustomError::Sqlite) + }).unwrap() .collect(); assert_eq!(results.unwrap().concat(), "hello, world!"); @@ -1602,8 +1581,9 @@ mod test { let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); let bad_type: CustomResult> = query - .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) - .unwrap() + .query_and_then(NO_PARAMS, |row| { + row.get_checked(1).map_err(CustomError::Sqlite) + }).unwrap() .collect(); match bad_type.unwrap_err() { @@ -1612,8 +1592,9 @@ mod test { } let bad_idx: CustomResult> = query - .query_and_then(&[], |row| row.get_checked(3).map_err(CustomError::Sqlite)) - .unwrap() + .query_and_then(NO_PARAMS, |row| { + row.get_checked(3).map_err(CustomError::Sqlite) + }).unwrap() .collect(); match bad_idx.unwrap_err() { @@ -1622,7 +1603,7 @@ mod test { } let non_sqlite_err: CustomResult> = query - .query_and_then(&[], |_| Err(CustomError::SomeError)) + .query_and_then(NO_PARAMS, |_| Err(CustomError::SomeError)) .unwrap() .collect(); @@ -1642,7 +1623,7 @@ mod test { db.execute_batch(sql).unwrap(); let query = "SELECT x, y FROM foo ORDER BY x DESC"; - let results: CustomResult = db.query_row_and_then(query, &[], |row| { + let results: CustomResult = db.query_row_and_then(query, NO_PARAMS, |row| { row.get_checked(1).map_err(CustomError::Sqlite) }); @@ -1659,7 +1640,7 @@ mod test { db.execute_batch(sql).unwrap(); let query = "SELECT x, y FROM foo ORDER BY x DESC"; - let bad_type: CustomResult = db.query_row_and_then(query, &[], |row| { + let bad_type: CustomResult = db.query_row_and_then(query, NO_PARAMS, |row| { row.get_checked(1).map_err(CustomError::Sqlite) }); @@ -1668,7 +1649,7 @@ mod test { err => panic!("Unexpected error {}", err), } - let bad_idx: CustomResult = db.query_row_and_then(query, &[], |row| { + let bad_idx: CustomResult = db.query_row_and_then(query, NO_PARAMS, |row| { row.get_checked(3).map_err(CustomError::Sqlite) }); @@ -1678,7 +1659,7 @@ mod test { } let non_sqlite_err: CustomResult = - db.query_row_and_then(query, &[], |_| Err(CustomError::SomeError)); + db.query_row_and_then(query, NO_PARAMS, |_| Err(CustomError::SomeError)); match non_sqlite_err.unwrap_err() { CustomError::SomeError => (), @@ -1695,7 +1676,7 @@ mod test { END;"; db.execute_batch(sql).unwrap(); - db.query_row("SELECT * FROM foo", &[], |r| { + db.query_row("SELECT * FROM foo", NO_PARAMS, |r| { assert_eq!(2, r.column_count()) }).unwrap(); } diff --git a/src/statement.rs b/src/statement.rs index 7130f22..b131e20 100644 --- a/src/statement.rs +++ b/src/statement.rs @@ -1,4 +1,5 @@ use std::ffi::CStr; +use std::iter::IntoIterator; use std::os::raw::{c_char, c_int, c_void}; #[cfg(feature = "array")] use std::rc::Rc; @@ -71,8 +72,8 @@ impl<'conn> Statement<'conn> { /// fn update_rows(conn: &Connection) -> Result<()> { /// let mut stmt = try!(conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?")); /// - /// try!(stmt.execute(&[&1i32])); - /// try!(stmt.execute(&[&2i32])); + /// try!(stmt.execute(&[1i32])); + /// try!(stmt.execute(&[2i32])); /// /// Ok(()) /// } @@ -83,7 +84,11 @@ impl<'conn> Statement<'conn> { /// Will return `Err` if binding parameters fails, the executed statement /// returns rows (in which case `query` should be used instead), or the /// underling SQLite call fails. - pub fn execute(&mut self, params: &[&ToSql]) -> Result { + pub fn execute

(&mut self, params: P) -> Result + where + P: IntoIterator, + P::Item: ToSql, + { try!(self.bind_parameters(params)); self.execute_with_bound_parameters() } @@ -130,7 +135,11 @@ impl<'conn> Statement<'conn> { /// # Failure /// /// Will return `Err` if no row is inserted or many rows are inserted. - pub fn insert(&mut self, params: &[&ToSql]) -> Result { + pub fn insert

(&mut self, params: P) -> Result + where + P: IntoIterator, + P::Item: ToSql, + { let changes = try!(self.execute(params)); match changes { 1 => Ok(self.conn.last_insert_rowid()), @@ -148,10 +157,10 @@ impl<'conn> Statement<'conn> { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{Connection, Result}; + /// # use rusqlite::{Connection, Result, NO_PARAMS}; /// fn get_names(conn: &Connection) -> Result> { /// let mut stmt = try!(conn.prepare("SELECT name FROM people")); - /// let mut rows = try!(stmt.query(&[])); + /// let mut rows = try!(stmt.query(NO_PARAMS)); /// /// let mut names = Vec::new(); /// while let Some(result_row) = rows.next() { @@ -166,7 +175,11 @@ impl<'conn> Statement<'conn> { /// ## Failure /// /// Will return `Err` if binding parameters fails. - pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> Result> { + pub fn query<'a, P>(&'a mut self, params: P) -> Result> + where + P: IntoIterator, + P::Item: ToSql, + { try!(self.check_readonly()); try!(self.bind_parameters(params)); Ok(Rows::new(self)) @@ -207,10 +220,10 @@ impl<'conn> Statement<'conn> { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{Connection, Result}; + /// # use rusqlite::{Connection, Result, NO_PARAMS}; /// fn get_names(conn: &Connection) -> Result> { /// let mut stmt = try!(conn.prepare("SELECT name FROM people")); - /// let rows = try!(stmt.query_map(&[], |row| row.get(0))); + /// let rows = try!(stmt.query_map(NO_PARAMS, |row| row.get(0))); /// /// let mut names = Vec::new(); /// for name_result in rows { @@ -224,8 +237,10 @@ impl<'conn> Statement<'conn> { /// ## Failure /// /// Will return `Err` if binding parameters fails. - pub fn query_map<'a, T, F>(&'a mut self, params: &[&ToSql], f: F) -> Result> + pub fn query_map<'a, T, P, F>(&'a mut self, params: P, f: F) -> Result> where + P: IntoIterator, + P::Item: ToSql, F: FnMut(&Row) -> T, { let rows = self.query(params)?; @@ -278,12 +293,14 @@ impl<'conn> Statement<'conn> { /// # Failure /// /// Will return `Err` if binding parameters fails. - pub fn query_and_then<'a, T, E, F>( + pub fn query_and_then<'a, T, E, P, F>( &'a mut self, - params: &[&ToSql], + params: P, f: F, ) -> Result> where + P: IntoIterator, + P::Item: ToSql, E: convert::From, F: FnMut(&Row) -> result::Result, { @@ -344,7 +361,11 @@ impl<'conn> Statement<'conn> { /// Return `true` if a query in the SQL statement it executes returns one /// or more rows and `false` if the SQL returns an empty set. - pub fn exists(&mut self, params: &[&ToSql]) -> Result { + pub fn exists

(&mut self, params: P) -> Result + where + P: IntoIterator, + P::Item: ToSql, + { let mut rows = try!(self.query(params)); let exists = { match rows.next() { @@ -364,8 +385,10 @@ impl<'conn> Statement<'conn> { /// # Failure /// /// Will return `Err` if the underlying SQLite call fails. - pub fn query_row(&mut self, params: &[&ToSql], f: F) -> Result + pub fn query_row(&mut self, params: P, f: F) -> Result where + P: IntoIterator, + P::Item: ToSql, F: FnOnce(&Row) -> T, { let mut rows = try!(self.query(params)); @@ -396,18 +419,25 @@ impl<'conn> Statement<'conn> { Ok(self.stmt.bind_parameter_index(&c_name)) } - fn bind_parameters(&mut self, params: &[&ToSql]) -> Result<()> { - assert_eq!( - params.len(), - self.stmt.bind_parameter_count(), - "incorrect number of parameters to query(): expected {}, got {}", - self.stmt.bind_parameter_count(), - params.len() - ); - - for (i, p) in params.iter().enumerate() { - try!(self.bind_parameter(*p, i + 1)); + fn bind_parameters

(&mut self, params: P) -> Result<()> + where + P: IntoIterator, + P::Item: ToSql, + { + let expected = self.stmt.bind_parameter_count(); + let mut index = 0; + for p in params.into_iter() { + index += 1; // The leftmost SQL parameter has an index of 1. + if index > expected { + break; + } + try!(self.bind_parameter(&p, index)); } + assert_eq!( + index, expected, + "incorrect number of parameters: expected {}, got {}", + expected, index + ); Ok(()) } @@ -643,7 +673,7 @@ impl<'conn> Statement<'conn> { #[cfg(test)] mod test { - use {Connection, Error, Result}; + use {Connection, Error, Result, NO_PARAMS}; #[test] fn test_execute_named() { @@ -780,8 +810,9 @@ mod test { stmt.execute_named(&[(":x", &"one")]).unwrap(); let result: Option = db - .query_row("SELECT y FROM test WHERE x = 'one'", &[], |row| row.get(0)) - .unwrap(); + .query_row("SELECT y FROM test WHERE x = 'one'", NO_PARAMS, |row| { + row.get(0) + }).unwrap(); assert!(result.is_none()); } @@ -798,8 +829,9 @@ mod test { stmt.execute_named(&[(":y", &"two")]).unwrap(); let result: String = db - .query_row("SELECT x FROM test WHERE y = 'two'", &[], |row| row.get(0)) - .unwrap(); + .query_row("SELECT x FROM test WHERE y = 'two'", NO_PARAMS, |row| { + row.get(0) + }).unwrap(); assert_eq!(result, "one"); } @@ -811,16 +843,16 @@ mod test { let mut stmt = db .prepare("INSERT OR IGNORE INTO foo (x) VALUES (?)") .unwrap(); - assert_eq!(stmt.insert(&[&1i32]).unwrap(), 1); - assert_eq!(stmt.insert(&[&2i32]).unwrap(), 2); - match stmt.insert(&[&1i32]).unwrap_err() { + assert_eq!(stmt.insert(&[1i32]).unwrap(), 1); + assert_eq!(stmt.insert(&[2i32]).unwrap(), 2); + match stmt.insert(&[1i32]).unwrap_err() { Error::StatementChangedRows(0) => (), err => panic!("Unexpected error {}", err), } let mut multi = db .prepare("INSERT INTO foo (x) SELECT 3 UNION ALL SELECT 4") .unwrap(); - match multi.insert(&[]).unwrap_err() { + match multi.insert(NO_PARAMS).unwrap_err() { Error::StatementChangedRows(2) => (), err => panic!("Unexpected error {}", err), } @@ -840,14 +872,14 @@ mod test { assert_eq!( db.prepare("INSERT INTO foo VALUES (10)") .unwrap() - .insert(&[]) + .insert(NO_PARAMS) .unwrap(), 1 ); assert_eq!( db.prepare("INSERT INTO bar VALUES (10)") .unwrap() - .insert(&[]) + .insert(NO_PARAMS) .unwrap(), 1 ); @@ -863,9 +895,9 @@ mod test { END;"; db.execute_batch(sql).unwrap(); let mut stmt = db.prepare("SELECT 1 FROM foo WHERE x = ?").unwrap(); - assert!(stmt.exists(&[&1i32]).unwrap()); - assert!(stmt.exists(&[&2i32]).unwrap()); - assert!(!stmt.exists(&[&0i32]).unwrap()); + assert!(stmt.exists(&[1i32]).unwrap()); + assert!(stmt.exists(&[2i32]).unwrap()); + assert!(!stmt.exists(&[0i32]).unwrap()); } #[test] @@ -878,7 +910,7 @@ mod test { 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)); + let y: Result = stmt.query_row(&[1i32], |r| r.get(0)); assert_eq!(3i64, y.unwrap()); } @@ -891,7 +923,7 @@ mod test { END;"; db.execute_batch(sql).unwrap(); let mut stmt = db.prepare("SELECT y FROM foo").unwrap(); - let y: Result = stmt.query_row(&[], |r| r.get("y")); + let y: Result = stmt.query_row(NO_PARAMS, |r| r.get("y")); assert_eq!(3i64, y.unwrap()); } @@ -904,7 +936,7 @@ mod test { END;"; db.execute_batch(sql).unwrap(); let mut stmt = db.prepare("SELECT y as Y FROM foo").unwrap(); - let y: Result = stmt.query_row(&[], |r| r.get("y")); + let y: Result = stmt.query_row(NO_PARAMS, |r| r.get("y")); assert_eq!(3i64, y.unwrap()); } diff --git a/src/trace.rs b/src/trace.rs index 423569b..a11396b 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -139,13 +139,13 @@ mod test { let mut db = Connection::open_in_memory().unwrap(); db.trace(Some(tracer)); { - let _ = db.query_row("SELECT ?", &[&1i32], |_| {}); - let _ = db.query_row("SELECT ?", &[&"hello"], |_| {}); + let _ = db.query_row("SELECT ?", &[1i32], |_| {}); + let _ = db.query_row("SELECT ?", &["hello"], |_| {}); } db.trace(None); { - let _ = db.query_row("SELECT ?", &[&2i32], |_| {}); - let _ = db.query_row("SELECT ?", &[&"goodbye"], |_| {}); + let _ = db.query_row("SELECT ?", &[2i32], |_| {}); + let _ = db.query_row("SELECT ?", &["goodbye"], |_| {}); } let traced_stmts = TRACED_STMTS.lock().unwrap(); diff --git a/src/transaction.rs b/src/transaction.rs index 9f8194c..05dd3d5 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -419,7 +419,7 @@ impl Connection { #[cfg(test)] mod test { use super::DropBehavior; - use Connection; + use {Connection, NO_PARAMS}; fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); @@ -444,7 +444,7 @@ mod test { let tx = db.transaction().unwrap(); assert_eq!( 2i32, - tx.query_row::("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + tx.query_row::("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap() ); } @@ -473,7 +473,7 @@ mod test { let tx = db.transaction().unwrap(); assert_eq!( 6i32, - tx.query_row::("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + tx.query_row::("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap() ); } @@ -565,12 +565,12 @@ mod test { } fn insert(x: i32, conn: &Connection) { - conn.execute("INSERT INTO foo VALUES(?)", &[&x]).unwrap(); + conn.execute("INSERT INTO foo VALUES(?)", &[x]).unwrap(); } fn assert_current_sum(x: i32, conn: &Connection) { let i = conn - .query_row::("SELECT SUM(x) FROM foo", &[], |r| r.get(0)) + .query_row::("SELECT SUM(x) FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(x, i); } diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 075a552..6244643 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -132,7 +132,7 @@ mod test { use super::chrono::{ DateTime, Duration, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc, }; - use Connection; + use {Connection, NO_PARAMS}; fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); @@ -149,11 +149,11 @@ mod test { .unwrap(); let s: String = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!("2016-02-23", s); let t: NaiveDate = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(date, t); } @@ -166,11 +166,11 @@ mod test { .unwrap(); let s: String = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!("23:56:04", s); let v: NaiveTime = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(time, v); } @@ -186,17 +186,18 @@ mod test { .unwrap(); let s: String = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!("2016-02-23T23:56:04", s); let v: NaiveDateTime = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(dt, v); - db.execute("UPDATE foo set b = datetime(t)", &[]).unwrap(); // "YYYY-MM-DD HH:MM:SS" + db.execute("UPDATE foo set b = datetime(t)", NO_PARAMS) + .unwrap(); // "YYYY-MM-DD HH:MM:SS" let hms: NaiveDateTime = db - .query_row("SELECT b FROM foo", &[], |r| r.get(0)) + .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(dt, hms); } @@ -213,28 +214,29 @@ mod test { .unwrap(); let s: String = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!("2016-02-23T23:56:04.789+00:00", s); let v1: DateTime = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(utc, v1); let v2: DateTime = db - .query_row("SELECT '2016-02-23 23:56:04.789'", &[], |r| r.get(0)) + .query_row("SELECT '2016-02-23 23:56:04.789'", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(utc, v2); let v3: DateTime = db - .query_row("SELECT '2016-02-23 23:56:04'", &[], |r| r.get(0)) + .query_row("SELECT '2016-02-23 23:56:04'", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(utc - Duration::milliseconds(789), v3); let v4: DateTime = db - .query_row("SELECT '2016-02-23 23:56:04.789+00:00'", &[], |r| r.get(0)) - .unwrap(); + .query_row("SELECT '2016-02-23 23:56:04.789+00:00'", NO_PARAMS, |r| { + r.get(0) + }).unwrap(); assert_eq!(utc, v4); } @@ -251,12 +253,12 @@ mod test { // Stored string should be in UTC let s: String = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert!(s.ends_with("+00:00")); let v: DateTime = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(local, v); } diff --git a/src/types/mod.rs b/src/types/mod.rs index 4c3da3f..88407e9 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -81,7 +81,7 @@ mod value_ref; /// # use rusqlite::types::{Null}; /// fn main() {} /// fn insert_null(conn: &Connection) -> Result { -/// conn.execute("INSERT INTO people (name) VALUES (?)", &[&Null]) +/// conn.execute("INSERT INTO people (name) VALUES (?)", &[Null]) /// } /// ``` #[derive(Copy, Clone)] @@ -115,8 +115,7 @@ mod test { use super::Value; use std::f64::EPSILON; use std::os::raw::{c_double, c_int}; - use Connection; - use Error; + use {Connection, Error, NO_PARAMS}; fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); @@ -134,7 +133,7 @@ mod test { .unwrap(); let v: Vec = db - .query_row("SELECT b FROM foo", &[], |r| r.get(0)) + .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(v, v1234); } @@ -148,7 +147,7 @@ mod test { .unwrap(); let v: Vec = db - .query_row("SELECT b FROM foo", &[], |r| r.get(0)) + .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(v, empty); } @@ -161,7 +160,7 @@ mod test { db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap(); let from: String = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(from, s); } @@ -171,11 +170,11 @@ mod test { let db = checked_memory_handle(); let s = "hello, world!"; - db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_owned()]) + db.execute("INSERT INTO foo(t) VALUES (?)", &[s.to_owned()]) .unwrap(); let from: String = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(from, s); } @@ -184,12 +183,12 @@ mod test { fn test_value() { let db = checked_memory_handle(); - db.execute("INSERT INTO foo(i) VALUES (?)", &[&Value::Integer(10)]) + db.execute("INSERT INTO foo(i) VALUES (?)", &[Value::Integer(10)]) .unwrap(); assert_eq!( 10i64, - db.query_row::("SELECT i FROM foo", &[], |r| r.get(0)) + db.query_row::("SELECT i FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap() ); } @@ -207,7 +206,7 @@ mod test { let mut stmt = db .prepare("SELECT t, b FROM foo ORDER BY ROWID ASC") .unwrap(); - let mut rows = stmt.query(&[]).unwrap(); + let mut rows = stmt.query(NO_PARAMS).unwrap(); { let row1 = rows.next().unwrap().unwrap(); @@ -239,11 +238,11 @@ mod test { db.execute( "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)", - &[], + NO_PARAMS, ).unwrap(); let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap(); - let mut rows = stmt.query(&[]).unwrap(); + let mut rows = stmt.query(NO_PARAMS).unwrap(); let row = rows.next().unwrap().unwrap(); @@ -354,11 +353,11 @@ mod test { db.execute( "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)", - &[], + NO_PARAMS, ).unwrap(); let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap(); - let mut rows = stmt.query(&[]).unwrap(); + let mut rows = stmt.query(NO_PARAMS).unwrap(); let row = rows.next().unwrap().unwrap(); assert_eq!( diff --git a/src/types/serde_json.rs b/src/types/serde_json.rs index 9912e24..fdba891 100644 --- a/src/types/serde_json.rs +++ b/src/types/serde_json.rs @@ -27,7 +27,8 @@ impl FromSql for Value { #[cfg(test)] mod test { use super::serde_json; - use Connection; + use types::ToSql; + use {Connection, NO_PARAMS}; fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); @@ -44,15 +45,15 @@ mod test { let data: serde_json::Value = serde_json::from_str(json).unwrap(); db.execute( "INSERT INTO foo (t, b) VALUES (?, ?)", - &[&data, &json.as_bytes()], + &[&data as &ToSql, &json.as_bytes()], ).unwrap(); let t: serde_json::Value = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(data, t); let b: serde_json::Value = db - .query_row("SELECT b FROM foo", &[], |r| r.get(0)) + .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); assert_eq!(data, b); } diff --git a/src/types/time.rs b/src/types/time.rs index 1255315..2df097c 100644 --- a/src/types/time.rs +++ b/src/types/time.rs @@ -32,7 +32,7 @@ impl FromSql for time::Timespec { #[cfg(test)] mod test { use super::time; - use Connection; + use {Connection, NO_PARAMS}; fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); @@ -58,10 +58,10 @@ mod test { db.execute("INSERT INTO foo(t) VALUES (?)", &[&ts]).unwrap(); let from: time::Timespec = db - .query_row("SELECT t FROM foo", &[], |r| r.get(0)) + .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0)) .unwrap(); - db.execute("DELETE FROM foo", &[]).unwrap(); + db.execute("DELETE FROM foo", NO_PARAMS).unwrap(); assert_eq!(from, ts); } diff --git a/src/types/to_sql.rs b/src/types/to_sql.rs index a533013..65ffe39 100644 --- a/src/types/to_sql.rs +++ b/src/types/to_sql.rs @@ -114,10 +114,10 @@ to_sql_self!(f64); impl<'a, T: ?Sized> ToSql for &'a T where - &'a T: Into>, + T: ToSql, { fn to_sql(&self) -> Result { - Ok((*self).into()) + (*self).to_sql() } } diff --git a/src/unlock_notify.rs b/src/unlock_notify.rs index a06db48..c4f2f1f 100644 --- a/src/unlock_notify.rs +++ b/src/unlock_notify.rs @@ -102,7 +102,7 @@ mod test { use std::sync::mpsc::sync_channel; use std::thread; use std::time; - use {Connection, OpenFlags, Result, Transaction, TransactionBehavior}; + use {Connection, OpenFlags, Result, Transaction, TransactionBehavior, NO_PARAMS}; #[test] fn test_unlock_notify() { @@ -121,7 +121,7 @@ mod test { tx2.commit().unwrap(); }); assert_eq!(tx.recv().unwrap(), 1); - let the_answer: Result = db1.query_row("SELECT x FROM foo", &[], |r| r.get(0)); + let the_answer: Result = db1.query_row("SELECT x FROM foo", NO_PARAMS, |r| r.get(0)); assert_eq!(42i64, the_answer.unwrap()); child.join().unwrap(); } diff --git a/src/vtab/csvtab.rs b/src/vtab/csvtab.rs index 0b80dc0..5ed616e 100644 --- a/src/vtab/csvtab.rs +++ b/src/vtab/csvtab.rs @@ -341,7 +341,7 @@ impl From for Error { #[cfg(test)] mod test { use vtab::csvtab; - use {Connection, Result}; + use {Connection, Result, NO_PARAMS}; #[test] fn test_csv_module() { @@ -358,7 +358,7 @@ mod test { } let ids: Result> = s - .query_map(&[], |row| row.get::<_, i32>(0)) + .query_map(NO_PARAMS, |row| row.get::<_, i32>(0)) .unwrap() .collect(); let sum = ids.unwrap().iter().fold(0, |acc, &id| acc + id); @@ -381,7 +381,7 @@ mod test { v1.rowid < v2.rowid", ).unwrap(); - let mut rows = s.query(&[]).unwrap(); + let mut rows = s.query(NO_PARAMS).unwrap(); let row = rows.next().unwrap().unwrap(); assert_eq!(row.get::<_, i32>(0), 2); } diff --git a/src/vtab/series.rs b/src/vtab/series.rs index 25d6865..88fe393 100644 --- a/src/vtab/series.rs +++ b/src/vtab/series.rs @@ -265,7 +265,7 @@ impl VTabCursor for SeriesTabCursor { mod test { use ffi; use vtab::series; - use Connection; + use {Connection, NO_PARAMS}; #[test] fn test_series_module() { @@ -279,7 +279,7 @@ mod test { let mut s = db.prepare("SELECT * FROM generate_series(0,20,5)").unwrap(); - let series = s.query_map(&[], |row| row.get::<_, i32>(0)).unwrap(); + let series = s.query_map(NO_PARAMS, |row| row.get::<_, i32>(0)).unwrap(); let mut expected = 0; for value in series { diff --git a/tests/vtab.rs b/tests/vtab.rs index 99a16a6..30d4ee7 100644 --- a/tests/vtab.rs +++ b/tests/vtab.rs @@ -6,6 +6,7 @@ extern crate rusqlite; #[cfg(feature = "vtab")] #[test] fn test_dummy_module() { + use rusqlite::types::ToSql; use rusqlite::vtab::{ eponymous_only_module, sqlite3_vtab, sqlite3_vtab_cursor, Context, IndexInfo, VTab, VTabConnection, VTabCursor, Values, @@ -96,6 +97,8 @@ fn test_dummy_module() { let mut s = db.prepare("SELECT * FROM dummy()").unwrap(); - let dummy = s.query_row(&[], |row| row.get::<_, i32>(0)).unwrap(); + let dummy = s + .query_row(&[] as &[&ToSql], |row| row.get::<_, i32>(0)) + .unwrap(); assert_eq!(1, dummy); }