pub mod configuration_repository;
pub mod models;
pub mod repository;
pub mod schema;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("src/dal/database/migrations");
pub struct Database {
connection_string: String,
}
fn configure_connection(connection: &mut SqliteConnection) -> Result<(), diesel::result::Error> {
diesel::sql_query("PRAGMA busy_timeout = 5000").execute(connection)?;
diesel::sql_query("PRAGMA journal_mode = WAL").execute(connection)?;
diesel::sql_query("PRAGMA synchronous = NORMAL").execute(connection)?;
Ok(())
}
impl Database {
pub fn new(connection_string: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
let mut connection = SqliteConnection::establish(connection_string)?;
configure_connection(&mut connection)?;
connection.run_pending_migrations(MIGRATIONS)?;
Ok(Self {
connection_string: connection_string.to_string(),
})
}
pub fn get_connection(
&self,
) -> Result<SqliteConnection, Box<dyn std::error::Error + Send + Sync>> {
let mut connection = SqliteConnection::establish(&self.connection_string)?;
configure_connection(&mut connection)?;
if self.connection_string == ":memory:" {
connection.run_pending_migrations(MIGRATIONS)?;
}
Ok(connection)
}
pub fn repository(
&self,
) -> Result<repository::DocumentRepository, Box<dyn std::error::Error + Send + Sync>> {
let connection = self.get_connection()?;
Ok(repository::DocumentRepository::new(connection))
}
pub fn into_repository(self) -> repository::DocumentRepository {
let connection = self.get_connection().expect("Failed to get connection");
repository::DocumentRepository::new(connection)
}
pub fn configuration_repository(
&self,
) -> Result<
configuration_repository::ConfigurationRepository,
Box<dyn std::error::Error + Send + Sync>,
> {
let connection = self.get_connection()?;
Ok(configuration_repository::ConfigurationRepository::new(
connection,
))
}
}