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