Skip to main content

encore/storage/postgres/
mod.rs

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