encore-dev 2.0.0-beta.15

Rust SDK for Encore applications
Documentation
//! What a handle's access does to the statements it runs, through a real
//! runtime and server: a read handle's writes are refused, in a statement or
//! a transaction, a read handle's transaction asking to write is an error,
//! and a write handle still writes after a read handle used its connection.
//! A read handle's connection string connects read-only too.
//!
//! `#[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 --test postgres_access -- --ignored
//! ```

use encore::storage::postgres::{Database, DatabaseRef, Error, ErrorCode};

#[path = "support/postgres.rs"]
mod support;

static DB: Database = Database::named("access");

const WRITE: &str = "CREATE TEMP TABLE IF NOT EXISTS encore_access (id int)";

fn refused(result: Result<(), Error>) -> bool {
    result.is_err_and(|err| {
        err.database_error().map(|db| db.code) == Some(ErrorCode::ReadOnlyTransaction)
    })
}

#[tokio::test(flavor = "multi_thread")]
#[ignore = "needs a PostgreSQL server at ENCORE_TEST_PG"]
async fn read_handles_refuse_writes_and_write_handles_still_write() {
    support::setup("access");
    let readers: [DatabaseRef; 2] = [DB.read(), DB.read_primary()];
    for reader in readers {
        let row = reader.query_one("SELECT 1", &[]).await.expect("a read");
        assert_eq!(row.get::<_, i32>(0), 1);
        assert!(
            refused(reader.batch_execute(WRITE).await),
            "a read handle wrote"
        );

        let tx = reader.transaction().await.expect("begin");
        assert!(
            refused(tx.batch_execute(WRITE).await),
            "its transaction wrote"
        );
        tx.rollback().await.unwrap();

        // Asking to write is a mistake, not silently read-only.
        let err = reader
            .build_transaction()
            .read_only(false)
            .start()
            .await
            .err()
            .expect("a read handle's transaction asking to write");
        assert!(matches!(err, Error::Other(_)), "{err}");
        let tx = reader
            .build_transaction()
            .read_only(true)
            .start()
            .await
            .expect("begin");
        tx.rollback().await.unwrap();

        let mut conn = reader.acquire().await.expect("acquire");
        assert!(
            refused(conn.batch_execute(WRITE).await),
            "its connection wrote"
        );
        let err = conn
            .build_transaction()
            .read_only(false)
            .start()
            .await
            .err()
            .expect("a read connection's transaction asking to write");
        assert!(matches!(err, Error::Other(_)), "{err}");
        conn.close().await;

        // The same connection, the pool having one.
        DB.write()
            .batch_execute(WRITE)
            .await
            .expect("a write handle wrote after a read handle");
        DB.batch_execute(WRITE).await.expect("the database wrote");
        let tx = DB.admin().transaction().await.expect("begin");
        tx.batch_execute(WRITE)
            .await
            .expect("an admin transaction wrote");
        tx.rollback().await.unwrap();
    }

    // Another client, through the runtime's proxy.
    let conn_strings = [
        (DB.connection_string(), false),
        (DB.write().connection_string(), false),
        (DB.read().connection_string(), true),
        (DB.read_primary().connection_string(), true),
    ];
    for (conn_string, read_only) in conn_strings {
        let conn_string = conn_string.expect("a connection string");
        let (client, conn) = tokio_postgres::connect(&conn_string, tokio_postgres::NoTls)
            .await
            .expect("connect through the proxy");
        tokio::spawn(conn);
        let row = client
            .query_one("SHOW default_transaction_read_only", &[])
            .await
            .unwrap();
        let expected = if read_only { "on" } else { "off" };
        assert_eq!(row.get::<_, String>(0), expected, "{conn_string}");
        match client.batch_execute(WRITE).await {
            Ok(()) => assert!(!read_only, "{conn_string} wrote"),
            Err(err) => {
                assert!(read_only, "{conn_string}: {err}");
                assert_eq!(
                    err.code(),
                    Some(&tokio_postgres::error::SqlState::READ_ONLY_SQL_TRANSACTION),
                    "{conn_string}: {err}"
                );
            }
        }
    }
}