Merge branch 'master' of https://github.com/jgallagher/rusqlite into stmt-cache

This commit is contained in:
Gwenael Treguier
2015-12-13 11:23:54 +01:00
17 changed files with 2134 additions and 528 deletions

View File

@@ -1,7 +1,7 @@
//! Prepared statements cache for faster execution.
extern crate lru_cache;
use {SqliteResult, SqliteConnection, SqliteStatement};
use {Result, Connection, Statement};
use self::lru_cache::LruCache;
/// Prepared statements cache.
@@ -9,14 +9,17 @@ use self::lru_cache::LruCache;
/// FIXME limitation: the same SQL can be cached only once...
#[derive(Debug)]
pub struct StatementCache<'conn> {
pub conn: &'conn SqliteConnection,
cache: LruCache<String, SqliteStatement<'conn>>,
pub conn: &'conn Connection,
cache: LruCache<String, Statement<'conn>>,
}
impl<'conn> StatementCache<'conn> {
/// Create a statement cache.
pub fn new(conn: &'conn SqliteConnection, capacity: usize) -> StatementCache<'conn> {
StatementCache{ conn: conn, cache: LruCache::new(capacity) }
pub fn new(conn: &'conn Connection, capacity: usize) -> StatementCache<'conn> {
StatementCache {
conn: conn,
cache: LruCache::new(capacity),
}
}
/// Search the cache for a prepared-statement object that implements `sql`.
@@ -25,11 +28,11 @@ impl<'conn> StatementCache<'conn> {
/// # Failure
///
/// Will return `Err` if no cached statement can be found and the underlying SQLite prepare call fails.
pub fn get(&mut self, sql: &str) -> SqliteResult<SqliteStatement<'conn>> {
pub fn get(&mut self, sql: &str) -> Result<Statement<'conn>> {
let stmt = self.cache.remove(sql);
match stmt {
Some(stmt) => Ok(stmt),
_ => self.conn.prepare(sql)
_ => self.conn.prepare(sql),
}
}
@@ -41,7 +44,7 @@ impl<'conn> StatementCache<'conn> {
///
/// Will return `Err` if `stmt` (or the already cached statement implementing the same SQL) statement is `discard`ed
/// and the underlying SQLite finalize call fails.
pub fn release(&mut self, stmt: SqliteStatement<'conn>, discard: bool) -> SqliteResult<()> {
pub fn release(&mut self, mut stmt: Statement<'conn>, discard: bool) -> Result<()> {
if discard {
return stmt.finalize();
}
@@ -68,19 +71,19 @@ impl<'conn> StatementCache<'conn> {
#[cfg(test)]
mod test {
use SqliteConnection;
use Connection;
use super::StatementCache;
#[test]
#[test]
fn test_cache() {
let db = SqliteConnection::open_in_memory().unwrap();
let db = Connection::open_in_memory().unwrap();
let mut cache = StatementCache::new(&db, 10);
let sql = "PRAGMA schema_version";
let mut stmt = cache.get(sql).unwrap();
//println!("NEW {:?}", stmt);
// println!("NEW {:?}", stmt);
cache.release(stmt, false).unwrap();
stmt = cache.get(sql).unwrap();
//println!("CACHED {:?}", stmt);
// println!("CACHED {:?}", stmt);
cache.release(stmt, true).unwrap();
cache.flush();
}