2016-05-19 03:15:56 +08:00
|
|
|
use std::convert;
|
|
|
|
use std::result;
|
2015-11-11 21:39:54 +08:00
|
|
|
use libc::c_int;
|
2015-08-05 03:48:54 +08:00
|
|
|
|
2016-05-19 03:15:56 +08:00
|
|
|
use {Result, Error, Connection, Statement, MappedRows, AndThenRows, Rows, Row, str_to_cstring};
|
2015-11-11 21:39:54 +08:00
|
|
|
use types::ToSql;
|
2015-08-05 03:48:54 +08:00
|
|
|
|
2015-12-13 02:50:12 +08:00
|
|
|
impl Connection {
|
2015-08-07 08:19:57 +08:00
|
|
|
/// Convenience method to prepare and execute a single SQL statement with named parameter(s).
|
2015-12-05 20:43:03 +08:00
|
|
|
///
|
2015-12-11 09:30:05 +08:00
|
|
|
/// On success, returns the number of rows that were changed or inserted or deleted (via
|
|
|
|
/// `sqlite3_changes`).
|
|
|
|
///
|
2015-12-05 20:43:03 +08:00
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```rust,no_run
|
2015-12-13 03:06:03 +08:00
|
|
|
/// # use rusqlite::{Connection, Result};
|
|
|
|
/// fn insert(conn: &Connection) -> Result<i32> {
|
2015-12-11 09:30:05 +08:00
|
|
|
/// conn.execute_named("INSERT INTO test (name) VALUES (:name)", &[(":name", &"one")])
|
2015-12-05 20:43:03 +08:00
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
|
|
|
/// underlying SQLite call fails.
|
2015-12-13 03:06:03 +08:00
|
|
|
pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> Result<c_int> {
|
2015-08-07 08:19:57 +08:00
|
|
|
self.prepare(sql).and_then(|mut stmt| stmt.execute_named(params))
|
|
|
|
}
|
|
|
|
|
2015-12-11 09:30:05 +08:00
|
|
|
/// Convenience method to execute a query with named parameter(s) that is expected to return
|
|
|
|
/// a single row.
|
2015-08-07 08:19:57 +08:00
|
|
|
///
|
|
|
|
/// If the query returns more than one row, all rows except the first are ignored.
|
2015-12-05 20:43:03 +08:00
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
|
|
|
/// underlying SQLite call fails.
|
2016-02-03 02:12:00 +08:00
|
|
|
pub fn query_row_named<T, F>(&self, sql: &str, params: &[(&str, &ToSql)], f: F) -> Result<T>
|
2015-12-13 03:11:24 +08:00
|
|
|
where F: FnOnce(Row) -> T
|
2015-12-11 06:01:19 +08:00
|
|
|
{
|
2015-08-07 08:19:57 +08:00
|
|
|
let mut stmt = try!(self.prepare(sql));
|
|
|
|
let mut rows = try!(stmt.query_named(params));
|
|
|
|
|
2015-12-11 09:48:38 +08:00
|
|
|
rows.get_expected_row().map(f)
|
2015-08-07 08:19:57 +08:00
|
|
|
}
|
2015-08-05 03:48:54 +08:00
|
|
|
}
|
|
|
|
|
2015-12-13 03:08:04 +08:00
|
|
|
impl<'conn> Statement<'conn> {
|
2015-08-05 03:48:54 +08:00
|
|
|
/// Return the index of an SQL parameter given its name.
|
2015-08-08 22:19:05 +08:00
|
|
|
///
|
2015-12-05 20:43:03 +08:00
|
|
|
/// # Failure
|
|
|
|
///
|
2015-12-11 09:41:31 +08:00
|
|
|
/// Will return Err if `name` is invalid. Will return Ok(None) if the name
|
|
|
|
/// is valid but not a bound parameter of this statement.
|
2015-12-13 03:06:03 +08:00
|
|
|
pub fn parameter_index(&self, name: &str) -> Result<Option<i32>> {
|
2015-12-11 09:41:31 +08:00
|
|
|
let c_name = try!(str_to_cstring(name));
|
2016-05-17 23:06:43 +08:00
|
|
|
Ok(self.stmt.bind_parameter_index(&c_name))
|
2015-08-05 03:48:54 +08:00
|
|
|
}
|
|
|
|
|
2015-12-12 05:34:58 +08:00
|
|
|
/// Execute the prepared statement with named parameter(s). If any parameters
|
|
|
|
/// that were in the prepared statement are not included in `params`, they
|
|
|
|
/// will continue to use the most-recently bound value from a previous call
|
|
|
|
/// to `execute_named`, or `NULL` if they have never been bound.
|
2015-08-05 03:48:54 +08:00
|
|
|
///
|
|
|
|
/// On success, returns the number of rows that were changed or inserted or deleted (via
|
|
|
|
/// `sqlite3_changes`).
|
2015-12-05 20:43:03 +08:00
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```rust,no_run
|
2015-12-13 03:06:03 +08:00
|
|
|
/// # use rusqlite::{Connection, Result};
|
|
|
|
/// fn insert(conn: &Connection) -> Result<i32> {
|
2015-12-11 09:30:05 +08:00
|
|
|
/// let mut stmt = try!(conn.prepare("INSERT INTO test (name) VALUES (:name)"));
|
|
|
|
/// stmt.execute_named(&[(":name", &"one")])
|
2015-12-05 20:43:03 +08:00
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// 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.
|
2015-12-13 03:06:03 +08:00
|
|
|
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<c_int> {
|
2015-12-11 09:49:47 +08:00
|
|
|
try!(self.bind_parameters_named(params));
|
2016-05-17 23:06:43 +08:00
|
|
|
self.execute_()
|
2015-08-05 03:48:54 +08:00
|
|
|
}
|
2015-08-06 04:07:49 +08:00
|
|
|
|
2016-05-19 00:33:58 +08:00
|
|
|
/// Execute the prepared statement with named parameter(s), returning a handle for the
|
2015-12-12 05:34:58 +08:00
|
|
|
/// resulting rows. If any parameters that were in the prepared statement are not included in
|
|
|
|
/// `params`, they will continue to use the most-recently bound value from a previous call to
|
|
|
|
/// `query_named`, or `NULL` if they have never been bound.
|
2015-12-05 20:43:03 +08:00
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```rust,no_run
|
2015-12-13 03:09:37 +08:00
|
|
|
/// # use rusqlite::{Connection, Result, Rows};
|
2015-12-13 03:06:03 +08:00
|
|
|
/// fn query(conn: &Connection) -> Result<()> {
|
2015-12-11 09:30:05 +08:00
|
|
|
/// let mut stmt = try!(conn.prepare("SELECT * FROM test where name = :name"));
|
|
|
|
/// let mut rows = try!(stmt.query_named(&[(":name", &"one")]));
|
2016-05-19 00:33:58 +08:00
|
|
|
/// while let Some(row) = rows.next() {
|
2015-12-11 09:30:05 +08:00
|
|
|
/// // ...
|
|
|
|
/// }
|
|
|
|
/// Ok(())
|
2015-12-05 20:43:03 +08:00
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// # Failure
|
|
|
|
///
|
|
|
|
/// Will return `Err` if binding parameters fails.
|
2016-02-03 02:12:00 +08:00
|
|
|
pub fn query_named<'a>(&'a mut self, params: &[(&str, &ToSql)]) -> Result<Rows<'a>> {
|
2015-12-11 09:49:47 +08:00
|
|
|
try!(self.bind_parameters_named(params));
|
2015-12-13 03:09:37 +08:00
|
|
|
Ok(Rows::new(self))
|
2015-08-06 04:07:49 +08:00
|
|
|
}
|
|
|
|
|
2016-05-19 03:15:56 +08:00
|
|
|
/// Execute the prepared statement with named parameter(s), returning an iterator over the
|
|
|
|
/// result of calling the mapping function over the query's rows. If any parameters that were
|
|
|
|
/// in the prepared statement are not included in `params`, they will continue to use the
|
|
|
|
/// most-recently bound value from a previous call to `query_named`, or `NULL` if they have
|
|
|
|
/// never been bound.
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```rust,no_run
|
|
|
|
/// # use rusqlite::{Connection, Result};
|
|
|
|
/// fn get_names(conn: &Connection) -> Result<Vec<String>> {
|
|
|
|
/// let mut stmt = try!(conn.prepare("SELECT name FROM people WHERE id = :id"));
|
|
|
|
/// let rows = try!(stmt.query_map_named(&[(":id", &"one")], |row| row.get(0)));
|
|
|
|
///
|
|
|
|
/// let mut names = Vec::new();
|
|
|
|
/// for name_result in rows {
|
|
|
|
/// names.push(try!(name_result));
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// Ok(names)
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// ## Failure
|
|
|
|
///
|
|
|
|
/// Will return `Err` if binding parameters fails.
|
|
|
|
pub fn query_map_named<'a, T, F>(&'a mut self,
|
|
|
|
params: &[(&str, &ToSql)],
|
|
|
|
f: F)
|
|
|
|
-> Result<MappedRows<'a, F>>
|
|
|
|
where F: FnMut(&Row) -> T
|
|
|
|
{
|
|
|
|
let rows = try!(self.query_named(params));
|
|
|
|
Ok(MappedRows {
|
|
|
|
rows: rows,
|
|
|
|
map: f,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Execute the prepared statement with named parameter(s), returning an iterator over the
|
|
|
|
/// result of calling the mapping function over the query's rows. If any parameters that were
|
|
|
|
/// in the prepared statement are not included in `params`, they will continue to use the
|
|
|
|
/// most-recently bound value from a previous call to `query_named`, or `NULL` if they have
|
|
|
|
/// never been bound.
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
///
|
|
|
|
/// ```rust,no_run
|
|
|
|
/// # use rusqlite::{Connection, Result};
|
|
|
|
/// struct Person { name: String };
|
|
|
|
///
|
|
|
|
/// fn name_to_person(name: String) -> Result<Person> {
|
|
|
|
/// // ... check for valid name
|
|
|
|
/// Ok(Person{ name: name })
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn get_names(conn: &Connection) -> Result<Vec<Person>> {
|
|
|
|
/// let mut stmt = try!(conn.prepare("SELECT name FROM people WHERE id = :id"));
|
|
|
|
/// let rows = try!(stmt.query_and_then_named(&[(":id", &"one")], |row| {
|
|
|
|
/// name_to_person(row.get(0))
|
|
|
|
/// }));
|
|
|
|
///
|
|
|
|
/// let mut persons = Vec::new();
|
|
|
|
/// for person_result in rows {
|
|
|
|
/// persons.push(try!(person_result));
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// Ok(persons)
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// ## Failure
|
|
|
|
///
|
|
|
|
/// Will return `Err` if binding parameters fails.
|
|
|
|
pub fn query_and_then_named<'a, T, E, F>(&'a mut self,
|
|
|
|
params: &[(&str, &ToSql)],
|
|
|
|
f: F)
|
|
|
|
-> Result<AndThenRows<'a, F>>
|
|
|
|
where E: convert::From<Error>,
|
|
|
|
F: FnMut(&Row) -> result::Result<T, E>
|
|
|
|
{
|
|
|
|
let rows = try!(self.query_named(params));
|
|
|
|
Ok(AndThenRows {
|
|
|
|
rows: rows,
|
|
|
|
map: f,
|
|
|
|
})
|
|
|
|
}
|
2016-05-19 00:33:58 +08:00
|
|
|
|
2015-12-13 03:06:03 +08:00
|
|
|
fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> {
|
2015-08-06 04:07:49 +08:00
|
|
|
for &(name, value) in params {
|
2015-12-11 09:41:31 +08:00
|
|
|
if let Some(i) = try!(self.parameter_index(name)) {
|
2016-05-23 08:16:54 +08:00
|
|
|
try!(self.conn.decode_result(unsafe {
|
|
|
|
// This should be
|
|
|
|
// `value.bind_parameter(self.stmt.ptr(), i)`
|
|
|
|
// but that doesn't compile until Rust 1.9 due to a compiler bug.
|
|
|
|
ToSql::bind_parameter(value, self.stmt.ptr(), i)
|
|
|
|
}));
|
2015-12-11 09:41:31 +08:00
|
|
|
} else {
|
2015-12-13 13:54:08 +08:00
|
|
|
return Err(Error::InvalidParameterName(name.into()));
|
2015-12-11 09:41:31 +08:00
|
|
|
}
|
2015-08-06 04:07:49 +08:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2015-08-05 03:48:54 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2015-12-13 02:50:12 +08:00
|
|
|
use Connection;
|
2016-05-19 03:15:56 +08:00
|
|
|
use error::Error;
|
2015-08-05 03:48:54 +08:00
|
|
|
|
2015-08-07 08:19:57 +08:00
|
|
|
#[test]
|
|
|
|
fn test_execute_named() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-08-07 08:19:57 +08:00
|
|
|
db.execute_batch("CREATE TABLE foo(x INTEGER)").unwrap();
|
|
|
|
|
2015-12-11 06:01:19 +08:00
|
|
|
assert_eq!(db.execute_named("INSERT INTO foo(x) VALUES (:x)", &[(":x", &1i32)]).unwrap(),
|
|
|
|
1);
|
|
|
|
assert_eq!(db.execute_named("INSERT INTO foo(x) VALUES (:x)", &[(":x", &2i32)]).unwrap(),
|
|
|
|
1);
|
2015-08-07 08:19:57 +08:00
|
|
|
|
2015-12-11 06:01:19 +08:00
|
|
|
assert_eq!(3i32,
|
2015-12-11 09:31:07 +08:00
|
|
|
db.query_row_named("SELECT SUM(x) FROM foo WHERE x > :x",
|
2016-05-19 03:15:56 +08:00
|
|
|
&[(":x", &0i32)],
|
|
|
|
|r| r.get(0))
|
|
|
|
.unwrap());
|
2015-08-07 08:19:57 +08:00
|
|
|
}
|
|
|
|
|
2015-12-11 06:01:19 +08:00
|
|
|
#[test]
|
2015-08-07 08:19:57 +08:00
|
|
|
fn test_stmt_execute_named() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-11 06:01:19 +08:00
|
|
|
let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \
|
|
|
|
INTEGER)";
|
2015-08-05 03:48:54 +08:00
|
|
|
db.execute_batch(sql).unwrap();
|
|
|
|
|
2015-12-11 09:27:09 +08:00
|
|
|
let mut stmt = db.prepare("INSERT INTO test (name) VALUES (:name)").unwrap();
|
2015-08-07 08:19:57 +08:00
|
|
|
stmt.execute_named(&[(":name", &"one")]).unwrap();
|
2015-12-11 09:16:46 +08:00
|
|
|
|
|
|
|
assert_eq!(1i32,
|
2015-12-11 09:31:07 +08:00
|
|
|
db.query_row_named("SELECT COUNT(*) FROM test WHERE name = :name",
|
2016-05-19 03:15:56 +08:00
|
|
|
&[(":name", &"one")],
|
|
|
|
|r| r.get(0))
|
|
|
|
.unwrap());
|
2015-08-05 03:48:54 +08:00
|
|
|
}
|
2015-08-06 04:07:49 +08:00
|
|
|
|
2015-12-11 06:01:19 +08:00
|
|
|
#[test]
|
2015-08-07 08:19:57 +08:00
|
|
|
fn test_query_named() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2016-05-19 03:15:56 +08:00
|
|
|
let sql = r#"
|
|
|
|
CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
|
|
|
|
INSERT INTO test(id, name) VALUES (1, "one");
|
|
|
|
"#;
|
2015-08-06 04:07:49 +08:00
|
|
|
db.execute_batch(sql).unwrap();
|
|
|
|
|
2016-05-19 03:15:56 +08:00
|
|
|
let mut stmt = db.prepare("SELECT id FROM test where name = :name").unwrap();
|
|
|
|
let mut rows = stmt.query_named(&[(":name", &"one")]).unwrap();
|
|
|
|
|
|
|
|
let id: i32 = rows.next().unwrap().unwrap().get(0);
|
|
|
|
assert_eq!(1, id);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_query_map_named() {
|
|
|
|
let db = Connection::open_in_memory().unwrap();
|
|
|
|
let sql = r#"
|
|
|
|
CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
|
|
|
|
INSERT INTO test(id, name) VALUES (1, "one");
|
|
|
|
"#;
|
|
|
|
db.execute_batch(sql).unwrap();
|
|
|
|
|
|
|
|
let mut stmt = db.prepare("SELECT id FROM test where name = :name").unwrap();
|
|
|
|
let mut rows = stmt.query_map_named(&[(":name", &"one")], |row| {
|
2016-05-20 09:04:33 +08:00
|
|
|
let id: i32 = row.get(0);
|
|
|
|
2 * id
|
|
|
|
})
|
|
|
|
.unwrap();
|
2016-05-19 03:15:56 +08:00
|
|
|
|
|
|
|
let doubled_id: i32 = rows.next().unwrap().unwrap();
|
|
|
|
assert_eq!(2, doubled_id);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_query_and_then_named() {
|
|
|
|
|
|
|
|
let db = Connection::open_in_memory().unwrap();
|
|
|
|
let sql = r#"
|
|
|
|
CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag INTEGER);
|
|
|
|
INSERT INTO test(id, name) VALUES (1, "one");
|
|
|
|
INSERT INTO test(id, name) VALUES (2, "one");
|
|
|
|
"#;
|
|
|
|
db.execute_batch(sql).unwrap();
|
|
|
|
|
2016-05-20 09:04:33 +08:00
|
|
|
let mut stmt = db.prepare("SELECT id FROM test where name = :name ORDER BY id ASC")
|
|
|
|
.unwrap();
|
2016-05-19 03:15:56 +08:00
|
|
|
let mut rows = stmt.query_and_then_named(&[(":name", &"one")], |row| {
|
2016-05-20 09:04:33 +08:00
|
|
|
let id: i32 = row.get(0);
|
|
|
|
if id == 1 {
|
|
|
|
Ok(id)
|
|
|
|
} else {
|
|
|
|
Err(Error::SqliteSingleThreadedMode)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.unwrap();
|
2016-05-19 03:15:56 +08:00
|
|
|
|
|
|
|
// first row should be Ok
|
|
|
|
let doubled_id: i32 = rows.next().unwrap().unwrap();
|
|
|
|
assert_eq!(1, doubled_id);
|
|
|
|
|
|
|
|
// second row should be Err
|
|
|
|
match rows.next().unwrap() {
|
|
|
|
Ok(_) => panic!("invalid Ok"),
|
|
|
|
Err(Error::SqliteSingleThreadedMode) => (),
|
|
|
|
Err(_) => panic!("invalid Err"),
|
|
|
|
}
|
2015-08-06 04:07:49 +08:00
|
|
|
}
|
2015-12-11 09:27:09 +08:00
|
|
|
|
|
|
|
#[test]
|
2015-12-12 05:34:58 +08:00
|
|
|
fn test_unbound_parameters_are_null() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-12 05:34:58 +08:00
|
|
|
let sql = "CREATE TABLE test (x TEXT, y TEXT)";
|
|
|
|
db.execute_batch(sql).unwrap();
|
|
|
|
|
|
|
|
let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)").unwrap();
|
|
|
|
stmt.execute_named(&[(":x", &"one")]).unwrap();
|
2015-12-11 09:27:09 +08:00
|
|
|
|
2016-05-17 01:52:17 +08:00
|
|
|
let result: Option<String> =
|
|
|
|
db.query_row("SELECT y FROM test WHERE x = 'one'", &[], |row| row.get(0))
|
|
|
|
.unwrap();
|
2015-12-12 05:34:58 +08:00
|
|
|
assert!(result.is_none());
|
2015-12-11 09:27:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-12-12 05:34:58 +08:00
|
|
|
fn test_unbound_parameters_are_reused() {
|
2015-12-13 02:50:12 +08:00
|
|
|
let db = Connection::open_in_memory().unwrap();
|
2015-12-12 05:34:58 +08:00
|
|
|
let sql = "CREATE TABLE test (x TEXT, y TEXT)";
|
|
|
|
db.execute_batch(sql).unwrap();
|
|
|
|
|
|
|
|
let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)").unwrap();
|
|
|
|
stmt.execute_named(&[(":x", &"one")]).unwrap();
|
|
|
|
stmt.execute_named(&[(":y", &"two")]).unwrap();
|
2015-12-11 09:27:09 +08:00
|
|
|
|
2016-05-17 01:52:17 +08:00
|
|
|
let result: String =
|
|
|
|
db.query_row("SELECT x FROM test WHERE y = 'two'", &[], |row| row.get(0))
|
|
|
|
.unwrap();
|
2015-12-12 05:34:58 +08:00
|
|
|
assert_eq!(result, "one");
|
2015-12-11 09:27:09 +08:00
|
|
|
}
|
2015-11-11 21:39:54 +08:00
|
|
|
}
|