#[cfg(feature = "embedded")]
pub(crate) mod embedded;
mod migrations;
pub(crate) use migrations::MigrationRunner;
pub use migrations::{MigrationReport, MigrationState};
use crate::config::DatabaseConfig;
use crate::error::{ForgeError, Result};
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use std::str::FromStr;
pub(crate) const MIN_SERVER_VERSION_NUM: i32 = 180_000;
const MAX_SERVER_VERSION_NUM: i32 = 190_000;
pub(crate) async fn connect(db: &DatabaseConfig) -> Result<sqlx::PgPool> {
let mut opts = PgConnectOptions::from_str(&db.postgres)
.map_err(|e| ForgeError::config(format!("invalid postgres connection string: {e}")))?
.application_name("forge");
let mut runtime_opts: Vec<(&str, String)> = Vec::new();
if !db.statement_timeout.is_zero() {
runtime_opts.push((
"statement_timeout",
db.statement_timeout.as_millis().to_string(),
));
}
if !db.lock_timeout.is_zero() {
runtime_opts.push(("lock_timeout", db.lock_timeout.as_millis().to_string()));
}
if !db.idle_in_transaction_timeout.is_zero() {
runtime_opts.push((
"idle_in_transaction_session_timeout",
db.idle_in_transaction_timeout.as_millis().to_string(),
));
}
if !runtime_opts.is_empty() {
opts = opts.options(runtime_opts);
}
let pool = PgPoolOptions::new()
.max_connections(db.max_connections)
.acquire_timeout(db.acquire_timeout)
.connect_with(opts)
.await
.map_err(|e| {
ForgeError::config(format!(
"could not connect to postgres (check host/credentials in FORGE_POSTGRES_URL): {}",
conn_cause(&e)
))
})?;
ping(&pool).await?;
verify_version(&pool).await?;
Ok(pool)
}
async fn ping(pool: &sqlx::PgPool) -> Result<()> {
sqlx::query_scalar!(r#"SELECT 1 AS "one!""#)
.fetch_one(pool)
.await
.map_err(|e| ForgeError::config(format!("postgres ping failed: {}", conn_cause(&e))))?;
Ok(())
}
async fn verify_version(pool: &sqlx::PgPool) -> Result<()> {
let num: i32 =
sqlx::query_scalar!(r#"SELECT current_setting('server_version_num')::int AS "v!""#)
.fetch_one(pool)
.await
.map_err(|e| {
ForgeError::config(format!(
"could not read postgres version: {}",
conn_cause(&e)
))
})?;
if !is_supported_server_version(num) {
return Err(ForgeError::config(format!(
"Postgres server_version_num={num} is unsupported; Forge requires PostgreSQL 18"
)));
}
Ok(())
}
fn is_supported_server_version(num: i32) -> bool {
(MIN_SERVER_VERSION_NUM..MAX_SERVER_VERSION_NUM).contains(&num)
}
fn conn_cause(e: &sqlx::Error) -> String {
match e {
sqlx::Error::Database(db) => db.message().to_string(),
sqlx::Error::Io(io) => format!("io error: {}", io.kind()),
sqlx::Error::PoolTimedOut => "connection pool timed out".to_string(),
sqlx::Error::PoolClosed => "connection pool closed".to_string(),
other => other.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::is_supported_server_version;
#[test]
fn postgres_18_is_the_only_supported_floor() {
assert!(!is_supported_server_version(179_999));
assert!(is_supported_server_version(180_000));
assert!(is_supported_server_version(180_001));
assert!(!is_supported_server_version(190_000));
}
}