# Repository Template Standards for the persistence layer. ## Responsibility Repositories: - Load/save aggregates and rows - Apply query filters (including **mandatory** `tenant_id` for tenant-owned entities) - Encapsulate SQLAlchemy queries Repositories must **not**: - Enforce entitlement or workflow decisions - Call external HTTP APIs - Publish events (services own outbox writes) - Map HTTP status codes - Contain business branching beyond trivial persistence concerns ## Conventions | Topic | Rule | | --- | --- | | Location | `app/repositories/` | | Naming | `{Aggregate}Repository` or grouped foundation repos matching service pattern | | Constructor | Accept DB session (or unit-of-work) explicitly | | Tenant | Methods that touch tenant data accept/filter `tenant_id` | | Soft delete | Default reads exclude soft-deleted unless `include_deleted=True` | | Return type | Models / rows; services map to DTOs | | Transactions | Participate in caller-managed session/transaction; do not silently commit policy that breaks outbox atomicity | ## Required Patterns ```text get_by_id(tenant_id, id) -> Model | None list(tenant_id, *, filters, sort, search, pagination) -> Sequence[Model] + total/meta add(entity) / save(entity) soft_delete(tenant_id, id) # when soft-delete policy applies # optional: update with version check for optimistic locking ``` Follow existing service repository base classes when present (`repositories/base.py`). Compose reusable predicates via specifications when the service uses `app/specifications/`. ## Tenant Isolation 1. Every query for tenant-owned tables includes `tenant_id`. 2. Updates/deletes must be tenant-scoped (no id-only mutation). 3. Repository tests must include cross-tenant denial cases. ## Testing See [testing-template.md](testing-template.md) — Repository section. ## Related Documents - [Service Architecture](../architecture/service-architecture.md) - [Entity Template](entity-template.md) - [Service Layer Template](service-layer-template.md) - [Mandatory Phase Artifacts](mandatory-phase-artifacts.md) - [Coding Standards](../development/coding-standards.md) - [Project Principles](../development/project-principles.md)