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
641pub async fn truncate<S: AsRef<str>>(pool: &PgPool, tables: &[S]) -> Result<(), sqlx::Error> {
648 if tables.is_empty() {
649 return Ok(());
650 }
651 let tables = quote_all(tables)?.join(", ");
652 let sql = format!("TRUNCATE {tables} RESTART IDENTITY CASCADE");
653 sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
654 Ok(())
655}
656
657pub async fn dangerously_recreate(pool: &PgPool, migrator: &Migrator) -> Result<(), MigrateError> {
672 let tables: Vec<String> =
673 sqlx::query("SELECT tablename::text AS name FROM pg_tables WHERE schemaname = 'public'")
674 .fetch_all(pool)
675 .await?
676 .iter()
677 .map(|row| row.try_get("name"))
678 .collect::<Result<_, _>>()?;
679 let types: Vec<String> = sqlx::query(
681 "SELECT t.typname::text AS name FROM pg_type t
682 JOIN pg_namespace n ON n.oid = t.typnamespace
683 WHERE t.typtype = 'e' AND n.nspname = 'public'
684 AND NOT EXISTS (
685 SELECT 1 FROM pg_depend d WHERE d.objid = t.oid AND d.deptype = 'e'
686 )",
687 )
688 .fetch_all(pool)
689 .await?
690 .iter()
691 .map(|row| row.try_get("name"))
692 .collect::<Result<_, _>>()?;
693
694 if !tables.is_empty() {
695 let names = quote_all(&tables)?.join(", ");
696 let sql = format!("DROP TABLE {names} CASCADE");
697 sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
698 }
699 for name in quote_all(&types)? {
700 let sql = format!("DROP TYPE {name} CASCADE");
701 sqlx::query(AssertSqlSafe(sql)).execute(pool).await?;
702 }
703 migrate(pool, migrator).await
704}
705
706#[cfg(test)]
707mod tests {
708 use super::*;
709
710 #[test]
711 fn debug_text_leaves_out_the_connection_string() {
712 let text = format!("{:?}", PoolConfig::new("postgres://me:hunter2@db/app"));
713 assert!(!text.contains("hunter2"), "{text}");
714 assert!(text.contains("max_connections"), "{text}");
715 }
716
717 #[test]
718 fn session_settings_become_connection_parameters() {
719 let base = "postgres://app@db/app";
720 assert_eq!(session_uri(base, 0, "", false).unwrap(), base);
721 assert_eq!(
722 session_uri(base, 5000, "orders", true).unwrap(),
723 "postgres://app@db/app?options=-c%20statement_timeout%3D5000%20-c%20\
724 default_transaction_read_only%3Don&application_name=orders"
725 );
726 assert_eq!(
727 session_uri("postgres://db/app?sslmode=require", 0, "orders", false).unwrap(),
728 "postgres://db/app?sslmode=require&application_name=orders"
729 );
730 }
731
732 #[test]
733 fn a_url_that_sets_them_already_is_kept_or_refused() {
734 let named = "postgres://db/app?application_name=mine";
736 assert_eq!(session_uri(named, 0, "orders", false).unwrap(), named);
737 let with_options = "postgres://db/app?options=-c%20work_mem%3D64MB";
739 assert!(session_uri(with_options, 5000, "", false).is_err());
740 assert!(session_uri(with_options, 0, "", true).is_err());
741 assert_eq!(
742 session_uri(with_options, 0, "", false).unwrap(),
743 with_options
744 );
745 for name in ["has space", "a&b=c", "é", &"a".repeat(64)] {
746 assert!(
747 session_uri("postgres://db/app", 0, name, false).is_err(),
748 "{name}"
749 );
750 }
751 }
752
753 #[test]
754 fn a_connection_is_retired_only_if_opened_by_the_last_stale_plan() {
755 let second = Duration::from_secs(1);
756 assert!(!opened_before(0, 10 * second, 9 * second));
758 let at_five = 5_000_000_000 + 1;
760 assert!(opened_before(at_five, 10 * second, 9 * second));
761 assert!(opened_before(at_five, 10 * second, 5 * second));
762 assert!(!opened_before(at_five, 10 * second, 4 * second));
763 assert!(opened_before(at_five, second, 9 * second));
765 }
766
767 #[test]
768 fn only_custom_settings_can_be_set() {
769 for name in [
770 "app.tenant",
771 "app.user_id",
772 "my_app.tenant_2",
773 "a.b.c",
774 "_x.y",
775 ] {
776 assert!(is_custom_setting(name), "{name}");
777 }
778 for name in [
779 "role",
780 "search_path",
781 "session_authorization",
782 "app.",
783 ".tenant",
784 "app..tenant",
785 "App.Tenant",
786 "app.tenant; RESET ROLE",
787 "app.2fa",
788 "",
789 ] {
790 assert!(!is_custom_setting(name), "{name}");
791 }
792 assert!(!is_custom_setting(&format!("app.{}", "a".repeat(60))));
793 }
794
795 #[tokio::test]
796 async fn a_refused_setting_name_fails_before_anything_is_sent() {
797 let pool = PgPoolOptions::new()
800 .connect_lazy("postgres://nobody@127.0.0.1:1/none")
801 .unwrap();
802 let error = begin_with(&pool, &[("app.tenant", "acme"), ("role", "postgres")])
803 .await
804 .unwrap_err();
805 assert!(
806 matches!(&error, sqlx::Error::InvalidArgument(text) if text.contains("role")),
807 "{error:?}"
808 );
809 }
810
811 #[test]
812 fn identifiers_are_quoted() {
813 assert_eq!(quote_identifier("users").as_deref(), Some("\"users\""));
814 assert_eq!(quote_identifier("_a1").as_deref(), Some("\"_a1\""));
815 }
816
817 #[test]
818 fn unsafe_identifiers_are_refused() {
819 for name in [
820 "", "1users", "Users", "a b", "a\"b", "a;b", "a.b", "users--", "é",
821 ] {
822 assert_eq!(quote_identifier(name), None, "{name:?}");
823 }
824 }
825
826 #[test]
827 fn quote_all_fails_on_any_bad_name() {
828 assert!(quote_all(&["good", "also_good"]).is_ok());
829 assert!(quote_all(&["good", "bad name"]).is_err());
830 }
831
832 #[test]
833 fn pool_settings_reach_the_options() {
834 let config = PoolConfig {
835 min_connections: 2,
836 max_connections: 7,
837 connect_timeout_ms: 1_500,
838 idle_timeout_ms: 9_000,
839 ..PoolConfig::new("postgres://x")
840 };
841 let options = config.options();
842 assert_eq!(options.get_min_connections(), 2);
843 assert_eq!(options.get_max_connections(), 7);
844 assert_eq!(options.get_acquire_timeout(), Duration::from_millis(1_500));
845 assert_eq!(options.get_idle_timeout(), Some(Duration::from_secs(9)));
846 }
847
848 #[test]
849 fn errors_that_are_not_from_the_database_are_not_unique_violations() {
850 assert!(!is_unique_violation(&sqlx::Error::RowNotFound));
851 }
852}