From e7c555aa2d065a986bd9f88cd882b4b8757d8a04 Mon Sep 17 00:00:00 2001 From: Joscha Date: Thu, 15 Dec 2022 14:24:42 +0100 Subject: [PATCH] Add single-threaded SimpleVault --- src/lib.rs | 1 + src/simple.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/simple.rs diff --git a/src/lib.rs b/src/lib.rs index 98a5757..5d65e1a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ // Clippy lints #![warn(clippy::use_self)] +pub mod simple; #[cfg(feature = "tokio")] pub mod tokio; diff --git a/src/simple.rs b/src/simple.rs new file mode 100644 index 0000000..071affe --- /dev/null +++ b/src/simple.rs @@ -0,0 +1,45 @@ +//! A simple, single-threaded vault. +//! +//! This vault may be useful if you want to re-use existing [`Action`]s and +//! [`Migration`]s but don't need the additional guarantees and overhead of the +//! other vaults. + +use rusqlite::Connection; + +use crate::{Action, Migration}; + +/// A simple, single-threaded vault. +pub struct SimpleVault(Connection); + +impl SimpleVault { + /// Create a new vault from an existing [`Connection`], applying the + /// migrations in the process. + pub fn new(conn: Connection, migrations: &[Migration]) -> rusqlite::Result { + Self::new_and_prepare(conn, migrations, |_| Ok(())) + } + + /// Create a new vault from an existing [`Connection`], applying the + /// migrations in the process. + /// + /// The `prepare` parameter allows access to the database after all + /// migrations have occurred. This parameter could be replaced by executing + /// an [`Action`] performing the same operations. + pub fn new_and_prepare( + mut conn: Connection, + migrations: &[Migration], + prepare: impl FnOnce(&mut Connection) -> rusqlite::Result<()>, + ) -> rusqlite::Result { + crate::migrate(&mut conn, migrations)?; + prepare(&mut conn)?; + Ok(Self(conn)) + } + + /// Execute an [`Action`] and return the result. + pub fn execute(&mut self, action: A) -> rusqlite::Result + where + A: Action + Send + 'static, + A::Result: Send, + { + action.run(&mut self.0) + } +}