shared-framework 0.0.17

Reusable building blocks for HTTP services — Hyper routing, SeaORM data layer, validation, OpenAPI docs, jobs, queues, cache.
Documentation
//! Database connection setup.
//!
//! [`DatabaseFactory`] builds a SeaORM [`DatabaseConnection`] from the
//! application environment. Use it once at startup and share the connection
//! (or registered repositories) afterwards.
use crate::env::EnvironmentKind;
use crate::AppEnvironment;
use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};
use tracing::log;

/// Builds database connections from application configuration.
pub struct DatabaseFactory;

impl DatabaseFactory {
    /// Connects using the environment's Postgres URL and pool settings.
    ///
    /// Uses up to 30 connections (minimum 10) with a 300-second max lifetime.
    /// SQL logging and statement spans follow the `log_sql` flag, with the
    /// log level derived from the environment kind. Returns a [`DbErr`] when
    /// the connection fails.
    pub async fn connect(env: &AppEnvironment) -> Result<DatabaseConnection, DbErr> {
        let mut con = &mut ConnectOptions::new(&env.pg_url);

        con = con.max_connections(30u32);
        con = con.min_connections(10u32);
        con = con.max_lifetime(std::time::Duration::from_secs(300));
        con = con.sqlx_logging_level(match env.kind {
            EnvironmentKind::Development => log::LevelFilter::Trace,
            EnvironmentKind::Debug => log::LevelFilter::Debug,
            EnvironmentKind::Staging => log::LevelFilter::Info,
            EnvironmentKind::Production => log::LevelFilter::Error,
        });
        con = con.sqlx_logging(env.log_sql);
        con = con.record_stmt_in_spans(env.log_sql);

        Database::connect(con.clone()).await
    }
}