Skip to main content

axa_postgres_sqlx/
lib.rs

1//! `PostgreSQL` pooling, migrations, and test resets over sqlx.
2//!
3//! This crate holds the operations every service repeats. It does not wrap
4//! queries: a service writes its own SQL with `sqlx::query!`, so a reviewer
5//! reads exactly what runs.
6//!
7//! It has the same shape as `axa-postgres-seaorm`, `axa-postgres-diesel`, and `axa-postgres-toasty`: a [`Pool`],
8//! a [`PoolConfig`], [`connect`], [`ping`], [`migrate`], [`revert`], [`pending`],
9//! [`truncate`], [`dangerously_recreate`], [`is_unique_violation`], and
10//! [`quote_identifier`], with [`status`] besides.
11//!
12//! ```no_run
13//! use axa_postgres_sqlx::{PoolConfig, connect, migrate, sqlx};
14//!
15//! static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate::Migrator::DEFAULT;
16//!
17//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
18//! let pool = connect(&PoolConfig::new("postgres://localhost/app")).await?;
19//! migrate(&pool, &MIGRATOR).await?;
20//! # Ok(())
21//! # }
22//! ```
23
24use std::{
25    ops::{Deref, DerefMut},
26    sync::{
27        OnceLock,
28        atomic::{AtomicU64, Ordering},
29    },
30    time::{Duration, Instant},
31};
32
33pub use sqlx;
34use sqlx::{
35    AssertSqlSafe, PgConnection, PgPool, Postgres, Row,
36    migrate::{MigrateError, Migrator},
37    pool::PoolConnection,
38    postgres::PgPoolOptions,
39};
40
41/// The handle a service holds: the pool.
42pub type Pool = PgPool;
43
44/// What this crate's connection and query functions return on failure.
45pub type Error = sqlx::Error;
46
47/// Pool settings.
48#[derive(Clone, PartialEq, Eq)]
49pub struct PoolConfig {
50    /// Connection string.
51    pub uri: String,
52    /// Connections kept open.
53    pub min_connections: u32,
54    /// Largest number of connections.
55    pub max_connections: u32,
56    /// How long to wait for a connection, in milliseconds.
57    pub connect_timeout_ms: u64,
58    /// How long an idle connection stays open, in milliseconds.
59    pub idle_timeout_ms: u64,
60    /// Postgres's `statement_timeout` on every connection, in milliseconds. `0` sets
61    /// none.
62    pub statement_timeout_ms: u64,
63    /// Postgres's `application_name` on every connection, so `pg_stat_activity` says
64    /// which service a query came from. Empty sets none.
65    pub application_name: String,
66    /// Open every transaction read-only, as for a read replica or a reporting
67    /// service, so that a write is refused by the database.
68    pub read_only: bool,
69}
70
71impl std::fmt::Debug for PoolConfig {
72    /// Leaves the connection string out, because it can carry a password.
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_struct("PoolConfig")
75            .field("min_connections", &self.min_connections)
76            .field("max_connections", &self.max_connections)
77            .field("connect_timeout_ms", &self.connect_timeout_ms)
78            .field("idle_timeout_ms", &self.idle_timeout_ms)
79            .field("statement_timeout_ms", &self.statement_timeout_ms)
80            .field("application_name", &self.application_name)
81            .field("read_only", &self.read_only)
82            .finish_non_exhaustive()
83    }
84}
85
86impl PoolConfig {
87    /// Settings for `uri` with a small pool.
88    #[must_use]
89    pub fn new(uri: impl Into<String>) -> Self {
90        Self {
91            uri: uri.into(),
92            min_connections: 1,
93            max_connections: 10,
94            connect_timeout_ms: 5_000,
95            idle_timeout_ms: 600_000,
96            statement_timeout_ms: 0,
97            application_name: String::new(),
98            read_only: false,
99        }
100    }
101
102    /// The sqlx options these settings describe.
103    #[must_use]
104    pub fn options(&self) -> PgPoolOptions {
105        PgPoolOptions::new()
106            .min_connections(self.min_connections)
107            .max_connections(self.max_connections)
108            .acquire_timeout(Duration::from_millis(self.connect_timeout_ms))
109            .idle_timeout(Duration::from_millis(self.idle_timeout_ms))
110            // Retire a connection whose cached statements a migration has made stale.
111            .before_acquire(|_connection, meta| {
112                Box::pin(async move { Ok(!opened_before_last_stale_plan(meta.age)) })
113            })
114    }
115}
116
117/// When this process first needed a clock for stale plans.
118static EPOCH: OnceLock<Instant> = OnceLock::new();
119
120/// Nanoseconds after [`EPOCH`] that a stale plan was last seen, plus one, or `0` for
121/// never.
122static LAST_STALE_PLAN: AtomicU64 = AtomicU64::new(0);
123
124fn epoch() -> Instant {
125    *EPOCH.get_or_init(Instant::now)
126}
127
128/// Whether `error` is Postgres refusing a statement this connection prepared before a
129/// migration changed what it returns: SQLSTATE `0A000` with "cached plan must not
130/// change result type". Each pooled connection that cached the statement fails so
131/// once, and a fresh connection does not.
132#[must_use]
133pub fn is_stale_plan(error: &sqlx::Error) -> bool {
134    error.as_database_error().is_some_and(|error| {
135        error.code().as_deref() == Some("0A000")
136            && error
137                .message()
138                .contains("cached plan must not change result type")
139    })
140}
141
142/// Record `error` if it is a stale plan, so that every connection opened before now is
143/// retired when next acquired, from every pool [`connect`] opened in this process, and
144/// the next attempt runs on a fresh one. Returns whether it was. `axa::Error` calls
145/// this for every sqlx error it answers, so a service that turns sqlx errors into it
146/// needs nothing more.
147pub fn note_stale_plan(error: &sqlx::Error) -> bool {
148    if !is_stale_plan(error) {
149        return false;
150    }
151    let since = u64::try_from(epoch().elapsed().as_nanos()).unwrap_or(u64::MAX - 1);
152    LAST_STALE_PLAN.fetch_max(since.saturating_add(1), Ordering::SeqCst);
153    true
154}
155
156/// Whether a connection `age` old was opened at or before the last stale plan.
157fn opened_before_last_stale_plan(age: Duration) -> bool {
158    opened_before(
159        LAST_STALE_PLAN.load(Ordering::SeqCst),
160        epoch().elapsed(),
161        age,
162    )
163}
164
165/// Whether a connection `age` old at `now`, both since [`EPOCH`], was opened at or
166/// before `last`, as [`LAST_STALE_PLAN`] holds it.
167fn opened_before(last: u64, now: Duration, age: Duration) -> bool {
168    if last == 0 {
169        return false;
170    }
171    now.saturating_sub(age) <= Duration::from_nanos(last - 1)
172}
173
174impl PoolConfig {
175    /// The connection string with the session settings added, as every connection
176    /// [`connect`] opens uses.
177    ///
178    /// # Errors
179    ///
180    /// [`sqlx::Error::Configuration`] when the URL sets `options` already and a
181    /// statement timeout or read-only mode is set here too, or when the application
182    /// name is not one Postgres keeps as it is.
183    pub fn connection_uri(&self) -> Result<String, sqlx::Error> {
184        session_uri(
185            &self.uri,
186            self.statement_timeout_ms,
187            &self.application_name,
188            self.read_only,
189        )
190        .map_err(|problem| sqlx::Error::Configuration(problem.into()))
191    }
192}
193
194/// `uri` with each session setting added as a libpq connection parameter, so that
195/// every connection the pool opens starts with them, at no extra round trip:
196/// `statement_timeout` and `default_transaction_read_only` in `options`, and
197/// `application_name`.
198///
199/// An `application_name` the URL already names is kept. `options` the URL already
200/// names, with a setting here to add, is refused, rather than either one silently
201/// replacing the other.
202fn session_uri(
203    uri: &str,
204    statement_timeout_ms: u64,
205    application_name: &str,
206    read_only: bool,
207) -> Result<String, String> {
208    let mut options = Vec::new();
209    if statement_timeout_ms > 0 {
210        options.push(format!("-c statement_timeout={statement_timeout_ms}"));
211    }
212    if read_only {
213        options.push("-c default_transaction_read_only=on".to_string());
214    }
215    let mut params = Vec::new();
216    if !options.is_empty() {
217        if has_param(uri, "options") {
218            return Err(
219                "the connection URL sets options already: set the statement timeout and \
220                 read-only mode there, or here, not both"
221                    .to_string(),
222            );
223        }
224        params.push(("options", options.join(" ")));
225    }
226    if !application_name.is_empty() && !has_param(uri, "application_name") {
227        if !is_application_name(application_name) {
228            return Err(
229                "an application name is ASCII letters, digits, `_`, `.`, and `-`, at most 63"
230                    .to_string(),
231            );
232        }
233        params.push(("application_name", application_name.to_string()));
234    }
235    if params.is_empty() {
236        return Ok(uri.to_string());
237    }
238    let separator = if uri.contains('?') { '&' } else { '?' };
239    let query: Vec<String> = params
240        .iter()
241        .map(|(name, value)| format!("{name}={}", percent_encode(value)))
242        .collect();
243    Ok(format!("{uri}{separator}{}", query.join("&")))
244}
245
246/// Whether the query of `uri` names `name`.
247fn has_param(uri: &str, name: &str) -> bool {
248    uri.split_once('?').is_some_and(|(_, query)| {
249        query
250            .split('&')
251            .any(|pair| pair.split('=').next() == Some(name))
252    })
253}
254
255/// Whether `name` is an application name Postgres keeps as it is: ASCII letters,
256/// digits, `_`, `.`, and `-`, from 1 to 63 bytes.
257fn is_application_name(name: &str) -> bool {
258    (1..=63).contains(&name.len())
259        && name
260            .bytes()
261            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
262}
263
264/// `value` with every byte but the unreserved ones percent-encoded.
265fn percent_encode(value: &str) -> String {
266    use std::fmt::Write as _;
267    let mut encoded = String::new();
268    for byte in value.bytes() {
269        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
270            encoded.push(char::from(byte));
271        } else {
272            let _ = write!(encoded, "%{byte:02X}");
273        }
274    }
275    encoded
276}
277
278/// Open a pool and prove it works with one connection, with the session settings on
279/// every connection.
280///
281/// # Errors
282///
283/// Fails when the settings are refused, as [`PoolConfig::connection_uri`] says, or the
284/// database cannot be reached.
285pub async fn connect(config: &PoolConfig) -> Result<PgPool, sqlx::Error> {
286    config.options().connect(&config.connection_uri()?).await
287}
288
289/// Check that the database answers.
290///
291/// # Errors
292///
293/// Fails when it does not.
294pub async fn ping(pool: &PgPool) -> Result<(), sqlx::Error> {
295    sqlx::query("SELECT 1").execute(pool).await?;
296    Ok(())
297}
298
299/// Where a function gets its connection: the pool, or a connection the caller
300/// holds, usually an open transaction, so one function serves both.
301///
302/// `impl sqlx::Acquire` says the same, but its associated types stop the future
303/// being `Send`, which Axum handlers and `tokio::spawn` need.
304///
305/// ```no_run
306/// use axa_postgres_sqlx::{Db, sqlx};
307///
308/// async fn count(db: impl Into<Db<'_>>) -> Result<i64, sqlx::Error> {
309///     let mut conn = db.into().acquire().await?;
310///     sqlx::query_scalar("SELECT count(*) FROM items")
311///         .fetch_one(&mut *conn)
312///         .await
313/// }
314/// ```
315pub enum Db<'a> {
316    /// Take a connection from the pool for the length of the call.
317    Pool(&'a PgPool),
318    /// Use the caller's connection.
319    Conn(&'a mut PgConnection),
320}
321
322impl<'a> From<&'a PgPool> for Db<'a> {
323    fn from(pool: &'a PgPool) -> Self {
324        Self::Pool(pool)
325    }
326}
327
328impl<'a> From<&'a mut PgConnection> for Db<'a> {
329    fn from(conn: &'a mut PgConnection) -> Self {
330        Self::Conn(conn)
331    }
332}
333
334impl<'a> Db<'a> {
335    /// The connection to use.
336    ///
337    /// # Errors
338    ///
339    /// Fails when the pool has none to give.
340    pub async fn acquire(self) -> Result<Conn<'a>, sqlx::Error> {
341        match self {
342            Self::Pool(pool) => Ok(Conn::Pooled(pool.acquire().await?)),
343            Self::Conn(conn) => Ok(Conn::Borrowed(conn)),
344        }
345    }
346}
347
348/// A connection for the length of one call. It derefs to [`PgConnection`].
349pub enum Conn<'a> {
350    /// Taken from the pool, and given back when dropped.
351    Pooled(PoolConnection<Postgres>),
352    /// The caller's.
353    Borrowed(&'a mut PgConnection),
354}
355
356impl Deref for Conn<'_> {
357    type Target = PgConnection;
358
359    fn deref(&self) -> &PgConnection {
360        match self {
361            Self::Pooled(conn) => conn,
362            Self::Borrowed(conn) => conn,
363        }
364    }
365}
366
367impl DerefMut for Conn<'_> {
368    fn deref_mut(&mut self) -> &mut PgConnection {
369        match self {
370            Self::Pooled(conn) => conn,
371            Self::Borrowed(conn) => conn,
372        }
373    }
374}
375
376/// Whether an error is a violated unique constraint, which a service usually
377/// reports as `409` rather than `500`.
378#[must_use]
379pub fn is_unique_violation(error: &sqlx::Error) -> bool {
380    error
381        .as_database_error()
382        .is_some_and(sqlx::error::DatabaseError::is_unique_violation)
383}
384
385/// Quote a table or type name for use in SQL.
386///
387/// Identifiers cannot be bound as parameters, so this is the one place names
388/// reach SQL as text. Only lowercase ASCII letters, digits, and underscores
389/// are accepted, starting with a letter or underscore. That is stricter than
390/// Postgres, and it leaves nothing for an attacker to work with.
391///
392/// ```
393/// assert_eq!(axa_postgres_sqlx::quote_identifier("users").as_deref(), Some("\"users\""));
394/// assert_eq!(axa_postgres_sqlx::quote_identifier("users; DROP TABLE x"), None);
395/// ```
396#[must_use]
397pub fn quote_identifier(name: &str) -> Option<String> {
398    let mut chars = name.chars();
399    let first = chars.next()?;
400    let valid = (first.is_ascii_lowercase() || first == '_')
401        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
402    valid.then(|| format!("\"{name}\""))
403}
404
405/// Quote every name, failing on the first one [`quote_identifier`] refuses.
406fn quote_all<S: AsRef<str>>(names: &[S]) -> Result<Vec<String>, sqlx::Error> {
407    names
408        .iter()
409        .map(|name| {
410            quote_identifier(name.as_ref()).ok_or_else(|| {
411                sqlx::Error::Protocol(format!("invalid identifier: {}", name.as_ref()))
412            })
413        })
414        .collect()
415}
416
417/// Whether `name` is a custom setting a service may set for row-level security: two or
418/// more parts of lower-case ASCII letters, digits, and underscores, joined by dots, such
419/// as `app.tenant`. A name with no dot is Postgres's own, such as `role` or
420/// `search_path`, which this never sets.
421///
422/// ```
423/// assert!(axa_postgres_sqlx::is_custom_setting("app.tenant"));
424/// assert!(!axa_postgres_sqlx::is_custom_setting("search_path"));
425/// ```
426#[must_use]
427pub fn is_custom_setting(name: &str) -> bool {
428    let parts: Vec<&str> = name.split('.').collect();
429    name.len() <= 63
430        && parts.len() >= 2
431        && parts.iter().all(|part| {
432            part.chars()
433                .next()
434                .is_some_and(|first| first.is_ascii_lowercase() || first == '_')
435                && part
436                    .chars()
437                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
438        })
439}
440
441/// Open a transaction with each `(name, value)` set for its length only, such as
442/// `("app.tenant", tenant.as_str())` for a row-level security policy that reads
443/// `current_setting('app.tenant', true)`.
444///
445/// Each pair is set with `set_config($1, $2, true)`: bound, never formatted into the
446/// SQL, and gone when the transaction commits or rolls back, so a pooled connection
447/// never carries one request's tenant into the next. Run every query that needs the
448/// setting on the transaction this returns, as a query on the pool may run on another
449/// connection.
450///
451/// ```no_run
452/// # async fn example(pool: &sqlx::PgPool) -> Result<(), sqlx::Error> {
453/// let mut tx = axa_postgres_sqlx::begin_with(pool, &[("app.tenant", "acme")]).await?;
454/// let count: i64 = sqlx::query_scalar("SELECT count(*) FROM todos")
455///     .fetch_one(&mut *tx)
456///     .await?;
457/// tx.commit().await?;
458/// # Ok(())
459/// # }
460/// ```
461///
462/// A policy sees nothing unless the role the service connects as is subject to it: not
463/// a superuser, without `BYPASSRLS`, and, if it owns the table, with
464/// `FORCE ROW LEVEL SECURITY` on it.
465///
466/// # Errors
467///
468/// [`sqlx::Error::InvalidArgument`] for a name [`is_custom_setting`] refuses, before
469/// anything is sent, and any error from beginning the transaction or setting a value.
470pub async fn begin_with(
471    pool: &PgPool,
472    settings: &[(&str, &str)],
473) -> Result<sqlx::Transaction<'static, Postgres>, sqlx::Error> {
474    if let Some((name, _)) = settings.iter().find(|(name, _)| !is_custom_setting(name)) {
475        return Err(sqlx::Error::InvalidArgument(format!(
476            "not a custom setting: {name}"
477        )));
478    }
479    let mut tx = pool.begin().await?;
480    for (name, value) in settings {
481        sqlx::query("SELECT set_config($1, $2, true)")
482            .bind(name)
483            .bind(value)
484            .execute(&mut *tx)
485            .await?;
486    }
487    Ok(tx)
488}
489
490/// Whether row-level security can keep rows apart for the role a pool connects as.
491#[derive(Debug, Clone, PartialEq, Eq)]
492pub struct RowSecurity {
493    /// The role the pool connects as.
494    pub role: String,
495    /// Whether that role skips every policy: a superuser, or a role with `BYPASSRLS`.
496    pub bypasses: bool,
497    /// The tables asked about that do not exist, have no row-level security, or lack
498    /// `FORCE ROW LEVEL SECURITY`, so that their owner skips the policies.
499    pub unprotected: Vec<String>,
500}
501
502impl RowSecurity {
503    /// Whether the policies on every table asked about apply to the role.
504    #[must_use]
505    pub fn holds(&self) -> bool {
506        !self.bypasses && self.unprotected.is_empty()
507    }
508}
509
510/// Ask Postgres whether row-level security can apply to `pool`'s role, and whether
511/// each of `tables`, such as `todos` or `app.todos`, has it enabled and forced.
512///
513/// A policy does nothing for a superuser or a role with `BYPASSRLS`, and nothing for a
514/// table's owner unless the table has `FORCE ROW LEVEL SECURITY`. Each failure is
515/// silent: every query still answers, with every tenant's rows. Call this at boot, after
516/// migrating, and refuse to serve when it does not hold.
517///
518/// # Errors
519///
520/// Any error from the queries.
521pub async fn row_security<S: AsRef<str>>(
522    pool: &PgPool,
523    tables: &[S],
524) -> Result<RowSecurity, sqlx::Error> {
525    let role = sqlx::query(
526        "SELECT current_user::text AS role, rolsuper OR rolbypassrls AS bypasses
527         FROM pg_roles WHERE rolname = current_user",
528    )
529    .fetch_one(pool)
530    .await?;
531    let mut unprotected = Vec::new();
532    for table in tables {
533        let table = table.as_ref();
534        // Bound, and looked up with to_regclass, which takes the name as text.
535        let forced: Option<bool> = sqlx::query_scalar(
536            "SELECT relrowsecurity AND relforcerowsecurity FROM pg_class
537             WHERE oid = to_regclass($1)",
538        )
539        .bind(table)
540        .fetch_optional(pool)
541        .await?;
542        if forced != Some(true) {
543            unprotected.push(table.to_string());
544        }
545    }
546    Ok(RowSecurity {
547        role: role.get("role"),
548        bypasses: role.get("bypasses"),
549        unprotected,
550    })
551}
552
553/// Apply pending migrations. Sqlx holds a lock while it does, so services
554/// booting together take turns.
555///
556/// # Errors
557///
558/// Fails when a migration fails, or an applied one no longer matches.
559pub async fn migrate(pool: &PgPool, migrator: &Migrator) -> Result<(), MigrateError> {
560    migrator.run(pool).await
561}
562
563/// The newest applied versions, newest first. Empty on a database that has
564/// never been migrated.
565async fn applied_versions(pool: &PgPool) -> Result<Vec<i64>, sqlx::Error> {
566    let exists: bool = sqlx::query("SELECT to_regclass('_sqlx_migrations') IS NOT NULL AS found")
567        .fetch_one(pool)
568        .await?
569        .try_get("found")?;
570    if !exists {
571        return Ok(Vec::new());
572    }
573    let rows =
574        sqlx::query("SELECT version FROM _sqlx_migrations WHERE success ORDER BY version DESC")
575            .fetch_all(pool)
576            .await?;
577    rows.iter().map(|row| row.try_get("version")).collect()
578}
579
580/// Revert the newest `steps` migrations. Each needs a `.down.sql` file.
581///
582/// # Errors
583///
584/// Fails on a database error or a failed down migration.
585pub async fn revert(pool: &PgPool, migrator: &Migrator, steps: u32) -> Result<(), MigrateError> {
586    let applied = applied_versions(pool).await?;
587    let steps = usize::try_from(steps).unwrap_or(usize::MAX);
588    // `undo` reverts everything newer than its target, so the target is the
589    // version just past the last one to revert, or 0 to revert them all.
590    let target = applied.get(steps).copied().unwrap_or(0);
591    migrator.undo(pool, target).await
592}
593
594/// One migration and whether it has run.
595#[derive(Debug, Clone, PartialEq, Eq)]
596pub struct MigrationStatus {
597    /// Its version.
598    pub version: i64,
599    /// Its description.
600    pub description: String,
601    /// Whether it has been applied.
602    pub applied: bool,
603}
604
605/// Every migration in `migrator`, oldest first, with whether it has run.
606///
607/// # Errors
608///
609/// Fails on a database error.
610pub async fn status(
611    pool: &PgPool,
612    migrator: &Migrator,
613) -> Result<Vec<MigrationStatus>, sqlx::Error> {
614    let applied = applied_versions(pool).await?;
615    Ok(migrator
616        .iter()
617        .filter(|migration| !migration.migration_type.is_down_migration())
618        .map(|migration| MigrationStatus {
619            version: migration.version,
620            description: migration.description.to_string(),
621            applied: applied.contains(&migration.version),
622        })
623        .collect())
624}
625
626/// The names of the migrations in `migrator` not yet applied, in order, each as
627/// `version_description`.
628///
629/// # Errors
630///
631/// Fails on a database error.
632pub async fn pending(pool: &PgPool, migrator: &Migrator) -> Result<Vec<String>, sqlx::Error> {
633    Ok(status(pool, migrator)
634        .await?
635        .into_iter()
636        .filter(|migration| !migration.applied)
637        .map(|migration| format!("{}_{}", migration.version, migration.description))
638        .collect())
639}
640
641/// A migration of statements that cannot run in a transaction, such as
642/// `CREATE INDEX CONCURRENTLY`, which sqlx's migrator runs each file in. Name each one
643/// once and never change it: its name is what marks it done.
644///
645/// A statement that fails partway can leave something behind, as a failed
646/// `CREATE INDEX CONCURRENTLY` leaves an invalid index, so begin with what clears it:
647///
648/// ```
649/// use axa_postgres_sqlx::Background;
650///
651/// const NOTES_BY_ITEM: Background = Background {
652///     name: "2026_11_notes_by_item",
653///     statements: &[
654///         "DROP INDEX CONCURRENTLY IF EXISTS notes_by_item",
655///         "CREATE INDEX CONCURRENTLY notes_by_item ON notes (item_id)",
656///     ],
657/// };
658/// ```
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660pub struct Background {
661    /// Its name, 1 to 200 characters with no control characters, recorded once it has
662    /// run.
663    pub name: &'static str,
664    /// Its statements, each run alone, outside any transaction, in order.
665    pub statements: &'static [&'static str],
666}
667
668/// The table background migrations are recorded in.
669pub const BACKGROUND_TABLE: &str = "axa_background_migrations";
670
671/// The advisory lock one process holds while it runs background migrations.
672pub const BACKGROUND_LOCK: i64 = 0x6178_615f_6267_6d00;
673
674const BACKGROUND_SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_background_migrations (
675    name TEXT PRIMARY KEY,
676    finished_at TIMESTAMPTZ NOT NULL DEFAULT now()
677)";
678
679fn check_background(migrations: &[Background]) -> Result<(), sqlx::Error> {
680    let mut names = std::collections::HashSet::new();
681    for migration in migrations {
682        let name = migration.name;
683        if name.is_empty() || name.chars().count() > 200 || name.chars().any(char::is_control) {
684            return Err(sqlx::Error::Configuration(
685                "a background migration's name must be 1 to 200 characters with no control characters".into(),
686            ));
687        }
688        if !names.insert(name) {
689            return Err(sqlx::Error::Configuration(
690                format!("the background migration {name} is named twice").into(),
691            ));
692        }
693    }
694    Ok(())
695}
696
697async fn background_done(
698    connection: &mut sqlx::PgConnection,
699) -> Result<std::collections::HashSet<String>, sqlx::Error> {
700    let exists: bool =
701        sqlx::query_scalar("SELECT to_regclass('axa_background_migrations') IS NOT NULL")
702            .fetch_one(&mut *connection)
703            .await?;
704    if !exists {
705        return Ok(std::collections::HashSet::new());
706    }
707    let names: Vec<String> = sqlx::query_scalar("SELECT name FROM axa_background_migrations")
708        .fetch_all(&mut *connection)
709        .await?;
710    Ok(names.into_iter().collect())
711}
712
713/// Run each of `migrations` not yet recorded, in order, outside any transaction,
714/// recording each once all its statements have run. One process at a time holds
715/// [`BACKGROUND_LOCK`], so replicas booting together do not run one twice: a process
716/// that cannot take it answers `None` at once, and the one that holds it answers the
717/// names it ran. A failure stops the run, leaves that migration unrecorded, so the next
718/// run tries it again, and releases the lock.
719///
720/// # Errors
721///
722/// Fails on a name that is empty, too long, or used twice, on a database error, or on
723/// a statement that fails.
724pub async fn run_background(
725    pool: &PgPool,
726    migrations: &[Background],
727) -> Result<Option<Vec<String>>, sqlx::Error> {
728    check_background(migrations)?;
729    let mut connection = pool.acquire().await?;
730    let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
731        .bind(BACKGROUND_LOCK)
732        .fetch_one(&mut *connection)
733        .await?;
734    if !locked {
735        return Ok(None);
736    }
737    let ran = run_background_locked(&mut connection, migrations).await;
738    let unlocked = sqlx::query("SELECT pg_advisory_unlock($1)")
739        .bind(BACKGROUND_LOCK)
740        .execute(&mut *connection)
741        .await;
742    if unlocked.is_err() {
743        // The lock goes with the connection, so do not hand it back to the pool.
744        connection.detach();
745    }
746    ran.map(Some)
747}
748
749async fn run_background_locked(
750    connection: &mut sqlx::PgConnection,
751    migrations: &[Background],
752) -> Result<Vec<String>, sqlx::Error> {
753    sqlx::query(BACKGROUND_SETUP)
754        .execute(&mut *connection)
755        .await?;
756    let done = background_done(connection).await?;
757    let mut ran = Vec::new();
758    for migration in migrations.iter().filter(|m| !done.contains(m.name)) {
759        for statement in migration.statements {
760            // `&'static`, so written in the code and never built from input.
761            sqlx::raw_sql(*statement).execute(&mut *connection).await?;
762        }
763        sqlx::query("INSERT INTO axa_background_migrations (name) VALUES ($1)")
764            .bind(migration.name)
765            .execute(&mut *connection)
766            .await?;
767        ran.push(migration.name.to_string());
768    }
769    Ok(ran)
770}
771
772/// The names of `migrations` not yet recorded, in order, for
773/// `Checks::migrations`.
774///
775/// # Errors
776///
777/// Fails on a database error.
778pub async fn pending_background(
779    pool: &PgPool,
780    migrations: &[Background],
781) -> Result<Vec<String>, sqlx::Error> {
782    let mut connection = pool.acquire().await?;
783    let done = background_done(&mut connection).await?;
784    Ok(migrations
785        .iter()
786        .filter(|migration| !done.contains(migration.name))
787        .map(|migration| migration.name.to_string())
788        .collect())
789}
790
791/// Empty `tables`, restarting their sequences. Each name goes through
792/// [`quote_identifier`].
793///
794/// # Errors
795///
796/// Fails on an invalid name or a database error.
797pub async fn truncate<S: AsRef<str>>(pool: &PgPool, tables: &[S]) -> Result<(), sqlx::Error> {
798    if tables.is_empty() {
799        return Ok(());
800    }
801    let tables = quote_all(tables)?.join(", ");
802    let sql = format!("TRUNCATE {tables} RESTART IDENTITY CASCADE");
803    sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
804    Ok(())
805}
806
807/// Drop every table and enum type in `public`, then migrate from nothing.
808/// This gives each test an empty schema, whatever tables it touched.
809///
810/// **This destroys all data.** It exists for tests, and a service must never
811/// reach it outside the `test` environment.
812///
813/// It drops tables and types by name rather than dropping the schema, because
814/// `DROP SCHEMA public CASCADE` would also remove the extensions a database
815/// was prepared with, such as `citext`. Functions are left in place, so a
816/// migration that creates one should use `CREATE OR REPLACE`.
817///
818/// # Errors
819///
820/// Fails on a database error, or a name [`quote_identifier`] refuses.
821pub async fn dangerously_recreate(pool: &PgPool, migrator: &Migrator) -> Result<(), MigrateError> {
822    let tables: Vec<String> =
823        sqlx::query("SELECT tablename::text AS name FROM pg_tables WHERE schemaname = 'public'")
824            .fetch_all(pool)
825            .await?
826            .iter()
827            .map(|row| row.try_get("name"))
828            .collect::<Result<_, _>>()?;
829    // Types owned by an extension (`deptype = 'e'`) belong to that extension.
830    let types: Vec<String> = sqlx::query(
831        "SELECT t.typname::text AS name FROM pg_type t
832         JOIN pg_namespace n ON n.oid = t.typnamespace
833         WHERE t.typtype = 'e' AND n.nspname = 'public'
834           AND NOT EXISTS (
835               SELECT 1 FROM pg_depend d WHERE d.objid = t.oid AND d.deptype = 'e'
836           )",
837    )
838    .fetch_all(pool)
839    .await?
840    .iter()
841    .map(|row| row.try_get("name"))
842    .collect::<Result<_, _>>()?;
843
844    if !tables.is_empty() {
845        let names = quote_all(&tables)?.join(", ");
846        let sql = format!("DROP TABLE {names} CASCADE");
847        sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
848    }
849    for name in quote_all(&types)? {
850        let sql = format!("DROP TYPE {name} CASCADE");
851        sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
852    }
853    migrate(pool, migrator).await
854}
855
856#[cfg(test)]
857mod tests {
858    use super::*;
859
860    #[test]
861    fn debug_text_leaves_out_the_connection_string() {
862        let text = format!("{:?}", PoolConfig::new("postgres://me:hunter2@db/app"));
863        assert!(!text.contains("hunter2"), "{text}");
864        assert!(text.contains("max_connections"), "{text}");
865    }
866
867    #[test]
868    fn session_settings_become_connection_parameters() {
869        let base = "postgres://app@db/app";
870        assert_eq!(session_uri(base, 0, "", false).unwrap(), base);
871        assert_eq!(
872            session_uri(base, 5000, "orders", true).unwrap(),
873            "postgres://app@db/app?options=-c%20statement_timeout%3D5000%20-c%20\
874             default_transaction_read_only%3Don&application_name=orders"
875        );
876        assert_eq!(
877            session_uri("postgres://db/app?sslmode=require", 0, "orders", false).unwrap(),
878            "postgres://db/app?sslmode=require&application_name=orders"
879        );
880    }
881
882    #[test]
883    fn a_url_that_sets_them_already_is_kept_or_refused() {
884        // Its own application name wins.
885        let named = "postgres://db/app?application_name=mine";
886        assert_eq!(session_uri(named, 0, "orders", false).unwrap(), named);
887        // Its own options and a setting here would replace one another, so neither does.
888        let with_options = "postgres://db/app?options=-c%20work_mem%3D64MB";
889        assert!(session_uri(with_options, 5000, "", false).is_err());
890        assert!(session_uri(with_options, 0, "", true).is_err());
891        assert_eq!(
892            session_uri(with_options, 0, "", false).unwrap(),
893            with_options
894        );
895        for name in ["has space", "a&b=c", "é", &"a".repeat(64)] {
896            assert!(
897                session_uri("postgres://db/app", 0, name, false).is_err(),
898                "{name}"
899            );
900        }
901    }
902
903    #[test]
904    fn a_connection_is_retired_only_if_opened_by_the_last_stale_plan() {
905        let second = Duration::from_secs(1);
906        // Never a stale plan: nothing is retired.
907        assert!(!opened_before(0, 10 * second, 9 * second));
908        // A stale plan at 5s: a connection opened at 1s or 5s goes, one at 6s stays.
909        let at_five = 5_000_000_000 + 1;
910        assert!(opened_before(at_five, 10 * second, 9 * second));
911        assert!(opened_before(at_five, 10 * second, 5 * second));
912        assert!(!opened_before(at_five, 10 * second, 4 * second));
913        // An age past the epoch is opened before anything.
914        assert!(opened_before(at_five, second, 9 * second));
915    }
916
917    #[test]
918    fn only_custom_settings_can_be_set() {
919        for name in [
920            "app.tenant",
921            "app.user_id",
922            "my_app.tenant_2",
923            "a.b.c",
924            "_x.y",
925        ] {
926            assert!(is_custom_setting(name), "{name}");
927        }
928        for name in [
929            "role",
930            "search_path",
931            "session_authorization",
932            "app.",
933            ".tenant",
934            "app..tenant",
935            "App.Tenant",
936            "app.tenant; RESET ROLE",
937            "app.2fa",
938            "",
939        ] {
940            assert!(!is_custom_setting(name), "{name}");
941        }
942        assert!(!is_custom_setting(&format!("app.{}", "a".repeat(60))));
943    }
944
945    #[tokio::test]
946    async fn a_refused_setting_name_fails_before_anything_is_sent() {
947        // This pool would fail to connect, so an error that is not InvalidArgument
948        // would mean something was sent.
949        let pool = PgPoolOptions::new()
950            .connect_lazy("postgres://nobody@127.0.0.1:1/none")
951            .unwrap();
952        let error = begin_with(&pool, &[("app.tenant", "acme"), ("role", "postgres")])
953            .await
954            .unwrap_err();
955        assert!(
956            matches!(&error, sqlx::Error::InvalidArgument(text) if text.contains("role")),
957            "{error:?}"
958        );
959    }
960
961    #[test]
962    fn identifiers_are_quoted() {
963        assert_eq!(quote_identifier("users").as_deref(), Some("\"users\""));
964        assert_eq!(quote_identifier("_a1").as_deref(), Some("\"_a1\""));
965    }
966
967    #[test]
968    fn unsafe_identifiers_are_refused() {
969        for name in [
970            "", "1users", "Users", "a b", "a\"b", "a;b", "a.b", "users--", "é",
971        ] {
972            assert_eq!(quote_identifier(name), None, "{name:?}");
973        }
974    }
975
976    #[test]
977    fn quote_all_fails_on_any_bad_name() {
978        assert!(quote_all(&["good", "also_good"]).is_ok());
979        assert!(quote_all(&["good", "bad name"]).is_err());
980    }
981
982    #[test]
983    fn pool_settings_reach_the_options() {
984        let config = PoolConfig {
985            min_connections: 2,
986            max_connections: 7,
987            connect_timeout_ms: 1_500,
988            idle_timeout_ms: 9_000,
989            ..PoolConfig::new("postgres://x")
990        };
991        let options = config.options();
992        assert_eq!(options.get_min_connections(), 2);
993        assert_eq!(options.get_max_connections(), 7);
994        assert_eq!(options.get_acquire_timeout(), Duration::from_millis(1_500));
995        assert_eq!(options.get_idle_timeout(), Some(Duration::from_secs(9)));
996    }
997
998    #[test]
999    fn errors_that_are_not_from_the_database_are_not_unique_violations() {
1000        assert!(!is_unique_violation(&sqlx::Error::RowNotFound));
1001    }
1002}