Use discard() instead of cacheable = false to avoid prevent cached

statements from returning to the cache.
This commit is contained in:
John Gallagher 2016-01-07 11:24:20 -05:00
parent ed0923bba9
commit 7b29277d6f

View File

@ -15,11 +15,10 @@ pub struct StatementCache<'conn> {
/// Cacheable statement. /// Cacheable statement.
/// ///
/// Statement will return automatically to the cache by default. /// Statement will return automatically to the cache by default.
/// If you want the statement to be discarded, you can set the `cacheable` flag to `false`. /// If you want the statement to be discarded, call `discard()` on it.
pub struct CachedStatement<'c: 's, 's> { pub struct CachedStatement<'c: 's, 's> {
stmt: Option<Statement<'c>>, stmt: Option<Statement<'c>>,
cache: &'s StatementCache<'c>, cache: &'s StatementCache<'c>,
pub cacheable: bool,
} }
impl<'c, 's> Deref for CachedStatement<'c, 's> { impl<'c, 's> Deref for CachedStatement<'c, 's> {
@ -39,10 +38,8 @@ impl<'c, 's> DerefMut for CachedStatement<'c, 's> {
impl<'c, 's> Drop for CachedStatement<'c, 's> { impl<'c, 's> Drop for CachedStatement<'c, 's> {
#[allow(unused_must_use)] #[allow(unused_must_use)]
fn drop(&mut self) { fn drop(&mut self) {
if self.cacheable { if let Some(stmt) = self.stmt.take() {
self.cache.release(self.stmt.take().unwrap()); self.cache.release(stmt);
} else {
self.stmt.take().unwrap().finalize();
} }
} }
} }
@ -52,9 +49,12 @@ impl<'c, 's> CachedStatement<'c, 's> {
CachedStatement { CachedStatement {
stmt: Some(stmt), stmt: Some(stmt),
cache: cache, cache: cache,
cacheable: true,
} }
} }
pub fn discard(mut self) {
self.stmt = None;
}
} }
impl<'conn> StatementCache<'conn> { impl<'conn> StatementCache<'conn> {
@ -67,7 +67,7 @@ impl<'conn> StatementCache<'conn> {
} }
/// Search the cache for a prepared-statement object that implements `sql`. /// 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. /// If no such prepared-statement can be found, allocate and prepare a new one.
/// ///
/// # Failure /// # Failure
/// ///
@ -151,7 +151,7 @@ mod test {
} }
#[test] #[test]
fn test_cacheable() { fn test_discard() {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();
let cache = StatementCache::new(&db, 15); let cache = StatementCache::new(&db, 15);
@ -161,7 +161,7 @@ mod test {
assert_eq!(0, cache.len()); assert_eq!(0, cache.len());
assert_eq!(0, assert_eq!(0,
stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32,i64>(0)); stmt.query(&[]).unwrap().get_expected_row().unwrap().get::<i32,i64>(0));
stmt.cacheable = false; stmt.discard();
} }
assert_eq!(0, cache.len()); assert_eq!(0, cache.len());
} }