| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
use diesel::prelude::*; |
| 24 |
use diesel::r2d2; |
| 25 |
use diesel::r2d2::ConnectionManager; |
| 26 |
|
| 27 |
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations}; |
| 28 |
|
| 29 |
use std::path::PathBuf; |
| 30 |
use std::sync::LazyLock; |
| 31 |
|
| 32 |
use crate::errors::DataError; |
| 33 |
|
| 34 |
#[cfg(not(test))] |
| 35 |
use crate::xdg_dirs; |
| 36 |
|
| 37 |
type Pool = r2d2::Pool<ConnectionManager<SqliteConnection>>; |
| 38 |
|
| 39 |
const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations/"); |
| 40 |
|
| 41 |
static POOL: LazyLock<Pool> = LazyLock::new(|| init_pool(DB_PATH.to_str().unwrap())); |
| 42 |
|
| 43 |
#[cfg(not(test))] |
| 44 |
static DB_PATH: LazyLock<PathBuf> = LazyLock::new(|| { |
| 45 |
xdg_dirs::PODCASTS_XDG |
| 46 |
.place_data_file("podcasts.db") |
| 47 |
.unwrap() |
| 48 |
}); |
| 49 |
|
| 50 |
#[cfg(test)] |
| 51 |
pub(crate) static TEMPDIR: LazyLock<tempfile::TempDir> = |
| 52 |
LazyLock::new(|| tempfile::TempDir::with_prefix("podcasts_unit_test").unwrap()); |
| 53 |
|
| 54 |
#[cfg(test)] |
| 55 |
static DB_PATH: LazyLock<PathBuf> = LazyLock::new(|| TEMPDIR.path().join("podcasts.db")); |
| 56 |
|
| 57 |
|
| 58 |
pub(crate) fn connection() -> Pool { |
| 59 |
POOL.clone() |
| 60 |
} |
| 61 |
|
| 62 |
fn init_pool(db_path: &str) -> Pool { |
| 63 |
let manager = ConnectionManager::<SqliteConnection>::new(db_path); |
| 64 |
let pool = r2d2::Pool::builder() |
| 65 |
.max_size(1) |
| 66 |
.build(manager) |
| 67 |
.expect("Failed to create pool."); |
| 68 |
|
| 69 |
{ |
| 70 |
let mut db = pool.get().expect("Failed to initialize pool."); |
| 71 |
run_migration_on(&mut db).expect("Failed to run migrations during init."); |
| 72 |
} |
| 73 |
info!("Database pool initialized."); |
| 74 |
pool |
| 75 |
} |
| 76 |
|
| 77 |
fn run_migration_on( |
| 78 |
conn: &mut SqliteConnection, |
| 79 |
) -> Result<Vec<diesel::migration::MigrationVersion<'_>>, DataError> { |
| 80 |
info!("Running DB Migrations..."); |
| 81 |
conn.run_pending_migrations(MIGRATIONS) |
| 82 |
.map_err(|_| DataError::DieselMigrationError) |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
pub fn truncate_db() -> Result<(), DataError> { |
| 88 |
use diesel::connection::SimpleConnection; |
| 89 |
let db = connection(); |
| 90 |
let mut con = db.get()?; |
| 91 |
con.batch_execute("DELETE FROM episodes; DELETE FROM shows; DELETE FROM source")?; |
| 92 |
Ok(()) |
| 93 |
} |