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 Client<'_> {
661    /// `query` prepared on the connection, which keeps it: see
662    /// [`postgres::PooledClient::prepare_cached`].
663    async fn prepare_cached(
664        &self,
665        query: &str,
666    ) -> Result<tokio_postgres::Statement, tokio_postgres::Error> {
667        match self {
668            Client::Pooled(client) => client.prepare_cached(query).await,
669            Client::Connection(client) => client.prepare_cached(query).await,
670            Client::Transaction(tx) => tx.prepare_cached(query).await,
671        }
672    }
673
674    /// Runs `query`'s statement with `run`, prepared as
675    /// [`Self::prepare_cached`] does. Should the connection have kept one
676    /// that proves stale, it is prepared again and run once more, unless in
677    /// a transaction: see [`postgres::PooledClient::run_cached`].
678    async fn run_cached<T, F, Fut>(&self, query: &str, run: F) -> Result<T, tokio_postgres::Error>
679    where
680        F: Fn(tokio_postgres::Statement) -> Fut,
681        Fut: Future<Output = Result<T, tokio_postgres::Error>>,
682    {
683        match self {
684            Client::Pooled(client) => client.run_cached(query, run).await,
685            Client::Connection(client) => client.run_cached(query, run).await,
686            Client::Transaction(tx) => tx.run_cached(query, run).await,
687        }
688    }
689
690    /// Notes that running a statement failed with `err`, so that one the
691    /// connection kept that proves stale is prepared again.
692    fn statement_failed(&self, err: &tokio_postgres::Error) {
693        match self {
694            Client::Pooled(client) => client.statement_failed(err),
695            Client::Connection(client) => client.statement_failed(err),
696            Client::Transaction(tx) => tx.statement_failed(err),
697        };
698    }
699}
700
701impl<'a> On<'a> {
702    /// The client to run `statement` on, told it will, so that one that may
703    /// change the session's access mode has the next checkout set it again.
704    async fn client(self, statement: &str) -> Result<Client<'a>, Error> {
705        let client = match self {
706            On::Database(db, access) => db.pool_for(access)?.client().await.map(Client::Pooled),
707            On::Connection(conn) => conn.inner.client().await.map(Client::Connection),
708            On::Transaction(tx, _) => Ok(Client::Transaction(tx)),
709        }
710        .map_err(db_err)?;
711        match &client {
712            Client::Pooled(client) => client.will_run(statement),
713            Client::Connection(client) => client.will_run(statement),
714            Client::Transaction(tx) => tx.will_run(statement),
715        }
716        Ok(client)
717    }
718
719    /// Starts the trace span of a query.
720    fn span(self, query: &str) -> Result<QuerySpan, Error> {
721        Ok(match self {
722            On::Database(db, _) => db.pool()?.query_span(query),
723            On::Connection(conn) => conn.inner.query_span(query),
724            On::Transaction(tx, _) => tx.query_span(query),
725        })
726    }
727
728    /// The connection prepared statements belong to, if this is one.
729    fn conn(self) -> Option<ConnId> {
730        match self {
731            On::Database(..) => None,
732            On::Connection(conn) => Some(conn.id),
733            On::Transaction(_, id) => Some(id),
734        }
735    }
736}
737
738impl Database {
739    fn on(&self) -> On<'_> {
740        On::Database(self, CoreAccess::ReadWrite)
741    }
742}
743
744impl DatabaseRef {
745    fn on(&self) -> On<'_> {
746        On::Database(self.db, self.access.core())
747    }
748}
749
750impl Connection {
751    fn on(&self) -> On<'_> {
752        On::Connection(self)
753    }
754}
755
756impl Transaction<'_> {
757    fn on(&self) -> On<'_> {
758        On::Transaction(&self.inner, self.id)
759    }
760}
761
762/// The statement implementations, written once. Each runs under a query span.
763mod ops {
764    use super::*;
765
766    /// The parameters of a statement, as `tokio_postgres` takes them.
767    pub type Params<'a> = Vec<Param<&'a (dyn ToSql + Sync)>>;
768
769    pub fn params<'a>(params: &[&'a (dyn ToSql + Sync)]) -> Params<'a> {
770        params.iter().map(|p| Param(*p)).collect()
771    }
772
773    /// Ends `span` with the outcome of a query.
774    fn finish<T>(span: QuerySpan, result: Result<T, Error>) -> Result<T, Error> {
775        span.end(result.as_ref().err());
776        result
777    }
778
779    /// The statement to run on `client`: a query string prepared there, or a
780    /// statement the connection prepared earlier.
781    async fn resolve(
782        on: On<'_>,
783        client: &Client<'_>,
784        statement: StatementRef<'_>,
785    ) -> Result<tokio_postgres::Statement, Error> {
786        match statement {
787            StatementRef::Query(query) => client.prepare_cached(query).await.map_err(db_err),
788            StatementRef::Statement(statement) if on.conn() == Some(statement.conn) => {
789                Ok(statement.inner.clone())
790            }
791            StatementRef::Statement(_) => Err(Error::other(
792                "a prepared statement can only be used on the connection that prepared it, \
793                 or in a transaction on that connection",
794            )),
795        }
796    }
797
798    /// Runs `statement` on `client` with `run`. A query runs on the statement
799    /// the connection keeps for it, and should that one prove stale, as after
800    /// a schema change made elsewhere, on one prepared again: unless in a
801    /// transaction, which the failure has aborted. A statement the caller
802    /// prepared runs as it is.
803    async fn run_statement<T, F, Fut>(
804        on: On<'_>,
805        client: &Client<'_>,
806        statement: StatementRef<'_>,
807        run: F,
808    ) -> Result<T, Error>
809    where
810        F: Fn(tokio_postgres::Statement) -> Fut,
811        Fut: Future<Output = Result<T, tokio_postgres::Error>>,
812    {
813        match statement {
814            StatementRef::Query(query) => client.run_cached(query, run).await.map_err(db_err),
815            statement => {
816                let statement = resolve(on, client, statement).await?;
817                run(statement)
818                    .await
819                    .inspect_err(|err| client.statement_failed(err))
820                    .map_err(db_err)
821            }
822        }
823    }
824
825    pub async fn query_raw<T, P, I>(
826        on: On<'_>,
827        statement: &T,
828        params: I,
829    ) -> Result<RowStream, Error>
830    where
831        T: ?Sized + ToStatement,
832        P: BorrowToSql,
833        I: IntoIterator<Item = P>,
834        I::IntoIter: ExactSizeIterator,
835    {
836        let statement = statement.__convert();
837        let span = on.span(statement.text())?;
838        let result = async {
839            let client = on.client(statement.text()).await?;
840            // The parameters are an iterator, gone once sent: a statement
841            // that proves stale fails, and the next run prepares it again.
842            let statement = resolve(on, &client, statement).await?;
843            client
844                .query_raw(&statement, params.into_iter().map(Param))
845                .await
846                .inspect_err(|err| client.statement_failed(err))
847                .map(RowStream::new)
848                .map_err(db_err)
849        }
850        .await;
851        finish(span, result)
852    }
853
854    /// `query_raw`, for parameters already converted.
855    async fn query_stream(
856        on: On<'_>,
857        statement: StatementRef<'_>,
858        params: Params<'_>,
859    ) -> Result<RowStream, Error> {
860        let span = on.span(statement.text())?;
861        let result = async {
862            let client = &on.client(statement.text()).await?;
863            let params = &params;
864            run_statement(on, client, statement, |statement| async move {
865                let params = params.iter().map(|p| Param(p.0));
866                client.query_raw(&statement, params).await
867            })
868            .await
869            .map(RowStream::new)
870        }
871        .await;
872        finish(span, result)
873    }
874
875    async fn collect(mut stream: RowStream) -> Result<Vec<Row>, Error> {
876        let mut rows = Vec::new();
877        while let Some(row) = stream.next().await {
878            rows.push(row?);
879        }
880        Ok(rows)
881    }
882
883    pub async fn query(
884        on: On<'_>,
885        statement: StatementRef<'_>,
886        params: Params<'_>,
887    ) -> Result<Vec<Row>, Error> {
888        collect(query_stream(on, statement, params).await?).await
889    }
890
891    pub async fn query_opt(
892        on: On<'_>,
893        statement: StatementRef<'_>,
894        params: Params<'_>,
895    ) -> Result<Option<Row>, Error> {
896        let mut stream = query_stream(on, statement, params).await?;
897        let Some(first) = stream.next().await.transpose()? else {
898            return Ok(None);
899        };
900        if stream.next().await.transpose()?.is_some() {
901            return Err(Error::TooManyRows);
902        }
903        Ok(Some(first))
904    }
905
906    pub async fn query_one(
907        on: On<'_>,
908        statement: StatementRef<'_>,
909        params: Params<'_>,
910    ) -> Result<Row, Error> {
911        query_opt(on, statement, params).await?.ok_or(Error::NoRows)
912    }
913
914    pub async fn query_typed_raw<P, I>(
915        on: On<'_>,
916        query: &str,
917        params: I,
918    ) -> Result<RowStream, Error>
919    where
920        P: BorrowToSql,
921        I: IntoIterator<Item = (P, Type)>,
922    {
923        let span = on.span(query)?;
924        let result = async {
925            let client = on.client(query).await?;
926            client
927                .query_typed_raw(query, params.into_iter().map(|(p, ty)| (Param(p), ty)))
928                .await
929                .map(RowStream::new)
930                .map_err(db_err)
931        }
932        .await;
933        finish(span, result)
934    }
935
936    pub async fn query_typed(
937        on: On<'_>,
938        query: &str,
939        params: Vec<(Param<&(dyn ToSql + Sync)>, Type)>,
940    ) -> Result<Vec<Row>, Error> {
941        let span = on.span(query)?;
942        let result = async {
943            let client = on.client(query).await?;
944            client
945                .query_typed_raw(query, params)
946                .await
947                .map(RowStream::new)
948                .map_err(db_err)
949        }
950        .await;
951        collect(finish(span, result)?).await
952    }
953
954    pub async fn execute_raw<T, P, I>(on: On<'_>, statement: &T, params: I) -> Result<u64, Error>
955    where
956        T: ?Sized + ToStatement,
957        P: BorrowToSql,
958        I: IntoIterator<Item = P>,
959        I::IntoIter: ExactSizeIterator,
960    {
961        let statement = statement.__convert();
962        let span = on.span(statement.text())?;
963        let result = async {
964            let client = on.client(statement.text()).await?;
965            // As `query_raw`: a stale statement fails once.
966            let statement = resolve(on, &client, statement).await?;
967            client
968                .execute_raw(&statement, params.into_iter().map(Param))
969                .await
970                .inspect_err(|err| client.statement_failed(err))
971                .map_err(db_err)
972        }
973        .await;
974        finish(span, result)
975    }
976
977    pub async fn execute(
978        on: On<'_>,
979        statement: StatementRef<'_>,
980        params: Params<'_>,
981    ) -> Result<u64, Error> {
982        let span = on.span(statement.text())?;
983        let result = async {
984            let client = &on.client(statement.text()).await?;
985            let params = &params;
986            run_statement(on, client, statement, |statement| async move {
987                let params = params.iter().map(|p| Param(p.0));
988                client.execute_raw(&statement, params).await
989            })
990            .await
991        }
992        .await;
993        finish(span, result)
994    }
995
996    pub async fn simple_query(on: On<'_>, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
997        let span = on.span(query)?;
998        let result = async {
999            let client = on.client(query).await?;
1000            client.simple_query(query).await.map_err(db_err)
1001        }
1002        .await;
1003        finish(span, result)
1004    }
1005
1006    pub async fn batch_execute(on: On<'_>, query: &str) -> Result<(), Error> {
1007        let span = on.span(query)?;
1008        let result = async {
1009            let client = on.client(query).await?;
1010            client.batch_execute(query).await.map_err(db_err)
1011        }
1012        .await;
1013        finish(span, result)
1014    }
1015
1016    pub async fn prepare(on: On<'_>, query: &str, types: &[Type]) -> Result<Statement, Error> {
1017        let conn = on.conn().expect("only a connection prepares statements");
1018        let client = on.client(query).await?;
1019        let inner = client.prepare_typed(query, types).await.map_err(db_err)?;
1020        Ok(Statement {
1021            inner,
1022            conn,
1023            query: query.into(),
1024        })
1025    }
1026
1027    pub async fn copy_in<U>(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyInSink<U>, Error>
1028    where
1029        U: Buf + 'static + Send,
1030    {
1031        let span = on.span(statement.text())?;
1032        let result = async {
1033            let client = on.client(statement.text()).await?;
1034            let statement = resolve(on, &client, statement).await?;
1035            client.copy_in(&statement).await.map_err(db_err)
1036        }
1037        .await;
1038        finish(span, result)
1039    }
1040
1041    pub async fn copy_out(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyOutStream, Error> {
1042        let span = on.span(statement.text())?;
1043        let result = async {
1044            let client = on.client(statement.text()).await?;
1045            let statement = resolve(on, &client, statement).await?;
1046            client.copy_out(&statement).await.map_err(db_err)
1047        }
1048        .await;
1049        finish(span, result)
1050    }
1051}
1052
1053/// A type that can execute Postgres queries: [`DatabaseRef`], [`Transaction`],
1054/// or [`Connection`].
1055///
1056/// Accept `&impl Queryable` in helper functions so they work with databases,
1057/// transactions, and acquired connections alike. [`Database`] itself does not
1058/// implement `Queryable`; pass a [`DatabaseRef`] with the required privileges
1059/// instead.
1060pub trait Queryable: Send + Sync {
1061    /// See [`Database::execute`].
1062    fn execute<T>(
1063        &self,
1064        statement: &T,
1065        params: &[&(dyn ToSql + Sync)],
1066    ) -> impl Future<Output = Result<u64, Error>> + Send
1067    where
1068        T: ?Sized + ToStatement;
1069
1070    /// See [`Database::execute_raw`].
1071    fn execute_raw<T, P, I>(
1072        &self,
1073        statement: &T,
1074        params: I,
1075    ) -> impl Future<Output = Result<u64, Error>> + Send
1076    where
1077        T: ?Sized + ToStatement,
1078        P: BorrowToSql + Send,
1079        I: IntoIterator<Item = P> + Send,
1080        I::IntoIter: ExactSizeIterator + Send;
1081
1082    /// See [`Database::query`].
1083    fn query<T>(
1084        &self,
1085        statement: &T,
1086        params: &[&(dyn ToSql + Sync)],
1087    ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1088    where
1089        T: ?Sized + ToStatement;
1090
1091    /// See [`Database::query_one`].
1092    fn query_one<T>(
1093        &self,
1094        statement: &T,
1095        params: &[&(dyn ToSql + Sync)],
1096    ) -> impl Future<Output = Result<Row, Error>> + Send
1097    where
1098        T: ?Sized + ToStatement;
1099
1100    /// See [`Database::query_opt`].
1101    fn query_opt<T>(
1102        &self,
1103        statement: &T,
1104        params: &[&(dyn ToSql + Sync)],
1105    ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1106    where
1107        T: ?Sized + ToStatement;
1108
1109    /// See [`Database::query_raw`].
1110    fn query_raw<T, P, I>(
1111        &self,
1112        statement: &T,
1113        params: I,
1114    ) -> impl Future<Output = Result<RowStream, Error>> + Send
1115    where
1116        T: ?Sized + ToStatement,
1117        P: BorrowToSql + Send,
1118        I: IntoIterator<Item = P> + Send,
1119        I::IntoIter: ExactSizeIterator + Send;
1120
1121    /// See [`Database::query_typed`].
1122    fn query_typed(
1123        &self,
1124        query: &str,
1125        params: &[(&(dyn ToSql + Sync), Type)],
1126    ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send;
1127
1128    /// See [`Database::query_typed_raw`].
1129    fn query_typed_raw<P, I>(
1130        &self,
1131        query: &str,
1132        params: I,
1133    ) -> impl Future<Output = Result<RowStream, Error>> + Send
1134    where
1135        P: BorrowToSql + Send,
1136        I: IntoIterator<Item = (P, Type)> + Send,
1137        I::IntoIter: Send;
1138
1139    /// See [`Database::simple_query`].
1140    fn simple_query(
1141        &self,
1142        query: &str,
1143    ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send;
1144
1145    /// See [`Database::batch_execute`].
1146    fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
1147}
1148
1149/// The query methods, on each type queries run on. Documented once, on
1150/// [`Database`]; the others refer there.
1151macro_rules! query_methods {
1152    ($ty:ty) => {
1153        impl $ty {
1154            /// Executes a statement, returning the resulting rows.
1155            ///
1156            /// A statement may contain parameters, written `$1`, `$2`, … and
1157            /// given in `params`. That is the way to pass values: it keeps
1158            /// them out of the SQL text.
1159            ///
1160            /// ```ignore
1161            /// for row in DB.query("SELECT name FROM users WHERE age > $1", &[&18]).await? {
1162            ///     let name: String = row.get("name");
1163            /// }
1164            /// ```
1165            pub async fn query<T>(
1166                &self,
1167                statement: &T,
1168                params: &[&(dyn ToSql + Sync)],
1169            ) -> Result<Vec<Row>, Error>
1170            where
1171                T: ?Sized + ToStatement,
1172            {
1173                ops::query(self.on(), statement.__convert(), ops::params(params)).await
1174            }
1175
1176            /// Executes a statement which returns a single row, returning it.
1177            ///
1178            /// Returns an error if the query does not return exactly one row.
1179            pub async fn query_one<T>(
1180                &self,
1181                statement: &T,
1182                params: &[&(dyn ToSql + Sync)],
1183            ) -> Result<Row, Error>
1184            where
1185                T: ?Sized + ToStatement,
1186            {
1187                ops::query_one(self.on(), statement.__convert(), ops::params(params)).await
1188            }
1189
1190            /// Executes a statement which returns zero or one rows, returning
1191            /// it.
1192            ///
1193            /// Returns an error if the query returns more than one row.
1194            pub async fn query_opt<T>(
1195                &self,
1196                statement: &T,
1197                params: &[&(dyn ToSql + Sync)],
1198            ) -> Result<Option<Row>, Error>
1199            where
1200                T: ?Sized + ToStatement,
1201            {
1202                ops::query_opt(self.on(), statement.__convert(), ops::params(params)).await
1203            }
1204
1205            /// The maximally flexible version of `query`: the parameters are
1206            /// an iterator, and the rows come as a stream rather than
1207            /// collected.
1208            pub async fn query_raw<T, P, I>(
1209                &self,
1210                statement: &T,
1211                params: I,
1212            ) -> Result<RowStream, Error>
1213            where
1214                T: ?Sized + ToStatement,
1215                P: BorrowToSql,
1216                I: IntoIterator<Item = P>,
1217                I::IntoIter: ExactSizeIterator,
1218            {
1219                ops::query_raw(self.on(), statement, params).await
1220            }
1221
1222            /// Like `query`, but with the types of the parameters given, so
1223            /// the query needs no round trip to prepare it.
1224            pub async fn query_typed(
1225                &self,
1226                query: &str,
1227                params: &[(&(dyn ToSql + Sync), Type)],
1228            ) -> Result<Vec<Row>, Error> {
1229                let params = params
1230                    .iter()
1231                    .map(|(p, ty)| (Param(*p), ty.clone()))
1232                    .collect();
1233                ops::query_typed(self.on(), query, params).await
1234            }
1235
1236            /// The maximally flexible version of `query_typed`.
1237            pub async fn query_typed_raw<P, I>(
1238                &self,
1239                query: &str,
1240                params: I,
1241            ) -> Result<RowStream, Error>
1242            where
1243                P: BorrowToSql,
1244                I: IntoIterator<Item = (P, Type)>,
1245            {
1246                ops::query_typed_raw(self.on(), query, params).await
1247            }
1248
1249            /// Executes a statement, returning the number of rows modified.
1250            ///
1251            /// If the statement does not modify any rows (e.g. `SELECT`), 0
1252            /// is returned.
1253            pub async fn execute<T>(
1254                &self,
1255                statement: &T,
1256                params: &[&(dyn ToSql + Sync)],
1257            ) -> Result<u64, Error>
1258            where
1259                T: ?Sized + ToStatement,
1260            {
1261                ops::execute(self.on(), statement.__convert(), ops::params(params)).await
1262            }
1263
1264            /// The maximally flexible version of `execute`.
1265            pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
1266            where
1267                T: ?Sized + ToStatement,
1268                P: BorrowToSql,
1269                I: IntoIterator<Item = P>,
1270                I::IntoIter: ExactSizeIterator,
1271            {
1272                ops::execute_raw(self.on(), statement, params).await
1273            }
1274
1275            /// Executes a sequence of SQL statements using the simple query
1276            /// protocol, returning the resulting rows, with every value as
1277            /// text.
1278            ///
1279            /// The statements, separated by semicolons, take no parameters:
1280            /// never build the query from untrusted input.
1281            pub async fn simple_query(
1282                &self,
1283                query: &str,
1284            ) -> Result<Vec<SimpleQueryMessage>, Error> {
1285                ops::simple_query(self.on(), query).await
1286            }
1287
1288            /// Executes a sequence of SQL statements using the simple query
1289            /// protocol, stopping at the first error.
1290            ///
1291            /// The statements, separated by semicolons, take no parameters:
1292            /// never build the query from untrusted input.
1293            pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
1294                ops::batch_execute(self.on(), query).await
1295            }
1296        }
1297    };
1298}
1299
1300/// [`Queryable`], for a type with the [`query_methods!`].
1301macro_rules! queryable {
1302    ($ty:ty) => {
1303        impl Queryable for $ty {
1304            fn execute<T>(
1305                &self,
1306                statement: &T,
1307                params: &[&(dyn ToSql + Sync)],
1308            ) -> impl Future<Output = Result<u64, Error>> + Send
1309            where
1310                T: ?Sized + ToStatement,
1311            {
1312                <$ty>::execute(self, statement, params)
1313            }
1314
1315            fn execute_raw<T, P, I>(
1316                &self,
1317                statement: &T,
1318                params: I,
1319            ) -> impl Future<Output = Result<u64, Error>> + Send
1320            where
1321                T: ?Sized + ToStatement,
1322                P: BorrowToSql + Send,
1323                I: IntoIterator<Item = P> + Send,
1324                I::IntoIter: ExactSizeIterator + Send,
1325            {
1326                <$ty>::execute_raw(self, statement, params)
1327            }
1328
1329            fn query<T>(
1330                &self,
1331                statement: &T,
1332                params: &[&(dyn ToSql + Sync)],
1333            ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1334            where
1335                T: ?Sized + ToStatement,
1336            {
1337                <$ty>::query(self, statement, params)
1338            }
1339
1340            fn query_one<T>(
1341                &self,
1342                statement: &T,
1343                params: &[&(dyn ToSql + Sync)],
1344            ) -> impl Future<Output = Result<Row, Error>> + Send
1345            where
1346                T: ?Sized + ToStatement,
1347            {
1348                <$ty>::query_one(self, statement, params)
1349            }
1350
1351            fn query_opt<T>(
1352                &self,
1353                statement: &T,
1354                params: &[&(dyn ToSql + Sync)],
1355            ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1356            where
1357                T: ?Sized + ToStatement,
1358            {
1359                <$ty>::query_opt(self, statement, params)
1360            }
1361
1362            fn query_raw<T, P, I>(
1363                &self,
1364                statement: &T,
1365                params: I,
1366            ) -> impl Future<Output = Result<RowStream, Error>> + Send
1367            where
1368                T: ?Sized + ToStatement,
1369                P: BorrowToSql + Send,
1370                I: IntoIterator<Item = P> + Send,
1371                I::IntoIter: ExactSizeIterator + Send,
1372            {
1373                <$ty>::query_raw(self, statement, params)
1374            }
1375
1376            fn query_typed(
1377                &self,
1378                query: &str,
1379                params: &[(&(dyn ToSql + Sync), Type)],
1380            ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send {
1381                <$ty>::query_typed(self, query, params)
1382            }
1383
1384            fn query_typed_raw<P, I>(
1385                &self,
1386                query: &str,
1387                params: I,
1388            ) -> impl Future<Output = Result<RowStream, Error>> + Send
1389            where
1390                P: BorrowToSql + Send,
1391                I: IntoIterator<Item = (P, Type)> + Send,
1392                I::IntoIter: Send,
1393            {
1394                <$ty>::query_typed_raw(self, query, params)
1395            }
1396
1397            fn simple_query(
1398                &self,
1399                query: &str,
1400            ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send {
1401                <$ty>::simple_query(self, query)
1402            }
1403
1404            fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
1405                <$ty>::batch_execute(self, query)
1406            }
1407        }
1408    };
1409}
1410
1411/// What needs a connection of its own, on the types that are one.
1412macro_rules! connection_methods {
1413    ($ty:ty) => {
1414        impl $ty {
1415            /// Creates a new prepared statement.
1416            ///
1417            /// A prepared statement is parsed and planned once, and can then
1418            /// be run repeatedly, with different parameters each time. It
1419            /// belongs to this connection, and can only be used on it.
1420            pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
1421                ops::prepare(self.on(), query, &[]).await
1422            }
1423
1424            /// Like `prepare`, but with the types of the statement's
1425            /// parameters given, rather than left to Postgres to infer.
1426            pub async fn prepare_typed(
1427                &self,
1428                query: &str,
1429                parameter_types: &[Type],
1430            ) -> Result<Statement, Error> {
1431                ops::prepare(self.on(), query, parameter_types).await
1432            }
1433
1434            /// Executes a `COPY FROM STDIN` statement, returning a sink to
1435            /// write the copy data to.
1436            ///
1437            /// The copy is aborted if the sink is dropped without being
1438            /// finished.
1439            pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
1440            where
1441                T: ?Sized + ToStatement,
1442                U: Buf + 'static + Send,
1443            {
1444                ops::copy_in(self.on(), statement.__convert()).await
1445            }
1446
1447            /// Executes a `COPY TO STDOUT` statement, returning a stream of
1448            /// the resulting data.
1449            pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
1450            where
1451                T: ?Sized + ToStatement,
1452            {
1453                ops::copy_out(self.on(), statement.__convert()).await
1454            }
1455        }
1456    };
1457}
1458
1459query_methods!(Database);
1460query_methods!(DatabaseRef);
1461query_methods!(Connection);
1462query_methods!(Transaction<'_>);
1463
1464queryable!(DatabaseRef);
1465queryable!(Connection);
1466queryable!(Transaction<'_>);
1467
1468connection_methods!(Connection);
1469connection_methods!(Transaction<'_>);
1470
1471/// Errors returned by Postgres operations. See the [module docs](self#errors).
1472///
1473/// Does not convert automatically into [`encore::Error`](crate::Error); map it
1474/// to the appropriate error code at API boundaries.
1475#[derive(Debug, thiserror::Error)]
1476#[non_exhaustive]
1477pub enum Error {
1478    /// An error reported by Postgres, or a connection failure
1479    /// ([`ErrorCode::ConnectionFailure`], SQLSTATE `08001`).
1480    #[error(transparent)]
1481    Database(#[from] DatabaseError),
1482    /// `query_one` returned no rows.
1483    #[error("query returned no rows")]
1484    NoRows,
1485    /// `query_one` or `query_opt` returned more than one row.
1486    #[error("query returned more than one row")]
1487    TooManyRows,
1488    /// A client-side error, such as a parameter type mismatch, requesting a
1489    /// read-write transaction on a read handle, or failing to decode a value.
1490    #[error(transparent)]
1491    Other(Box<dyn std::error::Error + Send + Sync>),
1492}
1493
1494impl Error {
1495    /// The error the database reported, or the failure to reach it; `None`
1496    /// for the other kinds.
1497    pub fn database_error(&self) -> Option<&DatabaseError> {
1498        match self {
1499            Error::Database(err) => Some(err),
1500            _ => None,
1501        }
1502    }
1503
1504    /// An [`Error::Other`] with `message`.
1505    fn other(message: impl Into<String>) -> Self {
1506        Error::Other(message.into().into())
1507    }
1508}
1509
1510/// `err` as this module's error: a [`DatabaseError`] if the database
1511/// reported it or could not be reached, and otherwise [`Error::Other`].
1512fn db_err(err: impl Into<DbFailure>) -> Error {
1513    match err.into() {
1514        DbFailure::Client(err) => match DatabaseError::from_client_error(&err) {
1515            Some(db) => db.into(),
1516            None => Error::Other(Box::new(err)),
1517        },
1518        DbFailure::Core(err) => match err.database_error() {
1519            Some(db) => db.into(),
1520            None => Error::other(err.to_string()),
1521        },
1522        // A database that is not configured, or whose pool could not be
1523        // built, can't be reached.
1524        DbFailure::Config(err) => DatabaseError::connection_failure(format!("{err:#}")).into(),
1525    }
1526}
1527
1528/// `err`, from setting up the current test's instance of a database under
1529/// `encore test`, as this module's error.
1530fn test_err(err: crate::Error) -> Error {
1531    Error::Other(Box::new(err))
1532}
1533
1534/// An error a database operation failed with, of the kinds [`db_err`] reads.
1535enum DbFailure {
1536    Client(tokio_postgres::Error),
1537    Core(postgres::Error),
1538    Config(anyhow::Error),
1539}
1540
1541impl From<tokio_postgres::Error> for DbFailure {
1542    fn from(err: tokio_postgres::Error) -> Self {
1543        DbFailure::Client(err)
1544    }
1545}
1546
1547impl From<postgres::Error> for DbFailure {
1548    fn from(err: postgres::Error) -> Self {
1549        DbFailure::Core(err)
1550    }
1551}
1552
1553impl From<anyhow::Error> for DbFailure {
1554    fn from(err: anyhow::Error) -> Self {
1555        DbFailure::Config(err)
1556    }
1557}