Skip to main content

encore/storage/postgres/
mod.rs

1//! Postgres databases.
2//!
3//! Databases are declared at module scope. Connection pools are initialized
4//! lazily on the first query and reused across calls.
5//!
6//! ```no_run
7//! use encore::storage::postgres::{self, Database};
8//!
9//! static DB: Database = Database::new("hello").migrations("./migrations");
10//!
11//! async fn rename(id: i64, name: &str) -> Result<Option<String>, postgres::Error> {
12//!     DB.execute("UPDATE users SET name = $2 WHERE id = $1", &[&id, &name])
13//!         .await?;
14//!     let row = DB
15//!         .query_opt("SELECT email FROM users WHERE id = $1", &[&id])
16//!         .await?;
17//!     Ok(row.map(|row| row.get("email")))
18//! }
19//! ```
20//!
21//! # Queries
22//!
23//! Query methods mirror [`tokio_postgres::Client`] (`query`, `query_one`,
24//! `query_opt`, `query_raw`, `execute`, `batch_execute`, and so on) and return
25//! this module's [`Error`]. Supporting types ([`Row`], [`Statement`],
26//! [`types::ToSql`], etc.) match their `tokio_postgres` counterparts.
27//!
28//! Calling query methods directly on [`Database`] uses read-write privileges.
29//! Because calls appear directly on the `static`, Encore can analyze them
30//! statically and grant each service only the permissions it uses.
31//!
32//! Unlike a single `tokio_postgres` client, [`Database`] manages a connection
33//! pool. Operations that require a dedicated connection—such as prepared
34//! statements or `COPY`—are available on [`Connection`] (via
35//! [`Database::acquire`]) and [`Transaction`].
36//!
37//! # References
38//!
39//! Because Encore analyzes database usage statically, a [`Database`] cannot be
40//! passed around by value. To pass a database to helper functions or libraries,
41//! create a [`DatabaseRef`] with the privileges it needs—[`Database::read`],
42//! [`Database::write`], or [`Database::admin`]—which grants that access level
43//! to the service:
44//!
45//! ```no_run
46//! use encore::storage::postgres::{Database, Error, Queryable};
47//!
48//! static DB: Database = Database::named("hello");
49//!
50//! // Library code asks for something to query, as a trait.
51//! async fn count(db: &impl Queryable) -> Result<i64, Error> {
52//!     let row = db.query_one("SELECT count(*) FROM users", &[]).await?;
53//!     Ok(row.get(0))
54//! }
55//!
56//! async fn users() -> Result<i64, Error> {
57//!     count(&DB.read()).await
58//! }
59//! ```
60//!
61//! [`Queryable`] is also implemented by [`Transaction`] and [`Connection`], so
62//! the same helper functions work inside transactions and on acquired
63//! connections. [`Database`] itself does not implement [`Queryable`]:
64//!
65//! ```compile_fail,E0277
66//! # use encore::storage::postgres::{Database, Error, Queryable};
67//! # static DB: Database = Database::named("hello");
68//! # async fn count(db: &impl Queryable) -> Result<i64, Error> {
69//! #     let row = db.query_one("SELECT count(*) FROM users", &[]).await?;
70//! #     Ok(row.get(0))
71//! # }
72//! async fn users() -> Result<i64, Error> {
73//!     count(&DB).await
74//! }
75//! ```
76//!
77//! # Errors
78//!
79//! Failed queries return this module's [`Error`]:
80//!
81//! - [`Error::Database`]: a [`DatabaseError`] reported by Postgres (including
82//!   its SQLSTATE, a typed [`ErrorCode`] for common cases, and optional
83//!   [`ErrorDetails`] such as constraint or table name), or
84//!   [`ErrorCode::ConnectionFailure`] if the database could not be reached.
85//! - [`Error::NoRows`]: `query_one` returned no rows.
86//! - [`Error::TooManyRows`]: `query_one` or `query_opt` returned more than one
87//!   row.
88//! - [`Error::Other`]: a client-side error, such as a parameter type mismatch
89//!   or a value that could not be decoded.
90//!
91//! [`Error`] does not automatically convert into
92//! [`encore::Error`](crate::Error). Match on it where the error kind matters:
93//!
94//! ```no_run
95//! use encore::storage::postgres::{Database, DatabaseError, Error, ErrorCode};
96//!
97//! static DB: Database = Database::named("hello");
98//!
99//! async fn email(id: i64) -> Result<Option<String>, Error> {
100//!     match DB.query_one("SELECT email FROM users WHERE id = $1", &[&id]).await {
101//!         Ok(row) => Ok(Some(row.get("email"))),
102//!         Err(Error::NoRows) => Ok(None),
103//!         Err(err) => Err(err),
104//!     }
105//! }
106//!
107//! async fn add(email: &str) -> Result<bool, Error> {
108//!     match DB.execute("INSERT INTO users (email) VALUES ($1)", &[&email]).await {
109//!         Ok(_) => Ok(true),
110//!         Err(Error::Database(DatabaseError {
111//!             code: ErrorCode::UniqueViolation,
112//!             ..
113//!         })) => Ok(false),
114//!         Err(err) => Err(err),
115//!     }
116//! }
117//! ```
118//!
119//! Where a function returns [`encore::Error`](crate::Error), such as an API
120//! endpoint or Pub/Sub handler, convert it with the appropriate error code:
121//!
122//! ```no_run
123//! # use encore::storage::postgres::Database;
124//! # static DB: Database = Database::named("hello");
125//! async fn record(name: &str) -> Result<(), encore::Error> {
126//!     DB.execute("INSERT INTO users (name) VALUES ($1)", &[&name])
127//!         .await
128//!         .map_err(|e| encore::Error::internal(e.to_string()))?;
129//!     Ok(())
130//! }
131//! ```
132//!
133//! [`tokio_postgres::Client`]: https://docs.rs/tokio-postgres/latest/tokio_postgres/struct.Client.html
134
135mod row;
136#[cfg(test)]
137mod tests;
138pub mod types;
139
140use std::future::Future;
141use std::marker::PhantomData;
142use std::ops::Deref;
143use std::sync::{Arc, OnceLock};
144
145use bytes::Buf;
146use encore_sdk_core::postgres::Access as CoreAccess;
147use encore_sdk_core::postgres::IsolationLevel as CoreIsolationLevel;
148use encore_sdk_core::postgres::{self, Pool, QuerySpan, TransactionOptions};
149
150use crate::runtime::core;
151use crate::testing;
152
153use self::row::{ConnId, StatementRef};
154use self::types::{BorrowToSql, Param, ToSql, Type};
155
156pub use self::row::{Column, Row, RowIndex, RowStream, Statement, ToStatement};
157pub use encore_sdk_core::postgres::{DatabaseError, ErrorCode, ErrorDetails};
158pub use tokio_postgres::{
159    CopyInSink, CopyOutStream, IsolationLevel, SimpleColumn, SimpleQueryMessage, SimpleQueryRow,
160};
161
162/// A Postgres database, backed by a lazily-built connection pool.
163pub struct Database {
164    name: &'static str,
165    /// Read by Encore's parser from the declaration, not by the runtime.
166    #[allow(dead_code)]
167    migrations: Option<&'static str>,
168    pool: OnceLock<Arc<Pool>>,
169}
170
171impl Database {
172    /// Declares a new Postgres database.
173    ///
174    /// This function is `const` so it can initialize a module-scope `static`.
175    /// The connection pool is created on first use. Chain builder methods to
176    /// configure options:
177    ///
178    /// ```no_run
179    /// use encore::storage::postgres::Database;
180    ///
181    /// static DB: Database = Database::new("hello").migrations("./migrations");
182    /// ```
183    pub const fn new(name: &'static str) -> Self {
184        Self {
185            name,
186            migrations: None,
187            pool: OnceLock::new(),
188        }
189    }
190
191    /// References an existing Postgres database by name. To declare a new
192    /// database, use [`Database::new`] instead.
193    ///
194    /// `name` must be a string literal so Encore can resolve it statically.
195    /// Referenced databases take no configuration options; options are set
196    /// where the database is declared.
197    ///
198    /// ```no_run
199    /// use encore::storage::postgres::Database;
200    ///
201    /// static DB: Database = Database::named("hello");
202    /// ```
203    pub const fn named(name: &'static str) -> Self {
204        Self::new(name)
205    }
206
207    /// Sets the directory containing the database's migration files.
208    ///
209    /// `path` must be a slash-separated subdirectory path relative to the file
210    /// declaring the database (for example, `"./migrations"`).
211    ///
212    /// Must be called as part of the `static` declaration.
213    pub const fn migrations(mut self, path: &'static str) -> Self {
214        self.migrations = Some(path);
215        self
216    }
217
218    /// Attaches a classification tag (`key`, `value`) to the database, such as
219    /// `.tag("data", "pci")`, for policy evaluation.
220    ///
221    /// Call once per tag with unique keys. Both `key` and `value` must be
222    /// string literals of at most 63 characters (up to 32 tags per database).
223    /// Keys may contain lowercase letters, digits, `_`, and `-`, must start
224    /// with a letter, and cannot start with `encore` (reserved for Encore).
225    /// Values use the same character set or may be empty.
226    ///
227    /// Must be called as part of the `static` declaration.
228    ///
229    /// ```no_run
230    /// use encore::storage::postgres::Database;
231    ///
232    /// static DB: Database = Database::new("payments")
233    ///     .migrations("./migrations")
234    ///     .tag("data", "pci");
235    /// ```
236    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
237        self
238    }
239
240    /// A handle to the database with admin-level privileges.
241    ///
242    /// `const`, so a handle can initialize a module-scope `static`.
243    pub const fn admin(&'static self) -> DatabaseRef {
244        DatabaseRef {
245            db: self,
246            access: Access::Admin,
247        }
248    }
249
250    /// A handle to the database with read-write privileges.
251    pub const fn write(&'static self) -> DatabaseRef {
252        DatabaseRef {
253            db: self,
254            access: Access::Write,
255        }
256    }
257
258    /// A handle to the database with read-only privileges, which may connect
259    /// to a read replica. To always read from the primary server, use
260    /// [`Database::read_primary`].
261    ///
262    /// ```no_run
263    /// use encore::storage::postgres::{Database, DatabaseRef};
264    ///
265    /// static DB: Database = Database::named("hello");
266    /// static REPORTS: DatabaseRef = DB.read();
267    /// ```
268    pub const fn read(&'static self) -> DatabaseRef {
269        DatabaseRef {
270            db: self,
271            access: Access::Read { primary: false },
272        }
273    }
274
275    /// A handle to the database with read-only privileges that connects to the
276    /// primary server, even if there are read replicas available.
277    pub const fn read_primary(&'static self) -> DatabaseRef {
278        DatabaseRef {
279            db: self,
280            access: Access::Read { primary: true },
281        }
282    }
283
284    /// The pool queries run on: the database's own, or under `encore test` the
285    /// one of the current test's instance of it (see [`crate::testing`]).
286    fn pool(&self) -> Result<Arc<Pool>, Error> {
287        if let Some(test) = testing::active().map_err(test_err)? {
288            return test.database_pool(self.name).map_err(test_err);
289        }
290        if let Some(pool) = self.pool.get() {
291            return Ok(pool.clone());
292        }
293        let pool = core()
294            .postgres()
295            .database(&self.name.into())
296            .new_pool()
297            .map_err(db_err)?;
298        // A concurrent caller may win the race; either way `get` returns a pool.
299        let _ = self.pool.set(Arc::new(pool));
300        Ok(self.pool.get().expect("pool just set").clone())
301    }
302
303    /// Begin a transaction, on a connection of its own from the pool.
304    ///
305    /// The returned [`Transaction`] rolls back when dropped, so an early return
306    /// cannot leave one open. Commit explicitly:
307    ///
308    /// ```ignore
309    /// let tx = DB.transaction().await?;
310    /// tx.execute("INSERT INTO items (name) VALUES ($1)", &[&name]).await?;
311    /// tx.commit().await?;
312    /// ```
313    pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
314        self.begin(CoreAccess::ReadWrite, &TransactionOptions::default())
315            .await
316    }
317
318    /// A builder for a transaction with its characteristics set: isolation
319    /// level, read-only, deferrable.
320    ///
321    /// ```ignore
322    /// let tx = DB.build_transaction()
323    ///     .isolation_level(IsolationLevel::Serializable)
324    ///     .read_only(true)
325    ///     .start()
326    ///     .await?;
327    /// ```
328    pub fn build_transaction(&self) -> TransactionBuilder<'_> {
329        TransactionBuilder::new(Target::Database(self, CoreAccess::ReadWrite))
330    }
331
332    /// The pool a handle with `access` runs on. See [`Pool::with_access`].
333    fn pool_for(&self, access: CoreAccess) -> Result<Pool, Error> {
334        self.pool()?.with_access(access).map_err(db_err)
335    }
336
337    async fn begin(
338        &self,
339        access: CoreAccess,
340        options: &TransactionOptions,
341    ) -> Result<Transaction<'static>, Error> {
342        let pool = self.pool_for(access)?;
343        check_options(options, pool.is_read_only())?;
344        let inner = pool.begin_with_options(options).await.map_err(db_err)?;
345        Ok(Transaction::new(inner, ConnId::new()))
346    }
347
348    /// Acquire a connection from the database's connection pool. It is returned
349    /// to the pool when closed or dropped.
350    pub async fn acquire(&self) -> Result<Connection, Error> {
351        self.acquire_as(CoreAccess::ReadWrite).await
352    }
353
354    async fn acquire_as(&self, access: CoreAccess) -> Result<Connection, Error> {
355        let inner = self.pool_for(access)?.acquire().await.map_err(db_err)?;
356        Ok(Connection {
357            inner,
358            id: ConnId::new(),
359        })
360    }
361
362    /// Returns a read-write Postgres connection string for use with external
363    /// clients.
364    ///
365    /// Connections go through the runtime's local proxy to the database. For a
366    /// read-only connection string, call [`DatabaseRef::connection_string`] on
367    /// a read handle.
368    pub fn connection_string(&self) -> Result<String, Error> {
369        self.connection_string_as(CoreAccess::ReadWrite)
370    }
371
372    fn connection_string_as(&self, access: CoreAccess) -> Result<String, Error> {
373        if let Some(test) = testing::active().map_err(test_err)? {
374            return test
375                .database_connection_string(self.name, access)
376                .map_err(test_err);
377        }
378        Ok(core()
379            .postgres()
380            .database(&self.name.into())
381            .proxy_conn_string(access))
382    }
383}
384
385/// The privileges a [`DatabaseRef`] was made with.
386///
387/// What the service is granted comes from the calls that make the handles,
388/// which Encore's parser reads. Which connections a handle's statements run on
389/// the runtime decides from it: a read handle's are read-only, so a write
390/// fails with `read_only_sql_transaction` (SQLSTATE 25006) and a transaction
391/// is read-only. See [`Pool::with_access`].
392#[derive(Clone, Copy)]
393enum Access {
394    Admin,
395    Write,
396    Read { primary: bool },
397}
398
399impl Access {
400    /// The access the runtime runs the handle's statements with.
401    fn core(self) -> CoreAccess {
402        match self {
403            Access::Admin | Access::Write => CoreAccess::ReadWrite,
404            Access::Read { primary: false } => CoreAccess::Read,
405            Access::Read { primary: true } => CoreAccess::ReadPrimary,
406        }
407    }
408}
409
410/// A handle to a [`Database`] with a fixed privilege level, created by
411/// [`Database::admin`], [`Database::write`], [`Database::read`], or
412/// [`Database::read_primary`].
413///
414/// `DatabaseRef` is `Copy` and can be freely passed to other code. On a read
415/// handle, statements run on read-only connections: writes fail with
416/// `read_only_sql_transaction` (SQLSTATE 25006) and transactions default to
417/// read-only. If no separate read-only pool is configured, the read handle
418/// shares the primary pool with `default_transaction_read_only` enabled; this
419/// prevents accidental writes, though SQL running `SET
420/// default_transaction_read_only = off` on the same connection can bypass it.
421/// Against untrusted code, writes are enforced by the read-only database role.
422///
423/// `DatabaseRef` also implements [`Queryable`], which helper functions can take
424/// instead so they also work inside a [`Transaction`] or on a [`Connection`].
425#[derive(Clone, Copy)]
426pub struct DatabaseRef {
427    db: &'static Database,
428    access: Access,
429}
430
431impl DatabaseRef {
432    /// See [`Database::transaction`]. On a read handle the transaction is
433    /// read-only.
434    pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
435        self.db
436            .begin(self.access.core(), &TransactionOptions::default())
437            .await
438    }
439
440    /// See [`Database::build_transaction`]. On a read handle the transaction
441    /// is read-only: [`TransactionBuilder::start`] refuses
442    /// `read_only(false)`.
443    pub fn build_transaction(&self) -> TransactionBuilder<'static> {
444        TransactionBuilder::new(Target::Database(self.db, self.access.core()))
445    }
446
447    /// See [`Database::acquire`]. On a read handle the connection is
448    /// read-only, as are the transactions begun on it.
449    pub async fn acquire(&self) -> Result<Connection, Error> {
450        self.db.acquire_as(self.access.core()).await
451    }
452
453    /// Returns a Postgres connection string for use with external clients. See
454    /// [`Database::connection_string`].
455    ///
456    /// On a read handle, connections use the read-only pool and role when
457    /// available, or the primary pool otherwise. In either case the session
458    /// starts with `default_transaction_read_only` enabled, so writes fail with
459    /// `read_only_sql_transaction` (SQLSTATE 25006) unless overridden in SQL
460    /// (and the read-only pool's database role rejects writes regardless).
461    pub fn connection_string(&self) -> Result<String, Error> {
462        self.db.connection_string_as(self.access.core())
463    }
464}
465
466/// A dedicated connection acquired from a database pool via
467/// [`Database::acquire`], returned to the pool when closed or dropped.
468///
469/// In addition to the standard query methods, `Connection` supports operations
470/// that require a dedicated connection, such as prepared statements and `COPY`.
471pub struct Connection {
472    inner: postgres::Connection,
473    id: ConnId,
474}
475
476impl Connection {
477    /// Begin a transaction on the connection. The connection is borrowed until
478    /// the transaction ends, and stays acquired afterwards.
479    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
480        self.begin(&TransactionOptions::default()).await
481    }
482
483    /// A builder for a transaction with its characteristics set. See
484    /// [`Database::build_transaction`].
485    pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
486        TransactionBuilder::new(Target::Connection(self))
487    }
488
489    async fn begin(&mut self, options: &TransactionOptions) -> Result<Transaction<'_>, Error> {
490        check_options(options, self.inner.is_read_only())?;
491        let inner = self
492            .inner
493            .begin_with_options(options)
494            .await
495            .map_err(db_err)?;
496        Ok(Transaction::new(inner, self.id))
497    }
498
499    /// Whether the connection is closed: by [`Connection::close`], or because
500    /// the server ended it.
501    pub fn is_closed(&self) -> bool {
502        self.inner.is_closed()
503    }
504
505    /// Close the connection, returning it to the pool. Dropping does the same
506    /// thing.
507    pub async fn close(self) {
508        self.inner.close().await;
509    }
510}
511
512/// An open transaction. Rolls back on drop unless [`Transaction::commit`] is
513/// called.
514///
515/// One begun on a [`Connection`] borrows it until the transaction ends.
516pub struct Transaction<'c> {
517    inner: postgres::Transaction,
518    id: ConnId,
519    conn: PhantomData<&'c mut Connection>,
520}
521
522impl Transaction<'_> {
523    fn new(inner: postgres::Transaction, id: ConnId) -> Self {
524        Self {
525            inner,
526            id,
527            conn: PhantomData,
528        }
529    }
530
531    /// Commit the transaction.
532    pub async fn commit(self) -> Result<(), Error> {
533        self.inner.commit().await.map_err(db_err)
534    }
535
536    /// Roll the transaction back explicitly. Dropping does the same thing.
537    pub async fn rollback(self) -> Result<(), Error> {
538        self.inner.rollback().await.map_err(db_err)
539    }
540}
541
542/// Refuses options a transaction can't have: on a read-only connection, as
543/// a read handle's are, `read_only(false)`.
544fn check_options(options: &TransactionOptions, read_only: bool) -> Result<(), Error> {
545    if read_only && options.read_only == Some(false) {
546        return Err(Error::other(
547            "a read handle's transactions are read-only: read_only(false) is not allowed",
548        ));
549    }
550    Ok(())
551}
552
553/// What a [`TransactionBuilder`] begins its transaction on.
554enum Target<'a> {
555    /// A connection of its own, for a handle with the access.
556    Database(&'a Database, CoreAccess),
557    Connection(&'a mut Connection),
558}
559
560/// A builder for a transaction with its characteristics set, made by
561/// `build_transaction`.
562pub struct TransactionBuilder<'a> {
563    target: Target<'a>,
564    isolation_level: Option<IsolationLevel>,
565    read_only: Option<bool>,
566    deferrable: Option<bool>,
567}
568
569impl<'a> TransactionBuilder<'a> {
570    fn new(target: Target<'a>) -> Self {
571        Self {
572            target,
573            isolation_level: None,
574            read_only: None,
575            deferrable: None,
576        }
577    }
578
579    /// Sets the isolation level of the transaction.
580    pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self {
581        self.isolation_level = Some(isolation_level);
582        self
583    }
584
585    /// Sets the access mode of the transaction.
586    pub fn read_only(mut self, read_only: bool) -> Self {
587        self.read_only = Some(read_only);
588        self
589    }
590
591    /// Sets the deferrability of the transaction.
592    ///
593    /// It has an effect only on a transaction that is also `SERIALIZABLE` and
594    /// `READ ONLY`.
595    pub fn deferrable(mut self, deferrable: bool) -> Self {
596        self.deferrable = Some(deferrable);
597        self
598    }
599
600    /// Begins the transaction.
601    ///
602    /// On a read handle, or a connection one acquired, the transaction is
603    /// read-only, and `read_only(false)` is an `InvalidArgument` error.
604    pub async fn start(self) -> Result<Transaction<'a>, Error> {
605        let options = self.options()?;
606        match self.target {
607            Target::Database(db, access) => db.begin(access, &options).await,
608            Target::Connection(conn) => conn.begin(&options).await,
609        }
610    }
611
612    fn options(&self) -> Result<TransactionOptions, Error> {
613        let isolation = self
614            .isolation_level
615            .map(|level| match level {
616                IsolationLevel::ReadUncommitted => Ok(CoreIsolationLevel::ReadUncommitted),
617                IsolationLevel::ReadCommitted => Ok(CoreIsolationLevel::ReadCommitted),
618                IsolationLevel::RepeatableRead => Ok(CoreIsolationLevel::RepeatableRead),
619                IsolationLevel::Serializable => Ok(CoreIsolationLevel::Serializable),
620                _ => Err(Error::other("unsupported isolation level")),
621            })
622            .transpose()?;
623        Ok(TransactionOptions {
624            isolation,
625            read_only: self.read_only,
626            deferrable: self.deferrable,
627        })
628    }
629}
630
631/// What a statement runs on.
632#[derive(Clone, Copy)]
633enum On<'a> {
634    /// A connection of the pool, for a handle with the access.
635    Database(&'a Database, CoreAccess),
636    Connection(&'a Connection),
637    Transaction(&'a postgres::Transaction, ConnId),
638}
639
640/// The client a statement runs on, for as long as it takes to send it.
641enum Client<'a> {
642    /// Taken from the pool, and returned to it when dropped.
643    Pooled(postgres::PooledClient),
644    Connection(postgres::ConnClient<'a>),
645    Transaction(&'a postgres::Transaction),
646}
647
648impl Deref for Client<'_> {
649    type Target = tokio_postgres::Client;
650
651    fn deref(&self) -> &Self::Target {
652        match self {
653            Client::Pooled(client) => client,
654            Client::Connection(client) => client,
655            Client::Transaction(tx) => tx.client(),
656        }
657    }
658}
659
660impl<'a> On<'a> {
661    /// The client to run `statement` on, told it will, so that one that may
662    /// change the session's access mode has the next checkout set it again.
663    async fn client(self, statement: &str) -> Result<Client<'a>, Error> {
664        let client = match self {
665            On::Database(db, access) => db.pool_for(access)?.client().await.map(Client::Pooled),
666            On::Connection(conn) => conn.inner.client().await.map(Client::Connection),
667            On::Transaction(tx, _) => Ok(Client::Transaction(tx)),
668        }
669        .map_err(db_err)?;
670        match &client {
671            Client::Pooled(client) => client.will_run(statement),
672            Client::Connection(client) => client.will_run(statement),
673            Client::Transaction(tx) => tx.will_run(statement),
674        }
675        Ok(client)
676    }
677
678    /// Starts the trace span of a query.
679    fn span(self, query: &str) -> Result<QuerySpan, Error> {
680        Ok(match self {
681            On::Database(db, _) => db.pool()?.query_span(query),
682            On::Connection(conn) => conn.inner.query_span(query),
683            On::Transaction(tx, _) => tx.query_span(query),
684        })
685    }
686
687    /// The connection prepared statements belong to, if this is one.
688    fn conn(self) -> Option<ConnId> {
689        match self {
690            On::Database(..) => None,
691            On::Connection(conn) => Some(conn.id),
692            On::Transaction(_, id) => Some(id),
693        }
694    }
695}
696
697impl Database {
698    fn on(&self) -> On<'_> {
699        On::Database(self, CoreAccess::ReadWrite)
700    }
701}
702
703impl DatabaseRef {
704    fn on(&self) -> On<'_> {
705        On::Database(self.db, self.access.core())
706    }
707}
708
709impl Connection {
710    fn on(&self) -> On<'_> {
711        On::Connection(self)
712    }
713}
714
715impl Transaction<'_> {
716    fn on(&self) -> On<'_> {
717        On::Transaction(&self.inner, self.id)
718    }
719}
720
721/// The statement implementations, written once. Each runs under a query span.
722mod ops {
723    use super::*;
724
725    /// The parameters of a statement, as `tokio_postgres` takes them.
726    pub type Params<'a> = Vec<Param<&'a (dyn ToSql + Sync)>>;
727
728    pub fn params<'a>(params: &[&'a (dyn ToSql + Sync)]) -> Params<'a> {
729        params.iter().map(|p| Param(*p)).collect()
730    }
731
732    /// Ends `span` with the outcome of a query.
733    fn finish<T>(span: QuerySpan, result: Result<T, Error>) -> Result<T, Error> {
734        span.end(result.as_ref().err());
735        result
736    }
737
738    /// The statement to run on `client`: a query string prepared there, or a
739    /// statement the connection prepared earlier.
740    async fn resolve(
741        on: On<'_>,
742        client: &tokio_postgres::Client,
743        statement: StatementRef<'_>,
744    ) -> Result<tokio_postgres::Statement, Error> {
745        match statement {
746            StatementRef::Query(query) => client.prepare(query).await.map_err(db_err),
747            StatementRef::Statement(statement) if on.conn() == Some(statement.conn) => {
748                Ok(statement.inner.clone())
749            }
750            StatementRef::Statement(_) => Err(Error::other(
751                "a prepared statement can only be used on the connection that prepared it, \
752                 or in a transaction on that connection",
753            )),
754        }
755    }
756
757    pub async fn query_raw<T, P, I>(
758        on: On<'_>,
759        statement: &T,
760        params: I,
761    ) -> Result<RowStream, Error>
762    where
763        T: ?Sized + ToStatement,
764        P: BorrowToSql,
765        I: IntoIterator<Item = P>,
766        I::IntoIter: ExactSizeIterator,
767    {
768        let statement = statement.__convert();
769        let span = on.span(statement.text())?;
770        let result = async {
771            let client = on.client(statement.text()).await?;
772            let statement = resolve(on, &client, statement).await?;
773            client
774                .query_raw(&statement, params.into_iter().map(Param))
775                .await
776                .map(RowStream::new)
777                .map_err(db_err)
778        }
779        .await;
780        finish(span, result)
781    }
782
783    /// `query_raw`, for parameters already converted.
784    async fn query_stream(
785        on: On<'_>,
786        statement: StatementRef<'_>,
787        params: Params<'_>,
788    ) -> Result<RowStream, Error> {
789        let span = on.span(statement.text())?;
790        let result = async {
791            let client = on.client(statement.text()).await?;
792            let statement = resolve(on, &client, statement).await?;
793            client
794                .query_raw(&statement, params)
795                .await
796                .map(RowStream::new)
797                .map_err(db_err)
798        }
799        .await;
800        finish(span, result)
801    }
802
803    async fn collect(mut stream: RowStream) -> Result<Vec<Row>, Error> {
804        let mut rows = Vec::new();
805        while let Some(row) = stream.next().await {
806            rows.push(row?);
807        }
808        Ok(rows)
809    }
810
811    pub async fn query(
812        on: On<'_>,
813        statement: StatementRef<'_>,
814        params: Params<'_>,
815    ) -> Result<Vec<Row>, Error> {
816        collect(query_stream(on, statement, params).await?).await
817    }
818
819    pub async fn query_opt(
820        on: On<'_>,
821        statement: StatementRef<'_>,
822        params: Params<'_>,
823    ) -> Result<Option<Row>, Error> {
824        let mut stream = query_stream(on, statement, params).await?;
825        let Some(first) = stream.next().await.transpose()? else {
826            return Ok(None);
827        };
828        if stream.next().await.transpose()?.is_some() {
829            return Err(Error::TooManyRows);
830        }
831        Ok(Some(first))
832    }
833
834    pub async fn query_one(
835        on: On<'_>,
836        statement: StatementRef<'_>,
837        params: Params<'_>,
838    ) -> Result<Row, Error> {
839        query_opt(on, statement, params).await?.ok_or(Error::NoRows)
840    }
841
842    pub async fn query_typed_raw<P, I>(
843        on: On<'_>,
844        query: &str,
845        params: I,
846    ) -> Result<RowStream, Error>
847    where
848        P: BorrowToSql,
849        I: IntoIterator<Item = (P, Type)>,
850    {
851        let span = on.span(query)?;
852        let result = async {
853            let client = on.client(query).await?;
854            client
855                .query_typed_raw(query, params.into_iter().map(|(p, ty)| (Param(p), ty)))
856                .await
857                .map(RowStream::new)
858                .map_err(db_err)
859        }
860        .await;
861        finish(span, result)
862    }
863
864    pub async fn query_typed(
865        on: On<'_>,
866        query: &str,
867        params: Vec<(Param<&(dyn ToSql + Sync)>, Type)>,
868    ) -> Result<Vec<Row>, Error> {
869        let span = on.span(query)?;
870        let result = async {
871            let client = on.client(query).await?;
872            client
873                .query_typed_raw(query, params)
874                .await
875                .map(RowStream::new)
876                .map_err(db_err)
877        }
878        .await;
879        collect(finish(span, result)?).await
880    }
881
882    pub async fn execute_raw<T, P, I>(on: On<'_>, statement: &T, params: I) -> Result<u64, Error>
883    where
884        T: ?Sized + ToStatement,
885        P: BorrowToSql,
886        I: IntoIterator<Item = P>,
887        I::IntoIter: ExactSizeIterator,
888    {
889        let statement = statement.__convert();
890        let span = on.span(statement.text())?;
891        let result = async {
892            let client = on.client(statement.text()).await?;
893            let statement = resolve(on, &client, statement).await?;
894            client
895                .execute_raw(&statement, params.into_iter().map(Param))
896                .await
897                .map_err(db_err)
898        }
899        .await;
900        finish(span, result)
901    }
902
903    pub async fn execute(
904        on: On<'_>,
905        statement: StatementRef<'_>,
906        params: Params<'_>,
907    ) -> Result<u64, Error> {
908        let span = on.span(statement.text())?;
909        let result = async {
910            let client = on.client(statement.text()).await?;
911            let statement = resolve(on, &client, statement).await?;
912            client.execute_raw(&statement, params).await.map_err(db_err)
913        }
914        .await;
915        finish(span, result)
916    }
917
918    pub async fn simple_query(on: On<'_>, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
919        let span = on.span(query)?;
920        let result = async {
921            let client = on.client(query).await?;
922            client.simple_query(query).await.map_err(db_err)
923        }
924        .await;
925        finish(span, result)
926    }
927
928    pub async fn batch_execute(on: On<'_>, query: &str) -> Result<(), Error> {
929        let span = on.span(query)?;
930        let result = async {
931            let client = on.client(query).await?;
932            client.batch_execute(query).await.map_err(db_err)
933        }
934        .await;
935        finish(span, result)
936    }
937
938    pub async fn prepare(on: On<'_>, query: &str, types: &[Type]) -> Result<Statement, Error> {
939        let conn = on.conn().expect("only a connection prepares statements");
940        let client = on.client(query).await?;
941        let inner = client.prepare_typed(query, types).await.map_err(db_err)?;
942        Ok(Statement {
943            inner,
944            conn,
945            query: query.into(),
946        })
947    }
948
949    pub async fn copy_in<U>(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyInSink<U>, Error>
950    where
951        U: Buf + 'static + Send,
952    {
953        let span = on.span(statement.text())?;
954        let result = async {
955            let client = on.client(statement.text()).await?;
956            let statement = resolve(on, &client, statement).await?;
957            client.copy_in(&statement).await.map_err(db_err)
958        }
959        .await;
960        finish(span, result)
961    }
962
963    pub async fn copy_out(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyOutStream, Error> {
964        let span = on.span(statement.text())?;
965        let result = async {
966            let client = on.client(statement.text()).await?;
967            let statement = resolve(on, &client, statement).await?;
968            client.copy_out(&statement).await.map_err(db_err)
969        }
970        .await;
971        finish(span, result)
972    }
973}
974
975/// A type that can execute Postgres queries: [`DatabaseRef`], [`Transaction`],
976/// or [`Connection`].
977///
978/// Accept `&impl Queryable` in helper functions so they work with databases,
979/// transactions, and acquired connections alike. [`Database`] itself does not
980/// implement `Queryable`; pass a [`DatabaseRef`] with the required privileges
981/// instead.
982pub trait Queryable: Send + Sync {
983    /// See [`Database::execute`].
984    fn execute<T>(
985        &self,
986        statement: &T,
987        params: &[&(dyn ToSql + Sync)],
988    ) -> impl Future<Output = Result<u64, Error>> + Send
989    where
990        T: ?Sized + ToStatement;
991
992    /// See [`Database::execute_raw`].
993    fn execute_raw<T, P, I>(
994        &self,
995        statement: &T,
996        params: I,
997    ) -> impl Future<Output = Result<u64, Error>> + Send
998    where
999        T: ?Sized + ToStatement,
1000        P: BorrowToSql + Send,
1001        I: IntoIterator<Item = P> + Send,
1002        I::IntoIter: ExactSizeIterator + Send;
1003
1004    /// See [`Database::query`].
1005    fn query<T>(
1006        &self,
1007        statement: &T,
1008        params: &[&(dyn ToSql + Sync)],
1009    ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1010    where
1011        T: ?Sized + ToStatement;
1012
1013    /// See [`Database::query_one`].
1014    fn query_one<T>(
1015        &self,
1016        statement: &T,
1017        params: &[&(dyn ToSql + Sync)],
1018    ) -> impl Future<Output = Result<Row, Error>> + Send
1019    where
1020        T: ?Sized + ToStatement;
1021
1022    /// See [`Database::query_opt`].
1023    fn query_opt<T>(
1024        &self,
1025        statement: &T,
1026        params: &[&(dyn ToSql + Sync)],
1027    ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1028    where
1029        T: ?Sized + ToStatement;
1030
1031    /// See [`Database::query_raw`].
1032    fn query_raw<T, P, I>(
1033        &self,
1034        statement: &T,
1035        params: I,
1036    ) -> impl Future<Output = Result<RowStream, Error>> + Send
1037    where
1038        T: ?Sized + ToStatement,
1039        P: BorrowToSql + Send,
1040        I: IntoIterator<Item = P> + Send,
1041        I::IntoIter: ExactSizeIterator + Send;
1042
1043    /// See [`Database::query_typed`].
1044    fn query_typed(
1045        &self,
1046        query: &str,
1047        params: &[(&(dyn ToSql + Sync), Type)],
1048    ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send;
1049
1050    /// See [`Database::query_typed_raw`].
1051    fn query_typed_raw<P, I>(
1052        &self,
1053        query: &str,
1054        params: I,
1055    ) -> impl Future<Output = Result<RowStream, Error>> + Send
1056    where
1057        P: BorrowToSql + Send,
1058        I: IntoIterator<Item = (P, Type)> + Send,
1059        I::IntoIter: Send;
1060
1061    /// See [`Database::simple_query`].
1062    fn simple_query(
1063        &self,
1064        query: &str,
1065    ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send;
1066
1067    /// See [`Database::batch_execute`].
1068    fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
1069}
1070
1071/// The query methods, on each type queries run on. Documented once, on
1072/// [`Database`]; the others refer there.
1073macro_rules! query_methods {
1074    ($ty:ty) => {
1075        impl $ty {
1076            /// Executes a statement, returning the resulting rows.
1077            ///
1078            /// A statement may contain parameters, written `$1`, `$2`, … and
1079            /// given in `params`. That is the way to pass values: it keeps
1080            /// them out of the SQL text.
1081            ///
1082            /// ```ignore
1083            /// for row in DB.query("SELECT name FROM users WHERE age > $1", &[&18]).await? {
1084            ///     let name: String = row.get("name");
1085            /// }
1086            /// ```
1087            pub async fn query<T>(
1088                &self,
1089                statement: &T,
1090                params: &[&(dyn ToSql + Sync)],
1091            ) -> Result<Vec<Row>, Error>
1092            where
1093                T: ?Sized + ToStatement,
1094            {
1095                ops::query(self.on(), statement.__convert(), ops::params(params)).await
1096            }
1097
1098            /// Executes a statement which returns a single row, returning it.
1099            ///
1100            /// Returns an error if the query does not return exactly one row.
1101            pub async fn query_one<T>(
1102                &self,
1103                statement: &T,
1104                params: &[&(dyn ToSql + Sync)],
1105            ) -> Result<Row, Error>
1106            where
1107                T: ?Sized + ToStatement,
1108            {
1109                ops::query_one(self.on(), statement.__convert(), ops::params(params)).await
1110            }
1111
1112            /// Executes a statement which returns zero or one rows, returning
1113            /// it.
1114            ///
1115            /// Returns an error if the query returns more than one row.
1116            pub async fn query_opt<T>(
1117                &self,
1118                statement: &T,
1119                params: &[&(dyn ToSql + Sync)],
1120            ) -> Result<Option<Row>, Error>
1121            where
1122                T: ?Sized + ToStatement,
1123            {
1124                ops::query_opt(self.on(), statement.__convert(), ops::params(params)).await
1125            }
1126
1127            /// The maximally flexible version of `query`: the parameters are
1128            /// an iterator, and the rows come as a stream rather than
1129            /// collected.
1130            pub async fn query_raw<T, P, I>(
1131                &self,
1132                statement: &T,
1133                params: I,
1134            ) -> Result<RowStream, Error>
1135            where
1136                T: ?Sized + ToStatement,
1137                P: BorrowToSql,
1138                I: IntoIterator<Item = P>,
1139                I::IntoIter: ExactSizeIterator,
1140            {
1141                ops::query_raw(self.on(), statement, params).await
1142            }
1143
1144            /// Like `query`, but with the types of the parameters given, so
1145            /// the query needs no round trip to prepare it.
1146            pub async fn query_typed(
1147                &self,
1148                query: &str,
1149                params: &[(&(dyn ToSql + Sync), Type)],
1150            ) -> Result<Vec<Row>, Error> {
1151                let params = params
1152                    .iter()
1153                    .map(|(p, ty)| (Param(*p), ty.clone()))
1154                    .collect();
1155                ops::query_typed(self.on(), query, params).await
1156            }
1157
1158            /// The maximally flexible version of `query_typed`.
1159            pub async fn query_typed_raw<P, I>(
1160                &self,
1161                query: &str,
1162                params: I,
1163            ) -> Result<RowStream, Error>
1164            where
1165                P: BorrowToSql,
1166                I: IntoIterator<Item = (P, Type)>,
1167            {
1168                ops::query_typed_raw(self.on(), query, params).await
1169            }
1170
1171            /// Executes a statement, returning the number of rows modified.
1172            ///
1173            /// If the statement does not modify any rows (e.g. `SELECT`), 0
1174            /// is returned.
1175            pub async fn execute<T>(
1176                &self,
1177                statement: &T,
1178                params: &[&(dyn ToSql + Sync)],
1179            ) -> Result<u64, Error>
1180            where
1181                T: ?Sized + ToStatement,
1182            {
1183                ops::execute(self.on(), statement.__convert(), ops::params(params)).await
1184            }
1185
1186            /// The maximally flexible version of `execute`.
1187            pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
1188            where
1189                T: ?Sized + ToStatement,
1190                P: BorrowToSql,
1191                I: IntoIterator<Item = P>,
1192                I::IntoIter: ExactSizeIterator,
1193            {
1194                ops::execute_raw(self.on(), statement, params).await
1195            }
1196
1197            /// Executes a sequence of SQL statements using the simple query
1198            /// protocol, returning the resulting rows, with every value as
1199            /// text.
1200            ///
1201            /// The statements, separated by semicolons, take no parameters:
1202            /// never build the query from untrusted input.
1203            pub async fn simple_query(
1204                &self,
1205                query: &str,
1206            ) -> Result<Vec<SimpleQueryMessage>, Error> {
1207                ops::simple_query(self.on(), query).await
1208            }
1209
1210            /// Executes a sequence of SQL statements using the simple query
1211            /// protocol, stopping at the first error.
1212            ///
1213            /// The statements, separated by semicolons, take no parameters:
1214            /// never build the query from untrusted input.
1215            pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
1216                ops::batch_execute(self.on(), query).await
1217            }
1218        }
1219    };
1220}
1221
1222/// [`Queryable`], for a type with the [`query_methods!`].
1223macro_rules! queryable {
1224    ($ty:ty) => {
1225        impl Queryable for $ty {
1226            fn execute<T>(
1227                &self,
1228                statement: &T,
1229                params: &[&(dyn ToSql + Sync)],
1230            ) -> impl Future<Output = Result<u64, Error>> + Send
1231            where
1232                T: ?Sized + ToStatement,
1233            {
1234                <$ty>::execute(self, statement, params)
1235            }
1236
1237            fn execute_raw<T, P, I>(
1238                &self,
1239                statement: &T,
1240                params: I,
1241            ) -> impl Future<Output = Result<u64, Error>> + Send
1242            where
1243                T: ?Sized + ToStatement,
1244                P: BorrowToSql + Send,
1245                I: IntoIterator<Item = P> + Send,
1246                I::IntoIter: ExactSizeIterator + Send,
1247            {
1248                <$ty>::execute_raw(self, statement, params)
1249            }
1250
1251            fn query<T>(
1252                &self,
1253                statement: &T,
1254                params: &[&(dyn ToSql + Sync)],
1255            ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1256            where
1257                T: ?Sized + ToStatement,
1258            {
1259                <$ty>::query(self, statement, params)
1260            }
1261
1262            fn query_one<T>(
1263                &self,
1264                statement: &T,
1265                params: &[&(dyn ToSql + Sync)],
1266            ) -> impl Future<Output = Result<Row, Error>> + Send
1267            where
1268                T: ?Sized + ToStatement,
1269            {
1270                <$ty>::query_one(self, statement, params)
1271            }
1272
1273            fn query_opt<T>(
1274                &self,
1275                statement: &T,
1276                params: &[&(dyn ToSql + Sync)],
1277            ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1278            where
1279                T: ?Sized + ToStatement,
1280            {
1281                <$ty>::query_opt(self, statement, params)
1282            }
1283
1284            fn query_raw<T, P, I>(
1285                &self,
1286                statement: &T,
1287                params: I,
1288            ) -> impl Future<Output = Result<RowStream, Error>> + Send
1289            where
1290                T: ?Sized + ToStatement,
1291                P: BorrowToSql + Send,
1292                I: IntoIterator<Item = P> + Send,
1293                I::IntoIter: ExactSizeIterator + Send,
1294            {
1295                <$ty>::query_raw(self, statement, params)
1296            }
1297
1298            fn query_typed(
1299                &self,
1300                query: &str,
1301                params: &[(&(dyn ToSql + Sync), Type)],
1302            ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send {
1303                <$ty>::query_typed(self, query, params)
1304            }
1305
1306            fn query_typed_raw<P, I>(
1307                &self,
1308                query: &str,
1309                params: I,
1310            ) -> impl Future<Output = Result<RowStream, Error>> + Send
1311            where
1312                P: BorrowToSql + Send,
1313                I: IntoIterator<Item = (P, Type)> + Send,
1314                I::IntoIter: Send,
1315            {
1316                <$ty>::query_typed_raw(self, query, params)
1317            }
1318
1319            fn simple_query(
1320                &self,
1321                query: &str,
1322            ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send {
1323                <$ty>::simple_query(self, query)
1324            }
1325
1326            fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
1327                <$ty>::batch_execute(self, query)
1328            }
1329        }
1330    };
1331}
1332
1333/// What needs a connection of its own, on the types that are one.
1334macro_rules! connection_methods {
1335    ($ty:ty) => {
1336        impl $ty {
1337            /// Creates a new prepared statement.
1338            ///
1339            /// A prepared statement is parsed and planned once, and can then
1340            /// be run repeatedly, with different parameters each time. It
1341            /// belongs to this connection, and can only be used on it.
1342            pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
1343                ops::prepare(self.on(), query, &[]).await
1344            }
1345
1346            /// Like `prepare`, but with the types of the statement's
1347            /// parameters given, rather than left to Postgres to infer.
1348            pub async fn prepare_typed(
1349                &self,
1350                query: &str,
1351                parameter_types: &[Type],
1352            ) -> Result<Statement, Error> {
1353                ops::prepare(self.on(), query, parameter_types).await
1354            }
1355
1356            /// Executes a `COPY FROM STDIN` statement, returning a sink to
1357            /// write the copy data to.
1358            ///
1359            /// The copy is aborted if the sink is dropped without being
1360            /// finished.
1361            pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
1362            where
1363                T: ?Sized + ToStatement,
1364                U: Buf + 'static + Send,
1365            {
1366                ops::copy_in(self.on(), statement.__convert()).await
1367            }
1368
1369            /// Executes a `COPY TO STDOUT` statement, returning a stream of
1370            /// the resulting data.
1371            pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
1372            where
1373                T: ?Sized + ToStatement,
1374            {
1375                ops::copy_out(self.on(), statement.__convert()).await
1376            }
1377        }
1378    };
1379}
1380
1381query_methods!(Database);
1382query_methods!(DatabaseRef);
1383query_methods!(Connection);
1384query_methods!(Transaction<'_>);
1385
1386queryable!(DatabaseRef);
1387queryable!(Connection);
1388queryable!(Transaction<'_>);
1389
1390connection_methods!(Connection);
1391connection_methods!(Transaction<'_>);
1392
1393/// Errors returned by Postgres operations. See the [module docs](self#errors).
1394///
1395/// Does not convert automatically into [`encore::Error`](crate::Error); map it
1396/// to the appropriate error code at API boundaries.
1397#[derive(Debug, thiserror::Error)]
1398#[non_exhaustive]
1399pub enum Error {
1400    /// An error reported by Postgres, or a connection failure
1401    /// ([`ErrorCode::ConnectionFailure`], SQLSTATE `08001`).
1402    #[error(transparent)]
1403    Database(#[from] DatabaseError),
1404    /// `query_one` returned no rows.
1405    #[error("query returned no rows")]
1406    NoRows,
1407    /// `query_one` or `query_opt` returned more than one row.
1408    #[error("query returned more than one row")]
1409    TooManyRows,
1410    /// A client-side error, such as a parameter type mismatch, requesting a
1411    /// read-write transaction on a read handle, or failing to decode a value.
1412    #[error(transparent)]
1413    Other(Box<dyn std::error::Error + Send + Sync>),
1414}
1415
1416impl Error {
1417    /// The error the database reported, or the failure to reach it; `None`
1418    /// for the other kinds.
1419    pub fn database_error(&self) -> Option<&DatabaseError> {
1420        match self {
1421            Error::Database(err) => Some(err),
1422            _ => None,
1423        }
1424    }
1425
1426    /// An [`Error::Other`] with `message`.
1427    fn other(message: impl Into<String>) -> Self {
1428        Error::Other(message.into().into())
1429    }
1430}
1431
1432/// `err` as this module's error: a [`DatabaseError`] if the database
1433/// reported it or could not be reached, and otherwise [`Error::Other`].
1434fn db_err(err: impl Into<DbFailure>) -> Error {
1435    match err.into() {
1436        DbFailure::Client(err) => match DatabaseError::from_client_error(&err) {
1437            Some(db) => db.into(),
1438            None => Error::Other(Box::new(err)),
1439        },
1440        DbFailure::Core(err) => match err.database_error() {
1441            Some(db) => db.into(),
1442            None => Error::other(err.to_string()),
1443        },
1444        // A database that is not configured, or whose pool could not be
1445        // built, can't be reached.
1446        DbFailure::Config(err) => DatabaseError::connection_failure(format!("{err:#}")).into(),
1447    }
1448}
1449
1450/// `err`, from setting up the current test's instance of a database under
1451/// `encore test`, as this module's error.
1452fn test_err(err: crate::Error) -> Error {
1453    Error::Other(Box::new(err))
1454}
1455
1456/// An error a database operation failed with, of the kinds [`db_err`] reads.
1457enum DbFailure {
1458    Client(tokio_postgres::Error),
1459    Core(postgres::Error),
1460    Config(anyhow::Error),
1461}
1462
1463impl From<tokio_postgres::Error> for DbFailure {
1464    fn from(err: tokio_postgres::Error) -> Self {
1465        DbFailure::Client(err)
1466    }
1467}
1468
1469impl From<postgres::Error> for DbFailure {
1470    fn from(err: postgres::Error) -> Self {
1471        DbFailure::Core(err)
1472    }
1473}
1474
1475impl From<anyhow::Error> for DbFailure {
1476    fn from(err: anyhow::Error) -> Self {
1477        DbFailure::Config(err)
1478    }
1479}