sqlx_core_oldapi/pool/
options.rs

1use crate::connection::Connection;
2use crate::database::Database;
3use crate::error::Error;
4use crate::pool::inner::PoolInner;
5use crate::pool::Pool;
6use futures_core::future::BoxFuture;
7use std::fmt::{self, Debug, Formatter};
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10
11/// Configuration options for [`Pool`][super::Pool].
12///
13/// ### Callback Functions: Why Do I Need `Box::pin()`?
14/// Essentially, because it's impossible to write generic bounds that describe a closure
15/// with a higher-ranked lifetime parameter, returning a future with that same lifetime.
16///
17/// Ideally, you could define it like this:
18/// ```rust,ignore
19/// async fn takes_foo_callback(f: impl for<'a> Fn(&'a mut Foo) -> impl Future<'a, Output = ()>)
20/// ```
21///
22/// However, the compiler does not allow using `impl Trait` in the return type of an `impl Fn`.
23///
24/// And if you try to do it like this:
25/// ```rust,ignore
26/// async fn takes_foo_callback<F, Fut>(f: F)
27/// where
28///     F: for<'a> Fn(&'a mut Foo) -> Fut,
29///     Fut: for<'a> Future<Output = ()> + 'a
30/// ```
31///
32/// There's no way to tell the compiler that those two `'a`s should be the same lifetime.
33///
34/// It's possible to make this work with a custom trait, but it's fiddly and requires naming
35///  the type of the closure parameter.
36///
37/// Having the closure return `BoxFuture` allows us to work around this, as all the type information
38/// fits into a single generic parameter.
39///
40/// We still need to `Box` the future internally to give it a concrete type to avoid leaking a type
41/// parameter everywhere, and `Box` is in the prelude so it doesn't need to be manually imported,
42/// so having the closure return `Pin<Box<dyn Future>` directly is the path of least resistance from
43/// the perspectives of both API designer and consumer.
44#[derive(Clone)]
45pub struct PoolOptions<DB: Database> {
46    pub(crate) test_before_acquire: bool,
47    pub(crate) after_connect: Option<
48        Arc<
49            dyn Fn(&mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'_, Result<(), Error>>
50                + 'static
51                + Send
52                + Sync,
53        >,
54    >,
55    pub(crate) before_acquire: Option<
56        Arc<
57            dyn Fn(
58                    &mut DB::Connection,
59                    PoolConnectionMetadata,
60                ) -> BoxFuture<'_, Result<bool, Error>>
61                + 'static
62                + Send
63                + Sync,
64        >,
65    >,
66    pub(crate) after_release: Option<
67        Arc<
68            dyn Fn(
69                    &mut DB::Connection,
70                    PoolConnectionMetadata,
71                ) -> BoxFuture<'_, Result<bool, Error>>
72                + 'static
73                + Send
74                + Sync,
75        >,
76    >,
77    pub(crate) max_connections: u32,
78    pub(crate) acquire_timeout: Duration,
79    pub(crate) min_connections: u32,
80    pub(crate) max_lifetime: Option<Duration>,
81    pub(crate) idle_timeout: Option<Duration>,
82    pub(crate) fair: bool,
83
84    pub(crate) parent_pool: Option<Pool<DB>>,
85}
86
87/// Metadata for the connection being processed by a [`PoolOptions`] callback.
88#[derive(Debug)] // Don't want to commit to any other trait impls yet.
89#[non_exhaustive] // So we can safely add fields in the future.
90pub struct PoolConnectionMetadata {
91    /// The duration since the connection was first opened.
92    ///
93    /// For [`after_connect`][PoolOptions::after_connect], this is [`Duration::ZERO`].
94    pub age: Duration,
95
96    /// The duration that the connection spent in the idle queue.
97    ///
98    /// Only relevant for [`before_acquire`][PoolOptions::before_acquire].
99    /// For other callbacks, this is [`Duration::ZERO`].
100    pub idle_for: Duration,
101}
102
103impl<DB: Database> Default for PoolOptions<DB> {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109impl<DB: Database> PoolOptions<DB> {
110    /// Returns a default "sane" configuration, suitable for testing or light-duty applications.
111    ///
112    /// Production applications will likely want to at least modify
113    /// [`max_connections`][Self::max_connections].
114    ///
115    /// See the source of this method for the current default values.
116    pub fn new() -> Self {
117        Self {
118            // User-specifiable routines
119            after_connect: None,
120            before_acquire: None,
121            after_release: None,
122            test_before_acquire: true,
123            // A production application will want to set a higher limit than this.
124            max_connections: 10,
125            min_connections: 0,
126            acquire_timeout: Duration::from_secs(30),
127            idle_timeout: Some(Duration::from_secs(10 * 60)),
128            max_lifetime: Some(Duration::from_secs(30 * 60)),
129            fair: true,
130            parent_pool: None,
131        }
132    }
133
134    /// Set the maximum number of connections that this pool should maintain.
135    ///
136    /// Be mindful of the connection limits for your database as well as other applications
137    /// which may want to connect to the same database (or even multiple instances of the same
138    /// application in high-availability deployments).
139    pub fn max_connections(mut self, max: u32) -> Self {
140        self.max_connections = max;
141        self
142    }
143
144    /// Set the minimum number of connections to maintain at all times.
145    ///
146    /// When the pool is built, this many connections will be automatically spun up.
147    ///
148    /// If any connection is reaped by [`max_lifetime`] or [`idle_timeout`], or explicitly closed,
149    /// and it brings the connection count below this amount, a new connection will be opened to
150    /// replace it.
151    ///
152    /// This is only done on a best-effort basis, however. The routine that maintains this value
153    /// has a deadline so it doesn't wait forever if the database is being slow or returning errors.
154    ///
155    /// This value is clamped internally to not exceed [`max_connections`].
156    ///
157    /// We've chosen not to assert `min_connections <= max_connections` anywhere
158    /// because it shouldn't break anything internally if the condition doesn't hold,
159    /// and if the application allows either value to be dynamically set
160    /// then it should be checking this condition itself and returning
161    /// a nicer error than a panic anyway.
162    ///
163    /// [`max_lifetime`]: Self::max_lifetime
164    /// [`idle_timeout`]: Self::idle_timeout
165    /// [`max_connections`]: Self::max_connections
166    pub fn min_connections(mut self, min: u32) -> Self {
167        self.min_connections = min;
168        self
169    }
170
171    /// Set the maximum amount of time to spend waiting for a connection in [`Pool::acquire()`].
172    ///
173    /// Caps the total amount of time `Pool::acquire()` can spend waiting across multiple phases:
174    ///
175    /// * First, it may need to wait for a permit from the semaphore, which grants it the privilege
176    ///   of opening a connection or popping one from the idle queue.
177    /// * If an existing idle connection is acquired, by default it will be checked for liveness
178    ///   and integrity before being returned, which may require executing a command on the
179    ///   connection. This can be disabled with [`test_before_acquire(false)`][Self::test_before_acquire].
180    ///     * If [`before_acquire`][Self::before_acquire] is set, that will also be executed.
181    /// * If a new connection needs to be opened, that will obviously require I/O, handshaking,
182    ///   and initialization commands.
183    ///     * If [`after_connect`][Self::after_connect] is set, that will also be executed.
184    pub fn acquire_timeout(mut self, timeout: Duration) -> Self {
185        self.acquire_timeout = timeout;
186        self
187    }
188
189    /// Set the maximum lifetime of individual connections.
190    ///
191    /// Any connection with a lifetime greater than this will be closed.
192    ///
193    /// When set to `None`, all connections live until either reaped by [`idle_timeout`]
194    /// or explicitly disconnected.
195    ///
196    /// Infinite connections are not recommended due to the unfortunate reality of memory/resource
197    /// leaks on the database-side. It is better to retire connections periodically
198    /// (even if only once daily) to allow the database the opportunity to clean up data structures
199    /// (parse trees, query metadata caches, thread-local storage, etc.) that are associated with a
200    /// session.
201    ///
202    /// [`idle_timeout`]: Self::idle_timeout
203    pub fn max_lifetime(mut self, lifetime: impl Into<Option<Duration>>) -> Self {
204        self.max_lifetime = lifetime.into();
205        self
206    }
207
208    /// Set a maximum idle duration for individual connections.
209    ///
210    /// Any connection that remains in the idle queue longer than this will be closed.
211    ///
212    /// For usage-based database server billing, this can be a cost saver.
213    pub fn idle_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
214        self.idle_timeout = timeout.into();
215        self
216    }
217
218    /// If true, the health of a connection will be verified by a call to [`Connection::ping`]
219    /// before returning the connection.
220    ///
221    /// Defaults to `true`.
222    pub fn test_before_acquire(mut self, test: bool) -> Self {
223        self.test_before_acquire = test;
224        self
225    }
226
227    /// If set to `true`, calls to `acquire()` are fair and connections  are issued
228    /// in first-come-first-serve order. If `false`, "drive-by" tasks may steal idle connections
229    /// ahead of tasks that have been waiting.
230    ///
231    /// According to `sqlx-bench/benches/pg_pool` this may slightly increase time
232    /// to `acquire()` at low pool contention but at very high contention it helps
233    /// avoid tasks at the head of the waiter queue getting repeatedly preempted by
234    /// these "drive-by" tasks and tasks further back in the queue timing out because
235    /// the queue isn't moving.
236    ///
237    /// Currently only exposed for benchmarking; `fair = true` seems to be the superior option
238    /// in most cases.
239    #[doc(hidden)]
240    pub fn __fair(mut self, fair: bool) -> Self {
241        self.fair = fair;
242        self
243    }
244
245    /// Perform an asynchronous action after connecting to the database.
246    ///
247    /// If the operation returns with an error then the error is logged, the connection is closed
248    /// and a new one is opened in its place and the callback is invoked again.
249    ///
250    /// This occurs in a backoff loop to avoid high CPU usage and spamming logs during a transient
251    /// error condition.
252    ///
253    /// Note that this may be called for internally opened connections, such as when maintaining
254    /// [`min_connections`][Self::min_connections], that are then immediately returned to the pool
255    /// without invoking [`after_release`][Self::after_release].
256    ///
257    /// # Example: Additional Parameters
258    /// This callback may be used to set additional configuration parameters
259    /// that are not exposed by the database's `ConnectOptions`.
260    ///
261    /// This example is written for PostgreSQL but can likely be adapted to other databases.
262    ///
263    /// ```no_run
264    /// # async fn f() -> Result<(), Box<dyn std::error::Error>> {
265    /// use sqlx::Executor;
266    /// use sqlx::postgres::PgPoolOptions;
267    ///
268    /// let pool = PgPoolOptions::new()
269    ///     .after_connect(|conn, _meta| Box::pin(async move {
270    ///         // When directly invoking `Executor` methods,
271    ///         // it is possible to execute multiple statements with one call.
272    ///         conn.execute("SET application_name = 'your_app'; SET search_path = 'my_schema';")
273    ///             .await?;
274    ///
275    ///         Ok(())
276    ///     }))
277    ///     .connect("postgres:// …").await?;
278    /// # Ok(())
279    /// # }
280    /// ```
281    ///
282    /// For a discussion on why `Box::pin()` is required, see [the type-level docs][Self].
283    pub fn after_connect<F>(mut self, callback: F) -> Self
284    where
285        // We're passing the `PoolConnectionMetadata` here mostly for future-proofing.
286        // `age` and `idle_for` are obviously not useful for fresh connections.
287        for<'c> F: Fn(&'c mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'c, Result<(), Error>>
288            + 'static
289            + Send
290            + Sync,
291    {
292        self.after_connect = Some(Arc::new(callback));
293        self
294    }
295
296    /// Perform an asynchronous action on a previously idle connection before giving it out.
297    ///
298    /// Alongside the connection, the closure gets [`PoolConnectionMetadata`] which contains
299    /// potentially useful information such as the connection's age and the duration it was
300    /// idle.
301    ///
302    /// If the operation returns `Ok(true)`, the connection is returned to the task that called
303    /// [`Pool::acquire`].
304    ///
305    /// If the operation returns `Ok(false)` or an error, the error is logged (if applicable)
306    /// and then the connection is closed and [`Pool::acquire`] tries again with another idle
307    /// connection. If it runs out of idle connections, it opens a new connection instead.
308    ///
309    /// This is *not* invoked for new connections. Use [`after_connect`][Self::after_connect]
310    /// for those.
311    ///
312    /// # Example: Custom `test_before_acquire` Logic
313    /// If you only want to ping connections if they've been idle a certain amount of time,
314    /// you can implement your own logic here:
315    ///
316    /// This example is written for Postgres but should be trivially adaptable to other databases.
317    /// ```no_run
318    /// # async fn f() -> Result<(), Box<dyn std::error::Error>> {
319    /// use sqlx::{Connection, Executor};
320    /// use sqlx::postgres::PgPoolOptions;
321    ///
322    /// let pool = PgPoolOptions::new()
323    ///     .test_before_acquire(false)
324    ///     .before_acquire(|conn, meta| Box::pin(async move {
325    ///         // One minute
326    ///         if meta.idle_for.as_secs() > 60 {
327    ///             conn.ping().await?;
328    ///         }
329    ///
330    ///         Ok(true)
331    ///     }))
332    ///     .connect("postgres:// …").await?;
333    /// # Ok(())
334    /// # }
335    ///```
336    ///
337    /// For a discussion on why `Box::pin()` is required, see [the type-level docs][Self].
338    pub fn before_acquire<F>(mut self, callback: F) -> Self
339    where
340        for<'c> F: Fn(&'c mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'c, Result<bool, Error>>
341            + 'static
342            + Send
343            + Sync,
344    {
345        self.before_acquire = Some(Arc::new(callback));
346        self
347    }
348
349    /// Perform an asynchronous action on a connection before it is returned to the pool.
350    ///
351    /// Alongside the connection, the closure gets [`PoolConnectionMetadata`] which contains
352    /// potentially useful information such as the connection's age.
353    ///
354    /// If the operation returns `Ok(true)`, the connection is returned to the pool's idle queue.
355    /// If the operation returns `Ok(false)` or an error, the error is logged (if applicable)
356    /// and the connection is closed, allowing a task waiting on [`Pool::acquire`] to
357    /// open a new one in its place.
358    ///
359    /// # Example (Postgres): Close Memory-Hungry Connections
360    /// Instead of relying on [`max_lifetime`][Self::max_lifetime] to close connections,
361    /// we can monitor their memory usage directly and close any that have allocated too much.
362    ///
363    /// Note that this is purely an example showcasing a possible use for this callback
364    /// and may be flawed as it has not been tested.
365    ///
366    /// This example queries [`pg_backend_memory_contexts`](https://www.postgresql.org/docs/current/view-pg-backend-memory-contexts.html)
367    /// which is only allowed for superusers.
368    ///
369    /// ```no_run
370    /// # async fn f() -> Result<(), Box<dyn std::error::Error>> {
371    /// use sqlx::{Connection, Executor};
372    /// use sqlx::postgres::PgPoolOptions;
373    ///
374    /// let pool = PgPoolOptions::new()
375    ///     // Let connections live as long as they want.
376    ///     .max_lifetime(None)
377    ///     .after_release(|conn, meta| Box::pin(async move {
378    ///         // Only check connections older than 6 hours.
379    ///         if meta.age.as_secs() < 6 * 60 * 60 {
380    ///             return Ok(true);
381    ///         }
382    ///
383    ///         let total_memory_usage: i64 = sqlx::query_scalar(
384    ///             "select sum(used_bytes) from pg_backend_memory_contexts"
385    ///         )
386    ///         .fetch_one(conn)
387    ///         .await?;
388    ///
389    ///         // Close the connection if the backend memory usage exceeds 256 MiB.
390    ///         Ok(total_memory_usage <= (2 << 28))
391    ///     }))
392    ///     .connect("postgres:// …").await?;
393    /// # Ok(())
394    /// # }
395    pub fn after_release<F>(mut self, callback: F) -> Self
396    where
397        for<'c> F: Fn(&'c mut DB::Connection, PoolConnectionMetadata) -> BoxFuture<'c, Result<bool, Error>>
398            + 'static
399            + Send
400            + Sync,
401    {
402        self.after_release = Some(Arc::new(callback));
403        self
404    }
405
406    /// Set the parent `Pool` from which the new pool will inherit its semaphore.
407    ///
408    /// This is currently an internal-only API.
409    ///
410    /// ### Panics
411    /// If `self.max_connections` is greater than the setting the given pool was created with,
412    /// or `self.fair` differs from the setting the given pool was created with.
413    #[doc(hidden)]
414    pub fn parent(mut self, pool: Pool<DB>) -> Self {
415        self.parent_pool = Some(pool);
416        self
417    }
418
419    /// Create a new pool from this `PoolOptions` and immediately open at least one connection.
420    ///
421    /// This ensures the configuration is correct.
422    ///
423    /// The total number of connections opened is <code>min(1, [min_connections][Self::min_connections])</code>.
424    ///
425    /// Refer to the relevant `ConnectOptions` impl for your database for the expected URL format:
426    ///
427    /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions]
428    /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions]
429    /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions]
430    /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions]
431    pub async fn connect(self, url: &str) -> Result<Pool<DB>, Error> {
432        self.connect_with(url.parse()?).await
433    }
434
435    /// Create a new pool from this `PoolOptions` and immediately open at least one connection.
436    ///
437    /// This ensures the configuration is correct.
438    ///
439    /// The total number of connections opened is <code>min(1, [min_connections][Self::min_connections])</code>.
440    pub async fn connect_with(
441        self,
442        options: <DB::Connection as Connection>::Options,
443    ) -> Result<Pool<DB>, Error> {
444        // Don't take longer than `acquire_timeout` starting from when this is called.
445        let deadline = Instant::now() + self.acquire_timeout;
446
447        let inner = PoolInner::new_arc(self, options);
448
449        if inner.options.min_connections > 0 {
450            // If the idle reaper is spawned then this will race with the call from that task
451            // and may not report any connection errors.
452            inner.try_min_connections(deadline).await?;
453        }
454
455        // If `min_connections` is nonzero then we'll likely just pull a connection
456        // from the idle queue here, but it should at least get tested first.
457        let conn = inner.acquire().await?;
458        inner.release(conn);
459
460        Ok(Pool(inner))
461    }
462
463    /// Create a new pool from this `PoolOptions`, but don't open any connections right now.
464    ///
465    /// If [`min_connections`][Self::min_connections] is set, a background task will be spawned to
466    /// optimistically establish that many connections for the pool.
467    ///
468    /// Refer to the relevant `ConnectOptions` impl for your database for the expected URL format:
469    ///
470    /// * Postgres: [`PgConnectOptions`][crate::postgres::PgConnectOptions]
471    /// * MySQL: [`MySqlConnectOptions`][crate::mysql::MySqlConnectOptions]
472    /// * SQLite: [`SqliteConnectOptions`][crate::sqlite::SqliteConnectOptions]
473    /// * MSSQL: [`MssqlConnectOptions`][crate::mssql::MssqlConnectOptions]
474    pub fn connect_lazy(self, url: &str) -> Result<Pool<DB>, Error> {
475        Ok(self.connect_lazy_with(url.parse()?))
476    }
477
478    /// Create a new pool from this `PoolOptions`, but don't open any connections right now.
479    ///
480    /// If [`min_connections`][Self::min_connections] is set, a background task will be spawned to
481    /// optimistically establish that many connections for the pool.
482    pub fn connect_lazy_with(self, options: <DB::Connection as Connection>::Options) -> Pool<DB> {
483        // `min_connections` is guaranteed by the idle reaper now.
484        Pool(PoolInner::new_arc(self, options))
485    }
486}
487
488impl<DB: Database> Debug for PoolOptions<DB> {
489    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
490        f.debug_struct("PoolOptions")
491            .field("max_connections", &self.max_connections)
492            .field("min_connections", &self.min_connections)
493            .field("connect_timeout", &self.acquire_timeout)
494            .field("max_lifetime", &self.max_lifetime)
495            .field("idle_timeout", &self.idle_timeout)
496            .field("test_before_acquire", &self.test_before_acquire)
497            .finish()
498    }
499}