affluence/src/db/mod.rs

47 lines
1.3 KiB
Rust
Raw Normal View History

2023-05-15 17:38:13 +02:00
mod schema;
pub mod users;
2023-05-16 15:47:13 +02:00
use diesel::connection::SimpleConnection;
use diesel::r2d2::{ConnectionManager, Pool};
2023-05-16 16:25:33 +02:00
use diesel::sqlite::{Sqlite, SqliteConnection};
use std::error::Error;
2023-05-16 15:47:13 +02:00
2023-05-16 16:25:33 +02:00
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");
type DbError = Box<dyn Error + Send + Sync + 'static>;
fn run_migrations(connection: &mut impl MigrationHarness<Sqlite>) -> Result<(), DbError> {
// This will run the necessary migrations.
//
// See the documentation for `MigrationHarness` for
// all available methods.
connection.run_pending_migrations(MIGRATIONS)?;
Ok(())
}
fn initialize_db(conn: &mut SqliteConnection) -> Result<(), DbError> {
2023-05-16 15:47:13 +02:00
// Enable WAL mode and enforce foreign keys
2023-05-16 16:25:33 +02:00
conn.batch_execute(
"PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;",
)?;
run_migrations(conn)?;
Ok(())
2023-05-16 15:47:13 +02:00
}
2023-05-16 16:25:33 +02:00
pub fn initialize_pool(url: &str) -> Result<Pool<ConnectionManager<SqliteConnection>>, DbError> {
2023-05-16 15:47:13 +02:00
let manager = ConnectionManager::new(url);
2023-05-16 16:25:33 +02:00
let pool = Pool::builder()
.test_on_check_out(true)
.build(manager)
.expect("oops");
2023-05-16 15:47:13 +02:00
2023-05-16 16:25:33 +02:00
let mut conn = pool.get()?;
initialize_db(&mut conn)?;
2023-05-16 15:47:13 +02:00
2023-05-16 16:25:33 +02:00
Ok(pool)
2023-05-16 15:47:13 +02:00
}