axa-postgres-sqlx 0.2.1

PostgreSQL pooling, migrations, and test resets over sqlx for Axum services.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//! `PostgreSQL` pooling, migrations, and test resets over sqlx.
//!
//! This crate holds the operations every service repeats. It does not wrap
//! queries: a service writes its own SQL with `sqlx::query!`, so a reviewer
//! reads exactly what runs.
//!
//! It has the same shape as `axa-postgres-seaorm`, `axa-postgres-diesel`, and `axa-postgres-toasty`: a [`Pool`],
//! a [`PoolConfig`], [`connect`], [`ping`], [`migrate`], [`revert`], [`pending`],
//! [`truncate`], [`dangerously_recreate`], [`is_unique_violation`], and
//! [`quote_identifier`], with [`status`] besides.
//!
//! ```no_run
//! use axa_postgres_sqlx::{PoolConfig, connect, migrate, sqlx};
//!
//! static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate::Migrator::DEFAULT;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let pool = connect(&PoolConfig::new("postgres://localhost/app")).await?;
//! migrate(&pool, &MIGRATOR).await?;
//! # Ok(())
//! # }
//! ```

use std::{
    ops::{Deref, DerefMut},
    sync::{
        OnceLock,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant},
};

pub use sqlx;
use sqlx::{
    AssertSqlSafe, PgConnection, PgPool, Postgres, Row,
    migrate::{MigrateError, Migrator},
    pool::PoolConnection,
    postgres::PgPoolOptions,
};

/// The handle a service holds: the pool.
pub type Pool = PgPool;

/// What this crate's connection and query functions return on failure.
pub type Error = sqlx::Error;

/// Pool settings.
#[derive(Clone, PartialEq, Eq)]
pub struct PoolConfig {
    /// Connection string.
    pub uri: String,
    /// Connections kept open.
    pub min_connections: u32,
    /// Largest number of connections.
    pub max_connections: u32,
    /// How long to wait for a connection, in milliseconds.
    pub connect_timeout_ms: u64,
    /// How long an idle connection stays open, in milliseconds.
    pub idle_timeout_ms: u64,
    /// Postgres's `statement_timeout` on every connection, in milliseconds. `0` sets
    /// none.
    pub statement_timeout_ms: u64,
    /// Postgres's `application_name` on every connection, so `pg_stat_activity` says
    /// which service a query came from. Empty sets none.
    pub application_name: String,
    /// Open every transaction read-only, as for a read replica or a reporting
    /// service, so that a write is refused by the database.
    pub read_only: bool,
}

impl std::fmt::Debug for PoolConfig {
    /// Leaves the connection string out, because it can carry a password.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PoolConfig")
            .field("min_connections", &self.min_connections)
            .field("max_connections", &self.max_connections)
            .field("connect_timeout_ms", &self.connect_timeout_ms)
            .field("idle_timeout_ms", &self.idle_timeout_ms)
            .field("statement_timeout_ms", &self.statement_timeout_ms)
            .field("application_name", &self.application_name)
            .field("read_only", &self.read_only)
            .finish_non_exhaustive()
    }
}

impl PoolConfig {
    /// Settings for `uri` with a small pool.
    #[must_use]
    pub fn new(uri: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            min_connections: 1,
            max_connections: 10,
            connect_timeout_ms: 5_000,
            idle_timeout_ms: 600_000,
            statement_timeout_ms: 0,
            application_name: String::new(),
            read_only: false,
        }
    }

    /// The sqlx options these settings describe.
    #[must_use]
    pub fn options(&self) -> PgPoolOptions {
        PgPoolOptions::new()
            .min_connections(self.min_connections)
            .max_connections(self.max_connections)
            .acquire_timeout(Duration::from_millis(self.connect_timeout_ms))
            .idle_timeout(Duration::from_millis(self.idle_timeout_ms))
            // Retire a connection whose cached statements a migration has made stale.
            .before_acquire(|_connection, meta| {
                Box::pin(async move { Ok(!opened_before_last_stale_plan(meta.age)) })
            })
    }
}

/// When this process first needed a clock for stale plans.
static EPOCH: OnceLock<Instant> = OnceLock::new();

/// Nanoseconds after [`EPOCH`] that a stale plan was last seen, plus one, or `0` for
/// never.
static LAST_STALE_PLAN: AtomicU64 = AtomicU64::new(0);

