metis_core/dal/database/
mod.rs1pub mod models;
2pub mod repository;
3pub mod schema;
4
5use diesel::prelude::*;
6use diesel::sqlite::SqliteConnection;
7use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
8
9pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("src/dal/database/migrations");
10
11pub struct Database {
13 connection_string: String,
14}
15
16impl Database {
17 pub fn new(connection_string: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
22 let mut connection = SqliteConnection::establish(connection_string)?;
24 connection.run_pending_migrations(MIGRATIONS)?;
25
26 Ok(Self {
27 connection_string: connection_string.to_string(),
28 })
29 }
30
31 pub fn get_connection(
33 &self,
34 ) -> Result<SqliteConnection, Box<dyn std::error::Error + Send + Sync>> {
35 let mut connection = SqliteConnection::establish(&self.connection_string)?;
36
37 if self.connection_string == ":memory:" {
40 connection.run_pending_migrations(MIGRATIONS)?;
41 }
42
43 Ok(connection)
44 }
45
46 pub fn repository(
48 &self,
49 ) -> Result<repository::DocumentRepository, Box<dyn std::error::Error + Send + Sync>> {
50 let connection = self.get_connection()?;
51 Ok(repository::DocumentRepository::new(connection))
52 }
53
54 pub fn into_repository(self) -> repository::DocumentRepository {
56 let connection = self.get_connection().expect("Failed to get connection");
57 repository::DocumentRepository::new(connection)
58 }
59}