@@ -38,6 +38,10 @@ pub struct Database {
3838 write_lock : Arc < Mutex < ( ) > > ,
3939 /// The database metrics.
4040 metrics : DatabaseMetrics ,
41+ /// The temporary directory used for testing. We keep it here to ensure it lives as long as the
42+ /// database instance as the temp directory is deleted when [`tempfile::TempDir`] is dropped.
43+ #[ cfg( feature = "test-utils" ) ]
44+ tmp_dir : Option < tempfile:: TempDir > ,
4145}
4246
4347impl Database {
@@ -80,8 +84,20 @@ impl Database {
8084 connection : SqlxSqliteConnector :: from_sqlx_sqlite_pool ( sqlx_pool) ,
8185 write_lock : Arc :: new ( Mutex :: new ( ( ) ) ) ,
8286 metrics : DatabaseMetrics :: default ( ) ,
87+ #[ cfg( feature = "test-utils" ) ]
88+ tmp_dir : None ,
8389 } )
8490 }
91+
92+ /// Creates a new [`Database`] instance for testing purposes, using the provided temporary
93+ /// directory to store the database files.
94+ #[ cfg( feature = "test-utils" ) ]
95+ pub async fn test ( dir : tempfile:: TempDir ) -> Result < Self , DatabaseError > {
96+ let path = dir. path ( ) . join ( "test.db" ) ;
97+ let mut db = Self :: new ( path. to_str ( ) . unwrap ( ) ) . await ?;
98+ db. tmp_dir = Some ( dir) ;
99+ Ok ( db)
100+ }
85101}
86102
87103#[ async_trait:: async_trait]
@@ -132,6 +148,8 @@ impl From<DatabaseConnection> for Database {
132148 connection,
133149 write_lock : Arc :: new ( Mutex :: new ( ( ) ) ) ,
134150 metrics : DatabaseMetrics :: default ( ) ,
151+ #[ cfg( feature = "test-utils" ) ]
152+ tmp_dir : None ,
135153 }
136154 }
137155}
0 commit comments