fn epoch() -> Instant {
    *EPOCH.get_or_init(Instant::now)
}

/// Whether `error` is Postgres refusing a statement this connection prepared before a
/// migration changed what it returns: SQLSTATE `0A000` with "cached plan must not
/// change result type". Each pooled connection that cached the statement fails so
/// once, and a fresh connection does not.
#[must_use]
pub fn is_stale_plan(error: &sqlx::Error) -> bool {
    error.as_database_error().is_some_and(|error| {
        error.code().as_deref() == Some("0A000")
            && error
                .message()
                .contains("cached plan must not change result type")
    })
}

/// Record `error` if it is a stale plan, so that every connection opened before now is
/// retired when next acquired, from every pool [`connect`] opened in this process, and
/// the next attempt runs on a fresh one. Returns whether it was. `axa::Error` calls
/// this for every sqlx error it answers, so a service that turns sqlx errors into it
/// needs nothing more.
pub fn note_stale_plan(error: &sqlx::Error) -> bool {
    if !is_stale_plan(error) {
        return false;
    }
    let since = u64::try_from(epoch().elapsed().as_nanos()).unwrap_or(u64::MAX - 1);
    LAST_STALE_PLAN.fetch_max(since.saturating_add(1), Ordering::SeqCst);
    true
}

/// Whether a connection `age` old was opened at or before the last stale plan.
fn opened_before_last_stale_plan(age: Duration) -> bool {
    opened_before(
        LAST_STALE_PLAN.load(Ordering::SeqCst),
        epoch().elapsed(),
        age,
    )
}

/// Whether a connection `age` old at `now`, both since [`EPOCH`], was opened at or
/// before `last`, as [`LAST_STALE_PLAN`] holds it.
fn opened_before(last: u64, now: Duration, age: Duration) -> bool {
    if last == 0 {
        return false;
    }
    now.saturating_sub(age) <= Duration::from_nanos(last - 1)
}

impl PoolConfig {
    /// The connection string with the session settings added, as every connection
    /// [`connect`] opens uses.
    ///
    /// # Errors
    ///
    /// [`sqlx::Error::Configuration`] when the URL sets `options` already and a
    /// statement timeout or read-only mode is set here too, or when the application
    /// name is not one Postgres keeps as it is.
    pub fn connection_uri(&self) -> Result<String, sqlx::Error> {
        session_uri(
            &self.uri,
            self.statement_timeout_ms,
            &self.application_name,
            self.read_only,
        )
        .map_err(|problem| sqlx::Error::Configuration(problem.into()))
    }
}

/// `uri` with each session setting added as a libpq connection parameter, so that
/// every connection the pool opens starts with them, at no extra round trip:
/// `statement_timeout` and `default_transaction_read_only` in `options`, and
/// `application_name`.
///
/// An `application_name` the URL already names is kept. `options` the URL already
/// names, with a setting here to add, is refused, rather than either one silently
/// replacing the other.
fn session_uri(
    uri: &str,
    statement_timeout_ms: u64,
    application_name: &str,
    read_only: bool,
) -> Result<String, String> {
    let mut options = Vec::new();
    if statement_timeout_ms > 0 {
        options.push(format!("-c statement_timeout={statement_timeout_ms}"));
    }
    if read_only {
        options.push("-c default_transaction_read_only=on".to_string());
    }
    let mut params = Vec::new();
    if !options.is_empty() {
        if has_param(uri, "options") {
            return Err(
                "the connection URL sets options already: set the statement timeout and \
                 read-only mode there, or here, not both"
                    .to_string(),
            );
        }
        params.push(("options", options.join(" ")));
    }
    if !application_name.is_empty() && !has_param(uri, "application_name") {
        if !is_application_name(application_name) {
            return Err(
                "an application name is ASCII letters, digits, `_`, `.`, and `-`, at most 63"
                    .to_string(),
            );
        }
        params.push(("application_name", application_name.to_string()));
    }
    if params.is_empty() {
        return Ok(uri.to_string());
    }
    let separator = if uri.contains('?') { '&' } else { '?' };
    let query: Vec<String> = params
        .iter()
        .map(|(name, value)| format!("{name}={}", percent_encode(value)))
        .collect();
    Ok(format!("{uri}{separator}{}", query.join("&")))
}

