Adopt an existing schema¶
Use when the database already exists and its tables do not have
BaseModel's shape: integer keys, TIMESTAMP WITHOUT TIME ZONE or an
is_active with a different meaning.
Part of the Database recipe.
BaseModel fixes three choices: a UUID id, is_active defaulting to
True, and timezone-aware created_at/updated_at. On a new service that
is what you want. On a service with dozens of integer-keyed tables in production,
changing the key means migrating every FK and invalidating every token that
carries the id in sub.
So BaseModel is a composition of mixins, and you can assemble only the
columns your table actually has:
| Mixin | Columns | Database type |
|---|---|---|
UUIDPrimaryKeyMixin |
id: UUID |
UUID (PostgreSQL), CHAR(32) (SQLite) |
IntegerPrimaryKeyMixin |
id: int |
SERIAL (PostgreSQL), INTEGER (SQLite) |
ActiveFlagMixin |
is_active: bool |
BOOLEAN, default True |
TimestampMixin |
created_at, updated_at |
TIMESTAMP WITH TIME ZONE (UtcDateTime) |
NaiveTimestampMixin |
created_at, updated_at |
TIMESTAMP WITHOUT TIME ZONE (NaiveUtcDateTime) |
BaseModel is UUIDPrimaryKeyMixin + ActiveFlagMixin + TimestampMixin over
AsyncAttrs and DeclarativeBase. The DDL it emits did not change.
Integer key and naive timestamps¶
Use when tables have id SERIAL and store UTC in a column without timezone.
# src/db/models/order.py
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from tempest_fastapi_sdk.db import IntegerPrimaryKeyMixin, NaiveTimestampMixin
class Base(DeclarativeBase):
"""The service's declarative base, which predates the SDK."""
class OrderModel(IntegerPrimaryKeyMixin, NaiveTimestampMixin, Base):
"""An order in a table that is already in production."""
__tablename__ = "orders"
code: Mapped[str] = mapped_column(String(32), nullable=False)
On PostgreSQL this table comes out as:
CREATE TABLE orders (
code VARCHAR(32) NOT NULL,
id SERIAL NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT timezone('utc', now()) NOT NULL,
updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT timezone('utc', now()) NOT NULL,
PRIMARY KEY (id)
)
What each piece does:
IntegerPrimaryKeyMixindeclaresid: Mapped[int]withautoincrement=True. The type-checker seesint(measured with mypy--strictand pyright).NaiveTimestampMixinusesNaiveUtcDateTime. A UTC-aware value (datetime.UTC,timezone.utc) is stored without the zone; a naive value passes as is; reads always return a naivedatetime.- The server default is UTC even outside UTC.
now()on a column without timezone stores the wall clock of the sessionTimeZone. So PostgreSQL getstimezone('utc', now()): with the session onAmerica/Sao_Paulo, a rawINSERTstored17:37whilenow()::timestampreturned14:37(PostgreSQL 16, asyncpg). On SQLite the default isCURRENT_TIMESTAMP, which is already UTC.
A non-UTC offset is refused
NaiveUtcDateTime does not convert -03:00 to UTC for you: it raises
ValueError (wrapped in StatementError at flush), with the message
NaiveUtcDateTime only accepts naive or UTC datetimes. Converting
silently would hide the bug of whoever built the value in the wrong zone.
Table without is_active¶
Use when the table has no is_active, or has one with another default.
Leave ActiveFlagMixin out and declare the column as it is:
# src/db/models/coupon.py
from sqlalchemy import Boolean
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from tempest_fastapi_sdk.db import IntegerPrimaryKeyMixin, NaiveTimestampMixin
class Base(DeclarativeBase):
"""The service's declarative base."""
class CouponModel(IntegerPrimaryKeyMixin, NaiveTimestampMixin, Base):
"""A coupon that starts inactive until the campaign begins."""
__tablename__ = "coupons"
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
SoftDeleteMixin (the deleted_at column) stays independent and composes
with any of these.
The response schema¶
Use BaseResponseSchema[int] when the key is an integer. Unsubscripted,
BaseResponseSchema keeps id: UUID:
# src/schemas/order.py
from tempest_fastapi_sdk.schemas import (
BaseResponseSchema,
PrimaryKeySchemaMixin,
TimestampSchemaMixin,
)
class CouponResponseSchema(BaseResponseSchema[int]):
"""A coupon response: integer id, is_active and timestamps."""
code: str
class OrderResponseSchema(PrimaryKeySchemaMixin[int], TimestampSchemaMixin):
"""An order response, whose table has no is_active."""
code: str
TimestampSchemaMixin normalizes to aware UTC after validation. So the
naive value coming out of the column goes on the wire with Z:
OrderResponseSchema(id=1, code="A1", created_at=datetime(2024, 1, 1), ...)
serializes "created_at":"2024-01-01T00:00:00Z".
| Schema mixin | Field |
|---|---|
PrimaryKeySchemaMixin[IdT] |
id: IdT (UUID unsubscripted) |
ActiveFlagSchemaMixin |
is_active: bool |
TimestampSchemaMixin |
created_at, updated_at, normalized to UTC |
The repository¶
Use BaseRepository[Model, Response, int] when the key is an integer. The
third parameter is the key type, and its default (UUID) keeps
BaseRepository[Model] as it always was:
# src/db/repositories/order.py
from sqlalchemy.ext.asyncio import AsyncSession
from tempest_fastapi_sdk.db import BaseRepository
from src.db.models.order import OrderModel
from src.schemas.order import OrderResponseSchema
class OrderRepository(BaseRepository[OrderModel, OrderResponseSchema, int]):
"""Order CRUD over the integer-keyed table."""
def __init__(self, session: AsyncSession) -> None:
"""Bind the repository to the order model.
Args:
session (AsyncSession): The request session.
"""
super().__init__(session, model=OrderModel)
async def find_order(session: AsyncSession) -> OrderModel:
"""Fetch order 1.
Args:
session (AsyncSession): The request session.
Returns:
OrderModel: The order.
"""
return await OrderRepository(session).get_by_id(1)
- The model does not have to inherit from
BaseModel. The constructor accepts any mapped class withidandcreated_atand refuses anything else withTypeError, naming what is missing (missing: created_at). - The key reaches the signatures.
get_by_id,resolve,delete,delete_batch,exists_excluding,soft_delete,restoreandbulk_upsert(returning_ids=True)use the third parameter's type. With[..., int], mypy--strictand pyright refuseget_by_id(uuid4()); without it, they refuseget_by_id(1). soft_delete/restoreonly really exist withis_active. On a model without the column, both raiseTypeErrorexplaining the model does not mapis_active, before touching the database.- The audit trail still requires
BaseModel.add_audited,update_auditedanddelete_auditedread__audit_redact__and__secret_columns__, which onlyBaseModeldeclares. On a foreign model, in a repository built withaudit_model=..., they raiseTypeErrorand point torecord_event, which stores no snapshot and works with any model. Withoutaudit_model=, the first error is the usual one, whatever the model:RuntimeError("BaseRepository was created without an audit_model; ...").
The service, controller and tenant repository¶
Use the PrimaryKeyT parameter on BaseService, BaseController,
TenantScopedRepository and StoredFileServiceMixin when the entity's
primary key is not UUID. The default remains UUID, so declarations that
omit it (BaseService[Repo, Resp], BaseService[Repo, Resp, Update],
BaseController[Service], TenantScopedRepository[Model]) keep working
without changes.
# src/services/order.py
from tempest_fastapi_sdk.controllers import BaseController
from tempest_fastapi_sdk.schemas import BaseSchema
from tempest_fastapi_sdk.services import BaseService
from src.db.repositories.order import OrderRepository
from src.schemas.order import OrderResponseSchema
class OrderUpdateSchema(BaseSchema):
"""Editable fields of an order."""
code: str | None = None
class OrderService(
BaseService[OrderRepository, OrderResponseSchema, OrderUpdateSchema, int]
):
"""Integer-keyed CRUD service for orders."""
class OrderController(
BaseController[OrderService, OrderResponseSchema, OrderUpdateSchema, int]
):
"""Integer-keyed CRUD controller for orders."""
async def rename_order(
controller: OrderController, order_id: int, code: str
) -> OrderResponseSchema:
"""Update an order's code by its integer primary key.
Args:
controller (OrderController): Controller injected by the router.
order_id (int): Integer primary key of the order.
code (str): New order code.
Returns:
OrderResponseSchema: The updated order.
"""
return await controller.update(order_id, OrderUpdateSchema(code=code))
BaseService[Repo, Resp, Update, int]: typesget_by_id,updateanddeletewithint. Under mypy--strictand pyright, passinguuid4()is rejected; without the fourth parameter, theUUIDdefault stays in force and rejectsint.BaseController[Service, Resp, Update, int]: typesget_by_id,updateanddeletewithint, keeping overrides such asasync def get_by_id(self, id: int)valid in both mypy and pyright.StoredFileServiceMixin[OrderModel, int]: for models with a stored-file key column, the second parameter (defaultUUID) typesrefonset_fileandclear_fileasint | OrderModeland accepts models outsideBaseModel.
On multi-tenant tables with an integer entity key, TenantScopedRepository
takes the same third int parameter — only the entity key changes;
tenant_id remains UUID:
# src/db/repositories/tenant_order.py
from uuid import UUID
from sqlalchemy import String, Uuid
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from tempest_fastapi_sdk.db import (
IntegerPrimaryKeyMixin,
NaiveTimestampMixin,
TenantScopedRepository,
)
from src.schemas.order import OrderResponseSchema
class TenantBase(DeclarativeBase):
"""The service's declarative base."""
class TenantOrderModel(IntegerPrimaryKeyMixin, NaiveTimestampMixin, TenantBase):
"""Multi-tenant order with an integer primary key and a UUID tenant_id."""
__tablename__ = "tenant_orders"
tenant_id: Mapped[UUID] = mapped_column(Uuid(), nullable=False, index=True)
code: Mapped[str] = mapped_column(String(32), nullable=False)
class TenantOrderRepository(
TenantScopedRepository[TenantOrderModel, OrderResponseSchema, int]
):
"""Multi-tenant repository with an integer entity key."""
def __init__(self, session: AsyncSession, tenant_id: UUID) -> None:
"""Bind the repository to the current tenant.
Args:
session (AsyncSession): The request session.
tenant_id (UUID): The tenant identifier.
"""
super().__init__(session, model=TenantOrderModel, tenant_id=tenant_id)
async def remove_order(
repo: TenantOrderRepository, order_id: int
) -> None:
"""Delete an order by integer id within the current tenant.
Args:
repo (TenantOrderRepository): Tenant-scoped repository.
order_id (int): Integer primary key of the order.
"""
await repo.delete(order_id)
Migrations¶
The Alembic render_enum_types hook writes NaiveUtcDateTime as
sa.TIMESTAMP(timezone=False), the same way it already wrote UtcDateTime
as sa.TIMESTAMP(timezone=True). The generated migration imports nothing
from the SDK.
Recap¶
BaseModeldid not change: it is the composition ofUUIDPrimaryKeyMixin,ActiveFlagMixinandTimestampMixin.- An existing database composes only what it has:
IntegerPrimaryKeyMixinforSERIAL,NaiveTimestampMixinforTIMESTAMP WITHOUT TIME ZONE, andis_activedeclared by hand when its meaning differs. NaiveUtcDateTimestores naive UTC, reads naive, and refuses other zones.BaseResponseSchema[int]for integer keys; the schema mixins for tables withoutis_active.BaseRepository[Model, Response, int]andTenantScopedRepository[Model, Response, int]run CRUD, pagination, tenant-scoped deletes and upsert over a model outsideBaseModel, with the entity key typed (tenant_idstaysUUID).BaseService[Repo, Response, Update, int],BaseController[Service, Response, Update, int]andStoredFileServiceMixin[Model, int]carry the integer key up through the service and controller layers without changing theUUIDdefault.