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 db: Database,
10
11 // We just need to store the temporary file here so that it sticks around
12 // while TempDb is alive.
13 #[allow(dead_code)]
14 temp_db_file: NamedTempFile<File>,
15}
16
17impl TempDb {
18 /// Creates a new database at a temporary path.
19 ///
20 /// ## Errors
21 /// Returns [`anyhow::Error`] if we can't:
22 ///
23 /// - Create a new [`NamedTempFile`] for the database
24 /// - Initialize the database at the temporary path
25 pub async fn new() -> anyhow::Result<Self> {
26 let temp_db_file = NamedTempFile::with_suffix(".db")?;
27 let db = Database::new_with_records_table(temp_db_file.path()).await?;
28 Ok(Self { db, temp_db_file })
29 }
30}
31
32impl Deref for TempDb {
33 type Target = Database;
34
35 fn deref(&self) -> &Self::Target {
36 &self.db
37 }
38}