/// Whether the query of `uri` names `name`.
fn has_param(uri: &str, name: &str) -> bool {
    uri.split_once('?').is_some_and(|(_, query)| {
        query
            .split('&')
            .any(|pair| pair.split('=').next() == Some(name))
    })
}

/// Whether `name` is an application name Postgres keeps as it is: ASCII letters,
/// digits, `_`, `.`, and `-`, from 1 to 63 bytes.
fn is_application_name(name: &str) -> bool {
    (1..=63).contains(&name.len())
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
}

/// `value` with every byte but the unreserved ones percent-encoded.
fn percent_encode(value: &str) -> String {
    use std::fmt::Write as _;
    let mut encoded = String::new();
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
            encoded.push(char::from(byte));
        } else {
            let _ = write!(encoded, "%{byte:02X}");
        }
    }
    encoded
}

/// Open a pool and prove it works with one connection, with the session settings on
/// every connection.
///
/// # Errors
///
/// Fails when the settings are refused, as [`PoolConfig::connection_uri`] says, or the
/// database cannot be reached.
pub async fn connect(config: &PoolConfig) -> Result<PgPool, sqlx::Error> {
    config.options().connect(&config.connection_uri()?).await
}

/// Check that the database answers.
///
/// # Errors
///
/// Fails when it does not.
pub async fn ping(pool: &PgPool) -> Result<(), sqlx::Error> {
    sqlx::query("SELECT 1").execute(pool).await?;
    Ok(())
}

/// Where a function gets its connection: the pool, or a connection the caller
/// holds, usually an open transaction, so one function serves both.
///
/// `impl sqlx::Acquire` says the same, but its associated types stop the future
/// being `Send`, which Axum handlers and `tokio::spawn` need.
///
/// ```no_run
/// use axa_postgres_sqlx::{Db, sqlx};
///
/// async fn count(db: impl Into<Db<'_>>) -> Result<i64, sqlx::Error> {
///     let mut conn = db.into().acquire().await?;
///     sqlx::query_scalar("SELECT count(*) FROM items")
///         .fetch_one(&mut *conn)
///         .await
/// }
/// ```
pub enum Db<'a> {
    /// Take a connection from the pool for the length of the call.
    Pool(&'a PgPool),
    /// Use the caller's connection.
    Conn(&'a mut PgConnection),
}

impl<'a> From<&'a PgPool> for Db<'a> {
    fn from(pool: &'a PgPool) -> Self {
        Self::Pool(pool)
    }
}

impl<'a> From<&'a mut PgConnection> for Db<'a> {
    fn from(conn: &'a mut PgConnection) -> Self {
        Self::Conn(conn)
    }
}

impl<'a> Db<'a> {
    /// The connection to use.
    ///
    /// # Errors
    ///
    /// Fails when the pool has none to give.
    pub async fn acquire(self) -> Result<Conn<'a>, sqlx::Error> {
        match self {
            Self::Pool(pool) => Ok(Conn::Pooled(pool.acquire().await?)),
            Self::Conn(conn) => Ok(Conn::Borrowed(conn)),
        }
    }
}

/// A connection for the length of one call. It derefs to [`PgConnection`].
pub enum Conn<'a> {
    /// Taken from the pool, and given back when dropped.
    Pooled(PoolConnection<Postgres>),
    /// The caller's.
    Borrowed(&'a mut PgConnection),
}

impl Deref for Conn<'_> {
    type Target = PgConnection;

    fn deref(&self) -> &PgConnection {
        match self {
            Self::Pooled(conn) => conn,
            Self::Borrowed(conn) => conn,
        }
    }
}

impl DerefMut for Conn<'_> {
    fn deref_mut(&mut self) -> &mut PgConnection {
        match self {
            Self::Pooled(conn) => conn,
            Self::Borrowed(conn) => conn,
        }
    }
}

/// Whether an error is a violated unique constraint, which a service usually
/// reports as `409` rather than `500`.
#[must_use]
pub fn is_unique_violation(error: &sqlx::Error) -> bool {
    error
        .as_database_error()
        .is_some_and(sqlx::error::DatabaseError::is_unique_violation)
}

