This commit is contained in:
Mikayla Maki 2022-10-14 16:06:18 -07:00 committed by K Simmons
parent dbea3cf20c
commit 4b09f77950
7 changed files with 88 additions and 44 deletions

View file

@ -1,5 +1,6 @@
mod kvp;
mod migrations;
mod serialized_item;
use anyhow::Result;
use migrations::MIGRATIONS;
@ -9,9 +10,10 @@ use std::path::Path;
use std::sync::Arc;
pub use kvp::*;
pub use serialized_item::*;
pub struct Db {
connecion: Connection,
connection: Mutex<Connection>,
in_memory: bool,
}
@ -22,26 +24,26 @@ pub struct Db {
impl Db {
/// Open or create a database at the given file path. Falls back to in memory database if the
/// database at the given path is corrupted
pub fn open(path: &Path) -> Result<Arc<Mutex<Self>>> {
pub fn open(path: &Path) -> Result<Arc<Self>> {
let conn = Connection::open(path)?;
Self::initialize(conn, false).or_else(|_| Self::open_in_memory())
}
/// Open a in memory database for testing and as a fallback.
pub fn open_in_memory() -> Result<Arc<Mutex<Self>>> {
pub fn open_in_memory() -> Result<Arc<Self>> {
let conn = Connection::open_in_memory()?;
Self::initialize(conn, true)
}
fn initialize(mut conn: Connection, in_memory: bool) -> Result<Arc<Mutex<Self>>> {
fn initialize(mut conn: Connection, in_memory: bool) -> Result<Arc<Self>> {
MIGRATIONS.to_latest(&mut conn)?;
Ok(Arc::new(Mutex::new(Self {
connecion: conn,
Ok(Arc::new(Self {
connection: Mutex::new(conn),
in_memory,
})))
}))
}
}
@ -57,34 +59,26 @@ mod tests {
let real_db = Db::open(&dir.path().join("test.db")).unwrap();
for db in [&real_db, &fake_db] {
assert_eq!(
db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[None, None, None]
);
assert_eq!(db.read_kvp("key-1").unwrap(), None);
db.write([("key-1", "one"), ("key-3", "three")]).unwrap();
assert_eq!(
db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[
Some("one".as_bytes().to_vec()),
None,
Some("three".as_bytes().to_vec())
]
);
db.write_kvp("key-1", "one").unwrap();
assert_eq!(db.read_kvp("key-1").unwrap(), Some("one".to_string()));
db.delete(["key-3", "key-4"]).unwrap();
assert_eq!(
db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[Some("one".as_bytes().to_vec()), None, None,]
);
db.write_kvp("key-2", "two").unwrap();
assert_eq!(db.read_kvp("key-2").unwrap(), Some("two".to_string()));
db.delete_kvp("key-1").unwrap();
assert_eq!(db.read_kvp("key-1").unwrap(), None);
}
drop(real_db);
let real_db = Db::open(&dir.path().join("test.db")).unwrap();
assert_eq!(
real_db.read(["key-1", "key-2", "key-3"]).unwrap(),
&[Some("one".as_bytes().to_vec()), None, None,]
);
real_db.write_kvp("key-1", "one").unwrap();
assert_eq!(real_db.read_kvp("key-1").unwrap(), None);
real_db.write_kvp("key-2", "two").unwrap();
assert_eq!(real_db.read_kvp("key-2").unwrap(), Some("two".to_string()));
}
}