#![doc = include_str!("../README.md")]
pub mod config;
mod db_instance;
mod error;
pub mod state;
use std::{
borrow::Cow,
env, fs, io,
net::TcpListener,
path, process, thread,
time::{Duration, Instant},
};
pub use db_instance::{DbInstance, db_fixture};
pub use error::{Error, ExternalUrlError};
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
#[cfg(target_os = "linux")]
use process_guard::CommandExt;
use process_guard::{DEFAULT_FORCE_TIME, ProcessGuard, ShutdownPolicy, Signal};
use url::Url;
use crate::state::{Credentials, State};
const DEFAULT_POSTGRES_PORT: u16 = 5432;
pub fn connection_host(url: &Url) -> Option<Cow<'_, str>> {
if let Some((_, host)) = url.query_pairs().find(|(key, _)| key == "host") {
return Some(host);
}
url.host_str()
.map(|host| percent_decode_str(host).decode_utf8_lossy())
}
pub fn connection_port(url: &Url) -> Option<u16> {
url.query_pairs()
.find(|(key, _)| key == "port")
.and_then(|(_, port)| port.parse().ok())
.or_else(|| url.port())
}
pub fn run_psql_command(superuser_url: &Url, database: &str, sql: &str) -> Result<(), Error> {
let psql_binary = which::which("psql").unwrap_or_else(|_| "psql".into());
let username = superuser_url.username();
let password = superuser_url.password().unwrap_or_default();
let host = connection_host(superuser_url).expect("URL must have a host");
let port = connection_port(superuser_url).unwrap_or(5432);
let status = process::Command::new(&psql_binary)
.arg("-h")
.arg(host.as_ref())
.arg("-p")
.arg(port.to_string())
.arg("-U")
.arg(username)
.arg("-d")
.arg(database)
.arg("-c")
.arg(sql)
.env("PGPASSWORD", password)
.status()
.map_err(Error::RunPsql)?;
if !status.success() {
return Err(Error::PsqlFailed(status));
}
Ok(())
}
pub fn create_user_and_database(
superuser_url: &Url,
db_name: &str,
db_user: &str,
db_pw: &str,
) -> Result<(), Error> {
run_psql_command(
superuser_url,
"postgres",
&format!(
"CREATE ROLE {} LOGIN ENCRYPTED PASSWORD {};",
escape_ident(db_user),
escape_string(db_pw)
),
)?;
run_psql_command(
superuser_url,
"postgres",
&format!(
"CREATE DATABASE {} OWNER {};",
escape_ident(db_name),
escape_ident(db_user)
),
)?;
Ok(())
}
fn create_fixture_db(superuser_url: &Url) -> Result<Url, Error> {
let random_id = generate_random_string();
let db_name = format!("fixture_db_{}", random_id);
let db_user = format!("fixture_user_{}", random_id);
let db_pw = format!("fixture_pass_{}", random_id);
create_user_and_database(superuser_url, &db_name, &db_user, &db_pw)?;
let mut url = superuser_url.clone();
url.set_username(&db_user).expect("Failed to set username");
url.set_password(Some(&db_pw))
.expect("Failed to set password");
url.set_path(&db_name);
Ok(url)
}
fn find_unused_port() -> io::Result<u16> {
let listener = TcpListener::bind("127.0.0.1:0")?;
let port = listener.local_addr()?.port();
Ok(port)
}
#[derive(Debug)]
pub struct Postgres {
connection_url: Url,
credentials: Credentials,
#[allow(dead_code)] process: PostgresProcess,
psql_binary: path::PathBuf,
data_dir: path::PathBuf,
}
#[derive(Debug)]
struct PostgresProcess {
instance: ProcessGuard,
tmp_dir: tempfile::TempDir,
}
impl Drop for PostgresProcess {
fn drop(&mut self) {
if self.instance.shutdown().is_err() {
self.tmp_dir.disable_cleanup(true);
let _ = self.instance.take();
}
}
}
#[derive(Debug)]
pub struct PostgresClient<'a> {
instance: &'a Postgres,
client_url: Url,
}
#[derive(Debug)]
pub struct PostgresBuilder {
data_dir: Option<path::PathBuf>,
port: Option<u16>,
host: String,
fast: bool,
#[cfg(target_os = "linux")]
shutdown_on_parent_death: bool,
tcp: bool,
superuser: String,
superuser_pw: Option<String>,
postgres_binary: Option<path::PathBuf>,
initdb_binary: Option<path::PathBuf>,
pg_isready_binary: Option<path::PathBuf>,
psql_binary: Option<path::PathBuf>,
postgres_options: Vec<(String, String)>,
probe_delay: Duration,
startup_timeout: Duration,
shutdown_timeout: Option<Duration>,
force_shutdown_timeout: Duration,
}
impl Postgres {
#[inline]
pub fn build() -> PostgresBuilder {
PostgresBuilder {
data_dir: None,
port: None,
host: "127.0.0.1".to_string(),
fast: false,
#[cfg(target_os = "linux")]
shutdown_on_parent_death: false,
tcp: false,
superuser: "postgres".to_string(),
superuser_pw: None,
postgres_binary: None,
initdb_binary: None,
pg_isready_binary: None,
psql_binary: None,
postgres_options: Vec::new(),
probe_delay: Duration::from_millis(100),
startup_timeout: Duration::from_secs(10),
shutdown_timeout: None,
force_shutdown_timeout: DEFAULT_FORCE_TIME,
}
}
#[inline]
pub fn as_superuser(&self) -> PostgresClient<'_> {
self.as_user(&self.credentials.user, &self.credentials.password)
}
#[inline]
pub fn as_user(&self, username: &str, password: &str) -> PostgresClient<'_> {
let mut client_url = self.connection_url.clone();
client_url
.set_username(username)
.expect("Failed to set username");
client_url
.set_password(Some(password))
.expect("Failed to set password");
PostgresClient {
instance: self,
client_url,
}
}
pub fn data_dir(&self) -> &path::Path {
&self.data_dir
}
pub fn superuser_url(&self) -> Url {
self.as_superuser().client_url
}
}
impl<'a> PostgresClient<'a> {
pub fn psql(&self, database: &str) -> process::Command {
let mut cmd = process::Command::new(&self.instance.psql_binary);
let username = self.client_url.username();
let password = self.client_url.password().unwrap_or_default();
let host = connection_host(&self.client_url).expect("Client URL must have a host");
let port = connection_port(&self.client_url).expect("Client URL must have a port");
cmd.arg("-h")
.arg(host.as_ref())
.arg("-p")
.arg(port.to_string())
.arg("-U")
.arg(username)
.arg("-d")
.arg(database)
.env("PGPASSWORD", password);
cmd
}
pub fn load_sql<P: AsRef<path::Path>>(&self, database: &str, filename: P) -> Result<(), Error> {
let status = self
.psql(database)
.arg("-f")
.arg(filename.as_ref())
.status()
.map_err(Error::RunPsql)?;
if !status.success() {
return Err(Error::PsqlFailed(status));
}
Ok(())
}
pub fn run_sql(&self, database: &str, sql: &str) -> Result<(), Error> {
let status = self
.psql(database)
.arg("-c")
.arg(sql)
.status()
.map_err(Error::RunPsql)?;
if !status.success() {
return Err(Error::PsqlFailed(status));
}
Ok(())
}
#[inline]
pub fn create_database(&self, database: &str, owner: &str) -> Result<(), Error> {
self.run_sql(
"postgres",
&format!(
"CREATE DATABASE {} OWNER {};",
escape_ident(database),
escape_ident(owner)
),
)
}
#[inline]
pub fn create_user(&self, username: &str, password: &str) -> Result<(), Error> {
self.run_sql(
"postgres",
&format!(
"CREATE ROLE {} LOGIN ENCRYPTED PASSWORD {};",
escape_ident(username),
escape_string(password)
),
)
}
#[inline]
pub fn instance(&self) -> &Postgres {
self.instance
}
pub fn url(&self, database: &str) -> Url {
let mut url = self.client_url.clone();
url.set_path(database);
url
}
pub fn client_url(&self) -> &Url {
&self.client_url
}
}
impl PostgresBuilder {
#[inline]
pub fn fast(&mut self) -> &mut Self {
self.fast = true;
self
}
#[cfg(target_os = "linux")]
pub fn shutdown_on_parent_death(&mut self) -> &mut Self {
self.shutdown_on_parent_death = true;
self
}
#[inline]
pub fn data_dir<T: Into<path::PathBuf>>(&mut self, data_dir: T) -> &mut Self {
self.data_dir = Some(data_dir.into());
self
}
#[inline]
pub fn initdb_binary<T: Into<path::PathBuf>>(&mut self, initdb_binary: T) -> &mut Self {
self.initdb_binary = Some(initdb_binary.into());
self
}
#[inline]
pub fn pg_isready_binary<T: Into<path::PathBuf>>(&mut self, pg_isready_binary: T) -> &mut Self {
self.pg_isready_binary = Some(pg_isready_binary.into());
self
}
#[inline]
pub fn host(&mut self, host: String) -> &mut Self {
self.host = host;
self.tcp = true;
self
}
#[inline]
pub fn port(&mut self, port: u16) -> &mut Self {
self.port = Some(port);
self.tcp = true;
self
}
#[inline]
pub fn tcp(&mut self) -> &mut Self {
self.tcp = true;
self
}
#[inline]
pub fn postgres_binary<T: Into<path::PathBuf>>(&mut self, postgres_binary: T) -> &mut Self {
self.postgres_binary = Some(postgres_binary.into());
self
}
#[inline]
pub fn postgres_option<K, V>(&mut self, name: K, value: V) -> &mut Self
where
K: Into<String>,
V: Into<String>,
{
self.postgres_options.push((name.into(), value.into()));
self
}
#[inline]
pub fn probe_delay(&mut self, probe_delay: Duration) -> &mut Self {
self.probe_delay = probe_delay;
self
}
#[inline]
pub fn psql_binary<T: Into<path::PathBuf>>(&mut self, psql_binary: T) -> &mut Self {
self.psql_binary = Some(psql_binary.into());
self
}
#[inline]
pub fn startup_timeout(&mut self, startup_timeout: Duration) -> &mut Self {
self.startup_timeout = startup_timeout;
self
}
#[inline]
pub fn shutdown_timeout(&mut self, shutdown_timeout: Duration) -> &mut Self {
self.shutdown_timeout = Some(shutdown_timeout);
self
}
#[inline]
pub fn force_shutdown_timeout(&mut self, force_shutdown_timeout: Duration) -> &mut Self {
self.force_shutdown_timeout = force_shutdown_timeout;
self
}
#[inline]
pub fn superuser_pw<T: Into<String>>(&mut self, superuser_pw: T) -> &mut Self {
self.superuser_pw = Some(superuser_pw.into());
self
}
fn shutdown_policy(&self) -> ShutdownPolicy {
let (signal, default_grace_time) = if self.fast {
(Signal::SIGQUIT, Duration::from_secs(5))
} else {
(Signal::SIGINT, Duration::from_secs(20))
};
ShutdownPolicy::Graceful {
signal,
grace_time: self.shutdown_timeout.unwrap_or(default_grace_time),
force_time: self.force_shutdown_timeout,
}
}
pub fn start(&self) -> Result<Postgres, Error> {
let port = if self.tcp {
self.port
.unwrap_or_else(|| find_unused_port().expect("failed to find an unused port"))
} else {
DEFAULT_POSTGRES_PORT
};
let postgres_binary = self
.postgres_binary
.clone()
.map(Ok)
.unwrap_or_else(|| which::which("postgres").map_err(Error::FindPostgres))?;
let pg_isready_binary = self
.pg_isready_binary
.clone()
.map(Ok)
.unwrap_or_else(|| which::which("pg_isready").map_err(Error::FindPgIsready))?;
let psql_binary = self
.psql_binary
.clone()
.map(Ok)
.unwrap_or_else(|| which::which("psql").map_err(Error::FindPsql))?;
let tmp_dir = tempfile::tempdir().map_err(Error::CreateDatabaseDir)?;
let data_dir = self
.data_dir
.clone()
.unwrap_or_else(|| tmp_dir.path().join("db"));
let saved_state = State::load(&data_dir)?;
let initialized = saved_state.is_some();
let state = saved_state.unwrap_or_else(|| State {
admin: Credentials {
user: self.superuser.clone(),
password: self
.superuser_pw
.clone()
.unwrap_or_else(generate_random_string),
},
user: None,
database: None,
});
if !initialized {
let initdb_binary = self
.initdb_binary
.clone()
.map(Ok)
.unwrap_or_else(|| which::which("initdb").map_err(Error::FindInitdb))?;
let superuser_pw_file = tmp_dir.path().join("superuser-pw");
fs::write(&superuser_pw_file, state.admin.password.as_bytes())
.map_err(Error::WriteTemporaryPw)?;
let mut initdb = process::Command::new(initdb_binary);
initdb.args([
"--no-locale",
"--auth=md5",
"--encoding=UTF8",
]);
if self.data_dir.is_none() {
initdb.arg("--nosync");
}
let initdb_status = initdb
.arg("--pgdata")
.arg(&data_dir)
.arg("--pwfile")
.arg(&superuser_pw_file)
.arg("--username")
.arg(&state.admin.user)
.status()
.map_err(Error::RunInitDb)?;
if !initdb_status.success() {
return Err(Error::InitDbFailed(initdb_status));
}
}
let mut postgres_command = process::Command::new(postgres_binary);
postgres_command
.arg("-D")
.arg(&data_dir)
.arg("-p")
.arg(port.to_string())
.arg("-k")
.arg(tmp_dir.path());
if self.fast {
for option in [
"fsync=off",
"synchronous_commit=off",
"full_page_writes=off",
] {
postgres_command.arg("-c").arg(option);
}
}
for (name, value) in &self.postgres_options {
postgres_command.arg("-c").arg(format!("{name}={value}"));
}
if self.tcp {
postgres_command.arg("-h").arg(&self.host);
} else {
postgres_command.arg("-c").arg("listen_addresses=");
}
#[cfg(target_os = "linux")]
if self.shutdown_on_parent_death {
postgres_command.parent_death_signal(Signal::SIGQUIT);
}
let instance =
ProcessGuard::spawn_process_group(&mut postgres_command, self.shutdown_policy())
.map_err(Error::LaunchPostgres)?;
let process = PostgresProcess { instance, tmp_dir };
let started = Instant::now();
loop {
let mut pg_isready_command = process::Command::new(&pg_isready_binary);
pg_isready_command.arg("-h");
if self.tcp {
pg_isready_command.arg(&self.host);
} else {
pg_isready_command.arg(process.tmp_dir.path());
}
let status = pg_isready_command
.arg("-p")
.arg(port.to_string())
.stdout(process::Stdio::null())
.stderr(process::Stdio::null())
.status();
match status {
Ok(exit_status) if exit_status.success() => break,
_ => {
if started.elapsed() >= self.startup_timeout {
return Err(Error::StartupTimeout);
}
thread::sleep(self.probe_delay);
}
}
}
let connection_url = if self.tcp {
Url::parse(&format!("postgres://{}:{}", self.host, port))
.expect("Failed to construct TCP URL")
} else {
let socket_dir = process.tmp_dir.path().to_string_lossy();
let encoded_socket_dir = utf8_percent_encode(&socket_dir, NON_ALPHANUMERIC).to_string();
Url::parse(&format!("postgres://{encoded_socket_dir}:{port}"))
.expect("Failed to construct Unix socket URL")
};
let pg = Postgres {
connection_url,
credentials: state.admin.clone(),
process,
psql_binary,
data_dir,
};
let output = pg
.as_superuser()
.psql("postgres")
.args([
"-XwAt",
"-c",
"SELECT split_part(pg_read_file('postmaster.pid'), chr(10), 1)",
])
.stderr(process::Stdio::inherit())
.output()
.map_err(Error::RunPsql)?;
if !output.status.success() {
return Err(Error::PsqlFailed(output.status));
}
let expected_pid = pg
.process
.instance
.id()
.expect("PostgreSQL process is guarded");
if String::from_utf8_lossy(&output.stdout).trim() != expected_pid.to_string() {
return Err(Error::UnexpectedPostgres);
}
if !initialized {
state.store(pg.data_dir())?;
}
Ok(pg)
}
}
fn generate_random_string() -> String {
let raw: [u8; 16] = rand::random();
format!("{:x}", hex_fmt::HexFmt(&raw))
}
fn quote(quote_char: char, unescaped: &str) -> String {
let mut result = String::new();
result.push(quote_char);
for c in unescaped.chars() {
if c == quote_char {
result.push(quote_char);
result.push(quote_char);
} else {
result.push(c);
}
}
result.push(quote_char);
result
}
fn escape_ident(unescaped: &str) -> String {
quote('"', unescaped)
}
fn escape_string(unescaped: &str) -> String {
quote('\'', unescaped)
}
pub fn parse_external_test_url() -> Result<Option<Url>, Error> {
match env::var("PGDB_TESTS_URL") {
Ok(url_str) => {
let url = Url::parse(&url_str)
.map_err(|e| Error::InvalidExternalUrl(ExternalUrlError::ParseError(e)))?;
if url.scheme() != "postgres" {
return Err(Error::InvalidExternalUrl(ExternalUrlError::InvalidScheme));
}
if url.host_str().is_none() {
return Err(Error::InvalidExternalUrl(ExternalUrlError::MissingHost));
}
if url.username().is_empty() {
return Err(Error::InvalidExternalUrl(ExternalUrlError::MissingUsername));
}
Ok(Some(url))
}
Err(_) => Ok(None),
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use process_guard::{DEFAULT_FORCE_TIME, ShutdownPolicy, Signal};
use url::Url;
use super::Postgres;
#[test]
fn shutdown_policy_respects_mode_and_explicit_timeout() {
for fast in [false, true] {
for fast_first in [false, true] {
for timeout in [None, Some(Duration::ZERO), Some(Duration::from_secs(7))] {
let mut builder = Postgres::build();
if fast && fast_first {
builder.fast();
}
if let Some(timeout) = timeout {
builder.shutdown_timeout(timeout);
}
if fast && !fast_first {
builder.fast();
}
assert_eq!(
builder.shutdown_policy(),
ShutdownPolicy::Graceful {
signal: if fast {
Signal::SIGQUIT
} else {
Signal::SIGINT
},
grace_time: timeout.unwrap_or(Duration::from_secs(if fast {
5
} else {
20
})),
force_time: DEFAULT_FORCE_TIME,
}
);
}
}
}
}
#[test]
fn connection_parameters_decode_socket_urls() {
let url =
Url::parse("postgres://dev@%2Ftmp%2Fpgdb:5432/dev").expect("socket URL must be valid");
assert_eq!(super::connection_host(&url).as_deref(), Some("/tmp/pgdb"));
assert_eq!(super::connection_port(&url), Some(5432));
}
#[test]
fn can_change_superuser_pw() {
let pg = Postgres::build()
.superuser_pw("helloworld")
.start()
.expect("could not build postgres database");
let su = pg.as_superuser();
su.create_user("foo", "bar")
.expect("could not create normal user");
assert_eq!(su.client_url().password(), Some("helloworld"));
}
#[test]
fn fast_mode_disables_runtime_durability() {
let pg = Postgres::build()
.fast()
.start()
.expect("could not build postgres database");
let output = pg
.as_superuser()
.psql("postgres")
.args([
"-Atc",
"SELECT current_setting('fsync'), current_setting('synchronous_commit'), current_setting('full_page_writes')",
])
.output()
.expect("could not query postgres settings");
assert!(output.status.success());
assert_eq!(
String::from_utf8_lossy(&output.stdout).trim(),
"off|off|off"
);
}
#[test]
fn instances_support_isolated_sockets_and_tcp() {
let a = Postgres::build()
.start()
.expect("could not build postgres database");
let b = Postgres::build()
.start()
.expect("could not build postgres database");
let tcp = Postgres::build()
.tcp()
.start()
.expect("could not build TCP postgres database");
let a_url = a.superuser_url();
let b_url = b.superuser_url();
let tcp_url = tcp.superuser_url();
let a_host = super::connection_host(&a_url).expect("URL must have a host");
let b_host = super::connection_host(&b_url).expect("URL must have a host");
let tcp_host = super::connection_host(&tcp_url).expect("URL must have a host");
assert!(a_host.starts_with('/'));
assert!(b_host.starts_with('/'));
assert_ne!(a_host, b_host);
assert_eq!(super::connection_port(&a_url), Some(5432));
assert_eq!(super::connection_port(&b_url), Some(5432));
assert_eq!(tcp_host, "127.0.0.1");
}
#[test]
fn forceful_shutdown_waits_before_removing_temporary_directory() {
let pg = Postgres::build()
.shutdown_timeout(Duration::ZERO)
.start()
.expect("could not build postgres database");
let temporary_directory = pg.process.tmp_dir.path().to_path_buf();
drop(pg);
assert!(!temporary_directory.exists());
}
#[test]
fn ensure_proper_db_reuse_when_using_fixtures() {
let db_url = crate::db_fixture();
let db_url2 = crate::db_fixture();
match (&db_url, &db_url2) {
(crate::DbInstance::Local { .. }, crate::DbInstance::Local { .. }) => {
assert!(db_url.as_str().contains("fixture_user_"));
assert!(db_url.as_str().contains("fixture_pass_"));
assert!(db_url.as_str().contains("fixture_db_"));
assert!(db_url2.as_str().contains("fixture_user_"));
assert!(db_url2.as_str().contains("fixture_pass_"));
assert!(db_url2.as_str().contains("fixture_db_"));
assert_ne!(db_url.as_str(), db_url2.as_str());
}
(crate::DbInstance::External { .. }, crate::DbInstance::External { .. }) => {
assert!(db_url.as_str().contains("fixture_user_"));
assert!(db_url.as_str().contains("fixture_pass_"));
assert!(db_url.as_str().contains("fixture_db_"));
assert!(db_url2.as_str().contains("fixture_user_"));
assert!(db_url2.as_str().contains("fixture_pass_"));
assert!(db_url2.as_str().contains("fixture_db_"));
assert_ne!(db_url.as_str(), db_url2.as_str());
assert_eq!(db_url.as_url().host_str(), db_url2.as_url().host_str());
assert_eq!(db_url.as_url().port(), db_url2.as_url().port());
}
_ => panic!("Inconsistent DbUrl types returned from db_fixture"),
}
}
#[test]
fn external_db_cleanup_on_drop() {
if crate::parse_external_test_url().unwrap().is_none() {
return;
}
let superuser_url = crate::parse_external_test_url().unwrap().unwrap();
let psql_binary = which::which("psql").unwrap_or_else(|_| "psql".into());
let (db_name, db_user) = {
let db_url = crate::db_fixture();
match &db_url {
crate::DbInstance::External { url, .. } => {
let db_name = url.path().trim_start_matches('/').to_string();
let db_user = url.username().to_string();
(db_name, db_user)
}
_ => panic!("Expected external database"),
}
};
std::thread::sleep(std::time::Duration::from_millis(100));
let check_db_exists = |name: &str| -> bool {
let username = superuser_url.username();
let password = superuser_url.password().unwrap_or_default();
let host = superuser_url.host_str().unwrap();
let port = superuser_url.port().unwrap_or(5432);
let output = std::process::Command::new(&psql_binary)
.arg("-h")
.arg(host)
.arg("-p")
.arg(port.to_string())
.arg("-U")
.arg(username)
.arg("-d")
.arg("postgres")
.arg("-t")
.arg("-c")
.arg(format!(
"SELECT 1 FROM pg_database WHERE datname = '{}'",
name
))
.env("PGPASSWORD", password)
.output()
.expect("Failed to check database existence");
String::from_utf8_lossy(&output.stdout).trim() == "1"
};
let check_user_exists = |name: &str| -> bool {
let username = superuser_url.username();
let password = superuser_url.password().unwrap_or_default();
let host = superuser_url.host_str().unwrap();
let port = superuser_url.port().unwrap_or(5432);
let output = std::process::Command::new(&psql_binary)
.arg("-h")
.arg(host)
.arg("-p")
.arg(port.to_string())
.arg("-U")
.arg(username)
.arg("-d")
.arg("postgres")
.arg("-t")
.arg("-c")
.arg(format!("SELECT 1 FROM pg_roles WHERE rolname = '{}'", name))
.env("PGPASSWORD", password)
.output()
.expect("Failed to check user existence");
String::from_utf8_lossy(&output.stdout).trim() == "1"
};
assert!(
!check_db_exists(&db_name),
"Database should have been dropped"
);
assert!(
!check_user_exists(&db_user),
"User should have been dropped"
);
}
}