encore-dev 2.0.0-beta.5

Rust SDK for Encore applications
Documentation
//! How values cross the wire through this module's conversion traits, which
//! only a real PostgreSQL server can show.
//!
//! `#[ignore]`d so a plain `cargo test` stays hermetic. Run them with a server
//! reachable at `ENCORE_TEST_PG` (defaulting to a local trust-auth cluster):
//!
//! ```sh
//! cargo test -p encore-dev --lib storage::postgres::tests -- --ignored
//! ```

use super::ops;
use super::types::{to_sql_checked, BoxError, BytesMut, FromSql, IsNull, ToSql, Type};
use super::{Row, RowStream};

async fn connect() -> tokio_postgres::Client {
    let uri = std::env::var("ENCORE_TEST_PG")
        .unwrap_or_else(|_| "postgresql://postgres@127.0.0.1:5432/postgres".to_string());
    let (client, connection) = tokio_postgres::connect(&uri, tokio_postgres::NoTls)
        .await
        .expect("connect to ENCORE_TEST_PG");
    tokio::spawn(connection);
    client
}

/// The one row `query` returns for `params`.
async fn row(
    client: &tokio_postgres::Client,
    query: &str,
    params: &[&(dyn ToSql + Sync)],
) -> Result<Row, tokio_postgres::Error> {
    let stream = client.query_raw(query, ops::params(params)).await?;
    let mut rows = RowStream::new(stream);
    let row = rows.next().await.expect("a row").expect("a readable row");
    assert!(rows.next().await.is_none());
    assert_eq!(rows.rows_affected(), Some(1));
    Ok(row)
}

/// A type of an app's own, converting through this module's traits alone.
#[derive(Debug, PartialEq)]
struct Celsius(f64);

impl ToSql for Celsius {
    fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result<IsNull, BoxError> {
        self.0.to_sql(ty, out)
    }

    fn accepts(ty: &Type) -> bool {
        <f64 as ToSql>::accepts(ty)
    }

    to_sql_checked!();
}

impl<'a> FromSql<'a> for Celsius {
    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, BoxError> {
        f64::from_sql(ty, raw).map(Celsius)
    }

    fn accepts(ty: &Type) -> bool {
        <f64 as FromSql>::accepts(ty)
    }
}

#[tokio::test]
#[ignore = "needs a PostgreSQL server; see the module docs"]
async fn parameters_and_columns_round_trip() {
    let client = connect().await;
    let row = row(
        &client,
        "SELECT $1::int4 AS n, $2::text AS name, $3::int8 AS missing, $4::int8[] AS ids, \
         $5::float8 AS temp",
        &[&7i32, &"ada", &None::<i64>, &vec![1i64, 2], &Celsius(21.5)],
    )
    .await
    .expect("query");

    assert_eq!(row.len(), 5);
    assert!(!row.is_empty());
    assert_eq!(row.columns()[0].name(), "n");
    // By position or by name.
    assert_eq!(row.get::<_, i32>(0), 7);
    assert_eq!(row.get::<_, String>("name"), "ada");
    assert_eq!(row.get::<_, &str>("name"), "ada");
    assert_eq!(row.get::<_, Option<i64>>("missing"), None);
    assert_eq!(row.get::<_, Vec<i64>>("ids"), vec![1, 2]);
    assert_eq!(row.get::<_, Celsius>("temp"), Celsius(21.5));

    // What cannot be read is an error from `try_get`, not a panic.
    assert!(row.try_get::<_, i32>("name").is_err());
    assert!(row.try_get::<_, i64>("missing").is_err());
    assert!(row.try_get::<_, i32>("nope").is_err());
    assert!(row.try_get::<_, i32>(9).is_err());
    assert!(row.try_get::<_, Celsius>("name").is_err());
}

#[tokio::test]
#[ignore = "needs a PostgreSQL server; see the module docs"]
async fn a_parameter_of_the_wrong_type_is_rejected() {
    let client = connect().await;
    // Checked by the parameter's own type, built in or the app's.
    assert!(row(&client, "SELECT $1::int4", &[&"seven"]).await.is_err());
    assert!(row(&client, "SELECT $1::text", &[&Celsius(21.5)])
        .await
        .is_err());
    // The connection is still good.
    assert!(row(&client, "SELECT $1::int4", &[&7i32]).await.is_ok());
}