/// Quote a table or type name for use in SQL.
///
/// Identifiers cannot be bound as parameters, so this is the one place names
/// reach SQL as text. Only lowercase ASCII letters, digits, and underscores
/// are accepted, starting with a letter or underscore. That is stricter than
/// Postgres, and it leaves nothing for an attacker to work with.
///
/// ```
/// assert_eq!(axa_postgres_sqlx::quote_identifier("users").as_deref(), Some("\"users\""));
/// assert_eq!(axa_postgres_sqlx::quote_identifier("users; DROP TABLE x"), None);
/// ```
#[must_use]
pub fn quote_identifier(name: &str) -> Option<String> {
    let mut chars = name.chars();
    let first = chars.next()?;
    let valid = (first.is_ascii_lowercase() || first == '_')
        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
    valid.then(|| format!("\"{name}\""))
}

/// Quote every name, failing on the first one [`quote_identifier`] refuses.
fn quote_all<S: AsRef<str>>(names: &[S]) -> Result<Vec<String>, sqlx::Error> {
    names
        .iter()
        .map(|name| {
            quote_identifier(name.as_ref()).ok_or_else(|| {
                sqlx::Error::Protocol(format!("invalid identifier: {}", name.as_ref()))
            })
        })
        .collect()
}

/// Whether `name` is a custom setting a service may set for row-level security: two or
/// more parts of lower-case ASCII letters, digits, and underscores, joined by dots, such
/// as `app.tenant`. A name with no dot is Postgres's own, such as `role` or
/// `search_path`, which this never sets.
///
/// ```
/// assert!(axa_postgres_sqlx::is_custom_setting("app.tenant"));
/// assert!(!axa_postgres_sqlx::is_custom_setting("search_path"));
/// ```
#[must_use]
pub fn is_custom_setting(name: &str) -> bool {
    let parts: Vec<&str> = name.split('.').collect();
    name.len() <= 63
        && parts.len() >= 2
        && parts.iter().all(|part| {
            part.chars()
                .next()
                .is_some_and(|first| first.is_ascii_lowercase() || first == '_')
                && part
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
        })
}

/// Open a transaction with each `(name, value)` set for its length only, such as
/// `("app.tenant", tenant.as_str())` for a row-level security policy that reads
/// `current_setting('app.tenant', true)`.
///
/// Each pair is set with `set_config($1, $2, true)`: bound, never formatted into the
/// SQL, and gone when the transaction commits or rolls back, so a pooled connection
/// never carries one request's tenant into the next. Run every query that needs the
/// setting on the transaction this returns, as a query on the pool may run on another
/// connection.
///
/// ```no_run
/// # async fn example(pool: &sqlx::PgPool) -> Result<(), sqlx::Error> {
/// let mut tx = axa_postgres_sqlx::begin_with(pool, &[("app.tenant", "acme")]).await?;
/// let count: i64 = sqlx::query_scalar("SELECT count(*) FROM todos")
///     .fetch_one(&mut *tx)
///     .await?;
/// tx.commit().await?;
/// # Ok(())
/// # }
/// ```
///
/// A policy sees nothing unless the role the service connects as is subject to it: not
/// a superuser, without `BYPASSRLS`, and, if it owns the table, with
/// `FORCE ROW LEVEL SECURITY` on it.
///
/// # Errors
///
/// [`sqlx::Error::InvalidArgument`] for a name [`is_custom_setting`] refuses, before
/// anything is sent, and any error from beginning the transaction or setting a value.
pub async fn begin_with(
    pool: &PgPool,
    settings: &[(&str, &str)],
) -> Result<sqlx::Transaction<'static, Postgres>, sqlx::Error> {
    if let Some((name, _)) = settings.iter().find(|(name, _)| !is_custom_setting(name)) {
        return Err(sqlx::Error::InvalidArgument(format!(
            "not a custom setting: {name}"
        )));
    }
    let mut tx = pool.begin().await?;
    for (name, value) in settings {
        sqlx::query("SELECT set_config($1, $2, true)")
            .bind(name)
            .bind(value)
            .execute(&mut *tx)
            .await?;
    }
    Ok(tx)
}

/// Whether row-level security can keep rows apart for the role a pool connects as.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RowSecurity {
    /// The role the pool connects as.
    pub role: String,
    /// Whether that role skips every policy: a superuser, or a role with `BYPASSRLS`.
    pub bypasses: bool,
    /// The tables asked about that do not exist, have no row-level security, or lack
    /// `FORCE ROW LEVEL SECURITY`, so that their owner skips the policies.
    pub unprotected: Vec<String>,
}

impl RowSecurity {
    /// Whether the policies on every table asked about apply to the role.
    #[must_use]
    pub fn holds(&self) -> bool {
        !self.bypasses && self.unprotected.is_empty()
    }
}

