1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 use rusqlite::{self, CachedStatement, Connection, Statement}; 6 7 use std::ops::{Deref, DerefMut}; 8 9 /// MaybeCached is a type that can be used to help abstract 10 /// over cached and uncached rusqlite statements in a transparent manner. 11 pub enum MaybeCached<'conn> { 12 Uncached(Statement<'conn>), 13 Cached(CachedStatement<'conn>), 14 } 15 16 impl<'conn> Deref for MaybeCached<'conn> { 17 type Target = Statement<'conn>; 18 #[inline] deref(&self) -> &Statement<'conn>19 fn deref(&self) -> &Statement<'conn> { 20 match self { 21 MaybeCached::Cached(cached) => Deref::deref(cached), 22 MaybeCached::Uncached(uncached) => uncached, 23 } 24 } 25 } 26 27 impl<'conn> DerefMut for MaybeCached<'conn> { 28 #[inline] deref_mut(&mut self) -> &mut Statement<'conn>29 fn deref_mut(&mut self) -> &mut Statement<'conn> { 30 match self { 31 MaybeCached::Cached(cached) => DerefMut::deref_mut(cached), 32 MaybeCached::Uncached(uncached) => uncached, 33 } 34 } 35 } 36 37 impl<'conn> From<Statement<'conn>> for MaybeCached<'conn> { 38 #[inline] from(stmt: Statement<'conn>) -> Self39 fn from(stmt: Statement<'conn>) -> Self { 40 MaybeCached::Uncached(stmt) 41 } 42 } 43 44 impl<'conn> From<CachedStatement<'conn>> for MaybeCached<'conn> { 45 #[inline] from(stmt: CachedStatement<'conn>) -> Self46 fn from(stmt: CachedStatement<'conn>) -> Self { 47 MaybeCached::Cached(stmt) 48 } 49 } 50 51 impl<'conn> MaybeCached<'conn> { 52 #[inline] prepare( conn: &'conn Connection, sql: &str, cached: bool, ) -> rusqlite::Result<MaybeCached<'conn>>53 pub fn prepare( 54 conn: &'conn Connection, 55 sql: &str, 56 cached: bool, 57 ) -> rusqlite::Result<MaybeCached<'conn>> { 58 if cached { 59 Ok(MaybeCached::Cached(conn.prepare_cached(sql)?)) 60 } else { 61 Ok(MaybeCached::Uncached(conn.prepare(sql)?)) 62 } 63 } 64 } 65