1use super::*;
2
3use ::sqlx::postgres::PgPoolOptions;
4use ::sqlx::Error;
5use ::sqlx::Pool;
6use ::sqlx::Postgres;
7use async_trait::async_trait;
8use tracing::instrument;
9
10#[async_trait]
11pub trait SqlxDatabaseConfig {
12 async fn init_pool(&self) -> Result<Pool<Postgres>, Error>;
13}
14
15#[async_trait]
16impl SqlxDatabaseConfig for DatabaseConfig {
17 #[instrument(skip_all, name = "db::sqlx::init_pool", fields(host = %self.host, db = %self.db_name))]
18 async fn init_pool(&self) -> Result<Pool<Postgres>, Error> {
19 self.pool_options().connect(&self.postgres_uri()).await
20 }
21}
22
23impl DatabaseConfig {
24 fn pool_options(&self) -> PgPoolOptions {
25 PgPoolOptions::new()
26 .max_connections(self.max_connections)
27 .acquire_timeout(self.connection_timeout())
28 }
29}
30
31#[cfg(test)]
32mod tests {
33 use once_cell::sync::Lazy;
34
35 use super::*;
36
37 #[test]
38 fn test_pool_options() {
39 assert_eq!(
40 "\
41 PoolOptions { \
42 max_connections: 30, \
43 min_connections: 0, \
44 connect_timeout: 1ns, \
45 max_lifetime: Some(1800s), \
46 idle_timeout: Some(600s), \
47 test_before_acquire: true \
48 }\
49 ",
50 format!("{:?}", CONFIG.pool_options()),
51 );
52 }
53
54 static CONFIG: Lazy<DatabaseConfig> = Lazy::new(|| DatabaseConfig {
55 host: "localhost".to_string(),
56 user: "username".to_string(),
57 password: "supersecurepassword".to_string(),
58 db_name: "my_db".to_string(),
59 max_connections: 30,
60 });
61}