Line data Source code
1 : //! Centralizes the initialization of the database
2 :
3 : use rusqlite::config::DbConfig;
4 : use rusqlite::{Connection, LoadExtensionGuard};
5 : use std::fs::File;
6 : use std::io::Read;
7 : use std::path::PathBuf;
8 : use std::sync::{Arc, Mutex};
9 :
10 : // TODO: Can I use AsRef<Path>. See:
11 : // https://nick.groenen.me/notes/rust-path-vs-pathbuf/
12 :
13 : /// Returns a new `Connection` to the database.
14 18 : pub fn new(dbpath: String) -> anyhow::Result<Connection> {
15 18 : let db = Connection::open(dbpath)?;
16 18 : db.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, true)?;
17 18 : db.pragma_update(None, "journal_mode", "WAL")?;
18 : unsafe {
19 18 : let _guard = LoadExtensionGuard::new(&db)?;
20 18 : db.load_extension("libbliki_sqlite", Some("sqlite3_bliki_init"))?;
21 : }
22 18 : Ok(db)
23 18 : }
24 :
25 : /// Returns a new `Connection`. The database will be an in-memory
26 : /// database. Loads the schema from `src/schema.sql`. Optionally takes a path to
27 : /// an SQL file to execute against the databse. This is to seed any data the
28 : /// test scenario requires.
29 18 : pub(crate) fn setup_db(fixture_path: Option<PathBuf>) -> Connection {
30 18 : let db = new(":memory:".into()).unwrap();
31 18 : let mut file = File::open("sql/schema.sql").unwrap();
32 18 : let mut schema = String::new();
33 18 : file.read_to_string(&mut schema).unwrap();
34 18 : unsafe {
35 18 : let _guard = LoadExtensionGuard::new(&db).unwrap();
36 18 : db.execute_batch(&schema).unwrap();
37 18 : }
38 18 : if let Some(fixture_path) = fixture_path {
39 12 : let mut file = File::open(fixture_path).unwrap();
40 12 : let mut fixture = String::new();
41 12 : file.read_to_string(&mut fixture).unwrap();
42 12 : db.execute_batch(&fixture).unwrap()
43 6 : }
44 18 : db
45 18 : }
46 :
47 : /// Returns a new `Connection` to the database wrapped in an
48 : /// `Arc<Mutex<T>>`. Similar to `new_testdb`.
49 9 : pub fn setup_db_with_arcmutex(fixture_path: Option<PathBuf>) -> Arc<Mutex<Connection>> {
50 9 : let db = setup_db(fixture_path);
51 9 : Arc::new(Mutex::new(db))
52 9 : }
|