Skip to main content

yaiko_core/
database.rs

1use std::sync::Arc;
2
3use sqlx::Pool;
4
5#[cfg(feature = "postgres")]
6use sqlx::Postgres;
7
8#[cfg(feature = "sqlite")]
9use sqlx::Sqlite;
10
11/// Database connection pool wrapper
12///
13/// Supports both PostgreSQL and SQLite depending on enabled features.
14///
15/// # Example (SQLite)
16/// ```rust,no_run
17/// # #[cfg(feature = "sqlite")]
18/// # {
19/// # use yaiko_core::Database;
20/// # async fn demo() -> Result<(), sqlx::Error> {
21/// let db = Database::sqlite("sqlite:./app.db").await?;
22/// # let _ = db;
23/// # Ok(())
24/// # }
25/// # }
26/// ```
27///
28/// # Example (PostgreSQL)
29/// ```rust,no_run
30/// # #[cfg(feature = "postgres")]
31/// # {
32/// # use yaiko_core::Database;
33/// # async fn demo() -> Result<(), sqlx::Error> {
34/// let db = Database::postgres("postgres://user:pass@localhost/db").await?;
35/// # let _ = db;
36/// # Ok(())
37/// # }
38/// # }
39/// ```
40#[derive(Clone)]
41pub enum Database {
42    #[cfg(feature = "postgres")]
43    Postgres(Arc<Pool<Postgres>>),
44    #[cfg(feature = "sqlite")]
45    Sqlite(Arc<Pool<Sqlite>>),
46}
47
48impl Database {
49    /// Connect to a PostgreSQL database
50    #[cfg(feature = "postgres")]
51    pub async fn postgres(database_url: &str) -> Result<Self, sqlx::Error> {
52        let pool = sqlx::postgres::PgPoolOptions::new()
53            .max_connections(10)
54            .connect(database_url)
55            .await?;
56
57        Ok(Database::Postgres(Arc::new(pool)))
58    }
59
60    /// Connect to a SQLite database
61    #[cfg(feature = "sqlite")]
62    pub async fn sqlite(database_url: &str) -> Result<Self, sqlx::Error> {
63        let pool = sqlx::sqlite::SqlitePoolOptions::new()
64            .max_connections(5)
65            .connect(database_url)
66            .await?;
67
68        Ok(Database::Sqlite(Arc::new(pool)))
69    }
70
71    /// Check whether the selected database pool is reachable.
72    #[cfg(feature = "postgres")]
73    pub async fn ping_pg(&self) -> Result<(), sqlx::Error> {
74        match self {
75            Database::Postgres(pool) => sqlx::query("SELECT 1").execute(&**pool).await.map(|_| ()),
76            #[allow(unreachable_patterns)]
77            _ => Err(sqlx::Error::Configuration("Wrong database type".into())),
78        }
79    }
80
81    /// Check whether the selected database pool is reachable.
82    #[cfg(feature = "sqlite")]
83    pub async fn ping_sqlite(&self) -> Result<(), sqlx::Error> {
84        match self {
85            Database::Sqlite(pool) => sqlx::query("SELECT 1").execute(&**pool).await.map(|_| ()),
86            #[allow(unreachable_patterns)]
87            _ => Err(sqlx::Error::Configuration("Wrong database type".into())),
88        }
89    }
90
91    /// Begin a PostgreSQL transaction for explicit commit/rollback control.
92    #[cfg(feature = "postgres")]
93    pub async fn begin_pg(&self) -> Result<sqlx::Transaction<'_, Postgres>, sqlx::Error> {
94        match self {
95            Database::Postgres(pool) => pool.begin().await,
96            #[allow(unreachable_patterns)]
97            _ => Err(sqlx::Error::Configuration("Wrong database type".into())),
98        }
99    }
100
101    /// Begin a SQLite transaction for explicit commit/rollback control.
102    #[cfg(feature = "sqlite")]
103    pub async fn begin_sqlite(&self) -> Result<sqlx::Transaction<'_, Sqlite>, sqlx::Error> {
104        match self {
105            Database::Sqlite(pool) => pool.begin().await,
106            #[allow(unreachable_patterns)]
107            _ => Err(sqlx::Error::Configuration("Wrong database type".into())),
108        }
109    }
110
111    /// Execute a raw SQL query and return affected rows.
112    #[cfg(feature = "postgres")]
113    pub async fn execute_pg(&self, query: &str) -> Result<u64, sqlx::Error> {
114        match self {
115            Database::Postgres(pool) => {
116                let result = sqlx::query(query).execute(&**pool).await?;
117                Ok(result.rows_affected())
118            }
119            #[allow(unreachable_patterns)]
120            _ => Err(sqlx::Error::Configuration("Wrong database type".into())),
121        }
122    }
123
124    #[cfg(feature = "sqlite")]
125    pub async fn execute_sqlite(&self, query: &str) -> Result<u64, sqlx::Error> {
126        match self {
127            Database::Sqlite(pool) => {
128                let result = sqlx::query(query).execute(&**pool).await?;
129                Ok(result.rows_affected())
130            }
131            #[allow(unreachable_patterns)]
132            _ => Err(sqlx::Error::Configuration("Wrong database type".into())),
133        }
134    }
135
136    /// Get the underlying PostgreSQL pool
137    #[cfg(feature = "postgres")]
138    pub fn pg_pool(&self) -> Option<&Pool<Postgres>> {
139        match self {
140            Database::Postgres(pool) => Some(pool),
141            #[allow(unreachable_patterns)]
142            _ => None,
143        }
144    }
145
146    /// Get the underlying SQLite pool
147    #[cfg(feature = "sqlite")]
148    pub fn sqlite_pool(&self) -> Option<&Pool<Sqlite>> {
149        match self {
150            Database::Sqlite(pool) => Some(pool),
151            #[allow(unreachable_patterns)]
152            _ => None,
153        }
154    }
155}
156
157/// Trait for bindable parameters
158pub trait Bindable: Send + Sync {
159    #[cfg(feature = "postgres")]
160    fn bind_pg(&self, args: &mut sqlx::postgres::PgArguments);
161    #[cfg(feature = "sqlite")]
162    fn bind_sqlite(&self, args: &mut sqlx::sqlite::SqliteArguments<'_>);
163}