//! The database: connecting and the migrations compiled into the binary. use std::str::FromStr; use std::time::Duration; use anyhow::{Context, Result}; use sqlx::PgPool; use sqlx::migrate::Migrator; use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; use crate::config::Config; pub static MIGRATOR: Migrator = sqlx::migrate!("./migrations"); pub async fn connect(cfg: &Config) -> Result { let mut opts = PgConnectOptions::from_str(&cfg.database_url) .context("VISA_DATABASE_URL is not a PostgreSQL URL")? .application_name("visa"); if let Some(pw) = &cfg.database_password { opts = opts.password(pw); } PgPoolOptions::new() .max_connections(8) .acquire_timeout(Duration::from_secs(10)) .connect_with(opts) .await .context("connecting to the database") } pub async fn migrate(pool: &PgPool) -> Result<()> { MIGRATOR.run(pool).await.context("running the migrations") }