34 lines
876 B
Rust
34 lines
876 B
Rust
|
|
use anyhow::Result;
|
||
|
|
use diesel::prelude::*;
|
||
|
|
|
||
|
|
use crate::repository::Repository;
|
||
|
|
use crate::settings::Settings;
|
||
|
|
|
||
|
|
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
||
|
|
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
||
|
|
|
||
|
|
pub struct Database {
|
||
|
|
pub connection: SqliteConnection,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Database {
|
||
|
|
pub fn new(path: &str) -> Result<Self> {
|
||
|
|
let mut connection = SqliteConnection::establish(path)?;
|
||
|
|
connection.run_pending_migrations(MIGRATIONS)
|
||
|
|
.map_err(|e| anyhow::anyhow!("Error running migrations: {}", e))?;
|
||
|
|
|
||
|
|
Ok(Self { connection })
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn new_in_memory() -> Result<Self> {
|
||
|
|
Self::new(":memory:")
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn get_repository(&mut self) -> Repository {
|
||
|
|
Repository::new(self)
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn get_settings(&mut self) -> Settings {
|
||
|
|
Settings::new(self)
|
||
|
|
}
|
||
|
|
}
|