Debian Codegraph @

src/testing/mod.rs

raw symbols SCIP
1 use std::fmt::Write;
2 use std::ops::Deref;
3 use std::str::FromStr;
4 use std::sync::atomic::{AtomicBool, Ordering};
5 use std::time::{Duration, SystemTime};
6
7 use futures_core::future::BoxFuture;
8
9 use once_cell::sync::OnceCell;
10
11 use crate::connection::Connection;
12
13 use crate::error::Error;
14 use crate::executor::Executor;
15 use crate::pool::{Pool, PoolOptions};
16 use crate::query::query;
17 use crate::query_scalar::query_scalar;
18 use crate::{PgConnectOptions, PgConnection, Postgres};
19
20 pub(crate) use sqlx_core::testing::*;
21
22 // Using a blocking `OnceCell` here because the critical sections are short.
23 static MASTER_POOL: OnceCell<Pool<Postgres>> = OnceCell::new();
24 // Automatically delete any databases created before the start of the test binary.
25 static DO_CLEANUP: AtomicBool = AtomicBool::new(true);
26
27 impl TestSupport for Postgres {
28 fn test_context(args: &TestArgs) -> BoxFuture<'_, Result<TestContext<Self>, Error>> {
29 Box::pin(async move { test_context(args).await })
30 }
31
32 fn cleanup_test(db_name: &str) -> BoxFuture<'_, Result<(), Error>> {
33 Box::pin(async move {
34 let mut conn = MASTER_POOL
35 .get()
36 .expect("cleanup_test() invoked outside `#[sqlx::test]")
37 .acquire()
38 .await?;
39
40 conn.execute(&format!("drop database if exists {db_name:?};")[..])
41 .await?;
42
43 query("delete from _sqlx_test.databases where db_name = $1")
44 .bind(db_name)
45 .execute(&mut *conn)
46 .await?;
47
48 Ok(())
49 })
50 }
51
52 fn cleanup_test_dbs() -> BoxFuture<'static, Result<Option<usize>, Error>> {
53 Box::pin(async move {
54 let url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
55
56 let mut conn = PgConnection::connect(&url).await?;
57
58 let now = SystemTime::now()
59 .duration_since(SystemTime::UNIX_EPOCH)
60 .unwrap();
61
62 let num_deleted = do_cleanup(&mut conn, now).await?;
63 let _ = conn.close().await;
64 Ok(Some(num_deleted))
65 })
66 }
67
68 fn snapshot(
69 _conn: &mut Self::Connection,
70 ) -> BoxFuture<'_, Result<FixtureSnapshot<Self>, Error>> {
71 // TODO: I want to get the testing feature out the door so this will have to wait,
72 // but I'm keeping the code around for now because I plan to come back to it.
73 todo!()
74 }
75 }
76
77 async fn test_context(args: &TestArgs) -> Result<TestContext<Postgres>, Error> {
78 let url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
79
80 let master_opts = PgConnectOptions::from_str(&url).expect("failed to parse DATABASE_URL");
81
82 let pool = PoolOptions::new()
83 // Postgres' normal connection limit is 100 plus 3 superuser connections
84 // We don't want to use the whole cap and there may be fuzziness here due to
85 // concurrently running tests anyway.
86 .max_connections(20)
87 // Immediately close master connections. Tokio's I/O streams don't like hopping runtimes.
88 .after_release(|_conn, _| Box::pin(async move { Ok(false) }))
89 .connect_lazy_with(master_opts);
90
91 let master_pool = match MASTER_POOL.try_insert(pool) {
92 Ok(inserted) => inserted,
93 Err((existing, pool)) => {
94 // Sanity checks.
95 assert_eq!(
96 existing.connect_options().host,
97 pool.connect_options().host,
98 "DATABASE_URL changed at runtime, host differs"
99 );
100
101 assert_eq!(
102 existing.connect_options().database,
103 pool.connect_options().database,
104 "DATABASE_URL changed at runtime, database differs"
105 );
106
107 existing
108 }
109 };
110
111 let mut conn = master_pool.acquire().await?;
112
113 // language=PostgreSQL
114 conn.execute(
115 // Explicit lock avoids this latent bug: https://stackoverflow.com/a/29908840
116 // I couldn't find a bug on the mailing list for `CREATE SCHEMA` specifically,
117 // but a clearly related bug with `CREATE TABLE` has been known since 2007:
118 // https://www.postgresql.org/message-id/200710222037.l9MKbCJZ098744%40wwwmaster.postgresql.org
119 r#"
120 lock table pg_catalog.pg_namespace in share row exclusive mode;
121
122 create schema if not exists _sqlx_test;
123
124 create table if not exists _sqlx_test.databases (
125 db_name text primary key,
126 test_path text not null,
127 created_at timestamptz not null default now()
128 );
129
130 create index if not exists databases_created_at
131 on _sqlx_test.databases(created_at);
132
133 create sequence if not exists _sqlx_test.database_ids;
134 "#,
135 )
136 .await?;
137
138 // Record the current time _before_ we acquire the `DO_CLEANUP` permit. This
139 // prevents the first test thread from accidentally deleting new test dbs
140 // created by other test threads if we're a bit slow.
141 let now = SystemTime::now()
142 .duration_since(SystemTime::UNIX_EPOCH)
143 .unwrap();
144
145 // Only run cleanup if the test binary just started.
146 if DO_CLEANUP.swap(false, Ordering::SeqCst) {
147 do_cleanup(&mut conn, now).await?;
148 }
149
150 let new_db_name: String = query_scalar(
151 r#"
152 insert into _sqlx_test.databases(db_name, test_path)
153 select '_sqlx_test_' || nextval('_sqlx_test.database_ids'), $1
154 returning db_name
155 "#,
156 )
157 .bind(args.test_path)
158 .fetch_one(&mut *conn)
159 .await?;
160
161 conn.execute(&format!("create database {new_db_name:?}")[..])
162 .await?;
163
164 Ok(TestContext {
165 pool_opts: PoolOptions::new()
166 // Don't allow a single test to take all the connections.
167 // Most tests shouldn't require more than 5 connections concurrently,
168 // or else they're likely doing too much in one test.
169 .max_connections(5)
170 // Close connections ASAP if left in the idle queue.
171 .idle_timeout(Some(Duration::from_secs(1)))
172 .parent(master_pool.clone()),
173 connect_opts: master_pool
174 .connect_options()
175 .deref()
176 .clone()
177 .database(&new_db_name),
178 db_name: new_db_name,
179 })
180 }
181
182 async fn do_cleanup(conn: &mut PgConnection, created_before: Duration) -> Result<usize, Error> {
183 // since SystemTime is not monotonic we added a little margin here to avoid race conditions with other threads
184 let created_before = i64::try_from(created_before.as_secs()).unwrap() - 2;
185
186 let delete_db_names: Vec<String> = query_scalar(
187 "select db_name from _sqlx_test.databases \
188 where created_at < (to_timestamp($1) at time zone 'UTC')",
189 )
190 .bind(created_before)
191 .fetch_all(&mut *conn)
192 .await?;
193
194 if delete_db_names.is_empty() {
195 return Ok(0);
196 }
197
198 let mut deleted_db_names = Vec::with_capacity(delete_db_names.len());
199 let delete_db_names = delete_db_names.into_iter();
200
201 let mut command = String::new();
202
203 for db_name in delete_db_names {
204 command.clear();
205 writeln!(command, "drop database if exists {db_name:?};").ok();
206 match conn.execute(&*command).await {
207 Ok(_deleted) => {
208 deleted_db_names.push(db_name);
209 }
210 // Assume a database error just means the DB is still in use.
211 Err(Error::Database(dbe)) => {
212 eprintln!("could not clean test database {db_name:?}: {dbe}")
213 }
214 // Bubble up other errors
215 Err(e) => return Err(e),
216 }
217 }
218
219 query("delete from _sqlx_test.databases where db_name = any($1::text[])")
220 .bind(&deleted_db_names)
221 .execute(&mut *conn)
222 .await?;
223
224 Ok(deleted_db_names.len())
225 }