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_builder::QueryBuilder;
18 use crate::query_scalar::query_scalar;
19 use crate::{MySql, MySqlConnectOptions, MySqlConnection};
20
21 pub(crate) use sqlx_core::testing::*;
22
23 // Using a blocking `OnceCell` here because the critical sections are short.
24 static MASTER_POOL: OnceCell<Pool<MySql>> = OnceCell::new();
25 // Automatically delete any databases created before the start of the test binary.
26 static DO_CLEANUP: AtomicBool = AtomicBool::new(true);
27
28 impl TestSupport for MySql {
29 fn test_context(args: &TestArgs) -> BoxFuture<'_, Result<TestContext<Self>, Error>> {
30 Box::pin(async move { test_context(args).await })
31 }
32
33 fn cleanup_test(db_name: &str) -> BoxFuture<'_, Result<(), Error>> {
34 Box::pin(async move {
35 let mut conn = MASTER_POOL
36 .get()
37 .expect("cleanup_test() invoked outside `#[sqlx::test]")
38 .acquire()
39 .await?;
40
41 let db_id = db_id(db_name);
42
43 conn.execute(&format!("drop database if exists {db_name};")[..])
44 .await?;
45
46 query("delete from _sqlx_test_databases where db_id = ?")
47 .bind(db_id)
48 .execute(&mut *conn)
49 .await?;
50
51 Ok(())
52 })
53 }
54
55 fn cleanup_test_dbs() -> BoxFuture<'static, Result<Option<usize>, Error>> {
56 Box::pin(async move {
57 let url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
58
59 let mut conn = MySqlConnection::connect(&url).await?;
60
61 let now = SystemTime::now()
62 .duration_since(SystemTime::UNIX_EPOCH)
63 .unwrap();
64
65 let num_deleted = do_cleanup(&mut conn, now).await?;
66 let _ = conn.close().await;
67 Ok(Some(num_deleted))
68 })
69 }
70
71 fn snapshot(
72 _conn: &mut Self::Connection,
73 ) -> BoxFuture<'_, Result<FixtureSnapshot<Self>, Error>> {
74 // TODO: I want to get the testing feature out the door so this will have to wait,
75 // but I'm keeping the code around for now because I plan to come back to it.
76 todo!()
77 }
78 }
79
80 async fn test_context(args: &TestArgs) -> Result<TestContext<MySql>, Error> {
81 let url = dotenvy::var("DATABASE_URL").expect("DATABASE_URL must be set");
82
83 let master_opts = MySqlConnectOptions::from_str(&url).expect("failed to parse DATABASE_URL");
84
85 let pool = PoolOptions::new()
86 // MySql's normal connection limit is 150 plus 1 superuser connection
87 // We don't want to use the whole cap and there may be fuzziness here due to
88 // concurrently running tests anyway.
89 .max_connections(20)
90 // Immediately close master connections. Tokio's I/O streams don't like hopping runtimes.
91 .after_release(|_conn, _| Box::pin(async move { Ok(false) }))
92 .connect_lazy_with(master_opts);
93
94 let master_pool = match MASTER_POOL.try_insert(pool) {
95 Ok(inserted) => inserted,
96 Err((existing, pool)) => {
97 // Sanity checks.
98 assert_eq!(
99 existing.connect_options().host,
100 pool.connect_options().host,
101 "DATABASE_URL changed at runtime, host differs"
102 );
103
104 assert_eq!(
105 existing.connect_options().database,
106 pool.connect_options().database,
107 "DATABASE_URL changed at runtime, database differs"
108 );
109
110 existing
111 }
112 };
113
114 let mut conn = master_pool.acquire().await?;
115
116 // language=MySQL
117 conn.execute(
118 r#"
119 create table if not exists _sqlx_test_databases (
120 db_id bigint unsigned primary key auto_increment,
121 test_path text not null,
122 created_at timestamp not null default current_timestamp
123 );
124 "#,
125 )
126 .await?;
127
128 // Record the current time _before_ we acquire the `DO_CLEANUP` permit. This
129 // prevents the first test thread from accidentally deleting new test dbs
130 // created by other test threads if we're a bit slow.
131 let now = SystemTime::now()
132 .duration_since(SystemTime::UNIX_EPOCH)
133 .unwrap();
134
135 // Only run cleanup if the test binary just started.
136 if DO_CLEANUP.swap(false, Ordering::SeqCst) {
137 do_cleanup(&mut conn, now).await?;
138 }
139
140 query("insert into _sqlx_test_databases(test_path) values (?)")
141 .bind(args.test_path)
142 .execute(&mut *conn)
143 .await?;
144
145 // MySQL doesn't have `INSERT ... RETURNING`
146 let new_db_id: u64 = query_scalar("select last_insert_id()")
147 .fetch_one(&mut *conn)
148 .await?;
149
150 let new_db_name = db_name(new_db_id);
151
152 conn.execute(&format!("create database {new_db_name}")[..])
153 .await?;
154
155 eprintln!("created database {new_db_name}");
156
157 Ok(TestContext {
158 pool_opts: PoolOptions::new()
159 // Don't allow a single test to take all the connections.
160 // Most tests shouldn't require more than 5 connections concurrently,
161 // or else they're likely doing too much in one test.
162 .max_connections(5)
163 // Close connections ASAP if left in the idle queue.
164 .idle_timeout(Some(Duration::from_secs(1)))
165 .parent(master_pool.clone()),
166 connect_opts: master_pool
167 .connect_options()
168 .deref()
169 .clone()
170 .database(&new_db_name),
171 db_name: new_db_name,
172 })
173 }
174
175 async fn do_cleanup(conn: &mut MySqlConnection, created_before: Duration) -> Result<usize, Error> {
176 // since SystemTime is not monotonic we added a little margin here to avoid race conditions with other threads
177 let created_before_as_secs = created_before.as_secs() - 2;
178 let delete_db_ids: Vec<u64> = query_scalar(
179 "select db_id from _sqlx_test_databases \
180 where created_at < from_unixtime(?)",
181 )
182 .bind(created_before_as_secs)
183 .fetch_all(&mut *conn)
184 .await?;
185
186 if delete_db_ids.is_empty() {
187 return Ok(0);
188 }
189
190 let mut deleted_db_ids = Vec::with_capacity(delete_db_ids.len());
191
192 let mut command = String::new();
193
194 for db_id in delete_db_ids {
195 command.clear();
196
197 let db_name = db_name(db_id);
198
199 writeln!(command, "drop database if exists {db_name}").ok();
200 match conn.execute(&*command).await {
201 Ok(_deleted) => {
202 deleted_db_ids.push(db_id);
203 }
204 // Assume a database error just means the DB is still in use.
205 Err(Error::Database(dbe)) => {
206 eprintln!("could not clean test database {db_id:?}: {dbe}")
207 }
208 // Bubble up other errors
209 Err(e) => return Err(e),
210 }
211 }
212
213 let mut query = QueryBuilder::new("delete from _sqlx_test_databases where db_id in (");
214
215 let mut separated = query.separated(",");
216
217 for db_id in &deleted_db_ids {
218 separated.push_bind(db_id);
219 }
220
221 query.push(")").build().execute(&mut *conn).await?;
222
223 Ok(deleted_db_ids.len())
224 }
225
226 fn db_name(id: u64) -> String {
227 format!("_sqlx_test_database_{id}")
228 }
229
230 fn db_id(name: &str) -> u64 {
231 name.trim_start_matches("_sqlx_test_database_")
232 .parse()
233 .unwrap_or_else(|_1| panic!("failed to parse ID from database name {name:?}"))
234 }
235
236 #[test]
237 fn test_db_name_id() {
238 assert_eq!(db_name(12345), "_sqlx_test_database_12345");
239 assert_eq!(db_id("_sqlx_test_database_12345"), 12345);
240 }