Skip to main content

shared_framework/data/
connectors.rs

1//! Database connection setup.
2//!
3//! [`DatabaseFactory`] builds a SeaORM [`DatabaseConnection`] from the
4//! application environment. Use it once at startup and share the connection
5//! (or registered repositories) afterwards.
6use crate::env::EnvironmentKind;
7use crate::AppEnvironment;
8use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};
9use tracing::log;
10
11/// Builds database connections from application configuration.
12pub struct DatabaseFactory;
13
14impl DatabaseFactory {
15    /// Connects using the environment's Postgres URL and pool settings.
16    ///
17    /// Uses up to 30 connections (minimum 10) with a 300-second max lifetime.
18    /// SQL logging and statement spans follow the `log_sql` flag, with the
19    /// log level derived from the environment kind. Returns a [`DbErr`] when
20    /// the connection fails.
21    pub async fn connect(env: &AppEnvironment) -> Result<DatabaseConnection, DbErr> {
22        let mut con = &mut ConnectOptions::new(&env.pg_url);
23
24        con = con.max_connections(30u32);
25        con = con.min_connections(10u32);
26        con = con.max_lifetime(std::time::Duration::from_secs(300));
27        con = con.sqlx_logging_level(match env.kind {
28            EnvironmentKind::Development => log::LevelFilter::Trace,
29            EnvironmentKind::Debug => log::LevelFilter::Debug,
30            EnvironmentKind::Staging => log::LevelFilter::Info,
31            EnvironmentKind::Production => log::LevelFilter::Error,
32        });
33        con = con.sqlx_logging(env.log_sql);
34        con = con.record_stmt_in_spans(env.log_sql);
35
36        Database::connect(con.clone()).await
37    }
38}