encore-dev 2.0.0-beta.13

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::{DatabaseError, Error, ErrorCode, 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());
}

#[tokio::test]
#[ignore = "needs a PostgreSQL server; see the module docs"]
async fn a_server_error_is_a_database_error_with_its_fields() {
    let client = connect().await;
    let failed = |query: &'static str| {
        let client = &client;
        async move { super::db_err(client.batch_execute(query).await.unwrap_err()) }
    };

    let duplicate = failed(
        "CREATE TEMP TABLE dup (id int CONSTRAINT dup_pkey PRIMARY KEY); \
         INSERT INTO dup VALUES (1), (1)",
    )
    .await;
    let Error::Database(
        db @ DatabaseError {
            code: ErrorCode::UniqueViolation,
            ..
        },
    ) = &duplicate
    else {
        panic!("not a database error: {duplicate:?}");
    };
    assert_eq!(db.sql_state, "23505");
    assert_eq!(db.severity, "ERROR");
    assert!(db.message.contains("duplicate key"), "{db}");
    assert_eq!(db.detail(), Some("Key (id)=(1) already exists."));
    assert_eq!(db.table_name(), Some("dup"));
    assert_eq!(db.constraint_name(), Some("dup_pkey"));
    assert_eq!(duplicate.to_string(), db.to_string());
    assert!(
        duplicate
            .to_string()
            .ends_with("(Code unique_violation: SQLSTATE 23505)"),
        "{duplicate}"
    );

    // SQLSTATEs outside the table are Other, keeping their SQLSTATE.
    for (query, sql_state) in [("SELEC 1", "42601"), ("SELECT 1/0", "22012")] {
        let err = failed(query).await;
        let db = err.database_error().expect("a database error");
        assert_eq!(
            (db.code, db.sql_state.as_str()),
            (ErrorCode::Other, sql_state),
            "{query}"
        );
    }
}

#[tokio::test]
#[ignore = "needs a PostgreSQL server; see the module docs"]
async fn a_mistake_in_the_call_is_another_error() {
    let client = connect().await;
    let err = client
        .query_raw("SELECT $1::int4", ops::params(&[&"seven"]))
        .await
        .err()
        .expect("a parameter of the wrong type");
    let err = super::db_err(err);
    assert!(matches!(err, Error::Other(_)), "{err:?}");
    assert!(err.database_error().is_none());
}

#[test]
fn a_connection_failure_is_a_database_error() {
    use encore_sdk_core::postgres;

    for (err, message) in [
        (
            super::db_err(postgres::Error::Closed),
            "the connection is closed",
        ),
        (
            super::db_err(postgres::Error::ConnectTimeout),
            "timed out waiting for a connection",
        ),
        (
            super::db_err(anyhow::anyhow!("not configured")),
            "not configured",
        ),
    ] {
        let db = err.database_error().expect("a connection failure");
        assert_eq!(db.code, ErrorCode::ConnectionFailure);
        assert_eq!(db.sql_state, "08001");
        assert_eq!(db.message, message);
        assert_eq!(
            err.to_string(),
            format!("ERROR: {message} (Code connection_failure: SQLSTATE 08001)")
        );
    }
}

#[test]
fn the_other_kinds_say_what_they_are() {
    assert_eq!(Error::NoRows.to_string(), "query returned no rows");
    assert_eq!(
        Error::TooManyRows.to_string(),
        "query returned more than one row"
    );
    assert_eq!(Error::other("a mistake").to_string(), "a mistake");
    for err in [Error::NoRows, Error::TooManyRows, Error::other("a mistake")] {
        assert!(err.database_error().is_none(), "{err}");
    }
}

#[test]
fn a_read_only_connection_refuses_a_read_write_transaction() {
    use super::{check_options, TransactionOptions};

    let options = |read_only| TransactionOptions {
        read_only,
        ..Default::default()
    };
    let err = check_options(&options(Some(false)), true).unwrap_err();
    assert!(matches!(err, Error::Other(_)), "{err:?}");
    for read_only in [None, Some(true)] {
        assert!(check_options(&options(read_only), true).is_ok());
    }
    for read_only in [None, Some(true), Some(false)] {
        assert!(check_options(&options(read_only), false).is_ok());
    }
}

/// Small enough for a `Result` to carry, below clippy's `result_large_err`
/// limit of 128 bytes, with the database error unboxed.
#[test]
fn the_error_is_small() {
    assert!(std::mem::size_of::<Error>() <= 128);
}