Skip to main content

rs_zero/db/
pool.rs

1#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
2use sqlx::Pool as SqlxPool;
3#[cfg(feature = "db-mysql")]
4use sqlx::{MySql, mysql::MySqlPoolOptions};
5#[cfg(feature = "db-postgres")]
6use sqlx::{Postgres, postgres::PgPoolOptions};
7#[cfg(feature = "db-sqlite")]
8use sqlx::{Sqlite, sqlite::SqlitePoolOptions};
9
10#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
11use crate::db::{DatabaseConfig, DatabaseError, DatabaseKind, DatabaseResult};
12
13/// SQLite database pool.
14#[cfg(feature = "db-sqlite")]
15pub type SqliteDatabasePool = SqlxPool<Sqlite>;
16
17/// PostgreSQL database pool.
18#[cfg(feature = "db-postgres")]
19pub type PostgresDatabasePool = SqlxPool<Postgres>;
20
21/// MySQL database pool.
22#[cfg(feature = "db-mysql")]
23pub type MySqlDatabasePool = SqlxPool<MySql>;
24
25/// Database pool used by the enabled default adapter.
26#[cfg(feature = "db-sqlite")]
27pub type DatabasePool = SqliteDatabasePool;
28
29/// Database pool used when PostgreSQL is the enabled adapter.
30#[cfg(all(not(feature = "db-sqlite"), feature = "db-postgres"))]
31pub type DatabasePool = PostgresDatabasePool;
32
33/// Database pool used when MySQL is the only enabled adapter.
34#[cfg(all(
35    not(feature = "db-sqlite"),
36    not(feature = "db-postgres"),
37    feature = "db-mysql"
38))]
39pub type DatabasePool = MySqlDatabasePool;
40
41/// Connects a SQLx pool for the default enabled adapter.
42#[cfg(feature = "db-sqlite")]
43pub async fn connect_pool(config: &DatabaseConfig) -> DatabaseResult<DatabasePool> {
44    connect_sqlite_pool(config).await
45}
46
47/// Connects a SQLx pool for the default enabled adapter.
48#[cfg(all(not(feature = "db-sqlite"), feature = "db-postgres"))]
49pub async fn connect_pool(config: &DatabaseConfig) -> DatabaseResult<DatabasePool> {
50    connect_postgres_pool(config).await
51}
52
53/// Connects a SQLx pool for the default enabled adapter.
54#[cfg(all(
55    not(feature = "db-sqlite"),
56    not(feature = "db-postgres"),
57    feature = "db-mysql"
58))]
59pub async fn connect_pool(config: &DatabaseConfig) -> DatabaseResult<DatabasePool> {
60    connect_mysql_pool(config).await
61}
62
63/// Connects a SQLite SQLx pool.
64#[cfg(feature = "db-sqlite")]
65pub async fn connect_sqlite_pool(config: &DatabaseConfig) -> DatabaseResult<SqliteDatabasePool> {
66    if config.kind != DatabaseKind::Sqlite {
67        return Err(DatabaseError::Unsupported(
68            "sqlite database kind required".to_string(),
69        ));
70    }
71    Ok(SqlitePoolOptions::new()
72        .max_connections(config.max_connections)
73        .acquire_timeout(config.connect_timeout)
74        .connect(&config.url)
75        .await?)
76}
77
78/// Connects a PostgreSQL SQLx pool.
79#[cfg(feature = "db-postgres")]
80pub async fn connect_postgres_pool(
81    config: &DatabaseConfig,
82) -> DatabaseResult<PostgresDatabasePool> {
83    if config.kind != DatabaseKind::Postgres {
84        return Err(DatabaseError::Unsupported(
85            "postgres database kind required".to_string(),
86        ));
87    }
88    Ok(PgPoolOptions::new()
89        .max_connections(config.max_connections)
90        .acquire_timeout(config.connect_timeout)
91        .connect(&config.url)
92        .await?)
93}
94
95/// Connects a MySQL SQLx pool.
96#[cfg(feature = "db-mysql")]
97pub async fn connect_mysql_pool(config: &DatabaseConfig) -> DatabaseResult<MySqlDatabasePool> {
98    if config.kind != DatabaseKind::Mysql {
99        return Err(DatabaseError::Unsupported(
100            "mysql database kind required".to_string(),
101        ));
102    }
103    Ok(MySqlPoolOptions::new()
104        .max_connections(config.max_connections)
105        .acquire_timeout(config.connect_timeout)
106        .connect(&config.url)
107        .await?)
108}
109
110/// Runs a lightweight health check on the default pool type.
111#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
112pub async fn health_check(pool: &DatabasePool) -> DatabaseResult<()> {
113    sqlx::query("SELECT 1").execute(pool).await?;
114    Ok(())
115}
116
117/// Runs a lightweight health check and records SQL metrics.
118#[cfg(all(
119    feature = "observability",
120    any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql")
121))]
122pub async fn health_check_with_metrics(
123    pool: &DatabasePool,
124    metrics: &crate::observability::MetricsRegistry,
125) -> DatabaseResult<()> {
126    crate::observability::observe_sql_query(
127        Some(metrics),
128        default_database_kind_label(),
129        "db",
130        "health_check",
131        "select",
132        health_check(pool),
133    )
134    .await
135}
136
137/// Runs a lightweight PostgreSQL health check.
138#[cfg(feature = "db-postgres")]
139pub async fn health_check_postgres(pool: &PostgresDatabasePool) -> DatabaseResult<()> {
140    sqlx::query("SELECT 1").execute(pool).await?;
141    Ok(())
142}
143
144/// Runs a lightweight MySQL health check.
145#[cfg(feature = "db-mysql")]
146pub async fn health_check_mysql(pool: &MySqlDatabasePool) -> DatabaseResult<()> {
147    sqlx::query("SELECT 1").execute(pool).await?;
148    Ok(())
149}
150
151#[cfg(all(feature = "observability", feature = "db-sqlite"))]
152fn default_database_kind_label() -> &'static str {
153    "sqlite"
154}
155
156#[cfg(all(
157    feature = "observability",
158    not(feature = "db-sqlite"),
159    feature = "db-postgres"
160))]
161fn default_database_kind_label() -> &'static str {
162    "postgres"
163}
164
165#[cfg(all(
166    feature = "observability",
167    not(feature = "db-sqlite"),
168    not(feature = "db-postgres"),
169    feature = "db-mysql"
170))]
171fn default_database_kind_label() -> &'static str {
172    "mysql"
173}
174
175#[cfg(test)]
176mod tests {
177    use crate::db::{DatabaseConfig, DatabaseKind};
178    #[cfg(feature = "db-sqlite")]
179    use crate::db::{connect_pool, health_check};
180
181    #[cfg(feature = "db-sqlite")]
182    #[tokio::test]
183    async fn sqlite_pool_passes_health_check() {
184        let pool = connect_pool(&DatabaseConfig::default())
185            .await
186            .expect("pool");
187        health_check(&pool).await.expect("health");
188    }
189
190    #[test]
191    fn postgres_config_uses_postgres_kind() {
192        let config = DatabaseConfig::postgres("postgres://localhost/app");
193        assert_eq!(config.kind, DatabaseKind::Postgres);
194    }
195
196    #[test]
197    fn mysql_config_uses_mysql_kind() {
198        let config = DatabaseConfig::mysql("mysql://localhost/app");
199        assert_eq!(config.kind, DatabaseKind::Mysql);
200    }
201}