omry_integration/db.rs
1use omry_db::Database;
2use std::fs::File;
3use std::ops::Deref;
4use tempfile::NamedTempFile;
5
6/// Data structure to keep the temporary file holding the database alive,
7/// because it will get unlinked on drop.
8pub struct TempDb {
9 /// The database.
10 db: Database,
11
12 /// We need to store the temporary file here so that it sticks around
13 /// while [`TempDb`] is alive.
14 #[allow(dead_code)]
15 temp_db_file: NamedTempFile<File>,
16}
17
18impl TempDb {
19 /// Creates a new database at a temporary path.
20 ///
21 /// ## Errors
22 /// Returns [`anyhow::Error`] if we can't:
23 ///
24 /// - Create a new [`NamedTempFile`] for the database
25 /// - Initialize the database at the temporary path
26 pub async fn new() -> anyhow::Result<Self> {
27 let temp_db_file = NamedTempFile::with_suffix(".db")?;
28 let db = Database::new_with_records_table(temp_db_file.path()).await?;
29 Ok(Self { db, temp_db_file })
30 }
31}
32
33impl Deref for TempDb {
34 type Target = Database;
35
36 fn deref(&self) -> &Self::Target {
37 &self.db
38 }
39}