Debian Codegraph @

src/pool/mod.rs

raw symbols SCIP
1 //! Provides the connection pool for asynchronous SQLx connections.
2 //!
3 //! Opening a database connection for each and every operation to the database can quickly
4 //! become expensive. Furthermore, sharing a database connection between threads and functions
5 //! can be difficult to express in Rust.
6 //!
7 //! A connection pool is a standard technique that can manage opening and re-using connections.
8 //! Normally it also enforces a maximum number of connections as these are an expensive resource
9 //! on the database server.
10 //!
11 //! SQLx provides a canonical connection pool implementation intended to satisfy the majority
12 //! of use cases.
13 //!
14 //! See [Pool] for details.
15 //!
16 //! Type aliases are provided for each database to make it easier to sprinkle `Pool` through
17 //! your codebase:
18 //!
19 //! * [MssqlPool][crate::mssql::MssqlPool] (MSSQL)
20 //! * [MySqlPool][crate::mysql::MySqlPool] (MySQL)
21 //! * [PgPool][crate::postgres::PgPool] (PostgreSQL)
22 //! * [SqlitePool][crate::sqlite::SqlitePool] (SQLite)
23 //!
24 //! # Opening a connection pool
25 //!
26 //! A new connection pool with a default configuration can be created by supplying `Pool`
27 //! with the database driver and a connection string.
28 //!
29 //! ```rust,ignore
30 //! use sqlx::Pool;
31 //! use sqlx::postgres::Postgres;
32 //!
33 //! let pool = Pool::<Postgres>::connect("postgres://").await?;
34 //! ```
35 //!
36 //! For convenience, database-specific type aliases are provided:
37 //!
38 //! ```rust,ignore
39 //! use sqlx::mssql::MssqlPool;
40 //!
41 //! let pool = MssqlPool::connect("mssql://").await?;
42 //! ```
43 //!
44 //! # Using a connection pool
45 //!
46 //! A connection pool implements [`Executor`][crate::executor::Executor] and can be used directly
47 //! when executing a query. Notice that only an immutable reference (`&Pool`) is needed.
48 //!
49 //! ```rust,ignore
50 //! sqlx::query("DELETE FROM articles").execute(&pool).await?;
51 //! ```
52 //!
53 //! A connection or transaction may also be manually acquired with
54 //! [`Pool::acquire`] or
55 //! [`Pool::begin`].
56
57 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/;
58 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/::Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#;
59 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::pinrust-analyzer cargo core https://github.com/rust-lang/rust/library/core pin/::Pinrust-analyzer cargo core https://github.com/rust-lang/rust/library/core pin/Pin#;
60 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::syncrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/::Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#;
61 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::taskrust-analyzer cargo std https://github.com/rust-lang/rust/library/std task/::{Contextrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/wake/Context#, Pollrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#};
62 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::timerust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/::{Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#, Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#};
63
64 use event_listenerrust-analyzer cargo event-listener 5.4.2 crate/::EventListenerrust-analyzer cargo event-listener 5.4.2 EventListener#;
65 use futures_corerust-analyzer cargo futures-core 0.3.34 crate/::FusedFuturerust-analyzer cargo futures-core 0.3.34 future/FusedFuture#;
66 use futures_utilrust-analyzer cargo futures-util 0.3.34 crate/::FutureExtrust-analyzer cargo futures-util 0.3.34 future/future/FutureExt#;
67
68 use craterust-analyzer cargo sqlx-core 0.8.3 crate/::connectionrust-analyzer cargo sqlx-core 0.8.3 connection/::Connectionrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#;
69 use craterust-analyzer cargo sqlx-core 0.8.3 crate/::databaserust-analyzer cargo sqlx-core 0.8.3 database/::Databaserust-analyzer cargo sqlx-core 0.8.3 database/Database#;
70 use craterust-analyzer cargo sqlx-core 0.8.3 crate/::errorrust-analyzer cargo sqlx-core 0.8.3 error/::Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#;
71 use craterust-analyzer cargo sqlx-core 0.8.3 crate/::transactionrust-analyzer cargo sqlx-core 0.8.3 transaction/::Transactionrust-analyzer cargo sqlx-core 0.8.3 transaction/Transaction#;
72
73 pub use selfrust-analyzer cargo sqlx-core 0.8.3 pool/::connectionrust-analyzer cargo sqlx-core 0.8.3 pool/connection/::PoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/connection/PoolConnection#;
74 use selfrust-analyzer cargo sqlx-core 0.8.3 pool/::innerrust-analyzer cargo sqlx-core 0.8.3 pool/inner/::PoolInnerrust-analyzer cargo sqlx-core 0.8.3 pool/inner/PoolInner#;
75 #[doc(hidden)]
76 pub use selfrust-analyzer cargo sqlx-core 0.8.3 pool/::mayberust-analyzer cargo sqlx-core 0.8.3 pool/maybe/::MaybePoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/maybe/MaybePoolConnection#;
77 pub use selfrust-analyzer cargo sqlx-core 0.8.3 pool/::optionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/::{PoolConnectionMetadatarust-analyzer cargo sqlx-core 0.8.3 pool/options/PoolConnectionMetadata#, PoolOptionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/PoolOptions#};
78
79 #[macro_use]
80 mod executorrust-analyzer cargo sqlx-core 0.8.3 pool/executor/;
81
82 #[macro_use]
83 pub mod mayberust-analyzer cargo sqlx-core 0.8.3 pool/maybe/;
84
85 mod connectionrust-analyzer cargo sqlx-core 0.8.3 pool/connection/;
86 mod innerrust-analyzer cargo sqlx-core 0.8.3 pool/inner/;
87 mod optionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/;
88
89 /// An asynchronous pool of SQLx database connections.
90 ///
91 /// Create a pool with [Pool::connect] or [Pool::connect_with] and then call [Pool::acquire]
92 /// to get a connection from the pool; when the connection is dropped it will return to the pool
93 /// so it can be reused.
94 ///
95 /// You can also pass `&Pool` directly anywhere an `Executor` is required; this will automatically
96 /// checkout a connection for you.
97 ///
98 /// See [the module documentation](crate::pool) for examples.
99 ///
100 /// The pool has a maximum connection limit that it will not exceed; if `acquire()` is called
101 /// when at this limit and all connections are checked out, the task will be made to wait until
102 /// a connection becomes available.
103 ///
104 /// You can configure the connection limit, and other parameters, using [PoolOptions].
105 ///
106 /// Calls to `acquire()` are fair, i.e. fulfilled on a first-come, first-serve basis.
107 ///
108 /// `Pool` is `Send`, `Sync` and `Clone`. It is intended to be created once at the start of your
109 /// application/daemon/web server/etc. and then shared with all tasks throughout the process'
110 /// lifetime. How best to accomplish this depends on your program architecture.
111 ///
112 /// In Actix-Web, for example, you can share a single pool with all request handlers using [web::Data].
113 ///
114 /// Cloning `Pool` is cheap as it is simply a reference-counted handle to the inner pool state.
115 /// When the last remaining handle to the pool is dropped, the connections owned by the pool are
116 /// immediately closed (also by dropping). `PoolConnection` returned by [Pool::acquire] and
117 /// `Transaction` returned by [Pool::begin] both implicitly hold a reference to the pool for
118 /// their lifetimes.
119 ///
120 /// If you prefer to explicitly shutdown the pool and gracefully close its connections (which
121 /// depending on the database type, may include sending a message to the database server that the
122 /// connection is being closed), you can call [Pool::close] which causes all waiting and subsequent
123 /// calls to [Pool::acquire] to return [Error::PoolClosed], and waits until all connections have
124 /// been returned to the pool and gracefully closed.
125 ///
126 /// Type aliases are provided for each database to make it easier to sprinkle `Pool` through
127 /// your codebase:
128 ///
129 /// * [MssqlPool][crate::mssql::MssqlPool] (MSSQL)
130 /// * [MySqlPool][crate::mysql::MySqlPool] (MySQL)
131 /// * [PgPool][crate::postgres::PgPool] (PostgreSQL)
132 /// * [SqlitePool][crate::sqlite::SqlitePool] (SQLite)
133 ///
134 /// [web::Data]: https://docs.rs/actix-web/3/actix_web/web/struct.Data.html
135 ///
136 /// ### Note: Drop Behavior
137 /// Due to a lack of async `Drop`, dropping the last `Pool` handle may not immediately clean
138 /// up connections by itself. The connections will be dropped locally, which is sufficient for
139 /// SQLite, but for client/server databases like MySQL and Postgres, that only closes the
140 /// client side of the connection. The server will not know the connection is closed until
141 /// potentially much later: this is usually dictated by the TCP keepalive timeout in the server
142 /// settings.
143 ///
144 /// Because the connection may not be cleaned up immediately on the server side, you may run
145 /// into errors regarding connection limits if you are creating and dropping many pools in short
146 /// order.
147 ///
148 /// We recommend calling [`.close().await`] to gracefully close the pool and its connections
149 /// when you are done using it. This will also wake any tasks that are waiting on an `.acquire()`
150 /// call, so for long-lived applications it's a good idea to call `.close()` during shutdown.
151 ///
152 /// If you're writing tests, consider using `#[sqlx::test]` which handles the lifetime of
153 /// the pool for you.
154 ///
155 /// [`.close().await`]: Pool::close
156 ///
157 /// ### Why Use a Pool?
158 ///
159 /// A single database connection (in general) cannot be used by multiple threads simultaneously
160 /// for various reasons, but an application or web server will typically need to execute numerous
161 /// queries or commands concurrently (think of concurrent requests against a web server; many or all
162 /// of them will probably need to hit the database).
163 ///
164 /// You could place the connection in a `Mutex` but this will make it a huge bottleneck.
165 ///
166 /// Naively, you might also think to just open a new connection per request, but this
167 /// has a number of other caveats, generally due to the high overhead involved in working with
168 /// a fresh connection. Examples to follow.
169 ///
170 /// Connection pools facilitate reuse of connections to _amortize_ these costs, helping to ensure
171 /// that you're not paying for them each time you need a connection.
172 ///
173 /// ##### 1. Overhead of Opening a Connection
174 /// Opening a database connection is not exactly a cheap operation.
175 ///
176 /// For SQLite, it means numerous requests to the filesystem and memory allocations, while for
177 /// server-based databases it involves performing DNS resolution, opening a new TCP connection and
178 /// allocating buffers.
179 ///
180 /// Each connection involves a nontrivial allocation of resources for the database server, usually
181 /// including spawning a new thread or process specifically to handle the connection, both for
182 /// concurrency and isolation of faults.
183 ///
184 /// Additionally, database connections typically involve a complex handshake including
185 /// authentication, negotiation regarding connection parameters (default character sets, timezones,
186 /// locales, supported features) and upgrades to encrypted tunnels.
187 ///
188 /// If `acquire()` is called on a pool with all connections checked out but it is not yet at its
189 /// connection limit (see next section), then a new connection is immediately opened, so this pool
190 /// does not _automatically_ save you from the overhead of creating a new connection.
191 ///
192 /// However, because this pool by design enforces _reuse_ of connections, this overhead cost
193 /// is not paid each and every time you need a connection. In fact, if you set
194 /// [the `min_connections` option in PoolOptions][PoolOptions::min_connections], the pool will
195 /// create that many connections up-front so that they are ready to go when a request comes in,
196 /// and maintain that number on a best-effort basis for consistent performance.
197 ///
198 /// ##### 2. Connection Limits (MySQL, MSSQL, Postgres)
199 /// Database servers usually place hard limits on the number of connections that are allowed open at
200 /// any given time, to maintain performance targets and prevent excessive allocation of resources,
201 /// such as RAM, journal files, disk caches, etc.
202 ///
203 /// These limits have different defaults per database flavor, and may vary between different
204 /// distributions of the same database, but are typically configurable on server start;
205 /// if you're paying for managed database hosting then the connection limit will typically vary with
206 /// your pricing tier.
207 ///
208 /// In MySQL, the default limit is typically 150, plus 1 which is reserved for a user with the
209 /// `CONNECTION_ADMIN` privilege so you can still access the server to diagnose problems even
210 /// with all connections being used.
211 ///
212 /// In MSSQL the only documentation for the default maximum limit is that it depends on the version
213 /// and server configuration.
214 ///
215 /// In Postgres, the default limit is typically 100, minus 3 which are reserved for superusers
216 /// (putting the default limit for unprivileged users at 97 connections).
217 ///
218 /// In any case, exceeding these limits results in an error when opening a new connection, which
219 /// in a web server context will turn into a `500 Internal Server Error` if not handled, but should
220 /// be turned into either `403 Forbidden` or `429 Too Many Requests` depending on your rate-limiting
221 /// scheme. However, in a web context, telling a client "go away, maybe try again later" results in
222 /// a sub-optimal user experience.
223 ///
224 /// Instead, with a connection pool, clients are made to wait in a fair queue for a connection to
225 /// become available; by using a single connection pool for your whole application, you can ensure
226 /// that you don't exceed the connection limit of your database server while allowing response
227 /// time to degrade gracefully at high load.
228 ///
229 /// Of course, if multiple applications are connecting to the same database server, then you
230 /// should ensure that the connection limits for all applications add up to your server's maximum
231 /// connections or less.
232 ///
233 /// ##### 3. Resource Reuse
234 /// The first time you execute a query against your database, the database engine must first turn
235 /// the SQL into an actionable _query plan_ which it may then execute against the database. This
236 /// involves parsing the SQL query, validating and analyzing it, and in the case of Postgres 12+ and
237 /// SQLite, generating code to execute the query plan (native or bytecode, respectively).
238 ///
239 /// These database servers provide a way to amortize this overhead by _preparing_ the query,
240 /// associating it with an object ID and placing its query plan in a cache to be referenced when
241 /// it is later executed.
242 ///
243 /// Prepared statements have other features, like bind parameters, which make them safer and more
244 /// ergonomic to use as well. By design, SQLx pushes you towards using prepared queries/statements
245 /// via the [Query][crate::query::Query] API _et al._ and the `query!()` macro _et al._, for
246 /// reasons of safety, ergonomics, and efficiency.
247 ///
248 /// However, because database connections are typically isolated from each other in the database
249 /// server (either by threads or separate processes entirely), they don't typically share prepared
250 /// statements between connections so this work must be redone _for each connection_.
251 ///
252 /// As with section 1, by facilitating reuse of connections, `Pool` helps to ensure their prepared
253 /// statements (and thus cached query plans) can be reused as much as possible, thus amortizing
254 /// the overhead involved.
255 ///
256 /// Depending on the database server, a connection will have caches for all kinds of other data as
257 /// well and queries will generally benefit from these caches being "warm" (populated with data).
258 pub struct Poolrust-analyzer cargo sqlx-core 0.8.3 pool/Pool#<DB: Databaserust-analyzer cargo sqlx-core 0.8.3 database/Database#>(pub(craterust-analyzer cargo sqlx-core 0.8.3 crate/) Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#<PoolInnerrust-analyzer cargo sqlx-core 0.8.3 pool/inner/PoolInner#<DB>>);
259
260 /// A future that resolves when the pool is closed.
261 ///
262 /// See [`Pool::close_event()`] for details.
263 pub struct CloseEventrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent# {
264 listenerrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent#listener.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<EventListenerrust-analyzer cargo event-listener 5.4.2 EventListener#>,
265 }
266
267 impl<DB: Databaserust-analyzer cargo sqlx-core 0.8.3 database/Database#> Poolrust-analyzer cargo sqlx-core 0.8.3 pool/Pool#<DB> {
268 /// Create a new connection pool with a default pool configuration and
269 /// the given connection URL, and immediately establish one connection.
270 ///
271 /// Refer to the relevant `ConnectOptions` impl for your database for the expected URL format:
272 ///
273 /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions]
274 /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions]
275 /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions]
276 /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions]
277 ///
278 /// The default configuration is mainly suited for testing and light-duty applications.
279 /// For production applications, you'll likely want to make at least few tweaks.
280 ///
281 /// See [`PoolOptions::new()`] for details.
282 pub async fn connectrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]connect().(url: &str) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`], Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#> {
283 PoolOptionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/PoolOptions#::<DB>::newrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]new().().connectrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]connect().(url).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().
284 }
285
286 /// Create a new connection pool with a default pool configuration and
287 /// the given `ConnectOptions`, and immediately establish one connection.
288 ///
289 /// The default configuration is mainly suited for testing and light-duty applications.
290 /// For production applications, you'll likely want to make at least few tweaks.
291 ///
292 /// See [`PoolOptions::new()`] for details.
293 pub async fn connect_withrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]connect_with().(
294 options: <DB::Connectionrust-analyzer cargo sqlx-core 0.8.3 database/Database#Connection# as Connectionrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#>::Optionsrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#Options#,
295 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`], Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#> {
296 PoolOptionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/PoolOptions#::<DB>::newrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]new().().connect_withrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]connect_with().(options).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().
297 }
298
299 /// Create a new connection pool with a default pool configuration and
300 /// the given connection URL.
301 ///
302 /// The pool will establish connections only as needed.
303 ///
304 /// Refer to the relevant [`ConnectOptions`][crate::connection::ConnectOptions] impl for your database for the expected URL format:
305 ///
306 /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions]
307 /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions]
308 /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions]
309 /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions]
310 ///
311 /// The default configuration is mainly suited for testing and light-duty applications.
312 /// For production applications, you'll likely want to make at least few tweaks.
313 ///
314 /// See [`PoolOptions::new()`] for details.
315 pub fn connect_lazyrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]connect_lazy().(url: &str) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`], Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#> {
316 PoolOptionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/PoolOptions#::<DB>::newrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]new().().connect_lazyrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]connect_lazy().(url)
317 }
318
319 /// Create a new connection pool with a default pool configuration and
320 /// the given `ConnectOptions`.
321 ///
322 /// The pool will establish connections only as needed.
323 ///
324 /// The default configuration is mainly suited for testing and light-duty applications.
325 /// For production applications, you'll likely want to make at least few tweaks.
326 ///
327 /// See [`PoolOptions::new()`] for details.
328 pub fn connect_lazy_withrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]connect_lazy_with().(options: <DB::Connectionrust-analyzer cargo sqlx-core 0.8.3 database/Database#Connection# as Connectionrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#>::Optionsrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#Options#) -> Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`] {
329 PoolOptionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/PoolOptions#::<DB>::newrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]new().().connect_lazy_withrust-analyzer cargo sqlx-core 0.8.3 pool/options/impl#[`PoolOptions<DB>`]connect_lazy_with().(options)
330 }
331
332 /// Retrieves a connection from the pool.
333 ///
334 /// The total time this method is allowed to execute is capped by
335 /// [`PoolOptions::acquire_timeout`].
336 /// If that timeout elapses, this will return [`Error::PoolClosed`].
337 ///
338 /// ### Note: Cancellation/Timeout May Drop Connections
339 /// If `acquire` is cancelled or times out after it acquires a connection from the idle queue or
340 /// opens a new one, it will drop that connection because we don't want to assume it
341 /// is safe to return to the pool, and testing it to see if it's safe to release could introduce
342 /// subtle bugs if not implemented correctly. To avoid that entirely, we've decided to not
343 /// gracefully handle cancellation here.
344 ///
345 /// However, if your workload is sensitive to dropped connections such as using an in-memory
346 /// SQLite database with a pool size of 1, you can pretty easily ensure that a cancelled
347 /// `acquire()` call will never drop connections by tweaking your [`PoolOptions`]:
348 ///
349 /// * Set [`test_before_acquire(false)`][PoolOptions::test_before_acquire]
350 /// * Never set [`before_acquire`][PoolOptions::before_acquire] or
351 /// [`after_connect`][PoolOptions::after_connect].
352 ///
353 /// This should eliminate any potential `.await` points between acquiring a connection and
354 /// returning it.
355 pub fn acquirerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]acquire().(&self) -> impl Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#<Outputrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#Output# = Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<PoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/connection/PoolConnection#<DB>, Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#>> + 'static {
356 let shared = self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..clonerust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/impl#[`Arc<T, A>`][Clone]clone().();
357 async move { shared.acquirerust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]acquire().().rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll()..maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]map().(|conn| conn.reattachrust-analyzer cargo sqlx-core 0.8.3 pool/connection/impl#[`Floating<DB, Live<DB>>`]reattach().()) }
358 }
359
360 /// Attempts to retrieve a connection from the pool if there is one available.
361 ///
362 /// Returns `None` immediately if there are no idle connections available in the pool
363 /// or there are tasks waiting for a connection which have yet to wake.
364 pub fn try_acquirerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]try_acquire().(&self) -> Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<PoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/connection/PoolConnection#<DB>> {
365 self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..try_acquirerust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]try_acquire().().maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]map().(|conn| conn.into_liverust-analyzer cargo sqlx-core 0.8.3 pool/connection/impl#[`Floating<DB, Idle<DB>>`]into_live().().reattachrust-analyzer cargo sqlx-core 0.8.3 pool/connection/impl#[`Floating<DB, Live<DB>>`]reattach().())
366 }
367
368 /// Retrieves a connection and immediately begins a new transaction.
369 pub async fn beginrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]begin().(&self) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Transactionrust-analyzer cargo sqlx-core 0.8.3 transaction/Transaction#<'static, DB>, Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#> {
370 Transactionrust-analyzer cargo sqlx-core 0.8.3 transaction/Transaction#::beginrust-analyzer cargo sqlx-core 0.8.3 transaction/impl#[`Transaction<'c, DB>`]begin().(MaybePoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/maybe/MaybePoolConnection#::PoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/maybe/MaybePoolConnection#PoolConnection#(self.acquirerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]acquire().().rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().)).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/impl#[`Pin<P>`][Future]poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/impl#[`Pin<P>`][Future]poll().
371 }
372
373 /// Attempts to retrieve a connection and immediately begins a new transaction if successful.
374 pub async fn try_beginrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]try_begin().(&self) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Transactionrust-analyzer cargo sqlx-core 0.8.3 transaction/Transaction#<'static, DB>>, Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#> {
375 match self.try_acquirerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]try_acquire().() {
376 Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(conn) => Transactionrust-analyzer cargo sqlx-core 0.8.3 transaction/Transaction#::beginrust-analyzer cargo sqlx-core 0.8.3 transaction/impl#[`Transaction<'c, DB>`]begin().(MaybePoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/maybe/MaybePoolConnection#::PoolConnectionrust-analyzer cargo sqlx-core 0.8.3 pool/maybe/MaybePoolConnection#PoolConnection#(conn))
377 .rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/impl#[`Pin<P>`][Future]poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/impl#[`Pin<P>`][Future]poll().
378 .maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]map().(Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#),
379
380 Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None# => Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#),
381 }
382 }
383
384 /// Shut down the connection pool, immediately waking all tasks waiting for a connection.
385 ///
386 /// Upon calling this method, any currently waiting or subsequent calls to [`Pool::acquire`] and
387 /// the like will immediately return [`Error::PoolClosed`] and no new connections will be opened.
388 /// Checked-out connections are unaffected, but will be gracefully closed on-drop
389 /// rather than being returned to the pool.
390 ///
391 /// Returns a `Future` which can be `.await`ed to ensure all connections are
392 /// gracefully closed. It will first close any idle connections currently waiting in the pool,
393 /// then wait for all checked-out connections to be returned or closed.
394 ///
395 /// Waiting for connections to be gracefully closed is optional, but will allow the database
396 /// server to clean up the resources sooner rather than later. This is especially important
397 /// for tests that create a new pool every time, otherwise you may see errors about connection
398 /// limits being exhausted even when running tests in a single thread.
399 ///
400 /// If the returned `Future` is not run to completion, any remaining connections will be dropped
401 /// when the last handle for the given pool instance is dropped, which could happen in a task
402 /// spawned by `Pool` internally and so may be unpredictable otherwise.
403 ///
404 /// `.close()` may be safely called and `.await`ed on multiple handles concurrently.
405 pub fn closerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]close().(&self) -> impl Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#<Outputrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#Output# = ()> + '_ {
406 self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..closerust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]close().()
407 }
408
409 /// Returns `true` if [`.close()`][Pool::close] has been called on the pool, `false` otherwise.
410 pub fn is_closedrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]is_closed().(&self) -> bool {
411 self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..is_closedrust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]is_closed().()
412 }
413
414 /// Get a future that resolves when [`Pool::close()`] is called.
415 ///
416 /// If the pool is already closed, the future resolves immediately.
417 ///
418 /// This can be used to cancel long-running operations that hold onto a [`PoolConnection`]
419 /// so they don't prevent the pool from closing (which would otherwise wait until all
420 /// connections are returned).
421 ///
422 /// Examples
423 /// ========
424 /// These examples use Postgres and Tokio, but should suffice to demonstrate the concept.
425 ///
426 /// Do something when the pool is closed:
427 /// ```rust,no_run
428 /// # async fn bleh() -> sqlx::Result<()> {
429 /// use sqlx::PgPool;
430 ///
431 /// let pool = PgPool::connect("postgresql://...").await?;
432 ///
433 /// let pool2 = pool.clone();
434 ///
435 /// tokio::spawn(async move {
436 /// // Demonstrates that `CloseEvent` is itself a `Future` you can wait on.
437 /// // This lets you implement any kind of on-close event that you like.
438 /// pool2.close_event().await;
439 ///
440 /// println!("Pool is closing!");
441 ///
442 /// // Imagine maybe recording application statistics or logging a report, etc.
443 /// });
444 ///
445 /// // The rest of the application executes normally...
446 ///
447 /// // Close the pool before the application exits...
448 /// pool.close().await;
449 ///
450 /// # Ok(())
451 /// # }
452 /// ```
453 ///
454 /// Cancel a long-running operation:
455 /// ```rust,no_run
456 /// # async fn bleh() -> sqlx::Result<()> {
457 /// use sqlx::{Executor, PgPool};
458 ///
459 /// let pool = PgPool::connect("postgresql://...").await?;
460 ///
461 /// let pool2 = pool.clone();
462 ///
463 /// tokio::spawn(async move {
464 /// // `do_until` yields the inner future's output wrapped in `sqlx::Result`,
465 /// // in this case giving a double-wrapped result.
466 /// let res: sqlx::Result<sqlx::Result<()>> = pool2.close_event().do_until(async {
467 /// // This statement normally won't return for 30 days!
468 /// // (Assuming the connection doesn't time out first, of course.)
469 /// pool2.execute("SELECT pg_sleep('30 days')").await?;
470 ///
471 /// // If the pool is closed before the statement completes, this won't be printed.
472 /// // This is because `.do_until()` cancels the future it's given if the
473 /// // pool is closed first.
474 /// println!("Waited!");
475 ///
476 /// Ok(())
477 /// }).await;
478 ///
479 /// match res {
480 /// Ok(Ok(())) => println!("Wait succeeded"),
481 /// Ok(Err(e)) => println!("Error from inside do_until: {e:?}"),
482 /// Err(e) => println!("Error from do_until: {e:?}"),
483 /// }
484 /// });
485 ///
486 /// // This normally wouldn't return until the above statement completed and the connection
487 /// // was returned to the pool. However, thanks to `.do_until()`, the operation was
488 /// // cancelled as soon as we called `.close().await`.
489 /// pool.close().await;
490 ///
491 /// # Ok(())
492 /// # }
493 /// ```
494 pub fn close_eventrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]close_event().(&self) -> CloseEventrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent# {
495 self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..close_eventrust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]close_event().()
496 }
497
498 /// Returns the number of connections currently active. This includes idle connections.
499 pub fn sizerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]size().(&self) -> u32 {
500 self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..sizerust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]size().()
501 }
502
503 /// Returns the number of connections active and idle (not in use).
504 pub fn num_idlerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]num_idle().(&self) -> usize {
505 self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..num_idlerust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]num_idle().()
506 }
507
508 /// Gets a clone of the connection options for this pool
509 pub fn connect_optionsrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]connect_options().(&self) -> Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#<<DB::Connectionrust-analyzer cargo sqlx-core 0.8.3 database/Database#Connection# as Connectionrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#>::Optionsrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#Options#> {
510 self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0.
511 .connect_optionsrust-analyzer cargo sqlx-core 0.8.3 pool/inner/PoolInner#connect_options.
512 .readrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/rwlock/impl#[`RwLock<T>`]read().()
513 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("write-lock holder panicked")
514 .clonerust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/impl#[`Arc<T, A>`][Clone]clone().()
515 }
516
517 /// Updates the connection options this pool will use when opening any future connections. Any
518 /// existing open connection in the pool will be left as-is.
519 pub fn set_connect_optionsrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]set_connect_options().(&self, connect_options: <DB::Connectionrust-analyzer cargo sqlx-core 0.8.3 database/Database#Connection# as Connectionrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#>::Optionsrust-analyzer cargo sqlx-core 0.8.3 connection/Connection#Options#) {
520 // technically write() could also panic if the current thread already holds the lock,
521 // but because this method can't be re-entered by the same thread that shouldn't be a problem
522 let mut guard = self
523 .0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0.
524 .connect_optionsrust-analyzer cargo sqlx-core 0.8.3 pool/inner/PoolInner#connect_options.
525 .writerust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/rwlock/impl#[`RwLock<T>`]write().()
526 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("write-lock holder panicked");
527 *rust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/poison/rwlock/impl#[`RwLockWriteGuard<'_, T>`][DerefMut]deref_mut().guard = Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/impl#[`Arc<T>`]new().(connect_options);
528 }
529
530 /// Get the options for this pool
531 pub fn optionsrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`]options().(&self) -> &PoolOptionsrust-analyzer cargo sqlx-core 0.8.3 pool/options/PoolOptions#<DB> {
532 &self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..optionsrust-analyzer cargo sqlx-core 0.8.3 pool/inner/PoolInner#options.
533 }
534 }
535
536 /// Returns a new [Pool] tied to the same shared connection pool.
537 impl<DB: Databaserust-analyzer cargo sqlx-core 0.8.3 database/Database#> Clonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core clone/Clone# for Poolrust-analyzer cargo sqlx-core 0.8.3 pool/Pool#<DB> {
538 fn clonerust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`][Clone]clone().(&self) -> Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`][Clone] {
539 Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`][Clone](Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#::clonerust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/impl#[`Arc<T, A>`][Clone]clone().(&self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0.))
540 }
541 }
542
543 impl<DB: Databaserust-analyzer cargo sqlx-core 0.8.3 database/Database#> fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/::Debugrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/Debug# for Poolrust-analyzer cargo sqlx-core 0.8.3 pool/Pool#<DB> {
544 fn fmtrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[`Pool<DB>`][Debug]fmt().(&self, fmt: &mut fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/::Formatterrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/Formatter#<'_>) -> fmtrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc fmt/::Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/Result# {
545 fmt.debug_structrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/impl#[`Formatter<'a>`]debug_struct().("Pool")
546 .fieldrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]field().("size", &self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..sizerust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]size().())
547 .fieldrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]field().("num_idle", &self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..num_idlerust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]num_idle().())
548 .fieldrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]field().("is_closed", &self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..is_closedrust-analyzer cargo sqlx-core 0.8.3 pool/inner/impl#[`PoolInner<DB>`]is_closed().())
549 .fieldrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]field().("options", &self.0rust-analyzer cargo sqlx-core 0.8.3 pool/Pool#0..optionsrust-analyzer cargo sqlx-core 0.8.3 pool/inner/PoolInner#options.)
550 .finishrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/builders/impl#[`DebugStruct<'a, 'b>`]finish().()
551 }
552 }
553
554 impl CloseEventrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent# {
555 /// Execute the given future until it returns or the pool is closed.
556 ///
557 /// Cancels the future and returns `Err(PoolClosed)` if/when the pool is closed.
558 /// If the pool was already closed, the future is never run.
559 pub async fn do_untilrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[CloseEvent]do_until().<Fut: Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#>(&mut self, fut: Fut) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Fut::Outputrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#Output#, Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#> {
560 // Check that the pool wasn't closed already.
561 //
562 // We use `poll_immediate()` as it will use the correct waker instead of
563 // a no-op one like `.now_or_never()`, but it won't actually suspend execution here.
564 futures_utilrust-analyzer cargo futures-util 0.3.34 crate/::futurerust-analyzer cargo futures-util 0.3.34 future/::poll_immediaterust-analyzer cargo futures-util 0.3.34 future/poll_immediate/poll_immediate().(&mut *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&mut T`][Deref]deref().self)
565 .rust-analyzer cargo futures-util 0.3.34 future/poll_immediate/impl#[`PollImmediate<F>`][Future]poll().awaitrust-analyzer cargo futures-util 0.3.34 future/poll_immediate/impl#[`PollImmediate<F>`][Future]poll().
566 .map_orrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]map_or().(Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(()), |_| Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#::PoolClosedrust-analyzer cargo sqlx-core 0.8.3 error/Error#PoolClosed#))?rust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`][Try]branch().;
567
568 futures_utilrust-analyzer cargo futures-util 0.3.34 crate/::pin_mutrust-analyzer cargo futures-util 0.3.34 macros/pin_mut!!(fut);
569
570 // I find that this is clearer in intent than `futures_util::future::select()`
571 // or `futures_util::select_biased!{}` (which isn't enabled anyway).
572 futures_utilrust-analyzer cargo futures-util 0.3.34 crate/::futurerust-analyzer cargo futures-util 0.3.34 future/::poll_fnrust-analyzer cargo futures-util 0.3.34 future/poll_fn/poll_fn().(|cx| {
573 // Poll `fut` first as the wakeup event is more likely for it than `self`.
574 if let Pollrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#::Readyrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#Ready#(ret) = fut.as_mutrust-analyzer cargo core https://github.com/rust-lang/rust/library/core pin/impl#[`Pin<Ptr>`]as_mut().().pollrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().(cx) {
575 return Pollrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#::Readyrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#Ready#(Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(ret));
576 }
577
578 // Can't really factor out mapping to `Err(Error::PoolClosed)` though it seems like
579 // we should because that results in a different `Ok` type each time.
580 //
581 // Ideally we'd map to something like `Result<!, Error>` but using `!` as a type
582 // is not allowed on stable Rust yet.
583 self.poll_unpinrust-analyzer cargo futures-util 0.3.34 future/future/FutureExt#poll_unpin().(cx).maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/impl#[`Poll<T>`]map().(|_| Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#::PoolClosedrust-analyzer cargo sqlx-core 0.8.3 error/Error#PoolClosed#))
584 })
585 .rust-analyzer cargo futures-util 0.3.34 future/poll_fn/impl#[`PollFn<F>`][Future]poll().awaitrust-analyzer cargo futures-util 0.3.34 future/poll_fn/impl#[`PollFn<F>`][Future]poll().
586 }
587 }
588
589 impl Futurerust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future# for CloseEventrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent# {
590 type Outputrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[CloseEvent][Future]Output# = ();
591
592 fn pollrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[CloseEvent][Future]poll().(mut self: Pinrust-analyzer cargo core https://github.com/rust-lang/rust/library/core pin/Pin#<&mut Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[CloseEvent][Future]>, cx: &mut Contextrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/wake/Context#<'_>) -> Pollrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#<Selfrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[CloseEvent][Future]::Outputrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#Output#> {
593 if let Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(listener) = &mut self.listenerrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent#listener. {
594 futures_corerust-analyzer cargo futures-core 0.3.34 crate/::readyrust-analyzer cargo futures-core 0.3.34 task/poll/ready!!(listener.poll_unpinrust-analyzer cargo futures-util 0.3.34 future/future/FutureExt#poll_unpin().(cx));
595 }
596
597 // `EventListener` doesn't like being polled after it yields, and even if it did it
598 // would probably just wait for the next event, neither of which we want.
599 //
600 // So this way, once we get our close event, we fuse this future to immediately return.
601 self.listenerrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent#listener. = Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#;
602
603 Pollrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#::Readyrust-analyzer cargo core https://github.com/rust-lang/rust/library/core task/poll/Poll#Ready#(())
604 }
605 }
606
607 impl FusedFuturerust-analyzer cargo futures-core 0.3.34 future/FusedFuture# for CloseEventrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent# {
608 fn is_terminatedrust-analyzer cargo sqlx-core 0.8.3 pool/impl#[CloseEvent][FusedFuture]is_terminated().(&self) -> bool {
609 self.listenerrust-analyzer cargo sqlx-core 0.8.3 pool/CloseEvent#listener..is_nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]is_none().()
610 }
611 }
612
613 /// get the time between the deadline and now and use that as our timeout
614 ///
615 /// returns `Error::PoolTimedOut` if the deadline is in the past
616 fn deadline_as_timeoutrust-analyzer cargo sqlx-core 0.8.3 pool/deadline_as_timeout().(deadline: Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Durationrust-analyzer cargo core https://github.com/rust-lang/rust/library/core time/Duration#, Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#> {
617 deadline
618 .checked_duration_sincerust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant]checked_duration_since().(Instantrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/Instant#::nowrust-analyzer cargo std https://github.com/rust-lang/rust/library/std time/impl#[Instant]now().())
619 .ok_orrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]ok_or().(Errorrust-analyzer cargo sqlx-core 0.8.3 error/Error#::PoolTimedOutrust-analyzer cargo sqlx-core 0.8.3 error/Error#PoolTimedOut#)
620 }
621
622 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
623 #[allow(dead_code)]
624 fn assert_pool_traitsrust-analyzer cargo sqlx-core 0.8.3 pool/assert_pool_traits().() {
625 fn assert_send_syncrust-analyzer cargo sqlx-core 0.8.3 pool/assert_send_sync().<T: Sendrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Send# + Syncrust-analyzer cargo core https://github.com/rust-lang/rust/library/core marker/Sync#>() {}
626 fn assert_clonerust-analyzer cargo sqlx-core 0.8.3 pool/assert_clone().<T: Clonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core clone/Clone#>() {}
627
628 fn assert_poolrust-analyzer cargo sqlx-core 0.8.3 pool/assert_pool().<DB: Databaserust-analyzer cargo sqlx-core 0.8.3 database/Database#>() {
629 assert_send_syncrust-analyzer cargo sqlx-core 0.8.3 pool/assert_send_sync().::<Poolrust-analyzer cargo sqlx-core 0.8.3 pool/Pool#<DB>>();
630 assert_clonerust-analyzer cargo sqlx-core 0.8.3 pool/assert_clone().::<Poolrust-analyzer cargo sqlx-core 0.8.3 pool/Pool#<DB>>();
631 }
632 }