#![allow(dead_code)]
use sqlx::postgres::PgPool;
pub fn with_database(url: &str, dbname: &str) -> String {
let (head, query) = match url.split_once('?') {
Some((h, q)) => (h, Some(q)),
None => (url, None),
};
let (prefix, _) = head
.rsplit_once('/')
.expect("postgres URL should end in /dbname");
match query {
Some(q) => format!("{prefix}/{dbname}?{q}"),
None => format!("{prefix}/{dbname}"),
}
}
pub async fn hermetic_pg_db(base_url: &str, prefix: &str) -> (PgPool, String, String) {
let dbname = format!("{prefix}_{}", uuid::Uuid::new_v4().simple());
let admin = PgPool::connect(base_url)
.await
.expect("connect to the base database");
sqlx::raw_sql(&format!("CREATE DATABASE {dbname}"))
.execute(&admin)
.await
.expect("create the hermetic database");
let url = with_database(base_url, &dbname);
(admin, url, dbname)
}
pub async fn drop_hermetic_pg_db(admin: &PgPool, dbname: &str) {
if let Err(e) = sqlx::raw_sql(&format!("DROP DATABASE {dbname} WITH (FORCE)"))
.execute(admin)
.await
{
eprintln!("hermetic db cleanup: leaving {dbname} behind: {e}");
}
}