mirror of
https://github.com/isar/rusqlite.git
synced 2024-11-29 21:52:12 +08:00
Merge branch 'master' into savepoint-improvements
This commit is contained in:
commit
0e6e78e81a
@ -1,10 +1,6 @@
|
|||||||
language: rust
|
language: rust
|
||||||
sudo: false
|
sudo: false
|
||||||
|
|
||||||
env:
|
|
||||||
global:
|
|
||||||
secure: "FyGzHF0AIYdBcuM/2qIoABotx3MbNAlaHDzxPbbeUlVg64bnuib9G9K/qWve0a1BWCgv+8e/SbXZb7gt3JlUNE27aE4RZG4FEdtEpLYQp87Dc9d9HX0FwpUeFK3binsrtYl4WEBnIjQ3ICnUVey0E6GHEdkM+t5bWyJO5c4dJ30="
|
|
||||||
|
|
||||||
script:
|
script:
|
||||||
- cargo build
|
- cargo build
|
||||||
- cargo test
|
- cargo test
|
||||||
|
@ -22,6 +22,7 @@ trace = []
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
time = "~0.1.0"
|
time = "~0.1.0"
|
||||||
bitflags = "0.7"
|
bitflags = "0.7"
|
||||||
|
lru-cache = "0.0.7"
|
||||||
libc = "~0.2"
|
libc = "~0.2"
|
||||||
clippy = {version = "~0.0.58", optional = true}
|
clippy = {version = "~0.0.58", optional = true}
|
||||||
chrono = { version = "~0.2", optional = true }
|
chrono = { version = "~0.2", optional = true }
|
||||||
|
@ -10,6 +10,10 @@
|
|||||||
* BREAKING CHANGE: `Transaction::savepoint()` now returns a `Savepoint` instead of another
|
* BREAKING CHANGE: `Transaction::savepoint()` now returns a `Savepoint` instead of another
|
||||||
`Transaction`. Unlike `Transaction`, `Savepoint`s can be rolled back while keeping the current
|
`Transaction`. Unlike `Transaction`, `Savepoint`s can be rolled back while keeping the current
|
||||||
savepoint active.
|
savepoint active.
|
||||||
|
* Adds `Connection::prepare_cached`. `Connection` now keeps an internal cache of any statements
|
||||||
|
prepared via this method. The size of this cache defaults to 16 (`prepare_cached` will always
|
||||||
|
work but may re-prepare statements if more are prepared than the cache holds), and can be
|
||||||
|
controlled via `Connection::set_prepared_statement_cache_capacity`.
|
||||||
* Adds `insert` convenience method to `Statement` which returns the row ID of an inserted row.
|
* Adds `insert` convenience method to `Statement` which returns the row ID of an inserted row.
|
||||||
* Adds `exists` convenience method returning whether a query finds one or more rows.
|
* Adds `exists` convenience method returning whether a query finds one or more rows.
|
||||||
* Adds support for serializing types from the `serde_json` crate. Requires the `serde_json` feature.
|
* Adds support for serializing types from the `serde_json` crate. Requires the `serde_json` feature.
|
||||||
|
23
benches/lib.rs
Normal file
23
benches/lib.rs
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
#![feature(test)]
|
||||||
|
extern crate test;
|
||||||
|
|
||||||
|
extern crate rusqlite;
|
||||||
|
|
||||||
|
use rusqlite::Connection;
|
||||||
|
use rusqlite::cache::StatementCache;
|
||||||
|
use test::Bencher;
|
||||||
|
|
||||||
|
#[bench]
|
||||||
|
fn bench_no_cache(b: &mut Bencher) {
|
||||||
|
let db = Connection::open_in_memory().unwrap();
|
||||||
|
let sql = "SELECT 1, 'test', 3.14 UNION SELECT 2, 'exp', 2.71";
|
||||||
|
b.iter(|| db.prepare(sql).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[bench]
|
||||||
|
fn bench_cache(b: &mut Bencher) {
|
||||||
|
let db = Connection::open_in_memory().unwrap();
|
||||||
|
let cache = StatementCache::new(&db, 15);
|
||||||
|
let sql = "SELECT 1, 'test', 3.14 UNION SELECT 2, 'exp', 2.71";
|
||||||
|
b.iter(|| cache.get(sql).unwrap());
|
||||||
|
}
|
@ -8,7 +8,7 @@ fi
|
|||||||
|
|
||||||
cd $(git rev-parse --show-toplevel)
|
cd $(git rev-parse --show-toplevel)
|
||||||
rm -rf target/doc/
|
rm -rf target/doc/
|
||||||
multirust run nightly cargo doc --no-deps --features "load_extension trace"
|
multirust run nightly cargo doc --no-deps --features "backup cache functions load_extension trace blob"
|
||||||
echo '<meta http-equiv=refresh content=0;url=rusqlite/index.html>' > target/doc/index.html
|
echo '<meta http-equiv=refresh content=0;url=rusqlite/index.html>' > target/doc/index.html
|
||||||
ghp-import target/doc
|
ghp-import target/doc
|
||||||
git push origin gh-pages:gh-pages
|
git push origin gh-pages:gh-pages
|
||||||
|
269
src/cache.rs
Normal file
269
src/cache.rs
Normal file
@ -0,0 +1,269 @@
|
|||||||
|
//! Prepared statements cache for faster execution.
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
use lru_cache::LruCache;
|
||||||
|
use {Result, Connection, Statement};
|
||||||
|
use raw_statement::RawStatement;
|
||||||
|
|
||||||
|
impl Connection {
|
||||||
|
/// Prepare a SQL statement for execution, returning a previously prepared (but
|
||||||
|
/// not currently in-use) statement if one is available. The returned statement
|
||||||
|
/// will be cached for reuse by future calls to `prepare_cached` once it is
|
||||||
|
/// dropped.
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use rusqlite::{Connection, Result};
|
||||||
|
/// fn insert_new_people(conn: &Connection) -> Result<()> {
|
||||||
|
/// {
|
||||||
|
/// let mut stmt = try!(conn.prepare_cached("INSERT INTO People (name) VALUES (?)"));
|
||||||
|
/// 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"]));
|
||||||
|
/// }
|
||||||
|
/// Ok(())
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// # Failure
|
||||||
|
///
|
||||||
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
||||||
|
/// underlying SQLite call fails.
|
||||||
|
pub fn prepare_cached<'a>(&'a self, sql: &str) -> Result<CachedStatement<'a>> {
|
||||||
|
self.cache.get(&self, sql)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the maximum number of cached prepared statements this connection will hold.
|
||||||
|
/// By default, a connection will hold a relatively small number of cached statements.
|
||||||
|
/// If you need more, or know that you will not use cached statements, you can set
|
||||||
|
/// the capacity manually using this method.
|
||||||
|
pub fn set_prepared_statement_cache_capacity(&self, capacity: usize) {
|
||||||
|
self.cache.set_capacity(capacity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prepared statements LRU cache.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct StatementCache(RefCell<LruCache<String, RawStatement>>);
|
||||||
|
|
||||||
|
/// Cacheable statement.
|
||||||
|
///
|
||||||
|
/// Statement will return automatically to the cache by default.
|
||||||
|
/// If you want the statement to be discarded, call `discard()` on it.
|
||||||
|
pub struct CachedStatement<'conn> {
|
||||||
|
stmt: Option<Statement<'conn>>,
|
||||||
|
cache: &'conn StatementCache,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'conn> Deref for CachedStatement<'conn> {
|
||||||
|
type Target = Statement<'conn>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Statement<'conn> {
|
||||||
|
self.stmt.as_ref().unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'conn> DerefMut for CachedStatement<'conn> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Statement<'conn> {
|
||||||
|
self.stmt.as_mut().unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'conn> Drop for CachedStatement<'conn> {
|
||||||
|
#[allow(unused_must_use)]
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(stmt) = self.stmt.take() {
|
||||||
|
self.cache.cache_stmt(stmt.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'conn> CachedStatement<'conn> {
|
||||||
|
fn new(stmt: Statement<'conn>, cache: &'conn StatementCache) -> CachedStatement<'conn> {
|
||||||
|
CachedStatement {
|
||||||
|
stmt: Some(stmt),
|
||||||
|
cache: cache,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn discard(mut self) {
|
||||||
|
self.stmt = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StatementCache {
|
||||||
|
/// Create a statement cache.
|
||||||
|
pub fn with_capacity(capacity: usize) -> StatementCache {
|
||||||
|
StatementCache(RefCell::new(LruCache::new(capacity)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_capacity(&self, capacity: usize) {
|
||||||
|
self.0.borrow_mut().set_capacity(capacity)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search the cache for a prepared-statement object that implements `sql`.
|
||||||
|
// If no such prepared-statement can be found, allocate and prepare a new one.
|
||||||
|
//
|
||||||
|
// # Failure
|
||||||
|
//
|
||||||
|
// Will return `Err` if no cached statement can be found and the underlying SQLite prepare
|
||||||
|
// call fails.
|
||||||
|
fn get<'conn>(&'conn self,
|
||||||
|
conn: &'conn Connection,
|
||||||
|
sql: &str)
|
||||||
|
-> Result<CachedStatement<'conn>> {
|
||||||
|
let mut cache = self.0.borrow_mut();
|
||||||
|
let stmt = match cache.remove(sql) {
|
||||||
|
Some(raw_stmt) => Ok(Statement::new(conn, raw_stmt)),
|
||||||
|
None => conn.prepare(sql),
|
||||||
|
};
|
||||||
|
stmt.map(|stmt| CachedStatement::new(stmt, self))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return a statement to the cache.
|
||||||
|
fn cache_stmt(&self, stmt: RawStatement) {
|
||||||
|
let mut cache = self.0.borrow_mut();
|
||||||
|
stmt.clear_bindings();
|
||||||
|
let sql = String::from_utf8_lossy(stmt.sql().to_bytes()).to_string();
|
||||||
|
cache.insert(sql, stmt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use Connection;
|
||||||
|
use super::StatementCache;
|
||||||
|
|
||||||
|
impl StatementCache {
|
||||||
|
fn clear(&self) {
|
||||||
|
self.0.borrow_mut().clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn len(&self) -> usize {
|
||||||
|
self.0.borrow().len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capacity(&self) -> usize {
|
||||||
|
self.0.borrow().capacity()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cache() {
|
||||||
|
let db = Connection::open_in_memory().unwrap();
|
||||||
|
let cache = &db.cache;
|
||||||
|
let initial_capacity = cache.capacity();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert!(initial_capacity > 0);
|
||||||
|
|
||||||
|
let sql = "PRAGMA schema_version";
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert_eq!(0,
|
||||||
|
stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32, i64>(0));
|
||||||
|
}
|
||||||
|
assert_eq!(1, cache.len());
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert_eq!(0,
|
||||||
|
stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32, i64>(0));
|
||||||
|
}
|
||||||
|
assert_eq!(1, cache.len());
|
||||||
|
|
||||||
|
cache.clear();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert_eq!(initial_capacity, cache.capacity());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_set_capacity() {
|
||||||
|
let db = Connection::open_in_memory().unwrap();
|
||||||
|
let cache = &db.cache;
|
||||||
|
|
||||||
|
let sql = "PRAGMA schema_version";
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert_eq!(0,
|
||||||
|
stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32, i64>(0));
|
||||||
|
}
|
||||||
|
assert_eq!(1, cache.len());
|
||||||
|
|
||||||
|
db.set_prepared_statement_cache_capacity(0);
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert_eq!(0,
|
||||||
|
stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32, i64>(0));
|
||||||
|
}
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
|
||||||
|
db.set_prepared_statement_cache_capacity(8);
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert_eq!(0,
|
||||||
|
stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32, i64>(0));
|
||||||
|
}
|
||||||
|
assert_eq!(1, cache.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_discard() {
|
||||||
|
let db = Connection::open_in_memory().unwrap();
|
||||||
|
let cache = &db.cache;
|
||||||
|
|
||||||
|
let sql = "PRAGMA schema_version";
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
assert_eq!(0,
|
||||||
|
stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32, i64>(0));
|
||||||
|
stmt.discard();
|
||||||
|
}
|
||||||
|
assert_eq!(0, cache.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ddl() {
|
||||||
|
let db = Connection::open_in_memory().unwrap();
|
||||||
|
db.execute_batch(r#"
|
||||||
|
CREATE TABLE foo (x INT);
|
||||||
|
INSERT INTO foo VALUES (1);
|
||||||
|
"#)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let sql = "SELECT * FROM foo";
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!(1i32,
|
||||||
|
stmt.query_map(&[], |r| r.get(0)).unwrap().next().unwrap().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
db.execute_batch(r#"
|
||||||
|
ALTER TABLE foo ADD COLUMN y INT;
|
||||||
|
UPDATE foo SET y = 2;
|
||||||
|
"#)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut stmt = db.prepare_cached(sql).unwrap();
|
||||||
|
assert_eq!((1i32, 2i32),
|
||||||
|
stmt.query_map(&[], |r| (r.get(0), r.get(1)))
|
||||||
|
.unwrap()
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
85
src/lib.rs
85
src/lib.rs
@ -55,6 +55,7 @@
|
|||||||
|
|
||||||
extern crate libc;
|
extern crate libc;
|
||||||
extern crate libsqlite3_sys as ffi;
|
extern crate libsqlite3_sys as ffi;
|
||||||
|
extern crate lru_cache;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate bitflags;
|
extern crate bitflags;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -76,24 +77,32 @@ use libc::{c_int, c_char};
|
|||||||
|
|
||||||
use types::{ToSql, FromSql};
|
use types::{ToSql, FromSql};
|
||||||
use error::{error_from_sqlite_code, error_from_handle};
|
use error::{error_from_sqlite_code, error_from_handle};
|
||||||
|
use raw_statement::RawStatement;
|
||||||
|
use cache::StatementCache;
|
||||||
|
|
||||||
pub use transaction::{SqliteTransaction, Transaction, TransactionBehavior};
|
pub use transaction::{SqliteTransaction, Transaction, TransactionBehavior};
|
||||||
pub use error::{SqliteError, Error};
|
pub use error::{SqliteError, Error};
|
||||||
|
pub use cache::CachedStatement;
|
||||||
|
|
||||||
#[cfg(feature = "load_extension")]
|
#[cfg(feature = "load_extension")]
|
||||||
pub use load_extension_guard::{SqliteLoadExtensionGuard, LoadExtensionGuard};
|
pub use load_extension_guard::{SqliteLoadExtensionGuard, LoadExtensionGuard};
|
||||||
|
|
||||||
pub mod types;
|
pub mod types;
|
||||||
mod transaction;
|
mod transaction;
|
||||||
|
mod cache;
|
||||||
mod named_params;
|
mod named_params;
|
||||||
mod error;
|
mod error;
|
||||||
mod convenient;
|
mod convenient;
|
||||||
|
mod raw_statement;
|
||||||
#[cfg(feature = "load_extension")]mod load_extension_guard;
|
#[cfg(feature = "load_extension")]mod load_extension_guard;
|
||||||
#[cfg(feature = "trace")]pub mod trace;
|
#[cfg(feature = "trace")]pub mod trace;
|
||||||
#[cfg(feature = "backup")]pub mod backup;
|
#[cfg(feature = "backup")]pub mod backup;
|
||||||
#[cfg(feature = "functions")]pub mod functions;
|
#[cfg(feature = "functions")]pub mod functions;
|
||||||
#[cfg(feature = "blob")]pub mod blob;
|
#[cfg(feature = "blob")]pub mod blob;
|
||||||
|
|
||||||
|
// Number of cached prepared statements we'll hold on to.
|
||||||
|
const STATEMENT_CACHE_DEFAULT_CAPACITY: usize = 16;
|
||||||
|
|
||||||
/// Old name for `Result`. `SqliteResult` is deprecated.
|
/// Old name for `Result`. `SqliteResult` is deprecated.
|
||||||
pub type SqliteResult<T> = Result<T>;
|
pub type SqliteResult<T> = Result<T>;
|
||||||
|
|
||||||
@ -146,6 +155,7 @@ pub type SqliteConnection = Connection;
|
|||||||
/// A connection to a SQLite database.
|
/// A connection to a SQLite database.
|
||||||
pub struct Connection {
|
pub struct Connection {
|
||||||
db: RefCell<InnerConnection>,
|
db: RefCell<InnerConnection>,
|
||||||
|
cache: StatementCache,
|
||||||
path: Option<PathBuf>,
|
path: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -190,6 +200,7 @@ impl Connection {
|
|||||||
InnerConnection::open_with_flags(&c_path, flags).map(|db| {
|
InnerConnection::open_with_flags(&c_path, flags).map(|db| {
|
||||||
Connection {
|
Connection {
|
||||||
db: RefCell::new(db),
|
db: RefCell::new(db),
|
||||||
|
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
|
||||||
path: Some(path.as_ref().to_path_buf()),
|
path: Some(path.as_ref().to_path_buf()),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -208,6 +219,7 @@ impl Connection {
|
|||||||
InnerConnection::open_with_flags(&c_memory, flags).map(|db| {
|
InnerConnection::open_with_flags(&c_memory, flags).map(|db| {
|
||||||
Connection {
|
Connection {
|
||||||
db: RefCell::new(db),
|
db: RefCell::new(db),
|
||||||
|
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
|
||||||
path: None,
|
path: None,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -647,7 +659,7 @@ impl InnerConnection {
|
|||||||
&mut c_stmt,
|
&mut c_stmt,
|
||||||
ptr::null_mut())
|
ptr::null_mut())
|
||||||
};
|
};
|
||||||
self.decode_result(r).map(|_| Statement::new(conn, c_stmt))
|
self.decode_result(r).map(|_| Statement::new(conn, RawStatement::new(c_stmt)))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn changes(&mut self) -> c_int {
|
fn changes(&mut self) -> c_int {
|
||||||
@ -668,25 +680,23 @@ pub type SqliteStatement<'conn> = Statement<'conn>;
|
|||||||
/// A prepared statement.
|
/// A prepared statement.
|
||||||
pub struct Statement<'conn> {
|
pub struct Statement<'conn> {
|
||||||
conn: &'conn Connection,
|
conn: &'conn Connection,
|
||||||
stmt: *mut ffi::sqlite3_stmt,
|
stmt: RawStatement,
|
||||||
column_count: c_int,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'conn> Statement<'conn> {
|
impl<'conn> Statement<'conn> {
|
||||||
fn new(conn: &Connection, stmt: *mut ffi::sqlite3_stmt) -> Statement {
|
fn new(conn: &Connection, stmt: RawStatement) -> Statement {
|
||||||
Statement {
|
Statement {
|
||||||
conn: conn,
|
conn: conn,
|
||||||
stmt: stmt,
|
stmt: stmt,
|
||||||
column_count: unsafe { ffi::sqlite3_column_count(stmt) },
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get all the column names in the result set of the prepared statement.
|
/// Get all the column names in the result set of the prepared statement.
|
||||||
pub fn column_names(&self) -> Vec<&str> {
|
pub fn column_names(&self) -> Vec<&str> {
|
||||||
let n = self.column_count;
|
let n = self.column_count();
|
||||||
let mut cols = Vec::with_capacity(n as usize);
|
let mut cols = Vec::with_capacity(n as usize);
|
||||||
for i in 0..n {
|
for i in 0..n {
|
||||||
let slice = unsafe { CStr::from_ptr(ffi::sqlite3_column_name(self.stmt, i)) };
|
let slice = self.stmt.column_name(i);
|
||||||
let s = str::from_utf8(slice.to_bytes()).unwrap();
|
let s = str::from_utf8(slice.to_bytes()).unwrap();
|
||||||
cols.push(s);
|
cols.push(s);
|
||||||
}
|
}
|
||||||
@ -695,7 +705,7 @@ impl<'conn> Statement<'conn> {
|
|||||||
|
|
||||||
/// Return the number of columns in the result set returned by the prepared statement.
|
/// Return the number of columns in the result set returned by the prepared statement.
|
||||||
pub fn column_count(&self) -> i32 {
|
pub fn column_count(&self) -> i32 {
|
||||||
self.column_count
|
self.stmt.column_count()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the column index in the result set for a given column name.
|
/// Returns the column index in the result set for a given column name.
|
||||||
@ -705,10 +715,9 @@ impl<'conn> Statement<'conn> {
|
|||||||
/// Will return an `Error::InvalidColumnName` when there is no column with the specified `name`.
|
/// Will return an `Error::InvalidColumnName` when there is no column with the specified `name`.
|
||||||
pub fn column_index(&self, name: &str) -> Result<i32> {
|
pub fn column_index(&self, name: &str) -> Result<i32> {
|
||||||
let bytes = name.as_bytes();
|
let bytes = name.as_bytes();
|
||||||
let n = self.column_count;
|
let n = self.column_count();
|
||||||
for i in 0..n {
|
for i in 0..n {
|
||||||
let slice = unsafe { CStr::from_ptr(ffi::sqlite3_column_name(self.stmt, i)) };
|
if bytes == self.stmt.column_name(i).to_bytes() {
|
||||||
if bytes == slice.to_bytes() {
|
|
||||||
return Ok(i);
|
return Ok(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -739,18 +748,16 @@ impl<'conn> Statement<'conn> {
|
|||||||
/// Will return `Err` if binding parameters fails, the executed statement returns rows (in
|
/// 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.
|
/// which case `query` should be used instead), or the underling SQLite call fails.
|
||||||
pub fn execute(&mut self, params: &[&ToSql]) -> Result<c_int> {
|
pub fn execute(&mut self, params: &[&ToSql]) -> Result<c_int> {
|
||||||
unsafe {
|
|
||||||
try!(self.bind_parameters(params));
|
try!(self.bind_parameters(params));
|
||||||
self.execute_()
|
self.execute_()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn execute_(&mut self) -> Result<c_int> {
|
fn execute_(&mut self) -> Result<c_int> {
|
||||||
let r = ffi::sqlite3_step(self.stmt);
|
let r = self.stmt.step();
|
||||||
ffi::sqlite3_reset(self.stmt);
|
self.stmt.reset();
|
||||||
match r {
|
match r {
|
||||||
ffi::SQLITE_DONE => {
|
ffi::SQLITE_DONE => {
|
||||||
if self.column_count == 0 {
|
if self.column_count() == 0 {
|
||||||
Ok(self.conn.changes())
|
Ok(self.conn.changes())
|
||||||
} else {
|
} else {
|
||||||
Err(Error::ExecuteReturnedResults)
|
Err(Error::ExecuteReturnedResults)
|
||||||
@ -785,10 +792,7 @@ impl<'conn> Statement<'conn> {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if binding parameters fails.
|
/// Will return `Err` if binding parameters fails.
|
||||||
pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> Result<Rows<'a>> {
|
pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> Result<Rows<'a>> {
|
||||||
unsafe {
|
|
||||||
try!(self.bind_parameters(params));
|
try!(self.bind_parameters(params));
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Rows::new(self))
|
Ok(Rows::new(self))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -849,32 +853,39 @@ impl<'conn> Statement<'conn> {
|
|||||||
self.finalize_()
|
self.finalize_()
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn bind_parameters(&mut self, params: &[&ToSql]) -> Result<()> {
|
fn bind_parameters(&mut self, params: &[&ToSql]) -> Result<()> {
|
||||||
assert!(params.len() as c_int == ffi::sqlite3_bind_parameter_count(self.stmt),
|
assert!(params.len() as c_int == self.stmt.bind_parameter_count(),
|
||||||
"incorrect number of parameters to query(): expected {}, got {}",
|
"incorrect number of parameters to query(): expected {}, got {}",
|
||||||
ffi::sqlite3_bind_parameter_count(self.stmt),
|
self.stmt.bind_parameter_count(),
|
||||||
params.len());
|
params.len());
|
||||||
|
|
||||||
for (i, p) in params.iter().enumerate() {
|
for (i, p) in params.iter().enumerate() {
|
||||||
try!(self.conn.decode_result(p.bind_parameter(self.stmt, (i + 1) as c_int)));
|
try!(unsafe {
|
||||||
|
self.conn.decode_result(p.bind_parameter(self.stmt.ptr(), (i + 1) as c_int))
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn finalize_(&mut self) -> Result<()> {
|
fn finalize_(&mut self) -> Result<()> {
|
||||||
let r = unsafe { ffi::sqlite3_finalize(self.stmt) };
|
let mut stmt = RawStatement::new(ptr::null_mut());
|
||||||
self.stmt = ptr::null_mut();
|
mem::swap(&mut stmt, &mut self.stmt);
|
||||||
self.conn.decode_result(r)
|
self.conn.decode_result(stmt.finalize())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'conn> Into<RawStatement> for Statement<'conn> {
|
||||||
|
fn into(mut self) -> RawStatement {
|
||||||
|
let mut stmt = RawStatement::new(ptr::null_mut());
|
||||||
|
mem::swap(&mut stmt, &mut self.stmt);
|
||||||
|
stmt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'conn> fmt::Debug for Statement<'conn> {
|
impl<'conn> fmt::Debug for Statement<'conn> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
let sql = unsafe {
|
let sql = str::from_utf8(self.stmt.sql().to_bytes());
|
||||||
let c_slice = CStr::from_ptr(ffi::sqlite3_sql(self.stmt)).to_bytes();
|
|
||||||
str::from_utf8(c_slice)
|
|
||||||
};
|
|
||||||
f.debug_struct("Statement")
|
f.debug_struct("Statement")
|
||||||
.field("conn", self.conn)
|
.field("conn", self.conn)
|
||||||
.field("stmt", &self.stmt)
|
.field("stmt", &self.stmt)
|
||||||
@ -984,9 +995,7 @@ impl<'stmt> Rows<'stmt> {
|
|||||||
|
|
||||||
fn reset(&mut self) {
|
fn reset(&mut self) {
|
||||||
if let Some(stmt) = self.stmt.take() {
|
if let Some(stmt) = self.stmt.take() {
|
||||||
unsafe {
|
stmt.stmt.reset();
|
||||||
ffi::sqlite3_reset(stmt.stmt);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -996,7 +1005,7 @@ impl<'stmt> Iterator for Rows<'stmt> {
|
|||||||
|
|
||||||
fn next(&mut self) -> Option<Result<Row<'stmt>>> {
|
fn next(&mut self) -> Option<Result<Row<'stmt>>> {
|
||||||
self.stmt.and_then(|stmt| {
|
self.stmt.and_then(|stmt| {
|
||||||
match unsafe { ffi::sqlite3_step(stmt.stmt) } {
|
match stmt.stmt.step() {
|
||||||
ffi::SQLITE_ROW => {
|
ffi::SQLITE_ROW => {
|
||||||
let current_row = self.current_row.get() + 1;
|
let current_row = self.current_row.get() + 1;
|
||||||
self.current_row.set(current_row);
|
self.current_row.set(current_row);
|
||||||
@ -1091,8 +1100,8 @@ impl<'stmt> Row<'stmt> {
|
|||||||
unsafe {
|
unsafe {
|
||||||
let idx = try!(idx.idx(self.stmt));
|
let idx = try!(idx.idx(self.stmt));
|
||||||
|
|
||||||
if T::column_has_valid_sqlite_type(self.stmt.stmt, idx) {
|
if T::column_has_valid_sqlite_type(self.stmt.stmt.ptr(), idx) {
|
||||||
FromSql::column_result(self.stmt.stmt, idx)
|
FromSql::column_result(self.stmt.stmt.ptr(), idx)
|
||||||
} else {
|
} else {
|
||||||
Err(Error::InvalidColumnType)
|
Err(Error::InvalidColumnType)
|
||||||
}
|
}
|
||||||
@ -1115,7 +1124,7 @@ pub trait RowIndex {
|
|||||||
impl RowIndex for i32 {
|
impl RowIndex for i32 {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn idx(&self, stmt: &Statement) -> Result<i32> {
|
fn idx(&self, stmt: &Statement) -> Result<i32> {
|
||||||
if *self < 0 || *self >= stmt.column_count {
|
if *self < 0 || *self >= stmt.column_count() {
|
||||||
Err(Error::InvalidColumnIndex(*self))
|
Err(Error::InvalidColumnIndex(*self))
|
||||||
} else {
|
} else {
|
||||||
Ok(*self)
|
Ok(*self)
|
||||||
|
@ -1,7 +1,5 @@
|
|||||||
use libc::c_int;
|
use libc::c_int;
|
||||||
|
|
||||||
use super::ffi;
|
|
||||||
|
|
||||||
use {Result, Error, Connection, Statement, Rows, Row, str_to_cstring};
|
use {Result, Error, Connection, Statement, Rows, Row, str_to_cstring};
|
||||||
use types::ToSql;
|
use types::ToSql;
|
||||||
|
|
||||||
@ -56,11 +54,7 @@ impl<'conn> Statement<'conn> {
|
|||||||
/// is valid but not a bound parameter of this statement.
|
/// is valid but not a bound parameter of this statement.
|
||||||
pub fn parameter_index(&self, name: &str) -> Result<Option<i32>> {
|
pub fn parameter_index(&self, name: &str) -> Result<Option<i32>> {
|
||||||
let c_name = try!(str_to_cstring(name));
|
let c_name = try!(str_to_cstring(name));
|
||||||
let c_index = unsafe { ffi::sqlite3_bind_parameter_index(self.stmt, c_name.as_ptr()) };
|
Ok(self.stmt.bind_parameter_index(&c_name))
|
||||||
Ok(match c_index {
|
|
||||||
0 => None, // A zero is returned if no matching parameter is found.
|
|
||||||
n => Some(n),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute the prepared statement with named parameter(s). If any parameters
|
/// Execute the prepared statement with named parameter(s). If any parameters
|
||||||
@ -87,7 +81,7 @@ impl<'conn> Statement<'conn> {
|
|||||||
/// which case `query` should be used instead), or the underling SQLite call fails.
|
/// which case `query` should be used instead), or the underling SQLite call fails.
|
||||||
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<c_int> {
|
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<c_int> {
|
||||||
try!(self.bind_parameters_named(params));
|
try!(self.bind_parameters_named(params));
|
||||||
unsafe { self.execute_() }
|
self.execute_()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute the prepared statement with named parameter(s), returning an iterator over the
|
/// Execute the prepared statement with named parameter(s), returning an iterator over the
|
||||||
@ -120,7 +114,7 @@ impl<'conn> Statement<'conn> {
|
|||||||
fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> {
|
fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> {
|
||||||
for &(name, value) in params {
|
for &(name, value) in params {
|
||||||
if let Some(i) = try!(self.parameter_index(name)) {
|
if let Some(i) = try!(self.parameter_index(name)) {
|
||||||
try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt, i) }));
|
try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt.ptr(), i) }));
|
||||||
} else {
|
} else {
|
||||||
return Err(Error::InvalidParameterName(name.into()));
|
return Err(Error::InvalidParameterName(name.into()));
|
||||||
}
|
}
|
||||||
|
70
src/raw_statement.rs
Normal file
70
src/raw_statement.rs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
use std::ffi::CStr;
|
||||||
|
use std::ptr;
|
||||||
|
use libc::c_int;
|
||||||
|
use super::ffi;
|
||||||
|
|
||||||
|
// Private newtype for raw sqlite3_stmts that finalize themselves when dropped.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RawStatement(*mut ffi::sqlite3_stmt);
|
||||||
|
|
||||||
|
impl RawStatement {
|
||||||
|
pub fn new(stmt: *mut ffi::sqlite3_stmt) -> RawStatement {
|
||||||
|
RawStatement(stmt)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub unsafe fn ptr(&self) -> *mut ffi::sqlite3_stmt {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn column_count(&self) -> c_int {
|
||||||
|
unsafe { ffi::sqlite3_column_count(self.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn column_name(&self, idx: c_int) -> &CStr {
|
||||||
|
unsafe { CStr::from_ptr(ffi::sqlite3_column_name(self.0, idx)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn step(&self) -> c_int {
|
||||||
|
unsafe { ffi::sqlite3_step(self.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset(&self) -> c_int {
|
||||||
|
unsafe { ffi::sqlite3_reset(self.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bind_parameter_count(&self) -> c_int {
|
||||||
|
unsafe { ffi::sqlite3_bind_parameter_count(self.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bind_parameter_index(&self, name: &CStr) -> Option<c_int> {
|
||||||
|
let r = unsafe { ffi::sqlite3_bind_parameter_index(self.0, name.as_ptr()) };
|
||||||
|
match r {
|
||||||
|
0 => None,
|
||||||
|
i => Some(i),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_bindings(&self) -> c_int {
|
||||||
|
unsafe { ffi::sqlite3_clear_bindings(self.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sql(&self) -> &CStr {
|
||||||
|
unsafe { CStr::from_ptr(ffi::sqlite3_sql(self.0)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finalize(mut self) -> c_int {
|
||||||
|
self.finalize_()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finalize_(&mut self) -> c_int {
|
||||||
|
let r = unsafe { ffi::sqlite3_finalize(self.0) };
|
||||||
|
self.0 = ptr::null_mut();
|
||||||
|
r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for RawStatement {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.finalize_();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user