metis_core/dal/database/
mod.rs

1pub 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
11/// Database connection and migration management
12pub struct Database {
13    connection_string: String,
14}
15
16impl Database {
17    /// Create a new database connection and run migrations
18    ///
19    /// # Arguments
20    /// * `connection_string` - SQLite connection string (e.g., ":memory:", "database.db", "file:database.db?mode=rw")
21    pub fn new(connection_string: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
22        // Run migrations once to ensure the database is set up
23        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    /// Get a new connection to the database
32    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        // For in-memory databases, we need to run migrations on each connection
38        // since each connection is a separate database
39        if self.connection_string == ":memory:" {
40            connection.run_pending_migrations(MIGRATIONS)?;
41        }
42
43        Ok(connection)
44    }
45
46    /// Get a document repository with a new connection
47    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    /// Get a document repository (consumes the database) - kept for compatibility
55    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}