#![allow(clippy::disallowed_methods)]
use crate::Forge;
use crate::error::{ForgeError, Result};
use sqlx::{Connection, PgConnection};
use uuid::Uuid;
pub struct TestDatabase {
admin_url: String,
name: String,
url: String,
}
impl TestDatabase {
pub async fn new() -> Result<Self> {
let admin_url = std::env::var("TEST_DATABASE_URL").map_err(|_| {
ForgeError::config(
"TEST_DATABASE_URL is not set: DB-backed tests need a Postgres to create test databases against",
)
})?;
let suffix = Uuid::new_v4().simple().to_string();
let short = suffix.get(..12).unwrap_or(&suffix);
let name = format!("forge_test_{short}");
let url = with_database(&admin_url, &name);
let mut conn = PgConnection::connect(&admin_url).await.map_err(|e| {
ForgeError::config(format!("could not connect to TEST_DATABASE_URL: {e}"))
})?;
sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE \"{name}\"")))
.execute(&mut conn)
.await
.map_err(|e| ForgeError::config(format!("could not create test database: {e}")))?;
conn.close().await.ok();
Ok(Self {
admin_url,
name,
url,
})
}
pub fn url(&self) -> &str {
&self.url
}
pub fn config_toml(&self, extra: &str) -> String {
format!("[postgres]\nurl = \"{}\"\n{extra}", self.url)
}
pub async fn forge(&self) -> Result<Forge> {
self.forge_with("").await
}
pub async fn forge_with(&self, extra: &str) -> Result<Forge> {
Forge::init_from_str(&self.config_toml(extra)).await
}
pub async fn execute_raw(&self, sql: &'static str) -> Result<()> {
let mut conn = PgConnection::connect(&self.url)
.await
.map_err(|e| ForgeError::config(format!("could not connect to test database: {e}")))?;
let res = sqlx::raw_sql(sql)
.execute(&mut conn)
.await
.map_err(ForgeError::from_sqlx)
.map(|_| ());
conn.close().await.ok();
res
}
}
impl Drop for TestDatabase {
fn drop(&mut self) {
let admin_url = self.admin_url.clone();
let name = self.name.clone();
let _ = std::thread::spawn(move || {
let Ok(rt) = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
else {
return;
};
rt.block_on(async move {
if let Ok(mut conn) = PgConnection::connect(&admin_url).await {
let _ = sqlx::query(sqlx::AssertSqlSafe(format!(
"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)"
)))
.execute(&mut conn)
.await;
conn.close().await.ok();
}
});
})
.join();
}
}
fn with_database(url: &str, db: &str) -> String {
let (base, query) = match url.split_once('?') {
Some((b, q)) => (b, Some(q)),
None => (url, None),
};
let trimmed = base.trim_end_matches('/');
let prefix = match trimmed.rfind('/') {
Some(i) => trimmed.get(..i).unwrap_or(trimmed),
None => trimmed,
};
let mut out = format!("{prefix}/{db}");
if let Some(q) = query {
out.push('?');
out.push_str(q);
}
out
}
#[cfg(test)]
mod tests {
use super::with_database;
#[test]
fn with_database_swaps_path_and_keeps_query() {
assert_eq!(
with_database("postgres://u:p@h:5432/forge_dev", "forge_test_abc"),
"postgres://u:p@h:5432/forge_test_abc"
);
assert_eq!(
with_database("postgres://u:p@h:5432/forge_dev?sslmode=disable", "t1"),
"postgres://u:p@h:5432/t1?sslmode=disable"
);
}
}