1use 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
41pub type Pool = PgPool;
43
44pub type Error = sqlx::Error;
46
47#[derive(Clone, PartialEq, Eq)]
49pub struct PoolConfig {
50 pub uri: String,
52 pub min_connections: u32,
54 pub max_connections: u32,
56 pub connect_timeout_ms: u64,
58 pub idle_timeout_ms: u64,
60 pub statement_timeout_ms: u64,
63 pub application_name: String,
66 pub read_only: bool,
69}
70
71impl std::fmt::Debug for PoolConfig {
72 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 #[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 #[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 .before_acquire(|_connection, meta| {
112 Box::pin(async move { Ok(!opened_before_last_stale_plan(meta.age)) })
113 })
114 }
115}
116
117static EPOCH: OnceLock<Instant> = OnceLock::new();
119
120static LAST_STALE_PLAN: AtomicU64 = AtomicU64::new(0);
123
124fn epoch() -> Instant {
125 *EPOCH.get_or_init(Instant::now)
126}
127
128#[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
142pub 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
156fn 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
165fn 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 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
194fn 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
246fn 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
255fn 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
264fn 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
278pub async fn connect(config: &PoolConfig) -> Result<PgPool, sqlx::Error> {
286 config.options().connect(&config.connection_uri()?).await
287}
288
289pub async fn ping(pool: &PgPool) -> Result<(), sqlx::Error> {
295 sqlx::query("SELECT 1").execute(pool).await?;
296 Ok(())
297}
298
299pub enum Db<'a> {
316 Pool(&'a PgPool),
318 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 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
348pub enum Conn<'a> {
350 Pooled(PoolConnection<Postgres>),
352 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#[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#[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
405fn 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#[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
441pub 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#[derive(Debug, Clone, PartialEq, Eq)]
492pub struct RowSecurity {
493 pub role: String,
495 pub bypasses: bool,
497 pub unprotected: Vec<String>,
500}
501
502impl RowSecurity {
503 #[must_use]
505 pub fn holds(&self) -> bool {
506 !self.bypasses && self.unprotected.is_empty()
507 }
508}
509
510pub 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 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
553pub async fn migrate(pool: &PgPool, migrator: &Migrator) -> Result<(), MigrateError> {
560 migrator.run(pool).await
561}
562
563async 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
580pub 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 let target = applied.get(steps).copied().unwrap_or(0);
591 migrator.undo(pool, target).await
592}
593
594#[derive(Debug, Clone, PartialEq, Eq)]
596pub struct MigrationStatus {
597 pub version: i64,
599 pub description: String,
601 pub applied: bool,
603}
604
605pub 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
626pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660pub struct Background {
661 pub name: &'static str,
664 pub statements: &'static [&'static str],
666}
667
668pub const BACKGROUND_TABLE: &str = "axa_background_migrations";
670
671pub 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
713pub 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 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 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
772pub 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
791pub 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
807pub 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 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 let named = "postgres://db/app?application_name=mine";
886 assert_eq!(session_uri(named, 0, "orders", false).unwrap(), named);
887 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 assert!(!opened_before(0, 10 * second, 9 * second));
908 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 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 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}