/// Ask Postgres whether row-level security can apply to `pool`'s role, and whether
/// each of `tables`, such as `todos` or `app.todos`, has it enabled and forced.
///
/// A policy does nothing for a superuser or a role with `BYPASSRLS`, and nothing for a
/// table's owner unless the table has `FORCE ROW LEVEL SECURITY`. Each failure is
/// silent: every query still answers, with every tenant's rows. Call this at boot, after
/// migrating, and refuse to serve when it does not hold.
///
/// # Errors
///
/// Any error from the queries.
pub async fn row_security<S: AsRef<str>>(
    pool: &PgPool,
    tables: &[S],
) -> Result<RowSecurity, sqlx::Error> {
    let role = sqlx::query(
        "SELECT current_user::text AS role, rolsuper OR rolbypassrls AS bypasses
         FROM pg_roles WHERE rolname = current_user",
    )
    .fetch_one(pool)
    .await?;
    let mut unprotected = Vec::new();
    for table in tables {
        let table = table.as_ref();
        // Bound, and looked up with to_regclass, which takes the name as text.
        let forced: Option<bool> = sqlx::query_scalar(
            "SELECT relrowsecurity AND relforcerowsecurity FROM pg_class
             WHERE oid = to_regclass($1)",
        )
        .bind(table)
        .fetch_optional(pool)
        .await?;
        if forced != Some(true) {
            unprotected.push(table.to_string());
        }
    }
    Ok(RowSecurity {
        role: role.get("role"),
        bypasses: role.get("bypasses"),
        unprotected,
    })
}

/// Apply pending migrations. Sqlx holds a lock while it does, so services
/// booting together take turns.
///
/// # Errors
///
/// Fails when a migration fails, or an applied one no longer matches.
pub async fn migrate(pool: &PgPool, migrator: &Migrator) -> Result<(), MigrateError> {
    migrator.run(pool).await
}

/// The newest applied versions, newest first. Empty on a database that has
/// never been migrated.
async fn applied_versions(pool: &PgPool) -> Result<Vec<i64>, sqlx::Error> {
    let exists: bool = sqlx::query("SELECT to_regclass('_sqlx_migrations') IS NOT NULL AS found")
        .fetch_one(pool)
        .await?
        .try_get("found")?;
    if !exists {
        return Ok(Vec::new());
    }
    let rows =
        sqlx::query("SELECT version FROM _sqlx_migrations WHERE success ORDER BY version DESC")
            .fetch_all(pool)
            .await?;
    rows.iter().map(|row| row.try_get("version")).collect()
}

/// Revert the newest `steps` migrations. Each needs a `.down.sql` file.
///
/// # Errors
///
/// Fails on a database error or a failed down migration.
pub async fn revert(pool: &PgPool, migrator: &Migrator, steps: u32) -> Result<(), MigrateError> {
    let applied = applied_versions(pool).await?;
    let steps = usize::try_from(steps).unwrap_or(usize::MAX);
    // `undo` reverts everything newer than its target, so the target is the
    // version just past the last one to revert, or 0 to revert them all.
    let target = applied.get(steps).copied().unwrap_or(0);
    migrator.undo(pool, target).await
}

/// One migration and whether it has run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigrationStatus {
    /// Its version.
    pub version: i64,
    /// Its description.
    pub description: String,
    /// Whether it has been applied.
    pub applied: bool,
}

/// Every migration in `migrator`, oldest first, with whether it has run.
///
/// # Errors
///
/// Fails on a database error.
pub async fn status(
    pool: &PgPool,
    migrator: &Migrator,
) -> Result<Vec<MigrationStatus>, sqlx::Error> {
    let applied = applied_versions(pool).await?;
    Ok(migrator
        .iter()
        .filter(|migration| !migration.migration_type.is_down_migration())
        .map(|migration| MigrationStatus {
            version: migration.version,
            description: migration.description.to_string(),
            applied: applied.contains(&migration.version),
        })
        .collect())
}

/// The names of the migrations in `migrator` not yet applied, in order, each as
/// `version_description`.
///
/// # Errors
///
/// Fails on a database error.
pub async fn pending(pool: &PgPool, migrator: &Migrator) -> Result<Vec<String>, sqlx::Error> {
    Ok(status(pool, migrator)
        .await?
        .into_iter()
        .filter(|migration| !migration.applied)
        .map(|migration| format!("{}_{}", migration.version, migration.description))
        .collect())
}

