Debian Codegraph @

tests/any/pool.rs

raw symbols SCIP
1 use sqlx::any::{AnyConnectOptions, AnyPoolOptions};
2 use sqlx::Executor;
3 use std::sync::{
4 atomic::{AtomicI32, AtomicUsize, Ordering},
5 Arc, Mutex,
6 };
7 use std::time::Duration;
8
9 #[sqlx_macros::test]
10 async fn pool_should_invoke_after_connect() -> anyhow::Result<()> {
11 sqlx::any::install_default_drivers();
12
13 let counter = Arc::new(AtomicUsize::new(0));
14
15 let pool = AnyPoolOptions::new()
16 .after_connect({
17 let counter = counter.clone();
18 move |_conn, _meta| {
19 let counter = counter.clone();
20 Box::pin(async move {
21 counter.fetch_add(1, Ordering::SeqCst);
22
23 Ok(())
24 })
25 }
26 })
27 .connect(&dotenvy::var("DATABASE_URL")?)
28 .await?;
29
30 let _ = pool.acquire().await?;
31 let _ = pool.acquire().await?;
32 let _ = pool.acquire().await?;
33 let _ = pool.acquire().await?;
34
35 // since connections are released asynchronously,
36 // `.after_connect()` may be called more than once
37 assert!(counter.load(Ordering::SeqCst) >= 1);
38
39 Ok(())
40 }
41
42 // https://github.com/launchbadge/sqlx/issues/527
43 #[sqlx_macros::test]
44 async fn pool_should_be_returned_failed_transactions() -> anyhow::Result<()> {
45 sqlx::any::install_default_drivers();
46
47 let pool = AnyPoolOptions::new()
48 .max_connections(2)
49 .acquire_timeout(Duration::from_secs(3))
50 .connect(&dotenvy::var("DATABASE_URL")?)
51 .await?;
52
53 let query = "blah blah";
54
55 let mut tx = pool.begin().await?;
56 let res = sqlx::query(query).execute(&mut *tx).await;
57 assert!(res.is_err());
58 drop(tx);
59
60 let mut tx = pool.begin().await?;
61 let res = sqlx::query(query).execute(&mut *tx).await;
62 assert!(res.is_err());
63 drop(tx);
64
65 let mut tx = pool.begin().await?;
66 let res = sqlx::query(query).execute(&mut *tx).await;
67 assert!(res.is_err());
68 drop(tx);
69
70 Ok(())
71 }
72
73 #[sqlx_macros::test]
74 async fn test_pool_callbacks() -> anyhow::Result<()> {
75 sqlx::any::install_default_drivers();
76
77 #[derive(sqlx::FromRow, Debug, PartialEq, Eq)]
78 struct ConnStats {
79 id: i32,
80 before_acquire_calls: i32,
81 after_release_calls: i32,
82 }
83
84 sqlx_test::setup_if_needed();
85
86 let conn_options: AnyConnectOptions = std::env::var("DATABASE_URL")?.parse()?;
87
88 let current_id = AtomicI32::new(0);
89
90 let pool = AnyPoolOptions::new()
91 .max_connections(1)
92 .acquire_timeout(Duration::from_secs(5))
93 .after_connect(move |conn, meta| {
94 assert_eq!(meta.age, Duration::ZERO);
95 assert_eq!(meta.idle_for, Duration::ZERO);
96
97 let id = current_id.fetch_add(1, Ordering::AcqRel);
98
99 Box::pin(async move {
100 let statement = format!(
101 // language=SQL
102 r#"
103 CREATE TEMPORARY TABLE conn_stats(
104 id int primary key,
105 before_acquire_calls int default 0,
106 after_release_calls int default 0
107 );
108 INSERT INTO conn_stats(id) VALUES ({});
109 "#,
110 // Until we have generalized bind parameters
111 id
112 );
113
114 conn.execute(&statement[..]).await?;
115 Ok(())
116 })
117 })
118 .before_acquire(|conn, meta| {
119 // `age` and `idle_for` should both be nonzero
120 assert_ne!(meta.age, Duration::ZERO);
121 assert_ne!(meta.idle_for, Duration::ZERO);
122
123 Box::pin(async move {
124 // MySQL and MariaDB don't support UPDATE ... RETURNING
125 sqlx::query(
126 r#"
127 UPDATE conn_stats
128 SET before_acquire_calls = before_acquire_calls + 1
129 "#,
130 )
131 .execute(&mut *conn)
132 .await?;
133
134 let stats: ConnStats = sqlx::query_as("SELECT * FROM conn_stats")
135 .fetch_one(conn)
136 .await?;
137
138 // For even IDs, cap by the number of before_acquire calls.
139 // Ignore the check for odd IDs.
140 Ok((stats.id & 1) == 1 || stats.before_acquire_calls < 3)
141 })
142 })
143 .after_release(|conn, meta| {
144 // `age` should be nonzero but `idle_for` should be zero.
145 assert_ne!(meta.age, Duration::ZERO);
146 assert_eq!(meta.idle_for, Duration::ZERO);
147
148 Box::pin(async move {
149 sqlx::query(
150 r#"
151 UPDATE conn_stats
152 SET after_release_calls = after_release_calls + 1
153 "#,
154 )
155 .execute(&mut *conn)
156 .await?;
157
158 let stats: ConnStats = sqlx::query_as("SELECT * FROM conn_stats")
159 .fetch_one(conn)
160 .await?;
161
162 // For odd IDs, cap by the number of before_release calls.
163 // Ignore the check for even IDs.
164 Ok((stats.id & 1) == 0 || stats.after_release_calls < 4)
165 })
166 })
167 // Don't establish a connection yet.
168 .connect_lazy_with(conn_options);
169
170 // Expected pattern of (id, before_acquire_calls, after_release_calls)
171 let pattern = [
172 // The connection pool starts empty.
173 (0, 0, 0),
174 (0, 1, 1),
175 (0, 2, 2),
176 (1, 0, 0),
177 (1, 1, 1),
178 (1, 2, 2),
179 // We should expect one more `acquire` because the ID is odd
180 (1, 3, 3),
181 (2, 0, 0),
182 (2, 1, 1),
183 (2, 2, 2),
184 (3, 0, 0),
185 ];
186
187 for (id, before_acquire_calls, after_release_calls) in pattern {
188 let conn_stats: ConnStats = sqlx::query_as("SELECT * FROM conn_stats")
189 .fetch_one(&pool)
190 .await?;
191
192 assert_eq!(
193 conn_stats,
194 ConnStats {
195 id,
196 before_acquire_calls,
197 after_release_calls
198 }
199 );
200 }
201
202 pool.close().await;
203
204 Ok(())
205 }
206
207 #[ignore]
208 #[sqlx_macros::test]
209 async fn test_connection_maintenance() -> anyhow::Result<()> {
210 sqlx::any::install_default_drivers();
211 sqlx_test::setup_if_needed();
212 let conn_options: AnyConnectOptions = std::env::var("DATABASE_URL")?.parse()?;
213
214 let last_meta = Arc::new(Mutex::new(None));
215 let last_meta_ = last_meta.clone();
216 let pool = AnyPoolOptions::new()
217 .max_lifetime(Duration::from_millis(400))
218 .min_connections(3)
219 .before_acquire(move |_conn, _meta| {
220 *last_meta_.lock().unwrap() = Some(_meta);
221 Box::pin(async { Ok(true) })
222 })
223 .connect_lazy_with(conn_options);
224
225 // Open and release 5 connections
226 let conns = vec![
227 pool.acquire().await?,
228 pool.acquire().await?,
229 pool.acquire().await?,
230 pool.acquire().await?,
231 pool.acquire().await?,
232 ];
233 assert_eq!(pool.size(), 5);
234 assert_eq!(pool.num_idle(), 0);
235 for mut conn in conns {
236 conn.return_to_pool().await;
237 }
238
239 assert_eq!(pool.size(), 5);
240 assert_eq!(pool.num_idle(), 5);
241
242 // Wait for at least two iterations of maintenance task
243 sqlx_core::rt::sleep(Duration::from_secs(1)).await;
244
245 // Existing connections should have been closed due to max lifetime
246 // and the pool should have reopened min_connections new ones.
247 // One connection might be in the process of being replaced so we assert 2-3.
248 assert!(
249 pool.size() >= 2 && pool.size() <= 3,
250 "pool.size() = {}",
251 pool.size()
252 );
253 for _ in 0..2 {
254 // Check that the connections was both acquired from the pool AND it's new
255 let _ = pool.acquire().await.expect("failed to acquire connection");
256 let meta = last_meta
257 .lock()
258 .unwrap()
259 .take()
260 .expect("expected a connection from the pool");
261 assert!(
262 meta.age < Duration::from_secs(2),
263 "expected a fresh connection (age {:?})",
264 meta.age
265 );
266 }
267
268 Ok(())
269 }