karbon_framework/db/
database.rs1use super::{DbPool, DbPoolOptions};
2use crate::config::Config;
3
4#[derive(Debug, Clone)]
6pub struct Database {
7 pool: DbPool,
8}
9
10impl Database {
11 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 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 pub fn pool(&self) -> &DbPool {
33 &self.pool
34 }
35
36 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 pub async fn begin(&self) -> Result<sqlx::Transaction<'_, super::Db>, sqlx::Error> {
46 self.pool.begin().await
47 }
48
49 pub async fn ping(&self) -> Result<(), sqlx::Error> {
51 sqlx::query("SELECT 1").execute(&self.pool).await?;
52 Ok(())
53 }
54}