25 lines
755 B
Python
25 lines
755 B
Python
|
|
"""Tenant-scoping: ORM auto-filter and tenant context management."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import uuid
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
from sqlalchemy import event as sa_event
|
||
|
|
from sqlalchemy.orm import Session, with_loader_criteria
|
||
|
|
from sqlalchemy.sql import Select
|
||
|
|
|
||
|
|
from app.core.db import TenantMixin
|
||
|
|
|
||
|
|
|
||
|
|
def apply_tenant_filter(query: Select, tenant_id: uuid.UUID) -> Select:
|
||
|
|
"""Apply tenant_id filter to a SELECT query."""
|
||
|
|
# This is used explicitly when needed
|
||
|
|
return query.where(TenantMixin.tenant_id == tenant_id)
|
||
|
|
|
||
|
|
|
||
|
|
async def set_rls_context(session, tenant_id: uuid.UUID | str) -> None:
|
||
|
|
"""Set PostgreSQL RLS session variable."""
|
||
|
|
from app.core.db import set_tenant_context
|
||
|
|
await set_tenant_context(session, tenant_id)
|