Skip to main content

encore/storage/postgres/
row.rs

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