use crate::audit_context::{AUDIT_CONTEXT_VARS, RequestAuditContext};
use sqlx::PgPool;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use tokio::sync::Mutex;
use uuid::Uuid;
const ORG_FENCE_VARS: [&str; 3] = ["app.scope_unit_ids", "app.company_id", "app.acting_unit_id"];
tokio::task_local! {
static ORG_SCOPE_POOL: std::sync::Arc<sqlx::postgres::PgConnectOptions>;
static ORG_SCOPE: Arc<OrgScope>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OrgScope {
scope_unit_ids: Vec<Uuid>,
acting_unit_id: Uuid,
legacy_company_id: Option<Uuid>,
}
impl OrgScope {
pub fn for_company_unit(unit: Uuid) -> Self {
Self {
scope_unit_ids: vec![unit],
acting_unit_id: unit,
legacy_company_id: Some(unit),
}
}
pub fn scope_unit_ids(&self) -> &[Uuid] {
&self.scope_unit_ids
}
pub fn acting_unit_id(&self) -> Uuid {
self.acting_unit_id
}
pub fn legacy_company_id(&self) -> Option<Uuid> {
self.legacy_company_id
}
fn scope_unit_ids_csv(&self) -> String {
self.scope_unit_ids
.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",")
}
}
#[derive(Debug)]
pub enum OrgScopeError {
UnknownActingUnit(Uuid),
MissingSpineHelpers,
Database(sqlx::Error),
}
impl fmt::Display for OrgScopeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownActingUnit(id) => {
write!(f, "org scope: acting unit {id} is not an organization.org_units node")
}
Self::MissingSpineHelpers => write!(
f,
"org scope: organization.org_unit_subtree / org_unit_root are missing — \
has the org spine migration run in this database?"
),
Self::Database(e) => write!(f, "org scope: resolution query failed: {e}"),
}
}
}
impl std::error::Error for OrgScopeError {}
impl From<sqlx::Error> for OrgScopeError {
fn from(e: sqlx::Error) -> Self {
Self::Database(e)
}
}
pub async fn resolve_org_scope(
conn: &mut sqlx::PgConnection,
acting_unit: Uuid,
additional_entitled: &[Uuid],
) -> Result<OrgScope, OrgScopeError> {
let mut roots = vec![acting_unit];
roots.extend_from_slice(additional_entitled);
let scope_unit_ids: Vec<Uuid> = sqlx::query_scalar(
"SELECT u.id FROM organization.org_unit_subtree($1::uuid[]) AS u(id) \
UNION SELECT organization.org_unit_root()",
)
.bind(&roots)
.fetch_all(&mut *conn)
.await
.map_err(|e| {
match &e {
sqlx::Error::Database(db) if db.code().as_deref() == Some("42883")
|| db.code().as_deref() == Some("42P01") =>
{
OrgScopeError::MissingSpineHelpers
}
_ => OrgScopeError::Database(e),
}
})?;
if scope_unit_ids.is_empty() {
return Err(OrgScopeError::MissingSpineHelpers);
}
if !scope_unit_ids.contains(&acting_unit) {
return Err(OrgScopeError::UnknownActingUnit(acting_unit));
}
let legacy_company_id: Option<Uuid> = sqlx::query_scalar(
"WITH RECURSIVE up AS ( \
SELECT id, parent_id, kind FROM organization.org_units WHERE id = $1 \
UNION ALL \
SELECT o.id, o.parent_id, o.kind FROM organization.org_units o \
JOIN up ON o.id = up.parent_id \
) SELECT up.id FROM up WHERE up.kind::text = 'company' ORDER BY up.id LIMIT 1",
)
.bind(acting_unit)
.fetch_optional(&mut *conn)
.await?;
let mut sorted = scope_unit_ids;
sorted.sort_unstable();
sorted.dedup();
Ok(OrgScope {
scope_unit_ids: sorted,
acting_unit_id: acting_unit,
legacy_company_id,
})
}
pub async fn with_org_request_scope<F, R>(pool: &PgPool, scope: OrgScope, f: F) -> Result<R, sqlx::Error>
where
F: Future<Output = R>,
{
with_org_request_scope_internal(pool, scope, None, f).await
}
pub async fn with_org_request_scope_and_audit<F, R>(
pool: &PgPool,
scope: OrgScope,
audit: RequestAuditContext,
f: F,
) -> Result<R, sqlx::Error>
where
F: Future<Output = R>,
{
with_org_request_scope_internal(pool, scope, Some(&audit), f).await
}
async fn with_org_request_scope_internal<F, R>(
pool: &PgPool,
scope: OrgScope,
audit: Option<&RequestAuditContext>,
f: F,
) -> Result<R, sqlx::Error>
where
F: Future<Output = R>,
{
if audit.is_none()
&& crate::company_scope::current_request_conn().is_some()
&& ORG_SCOPE.try_with(|ambient| **ambient == scope).unwrap_or(false)
&& ORG_SCOPE_POOL
.try_with(|ambient| std::sync::Arc::ptr_eq(ambient, &pool.connect_options()))
.unwrap_or(false)
{
return Ok(f.await);
}
Box::pin(open_org_request_scope(pool, scope, audit, f)).await
}
async fn open_org_request_scope<F, R>(
pool: &PgPool,
scope: OrgScope,
audit: Option<&RequestAuditContext>,
f: F,
) -> Result<R, sqlx::Error>
where
F: Future<Output = R>,
{
let mut conn = pool.acquire().await?;
sqlx::query("SELECT set_config('app.scope_unit_ids', $1, false)")
.bind(scope.scope_unit_ids_csv())
.execute(&mut *conn)
.await?;
sqlx::query("SELECT set_config('app.company_id', $1, false)")
.bind(scope.legacy_company_id.map(|id| id.to_string()).unwrap_or_default())
.execute(&mut *conn)
.await?;
sqlx::query("SELECT set_config('app.acting_unit_id', $1, false)")
.bind(scope.acting_unit_id.to_string())
.execute(&mut *conn)
.await?;
if let Some(audit) = audit {
audit.bind_on(&mut conn, false).await?;
}
let holder = Arc::new(Mutex::new(conn));
let scope_arc = Arc::new(scope);
let pool_identity = pool.connect_options();
let audit_owned = audit.cloned();
let result = ORG_SCOPE_POOL
.scope(
pool_identity,
ORG_SCOPE.scope(scope_arc.clone(), async {
crate::company_scope::with_company_scope_internal(scope_arc.legacy_company_id, async {
let inner = crate::company_scope::with_request_conn_internal(holder.clone(), f);
match audit_owned {
Some(audit) => {
crate::audit_context::with_request_audit(audit, inner).await
}
None => inner.await,
}
})
.await
}),
)
.await;
{
let mut guard = holder.lock().await;
for var in ORG_FENCE_VARS.into_iter().chain(AUDIT_CONTEXT_VARS) {
if let Err(e) = sqlx::query("SELECT set_config($1, '', false)")
.bind(var)
.execute(&mut **guard)
.await
{
tracing::error!(
target: "backbone_orm::org_scope",
error = %e,
var,
"failed to reset fence variable on org request connection; the pool \
connection may carry the previous session's scope — treat as a \
fence-hygiene incident",
);
}
}
}
Ok(result)
}
pub fn current_org_scope() -> Option<OrgScope> {
ORG_SCOPE.try_with(|s| s.as_ref().clone()).ok()
}
pub async fn bind_org_scope_on(
conn: &mut sqlx::PgConnection,
scope: &OrgScope,
) -> Result<(), sqlx::Error> {
sqlx::query("SELECT set_config('app.scope_unit_ids', $1, true)")
.bind(scope.scope_unit_ids_csv())
.execute(&mut *conn)
.await?;
sqlx::query("SELECT set_config('app.company_id', $1, true)")
.bind(scope.legacy_company_id.map(|id| id.to_string()).unwrap_or_default())
.execute(&mut *conn)
.await?;
sqlx::query("SELECT set_config('app.acting_unit_id', $1, true)")
.bind(scope.acting_unit_id.to_string())
.execute(&mut *conn)
.await?;
Ok(())
}
pub async fn execute_unit_scoped<'q>(
pool: &PgPool,
unit: Uuid,
query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {
if let Some(conn) = crate::company_scope::current_request_conn() {
let mut g = conn.lock().await;
return query.execute(&mut **g).await;
}
let mut tx = pool.begin().await?;
sqlx::query("SELECT set_config('app.scope_unit_ids', $1, true)")
.bind(unit.to_string())
.execute(&mut *tx)
.await?;
let res = query.execute(&mut *tx).await?;
tx.commit().await?;
Ok(res)
}
pub async fn execute_scoped<'q>(
pool: &PgPool,
query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {
if let Some(conn) = crate::company_scope::current_request_conn() {
let mut g = conn.lock().await;
return query.execute(&mut **g).await;
}
query.execute(pool).await
}
pub async fn fetch_optional_row_scoped<'q>(
pool: &PgPool,
query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
) -> Result<Option<sqlx::postgres::PgRow>, sqlx::Error> {
if let Some(conn) = crate::company_scope::current_request_conn() {
let mut g = conn.lock().await;
return query.fetch_optional(&mut **g).await;
}
query.fetch_optional(pool).await
}
pub async fn fetch_all_rows_scoped<'q>(
pool: &PgPool,
query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
) -> Result<Vec<sqlx::postgres::PgRow>, sqlx::Error> {
if let Some(conn) = crate::company_scope::current_request_conn() {
let mut g = conn.lock().await;
return query.fetch_all(&mut **g).await;
}
query.fetch_all(pool).await
}
pub async fn fetch_one_row_scoped<'q>(
pool: &PgPool,
query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
) -> Result<sqlx::postgres::PgRow, sqlx::Error> {
if let Some(conn) = crate::company_scope::current_request_conn() {
let mut g = conn.lock().await;
return query.fetch_one(&mut **g).await;
}
query.fetch_one(pool).await
}
#[cfg(test)]
mod tests {
use super::{resolve_org_scope, with_org_request_scope, with_org_request_scope_and_audit};
use crate::audit_context::RequestAuditContext;
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use sqlx::Row;
use uuid::Uuid;
fn dsn() -> Option<String> {
std::env::var("BACKBONE_ORM_RLS_DSN").ok()
}
async fn admin_pool(dsn: &str) -> PgPool {
PgPoolOptions::new().max_connections(4).connect(dsn).await.unwrap()
}
async fn app_pool(dsn: &str, role: &str) -> PgPool {
let after_at = dsn.rsplit('@').next().unwrap();
let url = format!("postgresql://{role}:orgpw@{after_at}");
PgPoolOptions::new().max_connections(1).connect(&url).await.unwrap()
}
fn role_name() -> String {
format!("org_scope_app_{}", &Uuid::new_v4().simple().to_string()[..8])
}
async fn setup(admin: &PgPool, role: &str, root: Uuid, company: Uuid, branch: Uuid, other: Uuid) {
sqlx::raw_sql(&format!(
"DROP SCHEMA IF EXISTS organization CASCADE; \
DROP SCHEMA IF EXISTS org_scope_test CASCADE; \
CREATE SCHEMA organization; \
CREATE TABLE organization.org_units ( \
id uuid PRIMARY KEY, kind text NOT NULL, parent_id uuid, \
code text, name text NOT NULL, metadata jsonb NOT NULL DEFAULT '{{}}' \
); \
CREATE UNIQUE INDEX one_root ON organization.org_units (kind) WHERE kind = 'root'; \
CREATE OR REPLACE FUNCTION organization.org_unit_subtree(p_roots uuid[]) \
RETURNS SETOF uuid LANGUAGE sql STABLE AS $$ \
WITH RECURSIVE tree AS ( \
SELECT o.id FROM organization.org_units o WHERE o.id = ANY(p_roots) \
UNION ALL \
SELECT o.id FROM organization.org_units o JOIN tree t ON o.parent_id = t.id \
) SELECT id FROM tree $$; \
CREATE OR REPLACE FUNCTION organization.org_unit_root() RETURNS uuid \
LANGUAGE sql STABLE AS $$ \
SELECT id FROM organization.org_units WHERE kind = 'root' $$; \
CREATE SCHEMA org_scope_test; \
CREATE TABLE org_scope_test.t (id uuid PRIMARY KEY, org_unit_id uuid NOT NULL, code text); \
ALTER TABLE org_scope_test.t ENABLE ROW LEVEL SECURITY; \
ALTER TABLE org_scope_test.t FORCE ROW LEVEL SECURITY; \
CREATE POLICY t_org_isolation ON org_scope_test.t FOR ALL \
USING (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])) \
WITH CHECK (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])); \
CREATE ROLE {role} LOGIN PASSWORD 'orgpw'; \
GRANT USAGE ON SCHEMA organization, org_scope_test TO {role}; \
GRANT SELECT ON organization.org_units TO {role}; \
GRANT SELECT, INSERT, UPDATE, DELETE ON org_scope_test.t TO {role};",
))
.execute(admin)
.await
.unwrap();
sqlx::query(
"INSERT INTO organization.org_units (id, kind, parent_id, code, name) VALUES \
($1, 'root', NULL, 'root', 'Tenant root'), \
($2, 'company', $1, 'CO', 'Company'), \
($3, 'branch', $2, 'BR', 'Branch'), \
($4, 'company', $1, 'OTHER', 'Other Company')",
)
.bind(root)
.bind(company)
.bind(branch)
.bind(other)
.execute(admin)
.await
.unwrap();
}
#[tokio::test]
async fn resolver_and_fence_shape() {
let Some(dsn) = dsn() else { eprintln!("skipping: set BACKBONE_ORM_RLS_DSN"); return };
let root = Uuid::new_v4();
let company = Uuid::new_v4();
let branch = Uuid::new_v4();
let other = Uuid::new_v4();
let role = role_name();
let admin = admin_pool(&dsn).await;
setup(&admin, &role, root, company, branch, other).await;
sqlx::query("INSERT INTO org_scope_test.t (id, org_unit_id, code) VALUES ($1,$2,'CO-WH'), ($3,$4,'BR-WH'), ($5,$6,'OTHER-WH')")
.bind(Uuid::new_v4()).bind(company)
.bind(Uuid::new_v4()).bind(branch)
.bind(Uuid::new_v4()).bind(other)
.execute(&admin).await.unwrap();
let mut conn = admin.acquire().await.unwrap();
let scope = resolve_org_scope(&mut conn, branch, &[]).await.unwrap();
let mut got = scope.scope_unit_ids().to_vec();
got.sort_unstable();
let mut want = vec![branch, root];
want.sort_unstable();
assert_eq!(got, want);
assert_eq!(scope.acting_unit_id(), branch);
assert_eq!(scope.legacy_company_id(), Some(company));
let scope_union = resolve_org_scope(&mut conn, branch, &[other]).await.unwrap();
assert!(scope_union.scope_unit_ids().contains(&other));
let ghost = resolve_org_scope(&mut conn, Uuid::new_v4(), &[]).await;
assert!(ghost.is_err());
let pool = app_pool(&dsn, &role).await;
let (codes, twin_codes): (Vec<String>, Vec<String>) =
with_org_request_scope(&pool, scope, async {
let codes: Vec<String> = crate::company_scope::fetch_all_scoped(
&pool,
sqlx::query_as::<_, (String,)>("SELECT code FROM org_scope_test.t ORDER BY code"),
)
.await
.unwrap()
.into_iter()
.map(|r| r.0)
.collect();
let twin_codes: Vec<String> = super::fetch_all_rows_scoped(
&pool,
sqlx::query("SELECT code FROM org_scope_test.t ORDER BY code"),
)
.await
.unwrap()
.into_iter()
.map(|r| r.get::<String, &str>("code"))
.collect();
(codes, twin_codes)
})
.await
.unwrap();
assert_eq!(codes, ["BR-WH"], "branch session sees only its subtree (+ shared root rows), not the company or sister-company rows");
assert_eq!(
twin_codes, codes,
"the org-scope fetch-all twin fences identically to the scoped helper"
);
let bare: Vec<String> = sqlx::query("SELECT code FROM org_scope_test.t")
.fetch_all(&pool)
.await
.unwrap()
.into_iter()
.map(|r| r.get::<String, usize>(0))
.collect();
assert!(
bare.is_empty(),
"a bare pool read must not see fenced rows"
);
let mut after = pool.acquire().await.unwrap();
let setting: String =
sqlx::query_scalar("SELECT current_setting('app.scope_unit_ids', true)")
.fetch_one(&mut *after)
.await
.unwrap();
assert_eq!(setting, "", "scope leaked onto the pooled connection");
}
#[tokio::test]
async fn audit_context_binds_rides_and_clears_with_the_scope() {
let Some(maintenance_dsn) = dsn() else {
eprintln!("skipping: set BACKBONE_ORM_RLS_DSN");
return;
};
const PROOF_DB: &str = "backbone_orm_audit_ctx_probe";
let proof_dsn = {
let (before_db, ..) = maintenance_dsn.rsplit_once('/').unwrap();
format!("{before_db}/{PROOF_DB}")
};
let maintenance = admin_pool(&maintenance_dsn).await;
sqlx::raw_sql(&format!("DROP DATABASE IF EXISTS {PROOF_DB} WITH (FORCE)"))
.execute(&maintenance)
.await
.unwrap();
sqlx::raw_sql(&format!("CREATE DATABASE {PROOF_DB}"))
.execute(&maintenance)
.await
.unwrap();
let admin = admin_pool(&proof_dsn).await;
let root = Uuid::new_v4();
let company = Uuid::new_v4();
let role = role_name();
sqlx::raw_sql(&format!(
"CREATE SCHEMA organization; \
CREATE TABLE organization.org_units ( \
id uuid PRIMARY KEY, kind text NOT NULL, parent_id uuid, \
code text, name text NOT NULL, metadata jsonb NOT NULL DEFAULT '{{}}' \
); \
CREATE OR REPLACE FUNCTION organization.org_unit_subtree(p_roots uuid[]) \
RETURNS SETOF uuid LANGUAGE sql STABLE AS $$ \
WITH RECURSIVE tree AS ( \
SELECT o.id FROM organization.org_units o WHERE o.id = ANY(p_roots) \
UNION ALL \
SELECT o.id FROM organization.org_units o JOIN tree t ON o.parent_id = t.id \
) SELECT id FROM tree $$; \
CREATE OR REPLACE FUNCTION organization.org_unit_root() RETURNS uuid \
LANGUAGE sql STABLE AS $$ \
SELECT id FROM organization.org_units WHERE kind = 'root' $$; \
CREATE SCHEMA org_scope_test; \
CREATE TABLE org_scope_test.t (id uuid PRIMARY KEY, org_unit_id uuid NOT NULL \
DEFAULT nullif(current_setting('app.acting_unit_id', true), '')::uuid, code text); \
ALTER TABLE org_scope_test.t ENABLE ROW LEVEL SECURITY; \
ALTER TABLE org_scope_test.t FORCE ROW LEVEL SECURITY; \
CREATE POLICY t_org_isolation ON org_scope_test.t FOR ALL \
USING (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])) \
WITH CHECK (org_unit_id = ANY(string_to_array(current_setting('app.scope_unit_ids', true), ',')::uuid[])); \
CREATE TABLE org_scope_test.audit_probe ( \
id bigserial PRIMARY KEY, actor text NOT NULL, correlation_id text NOT NULL \
); \
CREATE FUNCTION org_scope_test.capture_probe() RETURNS trigger LANGUAGE plpgsql AS $$ \
BEGIN \
INSERT INTO org_scope_test.audit_probe (actor, correlation_id) \
VALUES (current_setting('app.actor', true), \
current_setting('app.correlation_id', true)); \
RETURN NULL; \
END $$; \
CREATE TRIGGER t_audit_probe AFTER INSERT ON org_scope_test.t \
FOR EACH ROW EXECUTE FUNCTION org_scope_test.capture_probe(); \
CREATE ROLE {role} LOGIN PASSWORD 'orgpw'; \
GRANT USAGE ON SCHEMA organization, org_scope_test TO {role}; \
GRANT SELECT ON organization.org_units TO {role}; \
GRANT SELECT, INSERT ON org_scope_test.t TO {role}; \
GRANT INSERT ON org_scope_test.audit_probe TO {role}; \
GRANT USAGE, SELECT ON SEQUENCE org_scope_test.audit_probe_id_seq TO {role};",
))
.execute(&admin)
.await
.unwrap();
sqlx::query(
"INSERT INTO organization.org_units (id, kind, parent_id, code, name) VALUES \
($1, 'root', NULL, 'ROOT', 'Tenant root'), \
($2, 'company', $1, 'CO', 'Company')",
)
.bind(root)
.bind(company)
.execute(&admin)
.await
.unwrap();
let pool = app_pool(&proof_dsn, &role).await;
let scope = {
let mut conn = admin.acquire().await.unwrap();
resolve_org_scope(&mut conn, company, &[]).await.unwrap()
};
let audit = RequestAuditContext {
actor: "user-77".to_string(),
correlation_id: "corr-77".to_string(),
client_ip: "203.0.113.7".to_string(),
user_agent: "probe-agent/1.0".to_string(),
http_method: "POST".to_string(),
resource_path: "/api/v1/probe/widgets".to_string(),
};
let inserted = Uuid::new_v4();
let settings: Vec<(String, String)> = with_org_request_scope_and_audit(
&pool,
scope.clone(),
audit.clone(),
async {
crate::company_scope::execute_scoped(
&pool,
sqlx::query("INSERT INTO org_scope_test.t (id, code) VALUES ($1, 'AUDITED')")
.bind(inserted),
)
.await
.unwrap();
crate::company_scope::fetch_all_scoped(
&pool,
sqlx::query_as::<_, (String, String)>(
"SELECT s.name, current_setting(s.name, true) FROM unnest(ARRAY[\
'app.actor','app.correlation_id','app.client_ip','app.user_agent',\
'app.http_method','app.resource_path']) AS s(name)",
),
)
.await
.unwrap()
},
)
.await
.unwrap();
for (var, want) in audit.pairs() {
let got = settings
.iter()
.find(|(n, _)| n == var)
.map(|(_, v)| v.as_str())
.unwrap_or_else(|| panic!("{var} missing from the inventory query"));
assert_eq!(got, want, "{var} must ride the request connection");
}
let landed: Uuid = sqlx::query_scalar("SELECT org_unit_id FROM org_scope_test.t WHERE id = $1")
.bind(inserted)
.fetch_one(&admin)
.await
.unwrap();
assert_eq!(landed, company, "audit channel must not disturb the fence");
let probe: (String, String) =
sqlx::query_as("SELECT actor, correlation_id FROM org_scope_test.audit_probe ORDER BY id DESC LIMIT 1")
.fetch_one(&admin)
.await
.unwrap();
assert_eq!(probe, ("user-77".to_string(), "corr-77".to_string()),
"a row-level trigger on the insert must read the bound attribution");
let mut after = pool.acquire().await.unwrap();
for var in crate::audit_context::AUDIT_CONTEXT_VARS {
let v: String = sqlx::query_scalar("SELECT current_setting($1, true)")
.bind(var)
.fetch_one(&mut *after)
.await
.unwrap();
assert_eq!(v, "", "{var} leaked onto the pooled connection");
}
drop(after);
let plain = Uuid::new_v4();
with_org_request_scope(&pool, scope, async {
crate::company_scope::execute_scoped(
&pool,
sqlx::query("INSERT INTO org_scope_test.t (id, code) VALUES ($1, 'PLAIN')")
.bind(plain),
)
.await
.unwrap();
})
.await
.unwrap();
let probe: (String, String) =
sqlx::query_as("SELECT actor, correlation_id FROM org_scope_test.audit_probe ORDER BY id DESC LIMIT 1")
.fetch_one(&admin)
.await
.unwrap();
assert_eq!(probe, (String::new(), String::new()),
"without an audit context the channel reads empty, never the previous request's");
sqlx::raw_sql(&format!(
"DROP SCHEMA organization CASCADE; DROP SCHEMA org_scope_test CASCADE; DROP ROLE {role};"
))
.execute(&admin)
.await
.unwrap();
pool.close().await;
admin.close().await;
sqlx::raw_sql(&format!("DROP DATABASE IF EXISTS {PROOF_DB} WITH (FORCE);"))
.execute(&maintenance)
.await
.unwrap();
maintenance.close().await;
}
}