1use sova_db::DbHandle;
4use sea_orm::{Database, DatabaseConnection};
5use sea_orm_migration::MigratorTrait;
6use tempfile::TempDir;
7
8pub struct SqliteTestDb {
10 _dir: TempDir,
11 url: String,
12}
13
14impl SqliteTestDb {
15 pub fn create() -> Self {
17 let dir = tempfile::tempdir().expect("tempdir");
18 let path = dir.path().join("test.db");
19 let url = format!("sqlite://{}?mode=rwc", path.display());
20 std::env::set_var("DATABASE_URL", &url);
22 Self { _dir: dir, url }
23 }
24
25 pub async fn migrate<M: MigratorTrait>() -> Self {
27 let db = Self::create();
28 apply_migrations::<M>(&db.url).await;
29 db
30 }
31
32 pub fn url(&self) -> &str {
33 &self.url
34 }
35
36 pub async fn connect(&self) -> DatabaseConnection {
38 Database::connect(&self.url)
39 .await
40 .expect("sqlite reconnect")
41 }
42
43 pub async fn handle(&self) -> DbHandle {
45 DbHandle::Conn(self.connect().await)
46 }
47}
48
49pub async fn apply_migrations<M: MigratorTrait>(url: &str) {
52 use sea_orm_migration::SchemaManager;
53 let conn = Database::connect(url).await.expect("sqlite connect");
54 let schema = SchemaManager::new(&conn);
55 for m in M::migrations() {
56 m.up(&schema).await.expect("migrate up");
57 }
58}