Skip to main content

begin_with

Function begin_with 

Source
pub async fn begin_with(
    pool: &PgPool,
    settings: &[(&str, &str)],
) -> Result<Transaction<'static, Postgres>, Error>
Expand description

Open a transaction with each (name, value) set for its length only, such as ("app.tenant", tenant.as_str()) for a row-level security policy that reads current_setting('app.tenant', true).

Each pair is set with set_config($1, $2, true): bound, never formatted into the SQL, and gone when the transaction commits or rolls back, so a pooled connection never carries one request’s tenant into the next. Run every query that needs the setting on the transaction this returns, as a query on the pool may run on another connection.

let mut tx = axa_postgres_sqlx::begin_with(pool, &[("app.tenant", "acme")]).await?;
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM todos")
    .fetch_one(&mut *tx)
    .await?;
tx.commit().await?;

A policy sees nothing unless the role the service connects as is subject to it: not a superuser, without BYPASSRLS, and, if it owns the table, with FORCE ROW LEVEL SECURITY on it.

§Errors

sqlx::Error::InvalidArgument for a name is_custom_setting refuses, before anything is sent, and any error from beginning the transaction or setting a value.