Skip to main content

karbon_framework/db/
database.rs

1use super::{DbPool, DbPoolOptions};
2use crate::config::Config;
3
4/// Database wrapper with connection pool
5#[derive(Debug, Clone)]
6pub struct Database {
7    pool: DbPool,
8}
9
10impl Database {
11    /// Connect to the database using app config
12    pub async fn connect(config: &Config) -> Result<Self, sqlx::Error> {
13        let pool = DbPoolOptions::new()
14            .max_connections(config.db_max_connections)
15            .connect(&config.database_url())
16            .await?;
17
18        Ok(Self { pool })
19    }
20
21    /// Connect with a raw URL
22    pub async fn connect_url(url: &str) -> Result<Self, sqlx::Error> {
23        let pool = DbPoolOptions::new()
24            .max_connections(5)
25            .connect(url)
26            .await?;
27
28        Ok(Self { pool })
29    }
30
31    /// Get a reference to the connection pool
32    pub fn pool(&self) -> &DbPool {
33        &self.pool
34    }
35
36    /// Run pending migrations from a directory path
37    pub async fn migrate(&self, path: &str) -> Result<(), sqlx::migrate::MigrateError> {
38        sqlx::migrate::Migrator::new(std::path::Path::new(path))
39            .await?
40            .run(&self.pool)
41            .await
42    }
43
44    /// Start a new transaction
45    pub async fn begin(&self) -> Result<sqlx::Transaction<'_, super::Db>, sqlx::Error> {
46        self.pool.begin().await
47    }
48
49    /// Health check — ping the database
50    pub async fn ping(&self) -> Result<(), sqlx::Error> {
51        sqlx::query("SELECT 1").execute(&self.pool).await?;
52        Ok(())
53    }
54}