use crate::{
db::MigrationFailureKind,
result::{ClassifyError, DiagnosticKind, ErrorKind},
secret::ExposeSecret,
};
#[cfg(feature = "postgres-admin")]
use super::admin::{PostgresResetError, PostgresResetSettings};
use super::{
POSTGRES_HEALTH_ERROR, PostgresBootstrapError, PostgresBootstrapSettings,
PostgresDiagnosticKind, PostgresHealth, PostgresHealthStatus, PostgresMigrationRunError,
PostgresOperation, PostgresPoolError, PostgresPoolSettings, PostgresStartupRetrySettings,
advisory_lock_key, database_name, diagnose_migration_error, diagnose_operation_timeout,
diagnose_sqlx_error, redact_database_url, schema_maintenance_advisory_lock_key,
};
#[test]
fn rejects_zero_max_connections() {
let error = PostgresPoolSettings::default()
.with_max_connections(0)
.build()
.expect_err("zero max connections must be rejected");
assert_eq!(error.issues()[0].path(), "postgres.pool.max_connections");
}
#[test]
fn rejects_min_connections_above_max() {
let error = PostgresPoolSettings::default()
.with_max_connections(2)
.with_min_connections(3)
.build()
.expect_err("min connections above max must be rejected");
assert_eq!(error.issues()[0].path(), "postgres.pool.min_connections");
}
#[test]
fn rejects_zero_acquire_timeout() {
let error = PostgresPoolSettings::default()
.with_acquire_timeout(std::time::Duration::ZERO)
.build()
.expect_err("zero acquire timeout must be rejected");
assert_eq!(error.issues()[0].path(), "postgres.pool.acquire_timeout");
}
#[test]
fn rejects_acquire_timeout_outside_the_timer_range() {
let error = PostgresPoolSettings::default()
.with_acquire_timeout(std::time::Duration::MAX)
.build()
.expect_err("unrepresentable deadlines must be rejected before acquiring a connection");
assert_eq!(error.issues()[0].path(), "postgres.pool.acquire_timeout");
assert!(PostgresPoolSettings::default().build().is_ok());
}
#[test]
fn rejects_invalid_pool_maintenance_intervals() {
use std::time::Duration;
for timeout in [Duration::ZERO, Duration::MAX] {
for (settings, field) in [
(
PostgresPoolSettings::default().with_idle_timeout(Some(timeout)),
"idle_timeout",
),
(
PostgresPoolSettings::default().with_max_lifetime(Some(timeout)),
"max_lifetime",
),
] {
let error = settings.build().unwrap_err();
assert_eq!(error.issues()[0].path(), format!("postgres.pool.{field}"));
}
}
PostgresPoolSettings::default()
.with_idle_timeout(None)
.with_max_lifetime(None)
.build()
.unwrap();
}
#[test]
fn rejects_startup_retry_delays_outside_the_timer_range() {
let error = PostgresStartupRetrySettings::default()
.with_max_attempts(2)
.with_initial_delay(std::time::Duration::MAX)
.with_max_delay(std::time::Duration::MAX)
.build()
.unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.startup_retry.max_delay");
}
#[test]
fn exposes_pool_config_values() {
let config = PostgresPoolSettings::default()
.with_max_connections(20)
.with_min_connections(2)
.with_test_before_acquire(false)
.build()
.expect("pool settings should be valid");
assert_eq!(config.max_connections(), 20);
assert_eq!(config.min_connections(), 2);
assert!(!config.test_before_acquire());
}
#[test]
fn validates_bootstrap_config_before_touching_database() {
let result = PostgresBootstrapSettings::new(" ")
.build()
.expect_err("empty URL should be rejected");
assert_eq!(result.issues()[0].path(), "postgres.database_url");
let result = PostgresBootstrapSettings::new("not-a-postgres-url")
.build()
.expect_err("invalid URL should be rejected");
assert_eq!(result.issues()[0].path(), "postgres.database_url");
}
#[tokio::test]
async fn bootstrap_requires_migrator_when_migration_is_enabled() {
let result = super::bootstrap_database(
PostgresBootstrapSettings::new("postgres://postgres:postgres@localhost/app")
.with_migrate_on_startup(true)
.build()
.expect("bootstrap settings should be valid"),
None,
)
.await
.expect_err("missing migrator should be rejected before connecting");
assert!(matches!(result, PostgresBootstrapError::MissingMigrator));
}
#[test]
fn parses_database_name_without_exposing_credentials() {
assert_eq!(
database_name("postgres://app:secret@localhost:5432/app_dev").as_deref(),
Some("app_dev")
);
assert_eq!(database_name("not-a-url"), None);
}
#[test]
#[cfg(feature = "postgres-admin")]
fn postgres_configuration_debug_redacts_database_urls() {
let database_url =
"postgres://private-user:private-password@localhost/app?sslpassword=private-query";
let bootstrap = PostgresBootstrapSettings::new(database_url)
.build()
.expect("bootstrap settings should be valid");
let settings = PostgresBootstrapSettings::new(database_url);
let reset = PostgresResetSettings::new(database_url)
.build()
.expect("reset settings should be valid");
let output = format!("{bootstrap:?} {settings:?} {reset:?}");
assert!(output.contains("[REDACTED]"));
for sensitive in [
database_url,
"private-user",
"private-password",
"private-query",
] {
assert!(!output.contains(sensitive));
}
}
#[test]
fn postgres_error_formatting_redacts_urls_and_source_details() {
#[derive(Debug)]
struct SensitiveDatabaseError(&'static str);
impl std::fmt::Display for SensitiveDatabaseError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.0)
}
}
impl std::error::Error for SensitiveDatabaseError {}
impl sqlx::error::DatabaseError for SensitiveDatabaseError {
fn message(&self) -> &str {
self.0
}
fn code(&self) -> Option<std::borrow::Cow<'_, str>> {
Some(std::borrow::Cow::Borrowed("42501"))
}
fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
self
}
fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
self
}
fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
self
}
fn kind(&self) -> sqlx::error::ErrorKind {
sqlx::error::ErrorKind::Other
}
}
let database_url =
"postgres://private-user:private-password@localhost/app?sslpassword=private-query";
let source_detail = "private-driver-error-detail";
let sqlx_error = sqlx::Error::Database(Box::new(SensitiveDatabaseError(source_detail)));
let diagnosis = diagnose_sqlx_error(PostgresOperation::Connect, database_url, &sqlx_error);
let diagnosis_output = format!("{diagnosis} {diagnosis:?}");
let pool_error = PostgresPoolError::Sqlx(sqlx_error);
let pool_output = format!("{pool_error} {pool_error:?}");
let bootstrap_error = PostgresBootstrapError::Connect {
diagnosis,
source: Box::new(pool_error),
};
let output = format!("{diagnosis_output} {pool_output} {bootstrap_error} {bootstrap_error:?}");
assert!(output.contains("[REDACTED]"));
for sensitive in [
database_url,
"private-user",
"private-password",
"private-query",
source_detail,
] {
assert!(!output.contains(sensitive));
}
}
#[test]
fn postgres_settings_deserialize_credentials_and_redact_debug_output() {
let database_url = "postgres://private-user:private-password@localhost/app";
let settings: PostgresBootstrapSettings = serde_json::from_value(serde_json::json!({
"database_url": database_url
}))
.expect("settings should deserialize");
assert_eq!(settings.database_url.expose_secret(), database_url);
let debug = format!("{settings:?}");
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains("private-user"));
assert!(!debug.contains("private-password"));
}
#[test]
fn postgres_health_exposes_only_a_stable_redacted_error() {
let health = PostgresHealth {
status: PostgresHealthStatus::Unavailable,
latency: std::time::Duration::from_millis(10),
};
assert_eq!(health.error(), Some("database health check failed"));
let output = format!("{health:?}");
assert!(output.contains("has_error"));
assert!(!output.contains(POSTGRES_HEALTH_ERROR));
}
#[test]
fn postgres_settings_convert_to_runtime_config() {
let settings = PostgresBootstrapSettings {
database_url: "postgres://app:secret@localhost/app".into(),
pool: PostgresPoolSettings {
max_connections: 20,
..PostgresPoolSettings::default()
},
create_on_startup: true,
migrate_on_startup: false,
startup_retry: PostgresStartupRetrySettings::default()
.with_max_attempts(3)
.with_initial_delay(std::time::Duration::from_millis(10))
.with_max_delay(std::time::Duration::from_millis(50)),
migration_lock_key: Some(42),
migration_lock_timeout: std::time::Duration::from_secs(7),
migration_timeout: std::time::Duration::from_secs(90),
};
let config = settings.clone().build().expect("settings should convert");
assert_eq!(
config.database_url().expose_secret(),
"postgres://app:secret@localhost/app"
);
assert_eq!(config.pool_config().max_connections(), 20);
assert!(config.create_on_startup());
assert!(!config.migrate_on_startup());
assert_eq!(config.startup_retry().max_attempts(), 3);
assert_eq!(config.migration_lock_key(), Some(42));
assert_eq!(
config.migration_lock_timeout(),
std::time::Duration::from_secs(7)
);
assert_eq!(
config.migration_timeout(),
std::time::Duration::from_secs(90)
);
let rebuilt = PostgresBootstrapSettings::from(config)
.build()
.expect("runtime config should round-trip through settings");
assert_eq!(rebuilt.migration_lock_key(), Some(42));
assert_eq!(
rebuilt.migration_lock_timeout(),
std::time::Duration::from_secs(7)
);
assert_eq!(
rebuilt.migration_timeout(),
std::time::Duration::from_secs(90)
);
}
#[test]
fn rejects_zero_postgres_advisory_lock_deadlines() {
let bootstrap = PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
.with_migration_lock_timeout(std::time::Duration::ZERO)
.build()
.expect_err("enabled migration locking must have a deadline");
assert_eq!(
bootstrap.issues()[0].path(),
"postgres.migration_lock_timeout"
);
let migration = PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
.with_migration_timeout(std::time::Duration::ZERO)
.build()
.expect_err("migration execution must have a deadline");
assert_eq!(migration.issues()[0].path(), "postgres.migration_timeout");
#[cfg(feature = "postgres-admin")]
{
let settings = PostgresResetSettings::new("postgres://app:secret@localhost/app");
let reset = settings
.clone()
.with_reset_lock_timeout(std::time::Duration::ZERO)
.build()
.expect_err("reset locking must have a deadline");
assert_eq!(
reset.issues()[0].path(),
"postgres.reset.reset_lock_timeout"
);
let reset = settings
.clone()
.with_reset_schema_timeout(std::time::Duration::ZERO)
.build()
.expect_err("schema reset must have a deadline");
assert_eq!(
reset.issues()[0].path(),
"postgres.reset.reset_schema_timeout"
);
let reset = settings
.with_post_reset_migration_timeout(std::time::Duration::ZERO)
.build()
.expect_err("post-reset migration must have a deadline");
assert_eq!(
reset.issues()[0].path(),
"postgres.reset.post_reset_migration_timeout"
);
}
}
#[test]
fn rejects_postgres_deadlines_outside_the_runtime_timer_range() {
let bootstrap = PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
.with_migration_lock_timeout(std::time::Duration::MAX)
.with_migration_timeout(std::time::Duration::MAX)
.build()
.expect_err("timer-overflowing migration deadlines must be rejected");
let paths = bootstrap
.issues()
.iter()
.map(|issue| issue.path())
.collect::<Vec<_>>();
assert!(paths.contains(&"postgres.migration_lock_timeout"));
assert!(paths.contains(&"postgres.migration_timeout"));
#[cfg(feature = "postgres-admin")]
{
let reset = PostgresResetSettings::new("postgres://app:secret@localhost/app")
.with_reset_lock_timeout(std::time::Duration::MAX)
.with_reset_schema_timeout(std::time::Duration::MAX)
.with_post_reset_migration_timeout(std::time::Duration::MAX)
.build()
.expect_err("timer-overflowing reset deadlines must be rejected");
let paths = reset
.issues()
.iter()
.map(|issue| issue.path())
.collect::<Vec<_>>();
assert!(paths.contains(&"postgres.reset.reset_lock_timeout"));
assert!(paths.contains(&"postgres.reset.reset_schema_timeout"));
assert!(paths.contains(&"postgres.reset.post_reset_migration_timeout"));
}
}
#[test]
fn postgres_bootstrap_timeout_settings_serde_round_trip() {
let settings =
PostgresBootstrapSettings::from_secret("postgres://app:secret@localhost/app".to_owned())
.with_additional_migration_advisory_lock(Some(42))
.with_migration_lock_timeout(std::time::Duration::from_secs(11))
.with_migration_timeout(std::time::Duration::from_secs(123));
let json = serde_json::to_string(&settings).expect("settings should serialize");
let decoded: PostgresBootstrapSettings<String> =
serde_json::from_str(&json).expect("settings should deserialize");
assert_eq!(decoded.migration_lock_key, Some(42));
assert_eq!(
decoded.migration_lock_timeout,
std::time::Duration::from_secs(11)
);
assert_eq!(
decoded.migration_timeout,
std::time::Duration::from_secs(123)
);
}
#[test]
#[cfg(feature = "postgres-admin")]
fn postgres_reset_timeout_settings_serde_round_trip() {
let settings =
PostgresResetSettings::from_secret("postgres://app:secret@localhost/app".to_owned())
.with_reset_lock_timeout(std::time::Duration::from_secs(13))
.with_reset_schema_timeout(std::time::Duration::from_secs(17))
.with_post_reset_migration_timeout(std::time::Duration::from_secs(19));
let json = serde_json::to_string(&settings).expect("settings should serialize");
let decoded: PostgresResetSettings<String> =
serde_json::from_str(&json).expect("settings should deserialize");
assert_eq!(
decoded.reset_lock_timeout,
std::time::Duration::from_secs(13)
);
assert_eq!(
decoded.reset_schema_timeout,
std::time::Duration::from_secs(17)
);
assert_eq!(
decoded.post_reset_migration_timeout,
std::time::Duration::from_secs(19)
);
let config = decoded
.map_database_url(crate::secret::SecretString::new)
.build()
.expect("decoded reset settings should build");
assert_eq!(
config.reset_lock_timeout(),
std::time::Duration::from_secs(13)
);
assert_eq!(
config.reset_schema_timeout(),
std::time::Duration::from_secs(17)
);
assert_eq!(
config.post_reset_migration_timeout(),
std::time::Duration::from_secs(19)
);
let rebuilt = PostgresResetSettings::from(config)
.build()
.expect("reset config should round-trip through settings");
assert_eq!(
rebuilt.reset_schema_timeout(),
std::time::Duration::from_secs(17)
);
}
#[test]
fn postgres_settings_adapt_and_validate_with_stable_paths() {
let settings = PostgresBootstrapSettings {
database_url: "postgres://app:secret@localhost/app".into(),
pool: PostgresPoolSettings {
max_connections: 0,
..PostgresPoolSettings::default()
},
..PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
};
let validation = settings
.validate_at("database")
.expect_err("invalid settings should report config paths");
assert_eq!(
validation.issues()[0].path(),
"database.pool.max_connections"
);
let error = settings
.clone()
.build()
.expect_err("invalid settings should not build");
assert_eq!(error.issues()[0].path(), "postgres.pool.max_connections");
assert!(settings.validate().is_err());
}
#[test]
fn diagnoses_migration_state_failures_for_operators() {
let missing = sqlx::migrate::MigrateError::VersionMissing(20260428000200);
let diagnosis = diagnose_migration_error("postgres://app:secret@localhost/app", &missing);
assert_eq!(diagnosis.kind(), PostgresDiagnosticKind::MigrationMissing);
assert_eq!(diagnosis.database(), Some("app"));
assert!(diagnosis.message().contains("20260428000200"));
assert!(!diagnosis.retryable());
assert_eq!(
diagnosis.to_diagnostic().kind(),
DiagnosticKind::ResourceMissing
);
let mismatch = sqlx::migrate::MigrateError::VersionMismatch(20260428000200);
assert_eq!(
MigrationFailureKind::from_error(&mismatch),
MigrationFailureKind::VersionMismatch {
version: 20260428000200
}
);
assert_eq!(
diagnose_migration_error("postgres://app:secret@localhost/app", &mismatch).kind(),
PostgresDiagnosticKind::MigrationChecksumMismatch
);
let permission = sqlx::migrate::MigrateError::Execute(sqlx::Error::Io(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"socket denied",
)));
assert_eq!(
diagnose_migration_error("postgres://app:secret@localhost/app", &permission).kind(),
PostgresDiagnosticKind::PermissionDenied
);
}
#[test]
fn operation_timeouts_have_stable_redacted_classification() {
let database_url = "postgres://private-user:private-password@localhost/app";
let diagnosis = diagnose_operation_timeout(
PostgresOperation::Migrate,
database_url,
std::time::Duration::from_secs(3),
);
let error = PostgresMigrationRunError::MigrationTimeout {
timeout: std::time::Duration::from_secs(3),
};
let bootstrap_error = PostgresBootstrapError::MigrationTimeout {
diagnosis: diagnosis.clone(),
timeout: std::time::Duration::from_secs(3),
};
let output = format!(
"{diagnosis} {diagnosis:?} {error} {error:?} {bootstrap_error} {bootstrap_error:?}"
);
assert_eq!(diagnosis.kind(), PostgresDiagnosticKind::OperationTimeout);
assert!(diagnosis.retryable());
assert_eq!(error.error_code().as_str(), "postgres_migration_timeout");
assert_eq!(error.error_kind(), ErrorKind::Timeout);
assert_eq!(
bootstrap_error.error_code().as_str(),
"postgres_migration_timeout"
);
assert_eq!(bootstrap_error.error_kind(), ErrorKind::Timeout);
assert!(bootstrap_error.error_descriptor().retryable());
assert!(!output.contains("private-user"));
assert!(!output.contains("private-password"));
#[cfg(feature = "postgres-admin")]
{
let reset_error = PostgresResetError::ResetSchemaTimeout {
diagnosis,
timeout: std::time::Duration::from_secs(3),
};
assert_eq!(
reset_error.error_code().as_str(),
"postgres_reset_schema_timeout"
);
assert_eq!(reset_error.error_kind(), ErrorKind::Timeout);
assert!(reset_error.error_descriptor().retryable());
let reset_output = format!("{reset_error} {reset_error:?}");
assert!(!reset_output.contains("private-user"));
assert!(!reset_output.contains("private-password"));
}
}
#[test]
#[cfg(feature = "postgres-admin")]
fn reset_config_rejects_system_databases() {
let system = PostgresResetSettings::new("postgres://app:secret@localhost/postgres")
.build()
.expect_err("system database should be rejected");
assert_eq!(system.issues()[0].path(), "postgres.reset.database_url");
}
#[test]
fn redacts_database_urls_without_losing_routing_information() {
assert_eq!(
redact_database_url("postgres://app:secret@localhost:5432/app"),
"postgres://app:****@localhost:5432/app"
);
assert_eq!(
redact_database_url(
"postgres://app:secret@localhost/app?sslmode=require&sslpassword=private-query"
),
"postgres://app:****@localhost/app?sslmode=****&sslpassword=****"
);
assert_eq!(
redact_database_url("postgres://localhost/app?password=private-query#private-fragment"),
"postgres://localhost/app?password=****#****"
);
assert_eq!(redact_database_url("not-a-url"), "<invalid-postgres-url>");
}
#[test]
fn advisory_lock_keys_are_stable_and_namespaced() {
let left = advisory_lock_key("app", "migrations");
let same = advisory_lock_key(" app ", " migrations ");
let other = advisory_lock_key("app", "workers");
assert_eq!(left, same);
assert_ne!(left, other);
let maintenance = schema_maintenance_advisory_lock_key("app");
assert_eq!(
super::runtime::schema_maintenance_lock_keys("app", Some(maintenance)),
vec![maintenance]
);
assert_eq!(
super::runtime::schema_maintenance_lock_keys("app", Some(other)),
vec![maintenance, other]
);
}
#[test]
fn pool_options_preserve_disabled_and_explicit_recycling_timeouts() {
use std::time::Duration;
for (idle, lifetime) in [
(None, None),
(Some(Duration::from_secs(7)), None),
(None, Some(Duration::from_secs(19))),
(Some(Duration::from_secs(7)), Some(Duration::from_secs(19))),
] {
let config = PostgresPoolSettings::default()
.with_idle_timeout(idle)
.with_max_lifetime(lifetime)
.build()
.unwrap();
let options = super::pool_options(config);
assert_eq!(options.get_idle_timeout(), idle);
assert_eq!(options.get_max_lifetime(), lifetime);
}
}