encore-dev 2.0.0-alpha.15

Rust SDK for Encore applications
Documentation
//! What queries take and return: statements, rows and streams of rows.

use std::fmt;
use std::future::poll_fn;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};

use futures_core::Stream;

use crate::error::{ErrCode, Error};

use super::db_err;
use super::types::{Decoded, FromSql, Type};

pub use tokio_postgres::Column;

/// A row of data returned from the database by a query.
pub struct Row(tokio_postgres::Row);

impl Row {
    pub(super) fn new(row: tokio_postgres::Row) -> Self {
        Self(row)
    }

    /// Information about the columns of data in the row.
    pub fn columns(&self) -> &[Column] {
        self.0.columns()
    }

    /// Whether the row contains no values.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The number of values in the row.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Reads a value from the row, by the column's zero-based position or its
    /// name.
    ///
    /// ```ignore
    /// let name: String = row.get("name");
    /// let age: Option<i32> = row.get(1);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the index is out of bounds or the value cannot be converted
    /// to the type asked for. [`Row::try_get`] returns an error instead.
    pub fn get<'a, I, T>(&'a self, idx: I) -> T
    where
        I: RowIndex + fmt::Display,
        T: FromSql<'a>,
    {
        match self.try_get(&idx) {
            Ok(value) => value,
            Err(err) => panic!("error retrieving column {idx}: {}", err.message),
        }
    }

    /// Like [`Row::get`], but returns an error rather than panicking.
    pub fn try_get<'a, I, T>(&'a self, idx: I) -> Result<T, Error>
    where
        I: RowIndex + fmt::Display,
        T: FromSql<'a>,
    {
        self.0
            .try_get::<I, Decoded<T>>(idx)
            .map(|value| value.0)
            .map_err(|err| Error::wrap(ErrCode::Internal, err))
    }
}

impl fmt::Debug for Row {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A type a [`Row`] is indexed by: a `usize`, for a column's position, or a
/// `&str`, for its name. Sealed: these are the only ones.
pub trait RowIndex: tokio_postgres::row::RowIndex {}

impl<I: tokio_postgres::row::RowIndex + ?Sized> RowIndex for I {}

/// A stream of rows, returned by the `_raw` query methods. Read it with
/// [`RowStream::next`], or as a [`Stream`].
///
/// ```ignore
/// let mut rows = DB.query_raw("SELECT name FROM users", [] as [&str; 0]).await?;
/// while let Some(row) = rows.next().await {
///     let name: String = row?.get("name");
/// }
/// ```
pub struct RowStream {
    inner: Pin<Box<tokio_postgres::RowStream>>,
}

impl RowStream {
    pub(super) fn new(inner: tokio_postgres::RowStream) -> Self {
        Self {
            inner: Box::pin(inner),
        }
    }

    /// The next row, or `None` once there are no more.
    pub async fn next(&mut self) -> Option<Result<Row, Error>> {
        poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
    }

    /// The number of rows affected by the statement. `None` until the stream
    /// has been read to its end.
    pub fn rows_affected(&self) -> Option<u64> {
        self.inner.rows_affected()
    }
}

impl Stream for RowStream {
    type Item = Result<Row, Error>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.get_mut()
            .inner
            .as_mut()
            .poll_next(cx)
            .map(|row| row.map(|row| row.map(Row::new).map_err(db_err)))
    }
}

/// Which connection a prepared statement belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct ConnId(u64);

impl ConnId {
    pub(super) fn new() -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        Self(NEXT.fetch_add(1, Ordering::Relaxed))
    }
}

/// A prepared statement, made by `prepare` on a [`Connection`](super::Connection)
/// or a [`Transaction`](super::Transaction).
///
/// It belongs to the connection that prepared it, and can only be used there:
/// on that connection, or in a transaction on it.
#[derive(Clone)]
pub struct Statement {
    pub(super) inner: tokio_postgres::Statement,
    pub(super) conn: ConnId,
    pub(super) query: Arc<str>,
}

impl Statement {
    /// The expected types of the statement's parameters.
    pub fn params(&self) -> &[Type] {
        self.inner.params()
    }

    /// Information about the columns returned when the statement is queried.
    pub fn columns(&self) -> &[Column] {
        self.inner.columns()
    }
}

mod sealed {
    pub trait Sealed {}
}

/// What a query method runs: a query string (`str`, `String`), or a
/// [`Statement`] prepared earlier. Sealed: these are the only ones.
pub trait ToStatement: sealed::Sealed + Sync {
    #[doc(hidden)]
    fn __convert(&self) -> StatementRef<'_>;
}

#[doc(hidden)]
pub enum StatementRef<'a> {
    Statement(&'a Statement),
    Query(&'a str),
}

impl StatementRef<'_> {
    /// The statement's SQL.
    pub(super) fn text(&self) -> &str {
        match self {
            StatementRef::Statement(statement) => &statement.query,
            StatementRef::Query(query) => query,
        }
    }
}

impl sealed::Sealed for Statement {}

impl ToStatement for Statement {
    fn __convert(&self) -> StatementRef<'_> {
        StatementRef::Statement(self)
    }
}

impl sealed::Sealed for str {}

impl ToStatement for str {
    fn __convert(&self) -> StatementRef<'_> {
        StatementRef::Query(self)
    }
}

impl sealed::Sealed for String {}

impl ToStatement for String {
    fn __convert(&self) -> StatementRef<'_> {
        StatementRef::Query(self)
    }
}