/// A migration of statements that cannot run in a transaction, such as
/// `CREATE INDEX CONCURRENTLY`, which sqlx's migrator runs each file in. Name each one
/// once and never change it: its name is what marks it done.
///
/// A statement that fails partway can leave something behind, as a failed
/// `CREATE INDEX CONCURRENTLY` leaves an invalid index, so begin with what clears it:
///
/// ```
/// use axa_postgres_sqlx::Background;
///
/// const NOTES_BY_ITEM: Background = Background {
///     name: "2026_11_notes_by_item",
///     statements: &[
///         "DROP INDEX CONCURRENTLY IF EXISTS notes_by_item",
///         "CREATE INDEX CONCURRENTLY notes_by_item ON notes (item_id)",
///     ],
/// };
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Background {
    /// Its name, 1 to 200 characters with no control characters, recorded once it has
    /// run.
    pub name: &'static str,
    /// Its statements, each run alone, outside any transaction, in order.
    pub statements: &'static [&'static str],
}

/// The table background migrations are recorded in.
pub const BACKGROUND_TABLE: &str = "axa_background_migrations";

/// The advisory lock one process holds while it runs background migrations.
pub const BACKGROUND_LOCK: i64 = 0x6178_615f_6267_6d00;

const BACKGROUND_SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_background_migrations (
    name TEXT PRIMARY KEY,
    finished_at TIMESTAMPTZ NOT NULL DEFAULT now()
)";

fn check_background(migrations: &[Background]) -> Result<(), sqlx::Error> {
    let mut names = std::collections::HashSet::new();
    for migration in migrations {
        let name = migration.name;
        if name.is_empty() || name.chars().count() > 200 || name.chars().any(char::is_control) {
            return Err(sqlx::Error::Configuration(
                "a background migration's name must be 1 to 200 characters with no control characters".into(),
            ));
        }
        if !names.insert(name) {
            return Err(sqlx::Error::Configuration(
                format!("the background migration {name} is named twice").into(),
            ));
        }
    }
    Ok(())
}

async fn background_done(
    connection: &mut sqlx::PgConnection,
) -> Result<std::collections::HashSet<String>, sqlx::Error> {
    let exists: bool =
        sqlx::query_scalar("SELECT to_regclass('axa_background_migrations') IS NOT NULL")
            .fetch_one(&mut *connection)
            .await?;
    if !exists {
        return Ok(std::collections::HashSet::new());
    }
    let names: Vec<String> = sqlx::query_scalar("SELECT name FROM axa_background_migrations")
        .fetch_all(&mut *connection)
        .await?;
    Ok(names.into_iter().collect())
}

/// Run each of `migrations` not yet recorded, in order, outside any transaction,
/// recording each once all its statements have run. One process at a time holds
/// [`BACKGROUND_LOCK`], so replicas booting together do not run one twice: a process
/// that cannot take it answers `None` at once, and the one that holds it answers the
/// names it ran. A failure stops the run, leaves that migration unrecorded, so the next
/// run tries it again, and releases the lock.
///
/// # Errors
///
/// Fails on a name that is empty, too long, or used twice, on a database error, or on
/// a statement that fails.
pub async fn run_background(
    pool: &PgPool,
    migrations: &[Background],
) -> Result<Option<Vec<String>>, sqlx::Error> {
    check_background(migrations)?;
    let mut connection = pool.acquire().await?;
    let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
        .bind(BACKGROUND_LOCK)
        .fetch_one(&mut *connection)
        .await?;
    if !locked {
        return Ok(None);
    }
    let ran = run_background_locked(&mut connection, migrations).await;
    let unlocked = sqlx::query("SELECT pg_advisory_unlock($1)")
        .bind(BACKGROUND_LOCK)
        .execute(&mut *connection)
        .await;
    if unlocked.is_err() {
        // The lock goes with the connection, so do not hand it back to the pool.
        connection.detach();
    }
    ran.map(Some)
}

