pgdb/db_instance.rs
1//! Reference counted database handles.
2//!
3//! A [`DbInstance`] represents ownership of a running database instance with cleanup semantics.
4//! Dropping the [`DbInstance`] will cause the underlying database to be dropped.
5
6use std::{
7 process,
8 sync::{Arc, Mutex, Weak},
9};
10
11use url::Url;
12
13use crate::{config::PostgresEnvironment, Postgres};
14
15/// A database instance.
16///
17/// Can be either a local database (with a reference to the running instance) or an external
18/// database URL. Dropping the instance will cause the database to be deleted.
19#[derive(Debug)]
20pub enum DbInstance {
21 /// A local database instance that will be kept alive as long as this DbUrl exists.
22 Local {
23 /// A reference to the running Postgres instance where this URL points.
24 _arc: Arc<Postgres>,
25 /// The actual URL.
26 url: Url,
27 },
28 /// An external database URL with admin credentials to clean it up later.
29 External {
30 /// The database URL.
31 url: Url,
32 /// The superuser URL for cleanup operations.
33 superuser_url: Url,
34 /// Whether to clean up the database and role on drop.
35 cleanup: bool,
36 },
37}
38
39impl DbInstance {
40 /// Returns the URL as a string.
41 pub fn as_str(&self) -> &str {
42 match self {
43 DbInstance::Local { url, .. } => url.as_str(),
44 DbInstance::External { url, .. } => url.as_str(),
45 }
46 }
47
48 /// Returns the URL.
49 pub fn as_url(&self) -> &Url {
50 match self {
51 DbInstance::Local { url, .. } => url,
52 DbInstance::External { url, .. } => url,
53 }
54 }
55}
56
57impl AsRef<str> for DbInstance {
58 fn as_ref(&self) -> &str {
59 self.as_str()
60 }
61}
62
63impl Drop for DbInstance {
64 fn drop(&mut self) {
65 if let DbInstance::External {
66 url,
67 superuser_url,
68 cleanup,
69 } = self
70 {
71 if !*cleanup {
72 return;
73 }
74
75 // Extract database and usernames from the URL
76 let db_name = url.path().trim_start_matches('/');
77 let db_user = url.username();
78
79 // Best effort cleanup - we don't want to panic in [`Drop::drop`].
80 // TODO: Do not use `which` here if a different `psql` binary was configured.
81 let psql_binary = which::which("psql").unwrap_or_else(|_| "psql".into());
82
83 // Helper to run cleanup SQL
84 let run_cleanup_sql = |sql: &str| {
85 let username = superuser_url.username();
86 let password = superuser_url.password().unwrap_or_default();
87
88 let host =
89 crate::connection_host(superuser_url).unwrap_or_else(|| "localhost".into());
90 let port = crate::connection_port(superuser_url).unwrap_or(5432);
91
92 let _ = process::Command::new(&psql_binary)
93 .arg("-h")
94 .arg(host.as_ref())
95 .arg("-p")
96 .arg(port.to_string())
97 .arg("-U")
98 .arg(username)
99 .arg("-d")
100 .arg("postgres")
101 .arg("-c")
102 .arg(sql)
103 .env("PGPASSWORD", password)
104 .output();
105 };
106
107 // Fixture owners may be dropped before their clients.
108 run_cleanup_sql(&format!(
109 "DROP DATABASE IF EXISTS {} WITH (FORCE);",
110 crate::escape_ident(db_name)
111 ));
112
113 // Drop user
114 run_cleanup_sql(&format!(
115 "DROP ROLE IF EXISTS {};",
116 crate::escape_ident(db_user)
117 ));
118 }
119 }
120
121 // TODO: Clean up database if local.
122}
123
124/// A convenience function for regular applications.
125///
126/// Some applications just need a clean database instance and can afford to share the underlying
127/// database.
128///
129/// If the `PGDB_TESTS_URL` environment variable is set, it will be used as an external database
130/// URL instead of creating a local instance. The URL must include superuser credentials. A new
131/// database will be created for each call, just like with local instances. Set
132/// `PGDB_TESTS_CLEANUP=false` to leave those databases and roles behind on drop.
133///
134/// Otherwise, uses a shared database instance if multiple tests are running at the same time (see
135/// [`DbInstance`] for details). The database may be shut down and recreated if the last [`DbInstance`] is
136/// dropped during testing, e.g. when parallel tests are not spawned quick enough.
137///
138/// This construction is necessary because `static` variables will not have `Drop` called on them,
139/// without this construction, the spawned Postgres server would not be stopped.
140pub fn db_fixture() -> DbInstance {
141 let environment =
142 PostgresEnvironment::read().expect("invalid PostgreSQL environment configuration");
143
144 // Check for external database URL first
145 if let Some(external_url) = crate::parse_external_test_url().expect("invalid PGDB_TESTS_URL") {
146 let url =
147 crate::create_fixture_db(&external_url).expect("failed to create external fixture DB");
148 return DbInstance::External {
149 url,
150 superuser_url: external_url,
151 cleanup: environment.tests_cleanup(),
152 };
153 }
154
155 static DB: Mutex<Weak<Postgres>> = Mutex::new(Weak::new());
156
157 let pg = {
158 let mut guard = DB.lock().expect("lock poisoned");
159 if let Some(arc) = guard.upgrade() {
160 // We still have an instance we can reuse.
161 arc
162 } else {
163 let mut builder = Postgres::build();
164 environment.apply(&mut builder);
165 let arc = Arc::new(builder.start().expect("failed to start global postgres DB"));
166 *guard = Arc::downgrade(&arc);
167 arc
168 }
169 };
170
171 // Use unified fixture creation for local databases too
172 let url =
173 crate::create_fixture_db(&pg.superuser_url()).expect("failed to create local fixture DB");
174 DbInstance::Local { _arc: pg, url }
175}