use sqlx::postgres::Postgres;
use sqlx::{Encode, PgPool, QueryBuilder, Type};
use crate::error::TenancyError;
use crate::tenant::Tenant;
#[cfg(feature = "postgres-rls")]
pub mod rls;
pub trait TenantScoped {
const TENANT_COLUMN: &'static str = "tenant_id";
}
pub fn scope_query(
query: &mut QueryBuilder<'_, Postgres>,
tenant: &Tenant,
alias: Option<&'static str>,
) {
scope_query_column(query, tenant, alias, "tenant_id");
}
pub fn scope_query_for<M: TenantScoped>(
query: &mut QueryBuilder<'_, Postgres>,
tenant: &Tenant,
alias: Option<&'static str>,
) {
scope_query_column(query, tenant, alias, M::TENANT_COLUMN);
}
fn scope_query_column(
query: &mut QueryBuilder<'_, Postgres>,
tenant: &Tenant,
alias: Option<&'static str>,
column: &'static str,
) {
let predicate = match alias {
Some(alias) => format!("\"{alias}\".\"{column}\" = "),
None => format!("\"{column}\" = "),
};
query.push(predicate);
query.push_bind(tenant.id.0);
}
pub async fn tenant_unique<V>(
pool: &PgPool,
tenant: &Tenant,
table: &'static str,
column: &'static str,
value: V,
) -> Result<bool, TenancyError>
where
V: for<'q> Encode<'q, Postgres> + Type<Postgres> + Send,
{
Ok(!value_exists(pool, tenant, table, column, value).await?)
}
pub async fn tenant_exists<V>(
pool: &PgPool,
tenant: &Tenant,
table: &'static str,
column: &'static str,
value: V,
) -> Result<bool, TenancyError>
where
V: for<'q> Encode<'q, Postgres> + Type<Postgres> + Send,
{
value_exists(pool, tenant, table, column, value).await
}
async fn value_exists<V>(
pool: &PgPool,
tenant: &Tenant,
table: &'static str,
column: &'static str,
value: V,
) -> Result<bool, TenancyError>
where
V: for<'q> Encode<'q, Postgres> + Type<Postgres> + Send,
{
let sql = format!(
"select exists(select 1 from \"{table}\" where \"{column}\" = $1 and \"tenant_id\" = $2)"
);
let exists: bool = sqlx::query_scalar(&sql)
.bind(value)
.bind(tenant.id.0)
.fetch_one(pool)
.await?;
Ok(exists)
}