encore-dev 2.0.0-beta.14

Rust SDK for Encore applications
Documentation
//! Postgres declarations and handles: what a `static` can hold, what code
//! taking [`Queryable`] accepts, and which parameter and column types the
//! conversion traits cover. Nothing here runs a query — the futures are made
//! and dropped, never polled — so no runtime is needed.

use std::future::Future;

use encore::storage::postgres::types::{to_sql_checked, BytesMut, FromSql, IsNull, ToSql, Type};
use encore::storage::postgres::{
    Connection, Database, DatabaseRef, Error, IsolationLevel, Queryable, Row, Statement,
    Transaction,
};

// Options chain onto the declaration; a handle can initialize a `static`.
static DB: Database = Database::new("hello").migrations("./migrations");
static PLAIN: Database = Database::new("plain");
static SHARED: Database = Database::named("shared");
static REPORTS: DatabaseRef = DB.read();

fn assert_send<F: Future + Send>(_: F) {}

// Library code, taking the trait.
async fn count(db: &impl Queryable) -> Result<i64, Error> {
    let row = db.query_one("SELECT count(*) FROM users", &[]).await?;
    row.try_get(0)
}

async fn rename(db: &impl Queryable, id: i64, name: &str) -> Result<u64, Error> {
    db.execute("UPDATE users SET name = $2 WHERE id = $1", &[&id, &name])
        .await
}

async fn names(db: &impl Queryable, ids: Vec<i64>) -> Result<Vec<String>, Error> {
    let mut rows = db
        .query_raw("SELECT name FROM users WHERE id = ANY($1)", [ids])
        .await?;
    let mut names = Vec::new();
    while let Some(row) = rows.next().await {
        names.push(row?.get("name"));
    }
    db.query_typed("SELECT $1", &[(&1i32, Type::INT4)]).await?;
    db.batch_execute("ANALYZE users").await?;
    db.simple_query("SELECT 1; SELECT 2").await?;
    Ok(names)
}

#[test]
fn every_handle_is_queryable() {
    assert_send(count(&REPORTS));
    assert_send(count(&DB.admin()));
    assert_send(count(&DB.write()));
    assert_send(count(&DB.read_primary()));
    assert_send(count(&PLAIN.read()));
    assert_send(count(&SHARED.read()));
    // A handle is `Copy`: passed on, and still usable.
    let writer = DB.write();
    assert_send(rename(&writer, 1, "ada"));
    assert_send(names(&writer, vec![1, 2]));
}

#[test]
fn the_database_and_its_handles_call_the_methods_directly() {
    // Without the trait in scope at the call; a query is a `&str` or a `String`.
    let sql = String::from("SELECT 1");
    assert_send(DB.query("SELECT 1", &[]));
    assert_send(DB.query(&sql, &[]));
    assert_send(DB.query_one("SELECT 1", &[]));
    assert_send(DB.query_opt("SELECT 1", &[]));
    assert_send(DB.query_raw("SELECT $1", [&1i32 as &(dyn ToSql + Sync)]));
    assert_send(DB.query_typed("SELECT $1", &[(&1i32, Type::INT4)]));
    assert_send(DB.query_typed_raw("SELECT $1", [(1i32, Type::INT4)]));
    assert_send(DB.execute("SELECT 1", &[]));
    assert_send(DB.execute_raw("SELECT $1", vec![1i32]));
    assert_send(DB.simple_query("SELECT 1"));
    assert_send(DB.batch_execute("SELECT 1"));
    assert_send(DB.transaction());
    assert_send(
        DB.build_transaction()
            .isolation_level(IsolationLevel::Serializable)
            .read_only(true)
            .deferrable(true)
            .start(),
    );
    assert_send(DB.acquire());
    assert_send(REPORTS.query("SELECT 1", &[]));
    assert_send(REPORTS.transaction());
    assert_send(REPORTS.build_transaction().start());
    assert_send(REPORTS.acquire());
}

// Transactions and connections run the same library code, and a connection's
// transaction borrows it.
async fn in_transaction(tx: Transaction<'_>) -> Result<(), Error> {
    count(&tx).await?;
    rename(&tx, 1, "ada").await?;
    tx.commit().await
}

async fn on_connection(mut conn: Connection) -> Result<(), Error> {
    count(&conn).await?;
    // What needs a connection of its own: prepared statements and `COPY`.
    let by_id: Statement = conn.prepare("SELECT name FROM users WHERE id = $1").await?;
    conn.prepare_typed("SELECT $1", &[Type::INT8]).await?;
    conn.query(&by_id, &[&1i64]).await?;
    conn.copy_out("COPY users TO STDOUT").await?;
    conn.copy_in::<_, bytes::Bytes>("COPY users FROM STDIN")
        .await?;

    let tx = conn.transaction().await?;
    count(&tx).await?;
    tx.query_opt(&by_id, &[&2i64]).await?;
    tx.rollback().await?;

    let tx = conn.build_transaction().read_only(true).start().await?;
    tx.commit().await?;

    conn.execute("SELECT 1", &[]).await?;
    assert!(!conn.is_closed());
    conn.close().await;
    Ok(())
}

#[test]
fn transactions_and_connections_are_queryable() {
    fn check<T, F: Future + Send>(_: fn(T) -> F) {}
    check(in_transaction);
    check(on_connection);
}

// A type of the app's own converts by implementing this crate's traits.
#[derive(Debug, PartialEq)]
struct Celsius(f64);

impl ToSql for Celsius {
    fn to_sql(
        &self,
        ty: &Type,
        out: &mut BytesMut,
    ) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
        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, Box<dyn std::error::Error + Sync + Send>> {
        f64::from_sql(ty, raw).map(Celsius)
    }

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

async fn temperature(db: &impl Queryable, row: &Row) -> Result<Celsius, Error> {
    db.execute(
        "INSERT INTO readings (value) VALUES ($1)",
        &[&Celsius(21.5)],
    )
    .await?;
    row.try_get("value")
}

#[test]
fn parameters_and_columns_convert_through_this_crates_traits() {
    fn check<'a, D: Queryable, F: Future + Send>(_: fn(&'a D, &'a Row) -> F) {}
    check::<DatabaseRef, _>(temperature);

    // The built-in types, through the forwarding implementations.
    let mut out = BytesMut::new();
    assert!(matches!(
        7i32.to_sql_checked(&Type::INT4, &mut out),
        Ok(IsNull::No)
    ));
    assert_eq!(i32::from_sql(&Type::INT4, &out).unwrap(), 7);
    assert!(matches!(
        None::<i32>.to_sql_checked(&Type::INT4, &mut out),
        Ok(IsNull::Yes)
    ));
    // A type of the app's own, and the type check `to_sql_checked!` adds.
    let mut out = BytesMut::new();
    Celsius(21.5)
        .to_sql_checked(&Type::FLOAT8, &mut out)
        .unwrap();
    assert_eq!(
        Celsius::from_sql(&Type::FLOAT8, &out).unwrap(),
        Celsius(21.5)
    );
    assert!(Celsius(21.5).to_sql_checked(&Type::TEXT, &mut out).is_err());
}