async fn run_background_locked(
    connection: &mut sqlx::PgConnection,
    migrations: &[Background],
) -> Result<Vec<String>, sqlx::Error> {
    sqlx::query(BACKGROUND_SETUP)
        .execute(&mut *connection)
        .await?;
    let done = background_done(connection).await?;
    let mut ran = Vec::new();
    for migration in migrations.iter().filter(|m| !done.contains(m.name)) {
        for statement in migration.statements {
            // `&'static`, so written in the code and never built from input.
            sqlx::raw_sql(*statement).execute(&mut *connection).await?;
        }
        sqlx::query("INSERT INTO axa_background_migrations (name) VALUES ($1)")
            .bind(migration.name)
            .execute(&mut *connection)
            .await?;
        ran.push(migration.name.to_string());
    }
    Ok(ran)
}

/// The names of `migrations` not yet recorded, in order, for
/// `Checks::migrations`.
///
/// # Errors
///
/// Fails on a database error.
pub async fn pending_background(
    pool: &PgPool,
    migrations: &[Background],
) -> Result<Vec<String>, sqlx::Error> {
    let mut connection = pool.acquire().await?;
    let done = background_done(&mut connection).await?;
    Ok(migrations
        .iter()
        .filter(|migration| !done.contains(migration.name))
        .map(|migration| migration.name.to_string())
        .collect())
}

/// Empty `tables`, restarting their sequences. Each name goes through
/// [`quote_identifier`].
///
/// # Errors
///
/// Fails on an invalid name or a database error.
pub async fn truncate<S: AsRef<str>>(pool: &PgPool, tables: &[S]) -> Result<(), sqlx::Error> {
    if tables.is_empty() {
        return Ok(());
    }
    let tables = quote_all(tables)?.join(", ");
    let sql = format!("TRUNCATE {tables} RESTART IDENTITY CASCADE");
    sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
    Ok(())
}

