Debian Codegraph @

podcasts-data/src/database.rs

raw symbols SCIP
1 // database.rs
2 //
3 // Copyright 2017 Jordan Petridis <[email protected]>
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 //
18 // SPDX-License-Identifier: GPL-3.0-or-later
19
20 //! Database Setup. This is only public to help with some unit tests.
21 // Diesel embed_migrations! triggers the lint
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 /// Get an r2d2 `SqliteConnection`.
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 /// Reset the database into a clean state.
86 // Test share a Temp file db.
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 }