Skip to main content

encore/storage/postgres/
row.rs

1//! Query statements, rows, and row streams.
2
3use std::fmt;
4use std::future::poll_fn;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::task::{Context, Poll};
9
10use futures_core::Stream;
11
12use super::types::{Decoded, FromSql, Type};
13use super::{Error, db_err};
14
15pub use tokio_postgres::Column;
16
17/// A row of data returned from the database by a query.
18pub struct Row(tokio_postgres::Row);
19
20impl Row {
21    pub(super) fn new(row: tokio_postgres::Row) -> Self {
22        Self(row)
23    }
24
25    /// Information about the columns of data in the row.
26    pub fn columns(&self) -> &[Column] {
27        self.0.columns()
28    }
29
30    /// Whether the row contains no values.
31    pub fn is_empty(&self) -> bool {
32        self.0.is_empty()
33    }
34
35    /// The number of values in the row.
36    pub fn len(&self) -> usize {
37        self.0.len()
38    }
39
40    /// Reads a value from the row, by the column's zero-based position or its
41    /// name.
42    ///
43    /// ```ignore
44    /// let name: String = row.get("name");
45    /// let age: Option<i32> = row.get(1);
46    /// ```
47    ///
48    /// # Panics
49    ///
50    /// Panics if the index is out of bounds or the value cannot be converted
51    /// to the type asked for. [`Row::try_get`] returns an error instead.
52    pub fn get<'a, I, T>(&'a self, idx: I) -> T
53    where
54        I: RowIndex + fmt::Display,
55        T: FromSql<'a>,
56    {
57        match self.try_get(&idx) {
58            Ok(value) => value,
59            Err(err) => panic!("error retrieving column {idx}: {err}"),
60        }
61    }
62
63    /// Like [`Row::get`], but returns an error rather than panicking.
64    pub fn try_get<'a, I, T>(&'a self, idx: I) -> Result<T, Error>
65    where
66        I: RowIndex + fmt::Display,
67        T: FromSql<'a>,
68    {
69        self.0
70            .try_get::<I, Decoded<T>>(idx)
71            .map(|value| value.0)
72            .map_err(|err| Error::Other(Box::new(err)))
73    }
74}
75
76impl fmt::Debug for Row {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        self.0.fmt(f)
79    }
80}
81
82/// A sealed trait for types that can index into a [`Row`]: `usize` (zero-based
83/// column position) or `&str` (column name).
84pub trait RowIndex: tokio_postgres::row::RowIndex {}
85
86impl<I: tokio_postgres::row::RowIndex + ?Sized> RowIndex for I {}
87
88/// A stream of rows, returned by the `_raw` query methods. Read it with
89/// [`RowStream::next`], or as a [`Stream`].
90///
91/// ```ignore
92/// let mut rows = DB.query_raw("SELECT name FROM users", [] as [&str; 0]).await?;
93/// while let Some(row) = rows.next().await {
94///     let name: String = row?.get("name");
95/// }
96/// ```
97pub struct RowStream {
98    inner: Pin<Box<tokio_postgres::RowStream>>,
99}
100
101impl RowStream {
102    pub(super) fn new(inner: tokio_postgres::RowStream) -> Self {
103        Self {
104            inner: Box::pin(inner),
105        }
106    }
107
108    /// The next row, or `None` once there are no more.
109    pub async fn next(&mut self) -> Option<Result<Row, Error>> {
110        poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
111    }
112
113    /// The number of rows affected by the statement. `None` until the stream
114    /// has been read to its end.
115    pub fn rows_affected(&self) -> Option<u64> {
116        self.inner.rows_affected()
117    }
118}
119
120impl Stream for RowStream {
121    type Item = Result<Row, Error>;
122
123    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
124        self.get_mut()
125            .inner
126            .as_mut()
127            .poll_next(cx)
128            .map(|row| row.map(|row| row.map(Row::new).map_err(db_err)))
129    }
130}
131
132/// Which connection a prepared statement belongs to.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub(super) struct ConnId(u64);
135
136impl ConnId {
137    pub(super) fn new() -> Self {
138        static NEXT: AtomicU64 = AtomicU64::new(0);
139        Self(NEXT.fetch_add(1, Ordering::Relaxed))
140    }
141}
142
143/// A prepared statement created by `prepare` on a
144/// [`Connection`](super::Connection) or [`Transaction`](super::Transaction).
145///
146/// Prepared statements are tied to the connection that created them and can
147/// only be executed on that connection or inside a transaction on it.
148#[derive(Clone)]
149pub struct Statement {
150    pub(super) inner: tokio_postgres::Statement,
151    pub(super) conn: ConnId,
152    pub(super) query: Arc<str>,
153}
154
155impl Statement {
156    /// The expected types of the statement's parameters.
157    pub fn params(&self) -> &[Type] {
158        self.inner.params()
159    }
160
161    /// Information about the columns returned when the statement is queried.
162    pub fn columns(&self) -> &[Column] {
163        self.inner.columns()
164    }
165}
166
167mod sealed {
168    pub trait Sealed {}
169}
170
171/// A sealed trait for values accepted as a query: a SQL string (`str`,
172/// `String`) or a prepared [`Statement`].
173pub trait ToStatement: sealed::Sealed + Sync {
174    #[doc(hidden)]
175    fn __convert(&self) -> StatementRef<'_>;
176}
177
178#[doc(hidden)]
179pub enum StatementRef<'a> {
180    Statement(&'a Statement),
181    Query(&'a str),
182}
183
184impl StatementRef<'_> {
185    /// The statement's SQL.
186    pub(super) fn text(&self) -> &str {
187        match self {
188            StatementRef::Statement(statement) => &statement.query,
189            StatementRef::Query(query) => query,
190        }
191    }
192}
193
194impl sealed::Sealed for Statement {}
195
196impl ToStatement for Statement {
197    fn __convert(&self) -> StatementRef<'_> {
198        StatementRef::Statement(self)
199    }
200}
201
202impl sealed::Sealed for str {}
203
204impl ToStatement for str {
205    fn __convert(&self) -> StatementRef<'_> {
206        StatementRef::Query(self)
207    }
208}
209
210impl sealed::Sealed for String {}
211
212impl ToStatement for String {
213    fn __convert(&self) -> StatementRef<'_> {
214        StatementRef::Query(self)
215    }
216}