/// Drop every table and enum type in `public`, then migrate from nothing.
/// This gives each test an empty schema, whatever tables it touched.
///
/// **This destroys all data.** It exists for tests, and a service must never
/// reach it outside the `test` environment.
///
/// It drops tables and types by name rather than dropping the schema, because
/// `DROP SCHEMA public CASCADE` would also remove the extensions a database
/// was prepared with, such as `citext`. Functions are left in place, so a
/// migration that creates one should use `CREATE OR REPLACE`.
///
/// # Errors
///
/// Fails on a database error, or a name [`quote_identifier`] refuses.
pub async fn dangerously_recreate(pool: &PgPool, migrator: &Migrator) -> Result<(), MigrateError> {
    let tables: Vec<String> =
        sqlx::query("SELECT tablename::text AS name FROM pg_tables WHERE schemaname = 'public'")
            .fetch_all(pool)
            .await?
            .iter()
            .map(|row| row.try_get("name"))
            .collect::<Result<_, _>>()?;
    // Types owned by an extension (`deptype = 'e'`) belong to that extension.
    let types: Vec<String> = sqlx::query(
        "SELECT t.typname::text AS name FROM pg_type t
         JOIN pg_namespace n ON n.oid = t.typnamespace
         WHERE t.typtype = 'e' AND n.nspname = 'public'
           AND NOT EXISTS (
               SELECT 1 FROM pg_depend d WHERE d.objid = t.oid AND d.deptype = 'e'
           )",
    )
    .fetch_all(pool)
    .await?
    .iter()
    .map(|row| row.try_get("name"))
    .collect::<Result<_, _>>()?;

    if !tables.is_empty() {
        let names = quote_all(&tables)?.join(", ");
        let sql = format!("DROP TABLE {names} CASCADE");
        sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
    }
    for name in quote_all(&types)? {
        let sql = format!("DROP TYPE {name} CASCADE");
        sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
    }
    migrate(pool, migrator).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn debug_text_leaves_out_the_connection_string() {
        let text = format!("{:?}", PoolConfig::new("postgres://me:hunter2@db/app"));
        assert!(!text.contains("hunter2"), "{text}");
        assert!(text.contains("max_connections"), "{text}");
    }

    #[test]
    fn session_settings_become_connection_parameters() {
        let base = "postgres://app@db/app";
        assert_eq!(session_uri(base, 0, "", false).unwrap(), base);
        assert_eq!(
            session_uri(base, 5000, "orders", true).unwrap(),
            "postgres://app@db/app?options=-c%20statement_timeout%3D5000%20-c%20\
             default_transaction_read_only%3Don&application_name=orders"
        );
        assert_eq!(
            session_uri("postgres://db/app?sslmode=require", 0, "orders", false).unwrap(),
            "postgres://db/app?sslmode=require&application_name=orders"
        );
    }

    #[test]
    fn a_url_that_sets_them_already_is_kept_or_refused() {
        // Its own application name wins.
        let named = "postgres://db/app?application_name=mine";
        assert_eq!(session_uri(named, 0, "orders", false).unwrap(), named);
        // Its own options and a setting here would replace one another, so neither does.
        let with_options = "postgres://db/app?options=-c%20work_mem%3D64MB";
        assert!(session_uri(with_options, 5000, "", false).is_err());
        assert!(session_uri(with_options, 0, "", true).is_err());
        assert_eq!(
            session_uri(with_options, 0, "", false).unwrap(),
            with_options
        );
        for name in ["has space", "a&b=c", "é", &"a".repeat(64)] {
            assert!(
                session_uri("postgres://db/app", 0, name, false).is_err(),
                "{name}"
            );
        }
    }

    #[test]
    fn a_connection_is_retired_only_if_opened_by_the_last_stale_plan() {
        let second = Duration::from_secs(1);
        // Never a stale plan: nothing is retired.
        assert!(!opened_before(0, 10 * second, 9 * second));
        // A stale plan at 5s: a connection opened at 1s or 5s goes, one at 6s stays.
        let at_five = 5_000_000_000 + 1;
        assert!(opened_before(at_five, 10 * second, 9 * second));
        assert!(opened_before(at_five, 10 * second, 5 * second));
        assert!(!opened_before(at_five, 10 * second, 4 * second));
        // An age past the epoch is opened before anything.
        assert!(opened_before(at_five, second, 9 * second));
    }

    #[test]
    fn only_custom_settings_can_be_set() {
        for name in [
            "app.tenant",
            "app.user_id",
            "my_app.tenant_2",
            "a.b.c",
            "_x.y",
        ] {
            assert!(is_custom_setting(name), "{name}");
        }
        for name in [
            "role",
            "search_path",
            "session_authorization",
            "app.",
            ".tenant",
            "app..tenant",
            "App.Tenant",
            "app.tenant; RESET ROLE",
            "app.2fa",
            "",
        ] {
            assert!(!is_custom_setting(name), "{name}");
        }
        assert!(!is_custom_setting(&format!("app.{}", "a".repeat(60))));
    }

    #[tokio::test]
    async fn a_refused_setting_name_fails_before_anything_is_sent() {
        // This pool would fail to connect, so an error that is not InvalidArgument
        // would mean something was sent.
        let pool = PgPoolOptions::new()
            .connect_lazy("postgres://nobody@127.0.0.1:1/none")
            .unwrap();
        let error = begin_with(&pool, &[("app.tenant", "acme"), ("role", "postgres")])
            .await
            .unwrap_err();
        assert!(
            matches!(&error, sqlx::Error::InvalidArgument(text) if text.contains("role")),
            "{error:?}"
        );
    }

    #[test]
    fn identifiers_are_quoted() {
        assert_eq!(quote_identifier("users").as_deref(), Some("\"users\""));
        assert_eq!(quote_identifier("_a1").as_deref(), Some("\"_a1\""));
    }

    #[test]
    fn unsafe_identifiers_are_refused() {
        for name in [
            "", "1users", "Users", "a b", "a\"b", "a;b", "a.b", "users--", "é",
        ] {
            assert_eq!(quote_identifier(name), None, "{name:?}");
        }
    }

    #[test]
    fn quote_all_fails_on_any_bad_name() {
        assert!(quote_all(&["good", "also_good"]).is_ok());
        assert!(quote_all(&["good", "bad name"]).is_err());
    }

    #[test]
    fn pool_settings_reach_the_options() {
        let config = PoolConfig {
            min_connections: 2,
            max_connections: 7,
            connect_timeout_ms: 1_500,
            idle_timeout_ms: 9_000,
            ..PoolConfig::new("postgres://x")
        };
        let options = config.options();
        assert_eq!(options.get_min_connections(), 2);
        assert_eq!(options.get_max_connections(), 7);
        assert_eq!(options.get_acquire_timeout(), Duration::from_millis(1_500));
        assert_eq!(options.get_idle_timeout(), Some(Duration::from_secs(9)));
    }

    #[test]
    fn errors_that_are_not_from_the_database_are_not_unique_violations() {
        assert!(!is_unique_violation(&sqlx::Error::RowNotFound));
    }
}