Ir para o conteúdo

tempest_fastapi_sdk.db

A camada de dados: BaseModel, BaseRepository, sessão assíncrona, mixins de model, migrations e hooks do Alembic.

« Admin, dados e API


BaseModel

Bases: UUIDPrimaryKeyMixin, ActiveFlagMixin, TimestampMixin, AsyncAttrs, DeclarativeBase

Abstract base for every SQLAlchemy model in the application.

Composes :class:UUIDPrimaryKeyMixin, :class:ActiveFlagMixin and :class:TimestampMixin over :class:~sqlalchemy.ext.asyncio.AsyncAttrs and :class:~sqlalchemy.orm.DeclarativeBase, giving every concrete model the four canonical columns: id (UUID primary key, cross-DB portable), is_active (soft-delete flag), created_at and updated_at (timezone-aware timestamps managed by the database).

Services adopting the SDK onto an existing schema with integer keys, naive UTC timestamps or without is_active can compose :class:IntegerPrimaryKeyMixin, :class:NaiveTimestampMixin, :class:TimestampMixin, :class:UUIDPrimaryKeyMixin and :class:ActiveFlagMixin directly on their own DeclarativeBase.

The class is marked __abstract__ so SQLAlchemy will not try to map it directly. Concrete subclasses get an auto-generated __tablename__ from their class name (e.g. UserModel → user, OrderItemModel → order_item); the Model suffix is stripped and the remainder is snake-cased. Explicit __tablename__ declarations still win when set.

Equality and hashing use (type, id) so the same row loaded across different sessions compares equal — useful in tests and sets. Unflushed instances (id is None) fall back to Python identity.

Attributes:

Name Type Description
metadata MetaData

Configured with :data:NAMING_CONVENTION so Alembic generates deterministic constraint names.

id UUID

Primary key. Generated as UUID v4. Uses sqlalchemy.Uuid so the same Python type works against PostgreSQL, MySQL, SQLite and MSSQL.

is_active bool

Whether the record is active. Defaults to True.

created_at datetime

Creation timestamp populated by the database on insert.

updated_at datetime

Last-update timestamp refreshed by the database on every update.

type_annotation_map class-attribute

type_annotation_map: dict[Any, Any] = {enum.Enum: TempestEnum()}

Default SQL type for every Mapped[SomeEnum] annotation.

Routes enum columns through :class:~tempest_fastapi_sdk.db.enums.TempestEnum so they store the member value, gain a CHECK constraint on backends without a native enum type, and get a collision-free type name on PostgreSQL — see that class for why each default differs from SQLAlchemy's.

A model that needs SQLAlchemy's stock behavior for one column can still declare it explicitly with mapped_column(sqlalchemy.Enum(...)); an explicit type always wins over the annotation map.

get_table_name classmethod

get_table_name() -> str

Return the name of the table this model is mapped to.

Reads the mapped table, not __tablename__: that is a declarative directive the mapper resolves, absent on a model declared with __table__ = Table(...), and typed by type-checkers as the directive rather than as str. The mapped table's name is the value the database sees in every case — the name derived from the class, an explicit __tablename__, or an explicit __table__. Under single-table inheritance a subclass answers its parent's table, which is where its rows live.

A classmethod rather than a property, because the common use is on the class (a dict key, the admin registry, a test), and chaining @classmethod with @property was removed in Python 3.13.

Example:

>>> from tempest_fastapi_sdk import BaseModel
>>> class OrderItemModel(BaseModel):
...     pass
>>> OrderItemModel.get_table_name()
'order_item'

Returns:

Name Type Description
str str

The table name.

Raises:

Type Description
NoInspectionAvailable

When called on an abstract model, which is not mapped at all.

TypeError

When the model is mapped onto an unnamed selectable (a join or a subquery) rather than a table.

get_secret_columns classmethod

get_secret_columns() -> frozenset[str]

Return every __secret_columns__ name declared along the MRO.

A plain class attribute lookup would return only the first declaration found, so class User(BaseUserModel, MFAMixin) would read BaseModel's empty set before reaching the mixin's. Walking the MRO and merging each class's own declaration makes the answer independent of the base order.

Example:

>>> from tempest_fastapi_sdk import BaseUserModel, MFAMixin
>>> class AgentModel(BaseUserModel, MFAMixin):
...     pass
>>> sorted(AgentModel.get_secret_columns())
['totp_secret']

Returns:

Type Description
frozenset[str]

frozenset[str]: The declared secret column names.

to_dict

to_dict(
    exclude: list[str] | None = None,
    include: dict[str, Any] | None = None,
    remove_none: bool = False,
) -> dict[str, Any]

Serialize the row to a plain dict.

Parameters:

Name Type Description Default
exclude list[str] | None

Column names to drop from the output.

None
include dict[str, Any] | None

Extra entries to merge into the output.

None
remove_none bool

Whether to strip keys whose value is None.

False

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The serialized representation.

update_from_dict

update_from_dict(data: dict[str, Any], allowed_fields: set[str] | None = None) -> None

Bulk-assign attributes from a dict.

Unknown keys are silently ignored — only mapped columns of self.__class__ are eligible. When allowed_fields is provided, only the intersection with model columns is applied; this is the recommended way to consume external payloads (e.g. PATCH bodies) so callers can't write to sensitive columns like id or role by mistake.

Parameters:

Name Type Description Default
data dict[str, Any]

The payload (typically schema.to_dict()).

required
allowed_fields set[str] | None

Whitelist of column names; only these keys are applied. None accepts every mapped column (use only for trusted payloads).

None

UUIDPrimaryKeyMixin

Declarative mixin providing a portable UUID v4 primary key id.

Uses :class:sqlalchemy.Uuid so the same Python type works across PostgreSQL, MySQL, SQLite and MSSQL.

Attributes:

Name Type Description
id UUID

Primary key, generated as UUID v4 by default.

IntegerPrimaryKeyMixin

Declarative mixin providing an auto-incrementing integer primary key id.

Intended for services adopting the SDK on top of an existing schema whose tables use INTEGER / SERIAL primary keys. Emits SERIAL on PostgreSQL and INTEGER (ROWID autoincrement) on SQLite.

Attributes:

Name Type Description
id int

Auto-incrementing integer primary key.

ActiveFlagMixin

Declarative mixin providing the canonical is_active boolean flag.

Kept separate from :class:~tempest_fastapi_sdk.db.mixins.SoftDeleteMixin (which adds an opt-in deleted_at timestamp column alongside is_active) so existing tables that either omit is_active or define it with their own semantics and default can compose only the columns they actually have.

Attributes:

Name Type Description
is_active bool

Whether the record is active. Defaults to True.

TimestampMixin

Declarative mixin providing timezone-aware UTC created_at / updated_at.

Uses :class:~tempest_fastapi_sdk.db.datetime_type.UtcDateTime (TIMESTAMP WITH TIME ZONE) so both PostgreSQL and SQLite bind and return aware UTC datetimes. For existing databases whose convention is TIMESTAMP WITHOUT TIME ZONE, compose :class:NaiveTimestampMixin instead.

Attributes:

Name Type Description
created_at datetime

Creation timestamp populated on flush and backed by server_default=NOW().

updated_at datetime

Last-update timestamp refreshed on every ORM UPDATE and backed by server_default=NOW().

NaiveTimestampMixin

Declarative mixin providing timezone-naive UTC created_at / updated_at.

Sibling of :class:TimestampMixin for existing databases storing UTC timestamps in TIMESTAMP WITHOUT TIME ZONE columns. Exposed as a static declarative mixin class (rather than a dynamic class factory) so SQLAlchemy Declarative, mypy --strict, Pyright and Pylance resolve created_at and updated_at statically without plugins.

Uses :class:~tempest_fastapi_sdk.db.datetime_type.NaiveUtcDateTime, which accepts naive or aware UTC values, strips UTC tzinfo on bind, refuses non-UTC offsets with ValueError, and always reads back naive datetime values.

Attributes:

Name Type Description
created_at datetime

Naive UTC creation timestamp populated on flush and backed by a server default of the current UTC time.

updated_at datetime

Naive UTC last-update timestamp refreshed on every ORM UPDATE and backed by a server default of the current UTC time.

BaseUserModel

Bases: BaseModel

Abstract user table with the columns the admin auth flow needs.

Inherits id/is_active/created_at/updated_at from :class:BaseModel and adds:

  • email (unique, indexed) — login identifier. Always stored lowercased; helpers handle the normalization.
  • hashed_password — bcrypt hash produced by :class:tempest_fastapi_sdk.PasswordUtils. Use :meth:set_password to write and :meth:check_password to verify so the hashing strategy stays consistent across callers.
  • is_admin — gate enforced by the admin auth backend; only users with is_admin=True may log in to /admin.
  • last_login_at — populated by the admin login view on every successful authentication.
  • email_verified_at — when the SDK last saw proof that the account holder reads the mailbox behind email; NULL when it never did. See the attribute entry below for what counts as proof.

The class is marked __abstract__ so SQLAlchemy does not try to map it directly; concrete projects subclass it and either keep the auto-derived __tablename__ (user) or override it.

The TOTP columns (totp_secret / totp_enabled_at / totp_last_step) live on :class:~tempest_fastapi_sdk.MFAMixin and the display name on :class:~tempest_fastapi_sdk.NameMixin, not here: a project that never enables MFA or never stores a display name should not carry the columns, so the migration lands only when the mixin is adopted (class UserModel(MFAMixin, NameMixin, BaseUserModel)). The type follows the runtime: user.name on a model without NameMixin is a type error, not an AttributeError waiting in production. Code that accepts any BaseUserModel narrows with isinstance(user, MFAMixin) / isinstance(user, NameMixin) before reading them.

Attributes:

Name Type Description
email str

Login identifier. Unique. 320 chars max (RFC 5321 mailbox limit).

hashed_password str

Bcrypt hash; never store plaintext.

is_admin bool

Whether the user can access the admin site.

last_login_at datetime | None

Last successful login timestamp.

email_verified_at datetime | None

When ownership of the current email was proven, or None when it never was. :class:~tempest_fastapi_sdk.UserAuthService sets it only where the SDK itself saw the proof: confirming an activation or e-mail-verification link that was mailed to this very address, confirming an e-mail change whose link was mailed to the new address, and creating an account from a social login whose provider reported email_verified is True. Activating through the admin site or tempest user activate, and the flows where the link comes back in the HTTP response (AUTH_AUTO_ACTIVATE, AUTH_RETURN_TOKEN_IN_RESPONSE, no EmailUtils), leave it alone. An ORM flush that changes email without also writing this column resets it to None, because the proof belonged to the previous address; a bulk UPDATE statement bypasses that and must clear it itself. Linking a social identity by e-mail (AUTH_OAUTH_LINK_BY_VERIFIED_EMAIL) requires it.

set_password

set_password(plain: str, *, rounds: int = 12) -> None

Hash plain and write it to :attr:hashed_password.

Parameters:

Name Type Description Default
plain str

The plaintext password.

required
rounds int

bcrypt cost factor. Defaults to 12.

12

Raises:

Type Description
ImportError

When the [auth] extra is not installed.

check_password

check_password(plain: str) -> bool

Return whether plain matches :attr:hashed_password.

Parameters:

Name Type Description Default
plain str

The plaintext password to verify.

required

Returns:

Name Type Description
bool bool

True when the password is correct.

Raises:

Type Description
ImportError

When the [auth] extra is not installed.

normalize_email staticmethod

normalize_email(value: str) -> str

Trim whitespace and lowercase value.

Parameters:

Name Type Description Default
value str

Raw user input.

required

Returns:

Name Type Description
str str

The normalized email.

BaseUserTokenModel

Bases: BaseModel

Abstract one-shot token used by the bundled auth flows.

Concrete subclasses pick the __tablename__ (user_tokens by convention) and add an FK to the project's concrete UserModel. The SDK never stores the plaintext token — only its hash via :func:tempest_fastapi_sdk.hash_opaque_token. The plaintext is returned exactly once (at creation) so it can be embedded in the activation / reset link.

Attributes:

Name Type Description
user_id UUID

Foreign key to the user this token authorizes. Inherits the project's user table name — concrete subclasses set the FK target explicitly.

token_hash str

SHA-256 hash of the plaintext token. Indexed + unique so lookups by hash are fast and duplicates impossible.

purpose str

One of :class:UserTokenPurposeEnum.

expires_at datetime

UTC timestamp the token becomes invalid. redeem() checks this against now() on every consumption.

used_at datetime | None

UTC timestamp the token was redeemed. Non-null means the token is spent and must not be accepted again.

payload str | None

Optional context the flow needs at redemption time — e.g. the pending new email for an EMAIL_CHANGE token. None for flows that carry no extra data (activation, password reset). Kept generic so future one-shot flows can reuse it. Bounded at 320 chars, the RFC-5321 maximum email length.

make_user_token_model

make_user_token_model(
    *,
    user_table: str,
    tablename: str = "user_tokens",
    class_name: str = "UserTokenModel",
) -> type[BaseUserTokenModel]

Build a concrete UserTokenModel subclass at runtime.

Used by tests and lightweight scripts. Production projects should instead ship a hand-written src/db/models/user_token.py so the FK column is editable and the class is importable for refactors.

Parameters:

Name Type Description Default
user_table str

Table name of the concrete UserModel the FK should reference (usually "users").

required
tablename str

__tablename__ for the generated class.

'user_tokens'
class_name str

Python class name; affects repr and Alembic identifiers.

'UserTokenModel'

Returns:

Type Description
type[BaseUserTokenModel]

type[BaseUserTokenModel]: A concrete mapped class.

BaseUserRecoveryCodeModel

Bases: BaseModel

Abstract recovery-code row used by the bundled MFA flow.

Concrete subclasses pick the __tablename__ (user_recovery_codes by convention) and add the FK to the project's concrete UserModel. The SDK never sees the plaintext after the enrollment response — only the hash is persisted.

Attributes:

Name Type Description
user_id UUID

Owner of the recovery code. Concrete subclasses MUST declare this as a ForeignKey so cascading deletes wipe the codes alongside the user.

code_hash str

SHA-256 hex digest of the plaintext recovery code. 64 characters.

used_at datetime | None

Timestamp the code was redeemed. NULL while available; populated by UserAuthService.mfa_verify when the user uses a recovery code to log in (e.g. lost Authenticator).

make_user_recovery_code_model

make_user_recovery_code_model(
    *,
    user_table: str,
    tablename: str = "user_recovery_codes",
    class_name: str = "UserRecoveryCodeModel",
) -> type[BaseUserRecoveryCodeModel]

Build a concrete recovery-code model bound to user_table.

Mirrors :func:tempest_fastapi_sdk.make_user_token_model — a one-call helper for projects that do not need to subclass the abstract base manually.

Parameters:

Name Type Description Default
user_table str

Name of the project's concrete user table (e.g. "users") — used as the FK target.

required
tablename str

Name of the recovery-code table. Defaults to "user_recovery_codes".

'user_recovery_codes'
class_name str

Python class name. Defaults to "UserRecoveryCodeModel".

'UserRecoveryCodeModel'

Returns:

Type Description
type[BaseUserRecoveryCodeModel]

type[BaseUserRecoveryCodeModel]: Concrete SQLAlchemy

type[BaseUserRecoveryCodeModel]

mapping with the FK + cascade set up correctly.

BaseWebAuthnCredentialModel

Bases: BaseModel

Abstract WebAuthn credential owned by one user.

Concrete subclasses pick the __tablename__ (user_webauthn_credentials by convention) and add the FK to the project's concrete UserModel.

Attributes:

Name Type Description
user_id UUID

Owner of the credential. Concrete subclasses MUST declare this as a ForeignKey so cascading deletes wipe the credentials alongside the user.

credential_id bytes

The authenticator's credential ID, raw. Unique across the table — an assertion arrives carrying only this, so it is how the login flow finds the account without a username.

credential_data bytes

The serialized AttestedCredentialData (AAGUID + credential ID + COSE public key) exactly as fido2 produced it. Stored as the opaque blob the library round-trips, so a format change upstream never needs a migration of parsed columns.

sign_count int

Signature counter reported by the authenticator at the last successful assertion. A counter that fails to advance is the spec's cloned-authenticator signal.

name str | None

User-supplied label ("YubiKey 5", "iPhone"), so a person managing several passkeys can tell them apart.

transports str | None

Comma-separated transport hints (usb, nfc, ble, internal, hybrid) reported at registration. Sent back in the assertion options so the browser can prompt for the right device.

aaguid str | None

Authenticator model identifier, hex. Useful for support ("which key is this?"), never for authorization.

backed_up bool

Whether the authenticator reported the credential as backed up (synced passkey) at registration. A device-bound credential is lost with the device; a synced one is not, which changes what account recovery must offer.

last_used_at datetime | None

Timestamp of the last successful assertion. NULL until the credential is first used.

make_web_authn_credential_model

make_web_authn_credential_model(
    *,
    user_table: str,
    tablename: str = "user_webauthn_credentials",
    class_name: str = "UserWebAuthnCredentialModel",
) -> type[BaseWebAuthnCredentialModel]

Build a concrete credential model bound to user_table.

Mirrors :func:tempest_fastapi_sdk.make_user_recovery_code_model — a one-call helper for projects that do not need to subclass the abstract base manually.

Parameters:

Name Type Description Default
user_table str

Name of the project's concrete user table (e.g. "users") — used as the FK target.

required
tablename str

Name of the credential table. Defaults to "user_webauthn_credentials".

'user_webauthn_credentials'
class_name str

Python class name. Defaults to "UserWebAuthnCredentialModel".

'UserWebAuthnCredentialModel'

Returns:

Type Description
type[BaseWebAuthnCredentialModel]

type[BaseWebAuthnCredentialModel]: Concrete SQLAlchemy mapping

type[BaseWebAuthnCredentialModel]

with the FK + cascade set up correctly.

BaseUserOAuthAccountModel

Bases: BaseModel

Abstract linked-identity row for the bundled OAuth login flow.

Concrete subclasses pick the __tablename__ (user_oauth_accounts by convention) and add the FK to the project's concrete UserModel. Both unique constraints are declared here rather than left to the subclass, so a hand-written mapping cannot ship without them:

  • UNIQUE (provider, subject) — one local user per third-party identity. Without it two rows could claim the same Google account, and which user a callback resolves to would depend on row order.
  • UNIQUE (user_id, provider) — one link per provider per user, which is what makes POST /auth/oauth/accounts/unlink name a single row.

Attributes:

Name Type Description
user_id UUID

Owner of the link. Concrete subclasses MUST declare this as a ForeignKey so cascading deletes wipe the links alongside the user.

provider str

Provider key as :attr:~tempest_fastapi_sdk.OAuthUser.provider reports it ("google", "github", "oidc:auth0" …).

subject str

Stable per-provider user id. Opaque; compare, never parse.

email str | None

Email the provider reported at link time. Stored for display and support, not used to resolve the login — the (provider, subject) pair is.

email_verified bool | None

Whether the provider stated it had verified that address. None means the provider said nothing either way, which is not the same as False.

name str | None

Display name the provider reported.

picture str | None

Avatar URL the provider reported.

last_login_at datetime | None

Last time this link completed a callback. NULL until the second login through it.

make_user_oauth_account_model

make_user_oauth_account_model(
    *,
    user_table: str,
    tablename: str = "user_oauth_accounts",
    class_name: str = "UserOAuthAccountModel",
) -> type[BaseUserOAuthAccountModel]

Build a concrete OAuth-account model bound to user_table.

Mirrors :func:~tempest_fastapi_sdk.make_user_refresh_token_model — a one-call helper for projects that do not need to subclass the abstract base manually. Production projects should still ship a hand-written src/db/models/user_oauth_account.py so the FK column is editable and the class is importable for refactors.

Parameters:

Name Type Description Default
user_table str

Name of the project's concrete user table (e.g. "users") — used as the FK target.

required
tablename str

Name of the linked-identity table. Defaults to "user_oauth_accounts".

'user_oauth_accounts'
class_name str

Python class name. Defaults to "UserOAuthAccountModel".

'UserOAuthAccountModel'

Returns:

Type Description
type[BaseUserOAuthAccountModel]

type[BaseUserOAuthAccountModel]: Concrete SQLAlchemy mapping

type[BaseUserOAuthAccountModel]

with the FK, the cascade and both unique constraints in place.

BaseRepository

BaseRepository(
    session: AsyncSession,
    *,
    model: type[ModelType],
    not_found_exception: type[AppException] = NotFoundException,
    conflict_exception: type[AppException] = ConflictException,
    create_conflict_exception: type[AppException] | None = None,
    update_conflict_exception: type[AppException] | None = None,
    bulk_create_conflict_exception: type[AppException] | None = None,
    bulk_update_conflict_exception: type[AppException] | None = None,
    not_found_message: str | None = None,
    create_conflict_message: str | None = None,
    update_conflict_message: str | None = None,
    bulk_create_conflict_message: str | None = None,
    bulk_update_conflict_message: str | None = None,
    audit_model: type[BaseAuditLogModel] | None = None,
    autocommit: bool = True,
    orderable_columns: Iterable[str] | None = None,
    max_page_size: int | None = None,
    searchable_columns: Iterable[str] | None = None,
)

Bases: Generic[ModelType, ResponseT, PrimaryKeyT]

Base async repository with generic CRUD operations.

Generic parameters

ModelType: The SQLAlchemy ORM model managed by the repository. ResponseT: Optional API response schema returned by :meth:map_to_response. Defaults to Any so BaseRepository[Model] stays compatible; pass BaseRepository[Model, ResponseSchema] to type :meth:map_to_response and bind :class:BaseService to the same schema. PrimaryKeyT: Optional primary-key type used by :meth:get_by_id, :meth:delete, :meth:delete_batch, :meth:soft_delete, :meth:restore, :meth:resolve, :meth:exists_excluding and bulk_upsert(returning_ids=True). Defaults to UUID.

The model does not have to inherit from :class:~tempest_fastapi_sdk.db.model.BaseModel: any mapped class with an id and a created_at (:class:RepositoryModelProtocol) is accepted, so BaseRepository[LegacyModel, LegacyResponse, int] runs CRUD, pagination and upsert over an integer-keyed table.

Instantiate directly for plain CRUD (BaseRepository(session, model=UserModel)) or subclass when adding custom queries — the subclass forwards model / not_found_exception to super().__init__ instead of declaring class attributes. The constructor signature is the contract. The two exceptions are the pagination guards orderable_columns and max_page_size, which a subclass may declare as class attributes (mirroring the filter schema, where the same names live) or pass to the constructor — the constructor wins.

Sorting is an oracle when order_by comes from a query parameter: ordering users by wallet ranks every row by balance, and a caller who controls their own row extracts another row's value by binary search over where theirs lands. Declaring orderable_columns makes every other column a 422 (:class:OrderByNotAllowedException, details["allowed"] listing only the declared set). Left None, any mapped column still sorts — the historical behavior — but the refusal no longer publishes the mapper's column list.

Text search is the same oracle on the searched column: fields that come from a query parameter let a caller learn, row by row, whether a column contains a substring. :meth:search, :meth:search_condition, :meth:full_text_search and :meth:full_text_condition therefore always refuse hashed_password and the model's __secret_columns__, and searchable_columns (class attribute or constructor argument, like orderable_columns) narrows fields to a declared set. The 422 names the rejected field and, only when a set is declared, details["allowed"].

Every filters argument is a mapping from column name to the value that column must hold, and the pairs are ANDed: {"user_id": 1234, "is_active": True} selects the rows where user_id = 1234 and is_active is true. A plain value is exact equality — on a string column that includes case, so {"status": "OPEN"} does not match "open" (measured on SQLite). An empty mapping adds no condition.

A key the model has no SQL-expressible attribute for — a typo such as {"usr_id": 1234}, or an unknown operator suffix such as {"user_id__bogus": 1} — raises :class:~tempest_fastapi_sdk.UnknownFilterKeyException (422, code="UNKNOWN_FILTER_KEY", details={"filter": <key>}) before any statement runs, in every method that takes filters and in :class:Q. Until #465 the key was dropped in silence: with only a misspelled key, :meth:list and :meth:count matched every row, and :meth:bulk_update and :meth:delete_many changed every row in the table.

On top of equality, the following conventions apply:

  • name (string) → case-insensitive ILIKE %value% search.
  • bool values → .is_(value) (correct SQL boolean check).
  • non-string iterable values (list / set / tuple / frozenset / range / generator / dict view) → .in_(values) membership; the iterable is materialized once, so passing a set needs no manual conversion to a list.
  • date values → func.date(column) == value whole-day match.
  • start_in / end_in (date) → range filter against the model's date column when present, falling back to created_at.
  • <column>__<op> suffix → operator filter, where <op> is one of: gt / gte / lt / lte / ne (comparison, e.g. {"updated_at__gt": watermark} → updated_at > watermark), in / notin / not_in (membership; not_in aliases notin), between ({"price__between": (10, 20)} → price BETWEEN 10 AND 20; value is an ordered two-item list/tuple), iexact (case-insensitive equality), like / ilike (raw un-escaped LIKE with your own wildcards), isnull, and contains / icontains / startswith / endswith (escaped ILIKE). Comparison suffixes are timestamp-precise, unlike start_in / end_in (whole-day); this is what delta-sync queries filter on. A None value on one of these suffixes has nothing to compare against, so the condition is dropped with a :class:~tempest_fastapi_sdk.DroppedFilterWarning.
  • None on a bare column → col IS NULL ({"deleted_at": None} matches what was never deleted), and on __ne → col IS NOT NULL. It used to be dropped, which silently widened the query to every row — see :func:~tempest_fastapi_sdk.build_filter_condition.

All error messages can be customized per repository instance via the constructor kwargs (not_found_message, create_conflict_message, etc.); when omitted, sensible defaults derived from self.model.__name__ are used.

Each message has a matching exception class kwarg (not_found_exception, conflict_exception and the per-operation create_conflict_exception / update_… / bulk_create_… / bulk_update_…). They exist because a message alone cannot be branched on: the default ConflictException answers code = "CONFLICT", so every duplicate-key failure in the service looks identical to a client. Passing a domain subclass — which declares its own code — makes the 409 identifiable without the repository knowing anything about the domain.

The same three abstract mappers map_to_schema / map_to_model / map_to_response are kept so concrete repositories own the translation between ORM rows and DTOs.

Attributes:

Name Type Description
model type[ModelType]

The SQLAlchemy model class operated on.

not_found_exception type[AppException]

Exception class raised when single-record lookups miss.

create_conflict_exception type[AppException]

Exception class raised when add / save_with_outbox / add_audited hit IntegrityError.

update_conflict_exception type[AppException]

Same, for update / update_audited.

bulk_create_conflict_exception type[AppException]

Same, for add_all / bulk_create_values / bulk_upsert.

bulk_update_conflict_exception type[AppException]

Same, for update_many / bulk_update / update_returning.

session AsyncSession

The async database session.

orderable_columns ClassVar[frozenset[str] | None]

Class-level default for the columns order_by may name in :meth:paginate, :meth:cursor_paginate and :meth:changes_since. None accepts any mapped column.

searchable_columns ClassVar[frozenset[str] | None]

Class-level default for the columns fields may name in the text-search methods. None accepts any mapped column that is not hashed_password or in __secret_columns__.

max_page_size ClassVar[int | None]

Class-level default ceiling on page_size (and the cursor limit). None — the default, because internal callers such as the admin export page by the thousand — applies no ceiling.

Initialize the repository.

Every *_message kwarg is optional — when not provided, the repository falls back to a generic message derived from the model class name (e.g. "User not found", "Conflict creating User").

Every *_exception kwarg is optional too, and each one pairs with the *_message of the same name. Passing a domain subclass is what gives the failure a code of its own: ConflictException answers "CONFLICT", so a client cannot tell a duplicate coin pack apart from any other 409 (the same reason :class:AppException warns when a subclass declares no code). Conflicts resolve most-specific-first — create_conflict_exception if given, else conflict_exception, else :class:ConflictException — so one kwarg can cover every write, or each write can differ.

The class is instantiated as cls(message=...), the same contract not_found_exception already has, so a subclass must accept a message keyword. Declaring code in the class body and taking message optionally satisfies both.

Parameters:

Name Type Description Default
session AsyncSession

The async database session.

required
model type[ModelType]

The SQLAlchemy model class this repository operates on. Required.

required
not_found_exception type[AppException]

Exception class raised when single-record lookups miss. Defaults to :class:NotFoundException; pass a domain-specific subclass for richer 404 messages. It is instantiated as exception_class(message=...), so a class whose __init__ takes only the record id — the shape one writes first, since the id is what the caller holds — turns every miss into a TypeError: a 500 where the 404 belongs, with nothing naming the cause. :func:~tempest_fastapi_sdk.not_found_exception builds a class that accepts both call shapes.

NotFoundException
conflict_exception type[AppException]

Exception class raised when a write hits IntegrityError. Defaults to :class:ConflictException; the per-operation kwargs below override it.

ConflictException
create_conflict_exception type[AppException] | None

Overrides conflict_exception for add, save_with_outbox and add_audited.

None
update_conflict_exception type[AppException] | None

Overrides conflict_exception for update and update_audited.

None
bulk_create_conflict_exception type[AppException] | None

Overrides conflict_exception for add_all, bulk_create_values and bulk_upsert.

None
bulk_update_conflict_exception type[AppException] | None

Overrides conflict_exception for update_many, bulk_update and update_returning.

None
not_found_message str | None

Message used when get, get_by_id, delete, soft_delete or restore find no matching record.

None
create_conflict_message str | None

Message used when add raises IntegrityError.

None
update_conflict_message str | None

Message used when update raises IntegrityError.

None
bulk_create_conflict_message str | None

Message used when add_all raises IntegrityError.

None
bulk_update_conflict_message str | None

Message used when update_many, bulk_update or update_returning raises IntegrityError.

None
autocommit bool

Whether a write method commits on its own. True (the default) keeps the historical behavior — add / update / delete each end in a COMMIT. False makes every write flush instead, leaving the commit to an explicit :meth:commit or to a :meth:transaction block; reach for it when a whole repository belongs to a caller-owned unit of work. It does not disable :meth:commit — an explicit call still commits.

True
orderable_columns Iterable[str] | None

The columns order_by may name on this instance. None falls back to the class attribute of the same name.

None
max_page_size int | None

Inclusive ceiling on page_size / limit for this instance. None falls back to the class attribute of the same name.

None
searchable_columns Iterable[str] | None

The columns the text-search methods may name in fields on this instance. None falls back to the class attribute of the same name.

None

Raises:

Type Description
TypeError

When model is not a mapped SQLAlchemy class, or does not map the id and created_at attributes :class:RepositoryModelProtocol requires.

ValueError

When the effective orderable_columns names something that is not a mapped column of model — a declaration typo would otherwise refuse the column the listing meant to allow, on every request — or when the effective max_page_size is below 1, or when the effective searchable_columns names an unmapped column, hashed_password or a __secret_columns__ entry.

dialect property

dialect: str

Return the SQLAlchemy dialect name of the bound database.

Read at call time rather than cached at construction because the same repository class runs against PostgreSQL in production and SQLite under test, and the search layer branches on it.

Returns:

Name Type Description
str str

The dialect name ("postgresql", "sqlite", …).

supports_full_text property

supports_full_text: bool

Whether the bound database can rank a full-text search.

Lets a caller tell a ranked result from an unranked one — on SQLite :meth:full_text_search still returns the right rows, it just cannot order them by relevance.

Returns:

Name Type Description
bool bool

True when the backend has a full-text engine.

commit async

commit() -> None

Commit the session's pending work.

Exists because the repository is the boundary that owns the session: a service composing business rules should be able to say "this is the durable point" without reaching for repository.session and coupling itself to SQLAlchemy. It is also more honest than the alternative it replaces — calling update purely for its commit side effect.

Inside an open :func:~tempest_fastapi_sdk.db.transaction.transaction block this flushes instead, because committing there would break the block's all-or-nothing guarantee. That makes the call safe to leave in place when a caller later wraps the code in a block, which a bare session.commit() is not.

flush async

flush() -> None

Send pending changes to the database without committing.

Use it to make a row visible to subsequent statements in the same transaction — typically to read back a server-generated primary key before inserting a child row that references it.

This forwards to the session unconditionally; it is the one member of the transaction group with no branching of its own, and it is kept for the same reason as :meth:commit — so callers never need a reference to session.

rollback async

rollback() -> None

Discard the session's pending, uncommitted work.

Raises:

Type Description
RuntimeError

When a :func:~tempest_fastapi_sdk.db.transaction.transaction block is open. A rollback there would discard the whole block — including writes made by other repositories sharing the session — while the caller believes it is undoing only its own step. Raise or let the exception propagate to abort the block, or wrap the recoverable part in :meth:savepoint.

transaction

transaction() -> AbstractAsyncContextManager[AsyncSession]

Group every write on this session into a single commit.

Sugar for :func:tempest_fastapi_sdk.db.transaction.transaction bound to this repository's session. Because the block is tracked on the session — not on the repository — repositories that share the session join the same block:

async with orders.transaction():
    await orders.add(order)
    await items.add_all(rows)   # different repository, same block

Returns:

Type Description
AbstractAsyncContextManager[AsyncSession]

AbstractAsyncContextManager[AsyncSession]: The block; the

AbstractAsyncContextManager[AsyncSession]

session is yielded so it can be bound with as.

explain

explain(*, analyze: bool = True) -> AbstractAsyncContextManager[ExplainReport]

Capture the query plan of everything run inside the block.

Sugar for :func:tempest_fastapi_sdk.db.explain.explain_queries bound to this repository's session. A development tool — it re-runs each captured SELECT to measure it, so it does not belong in a hot request path:

async with repository.explain() as report:
    await repository.paginate(filters={"status": "open"}, page=3)
print(report.report())

Parameters:

Name Type Description Default
analyze bool

Whether SELECT statements may be executed a second time to collect measured timings. Writes are never re-executed regardless.

True

Returns:

Type Description
AbstractAsyncContextManager[ExplainReport]

AbstractAsyncContextManager[ExplainReport]: The block; the

AbstractAsyncContextManager[ExplainReport]

report fills in on exit.

savepoint

savepoint() -> AbstractAsyncContextManager[AsyncSession]

Run a nested, individually revertible unit of work.

Sugar for :func:tempest_fastapi_sdk.db.transaction.savepoint bound to this repository's session. Use it for a step whose failure you intend to catch without losing the surrounding work.

Returns:

Type Description
AbstractAsyncContextManager[AsyncSession]

AbstractAsyncContextManager[AsyncSession]: The savepoint

AbstractAsyncContextManager[AsyncSession]

block; the session is yielded so it can be bound with as.

search_condition

search_condition(
    term: str, *, fields: Sequence[ColumnRef], token_match: TokenMatchEnum = ALL
) -> ColumnElement[bool] | None

Build a portable substring-search condition over fields.

Identical on every backend: each whitespace-separated token is matched case-insensitively against every listed column, with the user's own % and _ escaped so they match literally.

Returned rather than executed so it composes with the normal reads — pass it as where= to :meth:paginate and the search is paginated and counted like any other filter:

page = await repository.paginate(
    where=repository.search_condition("joao", fields=["name", "email"]),
    page=2,
)

Parameters:

Name Type Description Default
term str

The raw search term.

required
fields Sequence[ColumnRef]

Columns to search, by name or as mapped attributes (UserModel.name).

required
token_match TokenMatchEnum

Whether every token must match (default) or any single one is enough.

ALL

Returns:

Type Description
ColumnElement[bool] | None

ColumnElement[bool] | None: The condition, or None for a

ColumnElement[bool] | None

blank term — passing that back as where= applies no

ColumnElement[bool] | None

filter, so an empty search box lists everything.

Raises:

Type Description
ValidationException

When fields is empty or names a column the model does not have, a secret column, or one outside searchable_columns.

full_text_condition

full_text_condition(
    term: str,
    *,
    fields: Sequence[ColumnRef],
    language: TextSearchLanguageEnum = PORTUGUESE,
    weights: Mapping[str, TextSearchWeightEnum] | None = None,
    token_match: TokenMatchEnum = ALL,
) -> ColumnElement[bool] | None

Build a full-text condition, or the portable fallback.

On PostgreSQL this stems the term (so comprou finds comprar), drops stop words and accepts the search syntax users already type — "exact phrase", -excluded. On any other backend it degrades to :meth:search_condition, which finds the right rows without stemming or ranking.

Parameters:

Name Type Description Default
term str

The raw search term.

required
fields Sequence[ColumnRef]

Columns to search.

required
language TextSearchLanguageEnum

Stemming configuration.

PORTUGUESE
weights Mapping[str, TextSearchWeightEnum] | None

Per-column weight for the relevance score, keyed by column name. Pass the same mapping to :meth:full_text_search.

None
token_match TokenMatchEnum

Used only by the fallback path.

ALL

Returns:

Type Description
ColumnElement[bool] | None

ColumnElement[bool] | None: The condition, or None for a

ColumnElement[bool] | None

blank term.

Raises:

Type Description
ValidationException

When fields is empty or names a column the model does not have, a secret column, or one outside searchable_columns.

get async

get(
    filters: dict[str, Any],
    for_update: bool = False,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> ModelType

Return the single record matching filters.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

required
for_update bool

Whether to acquire a row-level lock (SELECT ... FOR UPDATE). Defaults to False.

False
with_ list[str] | None

Relationship paths to eager-load (selectinload), dotted for nested relations (e.g. ["author", "comments.replies"]). Avoids the lazy-load MissingGreenlet error when accessing relationships outside the session's async context.

None
where WhereClause | None

A :class:Q condition tree ANDed with filters for OR / NOT logic the dict cannot express.

None

Returns:

Name Type Description
ModelType ModelType

The matching row.

Raises:

Type Description
AppException

self.not_found_exception with the configured not_found_message if no record matches the filters.

ValueError

When a with_ path names a non-relationship.

get_or_none async

get_or_none(
    filters: dict[str, Any],
    for_update: bool = False,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> ModelType | None

Return the single record matching filters or None.

Unlike :meth:get, never raises when nothing matches.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

required
for_update bool

Whether to acquire a row-level lock.

False
with_ list[str] | None

Relationship paths to eager-load; see :meth:get.

None
where WhereClause | None

A :class:Q condition tree ANDed with filters.

None

Returns:

Type Description
ModelType | None

ModelType | None: The matching row, or None.

Raises:

Type Description
ValueError

When a with_ path names a non-relationship.

get_by_id async

get_by_id(
    id: PrimaryKeyT, for_update: bool = False, with_: list[str] | None = None
) -> ModelType

Return the record with the given primary key.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key to look up.

required
for_update bool

Whether to acquire a row-level lock.

False
with_ list[str] | None

Relationship paths to eager-load; see :meth:get.

None

Returns:

Name Type Description
ModelType ModelType

The matching row.

Raises:

Type Description
AppException

self.not_found_exception if no record with id exists.

ValueError

When a with_ path names a non-relationship.

resolve async

resolve(ref: PrimaryKeyT | ModelType, for_update: bool = False) -> ModelType

Resolve an id-or-instance reference to a model instance.

Accepts either a primary key or an already-loaded model instance and always returns the instance. This removes the if isinstance(x, UUID): ... else: ... boilerplate services reimplement whenever a method takes UUID | Model. Anything that is not an instance of :attr:model is treated as a primary key.

When given a detached instance (one whose session has been closed — e.g. a user loaded by an auth dependency on its own short-lived session) it is re-attached to this repository's session via :meth:AsyncSession.merge. Returning it as-is would later raise InvalidRequestError: Instance is not persistent within this Session on the first commit / refresh. merge issues a SELECT only when the row is not already in this session's identity map.

Parameters:

Name Type Description Default
ref PrimaryKeyT | ModelType

The primary key to look up, or an already-loaded instance to attach and return.

required
for_update bool

Whether to acquire a row-level lock when ref is a primary key (ignored when an instance is given).

False

Returns:

Name Type Description
ModelType ModelType

The resolved instance, attached to this session.

Raises:

Type Description
AppException

self.not_found_exception when ref is a primary key with no matching row.

exists async

exists(filters: dict[str, Any], where: WhereClause | None = None) -> bool

Return whether at least one row matches filters.

Executes a SELECT 1 ... LIMIT 1 so the row is never fully loaded.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

required
where WhereClause | None

A :class:Q condition tree ANDed with filters.

None

Returns:

Name Type Description
bool bool

True if at least one row matches.

exists_excluding async

exists_excluding(filters: dict[str, Any], *, exclude_id: PrimaryKeyT | None) -> bool

Return whether another row matches filters, excluding one id.

The "is this value already taken by someone else?" check that unique-field validation needs on update — e.g. confirming a new email / phone / username isn't used by a different record before saving. When exclude_id is None (the create case, no row to exclude yet) it behaves exactly like :meth:exists.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException. For this check the usual shape is one unique column, {"phone": "+5511..."}.

required
exclude_id PrimaryKeyT | None

The primary key to exclude from the match (typically the row being updated). None excludes nothing.

required

Returns:

Name Type Description
bool bool

True if a row other than exclude_id matches.

first async

first(
    filters: dict[str, Any] | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> ModelType | None

Return the first matching row or None.

Convenience wrapper around :meth:list for cases that only need one row but want to control ordering.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

None
order_by Any | None

A SQLAlchemy column expression to order by. None keeps insertion order.

None
ascending bool

Whether to order ascending.

True
with_ list[str] | None

Relationship paths to eager-load; see :meth:get.

None
where WhereClause | None

A :class:Q condition tree ANDed with filters.

None

Returns:

Type Description
ModelType | None

ModelType | None: The first matching row, or None.

Raises:

Type Description
ValueError

When a with_ path names a non-relationship.

list async

list(
    filters: dict[str, Any] | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> list[ModelType]

Return every record matching filters.

Returns [] (never raises) when nothing matches, in line with the SDK collection convention.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

None
order_by Any | None

A SQLAlchemy column expression (e.g. MyModel.name). None keeps insertion order.

None
ascending bool

Whether to order ascending. Ignored when order_by is None.

True
with_ list[str] | None

Relationship paths to eager-load; see :meth:get. Uses selectinload, so N related rows cost one extra query, not N.

None
where WhereClause | None

A :class:Q condition tree ANDed with filters for OR / NOT logic (e.g. Q(a=1) | Q(b=2)).

None

Returns:

Type Description
list[ModelType]

list[ModelType]: The matching rows.

Raises:

Type Description
ValueError

When a with_ path names a non-relationship.

search async

search(
    term: str,
    *,
    fields: Sequence[ColumnRef],
    token_match: TokenMatchEnum = ALL,
    filters: dict[str, Any] | None = None,
    where: WhereClause | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
    with_: List[str] | None = None,
    limit: int | None = None,
) -> List[ModelType]

Return rows whose fields contain the search term.

The portable layer: same behavior on PostgreSQL and SQLite, no index or extension required. Each whitespace-separated token is matched case-insensitively against every listed column, and the user's own % / _ are escaped so they match literally.

Returns [] when nothing matches, per the SDK collection convention. A blank term applies no text filter, so the result is whatever filters / where alone select — an empty search box lists rather than hides.

Parameters:

Name Type Description Default
term str

The raw search term.

required
fields Sequence[ColumnRef]

Columns to search, by name or as mapped attributes (UserModel.name).

required
token_match TokenMatchEnum

Whether every token must match (default) or any single one is enough.

ALL
filters dict[str, Any] | None

Extra conditions ANDed with the search, column name to value, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

None
where WhereClause | None

A further condition ANDed in.

None
order_by Any | None

A SQLAlchemy column expression. None keeps insertion order — this layer has no relevance score to order by; use :meth:full_text_search for that.

None
ascending bool

Order direction; ignored without order_by.

True
with_ List[str] | None

Relationship paths to eager-load.

None
limit int | None

Cap on rows returned.

None

Returns:

Type Description
List[ModelType]

List[ModelType]: The matching rows.

Raises:

Type Description
ValidationException

When fields is empty or names a column the model does not have, a secret column, or one outside searchable_columns.

ValueError

When a with_ path names a non-relationship.

full_text_search(
    term: str,
    *,
    fields: Sequence[ColumnRef],
    language: TextSearchLanguageEnum = PORTUGUESE,
    weights: Mapping[str, TextSearchWeightEnum] | None = None,
    token_match: TokenMatchEnum = ALL,
    filters: dict[str, Any] | None = None,
    where: WhereClause | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
    with_: List[str] | None = None,
    limit: int | None = None,
) -> List[ModelType]

Return rows matching the term, ranked by relevance on PostgreSQL.

Stems the term against language (so comprou finds comprar), drops stop words, and accepts the syntax users already type in a search box — "exact phrase" and -excluded. Results come back ordered by ts_rank, strongest first.

On a backend without full-text support this degrades to :meth:search: the right rows, unranked and unstemmed. Read :attr:supports_full_text when the caller needs to know which of the two it got.

Parameters:

Name Type Description Default
term str

The raw search term.

required
fields Sequence[ColumnRef]

Columns to search.

required
language TextSearchLanguageEnum

Stemming configuration.

PORTUGUESE
weights Mapping[str, TextSearchWeightEnum] | None

Per-column weight for the score, keyed by column name; columns left out rank lowest. A term in a title outranking the same term in a body is this parameter.

None
token_match TokenMatchEnum

Used only on the fallback path; PostgreSQL already treats separate words as AND.

ALL
filters dict[str, Any] | None

Extra conditions ANDed in, column name to value, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

None
where WhereClause | None

A further condition ANDed in.

None
order_by Any | None

An explicit ordering that replaces the relevance ranking. Leave it None to rank.

None
ascending bool

Direction for an explicit order_by.

True
with_ List[str] | None

Relationship paths to eager-load.

None
limit int | None

Cap on rows returned.

None

Returns:

Type Description
List[ModelType]

List[ModelType]: The matching rows, ranked where the backend

List[ModelType]

can rank them.

Raises:

Type Description
ValidationException

When fields is empty or names a column the model does not have, a secret column, or one outside searchable_columns.

ValueError

When a with_ path names a non-relationship.

paginate async

paginate(
    filters: dict[str, Any] | None = None,
    order_by: str | None = None,
    page: int = 1,
    page_size: int = 20,
    ascending: bool = True,
    query: Select[Any] | None = None,
    where: WhereClause | None = None,
) -> dict[str, Any]

Return a single page of records matching filters.

When order_by is None, falls back to self.model.created_at.desc(). The total count is computed from the same filtered (and possibly joined) query, so custom queries with joins still report a correct total.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

None
order_by str | None

Column name to order by, or None to fall back to created_at desc.

None
page int

The 1-indexed page number.

1
page_size int

The number of items per page.

20
ascending bool

Whether to order ascending. Ignored when order_by is None.

True
query Select[Any] | None

A pre-built Select; if None, defaults to select(self.model).

None
where WhereClause | None

A :class:Q condition tree ANDed with filters; applied to both the page and its count.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A mapping with keys items, total,

dict[str, Any]

page, page_size, pages — the same names

dict[str, Any]

class:BasePaginationSchema declares, so the envelope maps

dict[str, Any]

across field by field.

Raises:

Type Description
OrderByNotAllowedException

When order_by names something that is not a mapped column, or is outside orderable_columns. It arrives from a query parameter, so a bad value answers 422 rather than crashing the request.

PageSizeTooLargeException

When max_page_size is set and page_size exceeds it.

cursor_paginate async

cursor_paginate(
    filters: dict[str, Any] | None = None,
    cursor: str | None = None,
    limit: int = 20,
    order_by: str = "created_at",
    ascending: bool = False,
    query: Select[Any] | None = None,
) -> dict[str, Any]

Return a single cursor-paginated page of records.

Cursor pagination orders by (order_by, id) so the result is stable under concurrent inserts and scales without a COUNT(*). The cursor encodes the last row's (order_by_value, id) so the next page can continue precisely past it. The encoded value is JSON, so it comes back as a string for every non-JSON type; it is rehydrated into the column's Python type (datetime, date, time, UUID, Decimal, Enum) before the comparison is built, which is what keeps the predicate valid on PostgreSQL.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

None
cursor str | None

Opaque cursor from the previous page; None requests the first page.

None
limit int

Maximum items to return in this page.

20
order_by str

Column to sort by. Must exist on the model.

'created_at'
ascending bool

Whether to sort ascending. Defaults to False.

False
query Select[Any] | None

A pre-built Select to paginate; if None, defaults to select(self.model). Mirrors :meth:paginate so a hand-built query (joins, IS NULL predicates the filter dict can't express, etc.) can still be cursor-paginated. filters and the cursor/order clauses are applied on top of it.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Mapping with items, next_cursor,

dict[str, Any]

has_more and limit.

Raises:

Type Description
OrderByNotAllowedException

When order_by is not a mapped column on the model, or is outside orderable_columns — it comes from a query parameter, so a bad value is a 422 and not a server error.

PageSizeTooLargeException

When max_page_size is set and limit exceeds it.

ValueError

When cursor is malformed.

changes_since async

changes_since(
    since: datetime | None,
    *,
    filters: dict[str, Any] | None = None,
    cursor: str | None = None,
    limit: int = 50,
    order_by: str = "updated_at",
    include_deleted: bool = True,
    watermark_lag: timedelta = DEFAULT_SYNC_WATERMARK_LAG,
) -> dict[str, Any]

Return the rows that changed since a high-water mark.

The backbone of offline-first / delta sync: an offline client (mobile app, PWA) replays only what changed since its last successful pull instead of refetching the whole table. Rows are ordered ascending by order_by (oldest change first) and tie-broken by id, so the client can advance its watermark monotonically and resume mid-stream with the returned cursor.

Recommended watermark protocol:

  1. First sync: call with since=None (returns everything, cursor-paginated). Drain every page via next_cursor.
  2. Persist the returned server_time (NOT the max updated_at of the items) as the next since.
  3. Next sync: call with that since. The filter is updated_at > since (strict), and server_time is captured before the query runs, so a write stamped after that instant surfaces on the following pull.

server_time is set watermark_lag behind the instant the query started (:data:DEFAULT_SYNC_WATERMARK_LAG, five seconds). updated_at is stamped at flush time, not at commit, so a write that flushed before the pull and committed after it is older than the pull; with the mark at "now" no incremental pull would ever return it. Behind by the lag, the next pull re-reads the window and finds it, as long as its transaction lasted less than the lag. The same covers replicas whose clocks disagree by less than the lag. Rows changed inside the window therefore arrive twice: apply items idempotently (upsert by id). timedelta(0) restores the mark at "now", and the loss with it.

When the model mixes in :class:tempest_fastapi_sdk.SoftDeleteMixin, keep include_deleted=True (the default) so soft-deleted rows are returned as tombstones (deleted_at set) and the client can mirror the deletion locally. A pull that filtered them out would leave deleted rows stranded on the device forever.

Parameters:

Name Type Description Default
since datetime | None

Only rows whose order_by column is strictly greater than this are returned. None returns every row (initial full sync).

required
filters dict[str, Any] | None

Extra conditions applied on top, column name to value, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException. Typically the tenant/owner scope, {"user_id": user_id}. Do NOT pass an owner-less filter set: this method never scopes by itself.

None
cursor str | None

Opaque cursor from the previous page; None requests the first page.

None
limit int

Maximum items per page. Defaults to 50.

50
order_by str

Timestamp column the watermark applies to. Defaults to "updated_at". Must exist on the model.

'updated_at'
include_deleted bool

Whether to include soft-deleted rows (tombstones). Defaults to True. Ignored when the model has no deleted_at column.

True
watermark_lag timedelta

How far behind the query start server_time is set. Defaults to :data:DEFAULT_SYNC_WATERMARK_LAG. Must not be negative.

DEFAULT_SYNC_WATERMARK_LAG

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The :meth:cursor_paginate mapping

dict[str, Any]

(items / next_cursor / has_more / limit)

dict[str, Any]

plus server_time (:class:datetime) — the instant the

dict[str, Any]

query started minus watermark_lag, to be persisted as the

dict[str, Any]

next since.

Raises:

Type Description
OrderByNotAllowedException

When order_by is not a mapped column on the model, or is outside orderable_columns — declare the watermark column there when you declare the set.

PageSizeTooLargeException

When max_page_size is set and limit exceeds it.

ValueError

When cursor is malformed, or watermark_lag is negative.

add async

add(model: ModelType) -> ModelType

Insert model into the database.

Parameters:

Name Type Description Default
model ModelType

The instance to insert.

required

Returns:

Name Type Description
ModelType ModelType

The same instance after refresh so the

ModelType

id and timestamp columns are populated.

Raises:

Type Description
ConflictException

On integrity violations (unique constraint, FK error, etc.).

add_all async

add_all(models: List[ModelType]) -> List[ModelType]

Insert several models in a single transaction.

Parameters:

Name Type Description Default
models list[ModelType]

The instances to insert.

required

Returns:

Type Description
List[ModelType]

list[ModelType]: The same list after every instance is

List[ModelType]

refreshed.

Raises:

Type Description
ConflictException

On integrity violations.

save_with_outbox async

save_with_outbox(model: ModelType, event: BaseModel) -> ModelType

Insert model and an outbox event in one transaction.

This is the write half of the transactional outbox pattern: the business row and the event row commit together, so an event can never reference a row that was rolled back (and a committed row always has its event durably queued). A separate :class:~tempest_fastapi_sdk.db.outbox.OutboxRelay later publishes the event and marks it sent.

Parameters:

Name Type Description Default
model ModelType

The business instance to insert.

required
event BaseModel

The outbox row to insert alongside it — typically OutboxModel.new_event(topic, payload).

required

Returns:

Name Type Description
ModelType ModelType

The model instance after refresh so its

ModelType

id and timestamp columns are populated.

Raises:

Type Description
ConflictException

On integrity violations (the whole transaction — model and event — is rolled back).

snapshot staticmethod

snapshot(model: ModelType) -> dict[str, Any]

Capture a model's column values for a later audit diff.

Take this before mutating an instance, then pass it to :meth:update_audited so the audit entry can diff before/after.

Parameters:

Name Type Description Default
model ModelType

The instance to snapshot.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A JSON-able {column: value} snapshot.

add_audited async

add_audited(
    model: ModelType,
    *,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    event: str | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> ModelType

Insert model and a create audit row in one transaction.

Requires the repository to be built with audit_model=.... The business row and the audit row commit together, so the trail can never reference a row that was rolled back.

Parameters:

Name Type Description Default
model ModelType

The instance to insert.

required
actor str | None

Who performed the create (user id, e-mail, "system", ...).

None
context dict[str, Any] | None

Extra metadata (request id, reason, ...).

None
event str | None

Domain event name ("consent.granted"); needs :class:~tempest_fastapi_sdk.db.audit.AuditRequestMixin on the audit model.

None
ip str | None

Client IP; needs AuditRequestMixin.

None
user_agent str | None

User agent; needs AuditRequestMixin.

None
request_context AuditRequestContext | None

ip and user_agent from :meth:~tempest_fastapi_sdk.db.audit.AuditRequestContext.from_request; mutually exclusive with both.

None
actor_id UUID | None

The author's id, for an audit model that declares an actor_id column.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
ModelType ModelType

The instance after refresh.

Raises:

Type Description
RuntimeError

When no audit_model was configured.

ValueError

When an origin value targets a column the audit model does not have (the transaction is rolled back).

ConflictException

On integrity violations (the whole transaction is rolled back).

update_audited async

update_audited(
    model: ModelType,
    before: dict[str, Any],
    *,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    event: str | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> ModelType

Persist mutations on model and an update audit row.

before is a snapshot taken with :meth:snapshot before the instance was mutated; the audit row stores the changed-field diff. The business update and the audit row commit together.

Parameters:

Name Type Description Default
model ModelType

The mutated, session-attached instance.

required
before dict[str, Any]

The pre-mutation snapshot.

required
actor str | None

Who performed the update.

None
context dict[str, Any] | None

Extra metadata.

None
event str | None

Domain event name ("consent.granted"); needs :class:~tempest_fastapi_sdk.db.audit.AuditRequestMixin on the audit model.

None
ip str | None

Client IP; needs AuditRequestMixin.

None
user_agent str | None

User agent; needs AuditRequestMixin.

None
request_context AuditRequestContext | None

ip and user_agent from :meth:~tempest_fastapi_sdk.db.audit.AuditRequestContext.from_request; mutually exclusive with both.

None
actor_id UUID | None

The author's id, for an audit model that declares an actor_id column.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
ModelType ModelType

The instance after refresh.

Raises:

Type Description
RuntimeError

When no audit_model was configured.

ValueError

When an origin value targets a column the audit model does not have.

ConflictException

On integrity violations.

delete_audited async

delete_audited(
    model: ModelType,
    *,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    event: str | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> None

Delete model and write a delete audit row in one tx.

Snapshots the row before deleting it, so the trail keeps the final state of what was removed.

Parameters:

Name Type Description Default
model ModelType

The session-attached instance to delete.

required
actor str | None

Who performed the delete.

None
context dict[str, Any] | None

Extra metadata.

None
event str | None

Domain event name ("consent.granted"); needs :class:~tempest_fastapi_sdk.db.audit.AuditRequestMixin on the audit model.

None
ip str | None

Client IP; needs AuditRequestMixin.

None
user_agent str | None

User agent; needs AuditRequestMixin.

None
request_context AuditRequestContext | None

ip and user_agent from :meth:~tempest_fastapi_sdk.db.audit.AuditRequestContext.from_request; mutually exclusive with both.

None
actor_id UUID | None

The author's id, for an audit model that declares an actor_id column.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Raises:

Type Description
RuntimeError

When no audit_model was configured.

ValueError

When an origin value targets a column the audit model does not have.

record_event async

record_event(
    event: str,
    *,
    subject: ModelType | None = None,
    changes: dict[str, Any] | None = None,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> BaseAuditLogModel

Write an event audit row — a domain event with no mutation.

For facts that change no row of this repository's model ("consent granted", "export requested", "login failed"). entity is this repository's model name; entity_id is subject's id, or "" when the event concerns no single row. Commits like the other write methods — or only flushes inside an open :meth:transaction block / with autocommit=False.

Parameters:

Name Type Description Default
event str

Domain event name ("export.requested").

required
subject ModelType | None

The row the event concerns.

None
changes dict[str, Any] | None

Optional payload; stored as {} when None.

None
actor str | None

Who triggered the event.

None
context dict[str, Any] | None

Extra metadata.

None
ip str | None

Client IP.

None
user_agent str | None

User agent.

None
request_context AuditRequestContext | None

ip and user_agent together; mutually exclusive with both.

None
actor_id UUID | None

The author's id, for an audit model that declares an actor_id column.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
BaseAuditLogModel BaseAuditLogModel

The persisted audit row.

Raises:

Type Description
RuntimeError

When no audit_model was configured.

ValueError

When the audit model lacks :class:~tempest_fastapi_sdk.db.audit.AuditRequestMixin (the event name has nowhere to go), or another origin value targets a missing column.

update async

update(model: ModelType) -> ModelType

Persist mutations made on an attached model.

The instance must already be tracked by the session (e.g. returned by :meth:get) with its fields modified. This method only commits and refreshes.

Parameters:

Name Type Description Default
model ModelType

The mutated instance.

required

Returns:

Name Type Description
ModelType ModelType

The same instance after refresh.

Raises:

Type Description
ConflictException

On integrity violations.

update_many async

update_many(models: List[ModelType]) -> List[ModelType]

Commit several mutated instances in a single transaction.

Parameters:

Name Type Description Default
models list[ModelType]

The mutated instances.

required

Returns:

Type Description
List[ModelType]

list[ModelType]: The same list.

Raises:

Type Description
ConflictException

On integrity violations.

bulk_update async

bulk_update(filters: dict[str, Any], values: dict[str, Any]) -> int

Issue a single UPDATE ... WHERE against the table.

Bypasses the unit-of-work entirely — useful for mass mutations that don't need to refresh each affected row in the session.

A value may be an :class:F expression to compute the new value from existing columns in the database — {"stock": F("stock") - 1} decrements atomically, with no read-modify-write race.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value identifying the rows to mutate, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException before the statement runs, so a typo never widens the write. An empty mapping is rejected to prevent accidental table-wide updates.

required
values dict[str, Any]

Column-value pairs to set on the matching rows. An :class:F value is resolved to a SQL expression against this repository's model.

required

Returns:

Name Type Description
int int

The number of rows affected.

Raises:

Type Description
ValueError

If filters is empty.

ConflictException

On integrity violations.

update_returning async

update_returning(
    filters: dict[str, Any],
    values: dict[str, Any],
    *,
    returning: Sequence[str],
    where: WhereClause | None = None,
) -> List[dict[str, Any]]

Run one conditional UPDATE ... RETURNING and hand back the rows.

The read-back half of :meth:bulk_update: the same single statement, with the post-update value of each returning column read in the same round trip. That is what turns a conditional write into a decision the caller can act on — {"wallet_cents": F("wallet_cents") - 500} filtered by {"id": user_id, "wallet_cents__gte": 500} either debits and returns the new balance, or matches nothing and returns [], with no window between the check and the write for a concurrent request to slip into.

Reading first and writing after is the shape this replaces, and a SELECT ... FOR UPDATE does not rescue it portably: the SQLite dialect drops FOR UPDATE from the emitted SQL without a warning, so the lock exists only on PostgreSQL.

RETURNING needs PostgreSQL, or SQLite 3.35 or newer.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value identifying the rows to mutate, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException before the statement runs, so a typo never widens the write.

required
values dict[str, Any]

Column-value pairs to set. An :class:F value is resolved against this repository's model, so the new value is computed by the database.

required
returning Sequence[str]

Names of the mapped columns to read back from each updated row. Must not be empty.

required
where WhereClause | None

An extra condition ANDed with filters — a :class:Q tree, or a bound SQLAlchemy clause for what a filter dict cannot express (a correlated subquery, say).

None

Returns:

Type Description
List[dict[str, Any]]

list[dict[str, Any]]: One mapping per updated row, keyed by

List[dict[str, Any]]

the returning names. An empty list means no row matched

List[dict[str, Any]]

the condition.

Raises:

Type Description
ValueError

If returning is empty, or if both filters and where are empty.

ConflictException

On integrity violations (the bulk_update_conflict_exception of this instance).

bulk_create_values async

bulk_create_values(rows: List[dict[str, Any]]) -> int

Insert many rows in a single INSERT ... VALUES (...), (...) statement.

Unlike :meth:add_all, this bypasses the unit-of-work — the rows are not refreshed nor attached to the session. Use when you have a large batch (≥ 50 rows) and don't need the ORM instances back; the round-trip count drops from N to 1.

A conflict on any unique constraint fails the whole statement with the repository's conflict exception and rolls the session back (unless an open :meth:transaction block owns the rollback). When a conflict is the expected outcome, use :meth:bulk_upsert with on_conflict="nothing" instead.

Parameters:

Name Type Description Default
rows list[dict[str, Any]]

One mapping per row, keyed by column name (not attribute name; usually they match for SDK models).

required

Returns:

Name Type Description
int int

The driver's row count for the statement — the number

int

of rows inserted, which is len(rows) unless a trigger

int

skipped some. A count of 0 is returned as 0; only a

int

driver that reports -1 (count unknown) falls back to

int

len(rows).

Raises:

Type Description
ConflictException

On unique / FK violations.

ValueError

When rows is empty.

bulk_upsert async

bulk_upsert(
    rows: List[dict[str, Any]],
    *,
    conflict_columns: List[str],
    update_columns: List[str] | None = None,
    on_conflict: Literal["update", "nothing"] = "update",
    set_: UpsertSet | None = None,
    commit: bool = True,
    returning: Literal["rows"],
) -> List[ModelType]
bulk_upsert(
    rows: List[dict[str, Any]],
    *,
    conflict_columns: List[str],
    update_columns: List[str] | None = None,
    on_conflict: Literal["update", "nothing"] = "update",
    set_: UpsertSet | None = None,
    commit: bool = True,
    returning: Literal["ids"],
) -> List[PrimaryKeyT]
bulk_upsert(
    rows: List[dict[str, Any]],
    *,
    conflict_columns: List[str],
    update_columns: List[str] | None = None,
    on_conflict: Literal["update", "nothing"] = "update",
    set_: UpsertSet | None = None,
    commit: bool = True,
    returning: Literal["count"],
) -> int
bulk_upsert(
    rows: List[dict[str, Any]],
    *,
    conflict_columns: List[str],
    update_columns: List[str] | None = None,
    on_conflict: Literal["update", "nothing"] = "update",
    set_: UpsertSet | None = None,
    commit: bool = True,
    returning: None = None,
    returning_ids: Literal[False] = False,
) -> int
bulk_upsert(
    rows: List[dict[str, Any]],
    *,
    conflict_columns: List[str],
    update_columns: List[str] | None = None,
    on_conflict: Literal["update", "nothing"] = "update",
    set_: UpsertSet | None = None,
    commit: bool = True,
    returning: None = None,
    returning_ids: Literal[True],
) -> List[PrimaryKeyT]
bulk_upsert(
    rows: List[dict[str, Any]],
    *,
    conflict_columns: List[str],
    update_columns: List[str] | None = None,
    on_conflict: Literal["update", "nothing"] = "update",
    set_: UpsertSet | None = None,
    commit: bool = True,
    returning: Literal["ids", "rows", "count"] | None = None,
    returning_ids: bool = False,
) -> int | List[PrimaryKeyT] | List[ModelType]

Insert many rows in one round-trip, resolving key conflicts.

Picks the dialect-specific upsert syntax automatically — Postgres (postgresql.insert) and SQLite (sqlite.insert) are supported. Other dialects raise :class:NotImplementedError so the caller can fall back to a transactional SELECT FOR UPDATE loop.

on_conflict picks what a row whose conflict_columns already exist does:

  • "update" (the default) issues ON CONFLICT (...) DO UPDATE SET ...: the existing row is rewritten with the incoming values of update_columns.
  • "nothing" issues ON CONFLICT (...) DO NOTHING: the existing row is left untouched and the incoming one is dropped. This is the idempotent insert — running the same batch twice, or from two sessions at once, creates each key exactly once and never fails on that key. The conflict is resolved by the database, so no exception is raised and no rollback happens: the caller's transaction stays intact. Measured on PostgreSQL 16 and SQLite 3.47: a second session inserting the same keys waits for the first to commit, then skips them.

Only a conflict on conflict_columns is resolved. A violation of any other constraint (another unique index, a foreign key, NOT NULL) still fails the statement with the repository's conflict exception, as :meth:bulk_create_values does.

Parameters:

Name Type Description Default
rows list[dict[str, Any]]

One mapping per row.

required
conflict_columns list[str]

The columns whose conflict triggers the ON CONFLICT clause — typically the natural-key columns (e.g. ["sku"]). Must be backed by a UNIQUE index.

required
update_columns list[str] | None

Columns to refresh on conflict, for on_conflict="update". None updates every column except conflict_columns and the primary key. Must be None (or empty) with on_conflict="nothing", which updates nothing.

None
on_conflict Literal['update', 'nothing']

"update" rewrites the conflicting row, "nothing" keeps it.

'update'
set_ UpsertSet | None

The SET clause for on_conflict="update" when a plain copy of the incoming value is not enough: a mapping of column to value or SQL expression (Model.uses + 1, a case(...)), or a callable that receives stmt.excluded and returns that mapping, for expressions over the incoming row (lambda excluded: {"uses": Model.uses + excluded.uses}). Mutually exclusive with update_columns.

None
commit bool

True (the default) ends the call the way every write method does. False only flushes, as a repository built with autocommit=False would, so the upsert joins the caller's open transaction and the caller commits.

True
returning Literal['ids', 'rows', 'count'] | None

What to return. "rows" adds RETURNING of the whole model and returns the inserted or updated instances, loaded with populate_existing so an instance already in the session shows the new values. After a commit (which expires every instance) they are reloaded with one SELECT ... IN, so reading an attribute does not hit the database lazily — the MissingGreenlet an AsyncSession raises there. "ids" is returning_ids=True, "count" is returning_ids=False. None defers to returning_ids.

None
returning_ids bool

False returns a count. True adds RETURNING id and returns the primary keys instead: with "nothing" they are exactly the rows this call created (what a caller needs to publish one event per new row); with "update" they are every row inserted or updated, since neither dialect tells the two apart portably. The order is the database's, not necessarily the order of rows.

False

Returns:

Type Description
int | List[PrimaryKeyT] | List[ModelType]

int | list[PrimaryKeyT]: With returning_ids=False, a count.

int | List[PrimaryKeyT] | List[ModelType]

For "update" it is the driver's row count, which on

int | List[PrimaryKeyT] | List[ModelType]

PostgreSQL and SQLite is rows inserted plus rows updated

int | List[PrimaryKeyT] | List[ModelType]

(a conflicting row counts once). For "nothing" it is

int | List[PrimaryKeyT] | List[ModelType]

the number of rows actually inserted — 0 when every key

int | List[PrimaryKeyT] | List[ModelType]

already existed — taken from RETURNING so it does not

int | List[PrimaryKeyT] | List[ModelType]

depend on the driver's rowcount. With

int | List[PrimaryKeyT] | List[ModelType]

returning_ids=True, the list of primary keys described

int | List[PrimaryKeyT] | List[ModelType]

above. With returning="rows", the model instances.

Raises:

Type Description
ConflictException

On integrity errors other than the resolved conflict on conflict_columns.

NotImplementedError

When the active SQLAlchemy dialect has no native upsert.

ValueError

When rows is empty; when on_conflict is not "update" / "nothing"; when "nothing" is given a non-empty update_columns (a column list that would be ignored is almost always a mistaken call); or when "update" resolves to no column to update — use "nothing" for that; when set_ is combined with update_columns or with "nothing"; or when returning is combined with returning_ids=True.

delete async

delete(id: PrimaryKeyT) -> None

Delete a single row by its primary key.

Fires PRE_DELETE before and POST_DELETE after the commit only when a handler is registered — otherwise the row is never loaded and this stays a single DELETE statement. When signals are active the row is loaded once, passed to the handlers, and detached before commit so its column values remain readable in POST_DELETE.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key.

required

Raises:

Type Description
AppException

self.not_found_exception if no record with id exists.

delete_many async

delete_many(filters: dict[str, Any], where: WhereClause | None = None) -> int

Delete every row matching filters.

An empty filters dict (and no where) deletes every row in the table. Callers must opt in explicitly — the behavior is intentional.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value identifying the rows to delete, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException before the statement runs, so a typo never widens the write.

required
where WhereClause | None

A :class:Q condition tree ANDed with filters.

None

Returns:

Name Type Description
int int

The number of rows deleted.

delete_batch async

delete_batch(ids: List[PrimaryKeyT]) -> int

Delete several rows by primary key.

Parameters:

Name Type Description Default
ids list[PrimaryKeyT]

The primary keys to delete.

required

Returns:

Name Type Description
int int

The number of rows deleted.

soft_delete async

soft_delete(id: PrimaryKeyT) -> ModelType

Soft-delete a row by setting is_active=False.

Loads the row, flips is_active, persists. Returns the refreshed instance so callers can inspect the post-state.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key.

required

Returns:

Name Type Description
ModelType ModelType

The row with is_active=False.

Raises:

Type Description
TypeError

When :attr:model does not map is_active.

AppException

self.not_found_exception if no record with id exists.

restore async

restore(id: PrimaryKeyT) -> ModelType

Reactivate a soft-deleted row by setting is_active=True.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key.

required

Returns:

Name Type Description
ModelType ModelType

The row with is_active=True.

Raises:

Type Description
TypeError

When :attr:model does not map is_active.

AppException

self.not_found_exception if no record with id exists.

count async

count(filters: dict[str, Any] | None = None, where: WhereClause | None = None) -> int

Count the rows matching filters.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on this class. An unknown column or operator raises UnknownFilterKeyException.

None
where WhereClause | None

A :class:Q condition tree ANDed with filters.

None

Returns:

Name Type Description
int int

The matching row count.

map_to_schema

map_to_schema(instance: ModelType) -> object

Map an ORM row to its schema/domain representation.

Concrete repositories MUST implement this to bridge the data layer and the rest of the application.

Parameters:

Name Type Description Default
instance ModelType

The ORM row to convert.

required

Returns:

Name Type Description
object object

The schema/domain object.

Raises:

Type Description
NotImplementedError

Always — subclasses must override.

map_to_model

map_to_model(data: dict[str, Any]) -> ModelType

Build an ORM instance from a plain dict payload.

Default implementation constructs self.model(**data); override for custom field mapping.

Parameters:

Name Type Description Default
data dict[str, Any]

The payload.

required

Returns:

Name Type Description
ModelType ModelType

A new (unpersisted) ORM instance.

map_to_response

map_to_response(instance: ModelType) -> ResponseT | Awaitable[ResponseT]

Map an ORM row to its API response schema.

Concrete repositories MUST implement this when used from the service or router layer. Subclasses may implement it either synchronously (returning ResponseT) or as async def (returning Awaitable[ResponseT]).

Parameters:

Name Type Description Default
instance ModelType

The ORM row to convert.

required

Returns:

Type Description
ResponseT | Awaitable[ResponseT]

ResponseT | Awaitable[ResponseT]: The response schema, or an

ResponseT | Awaitable[ResponseT]

awaitable resolving to it.

Raises:

Type Description
NotImplementedError

Always — subclasses must override.

RepositoryModelProtocol

Bases: Protocol

Structural contract a model must meet to back a :class:BaseRepository.

Any SQLAlchemy-mapped class satisfies it, whether it inherits from the SDK's :class:~tempest_fastapi_sdk.db.model.BaseModel or from a service-owned DeclarativeBase composed with :class:~tempest_fastapi_sdk.db.model.IntegerPrimaryKeyMixin and :class:~tempest_fastapi_sdk.db.model.NaiveTimestampMixin.

The protocol names only __mapper__. The id and created_at columns the repository also needs are checked by the constructor on the mapper, at runtime: declaring them here as read-only properties made mypy (1.x) reject BaseModel itself whenever BaseRepository[SomeModel] was written before the model's Mapped[...] annotations were analysed, and that is the order a repository module that imports its model has. The key type the signatures use comes from the third type parameter, PrimaryKeyT.

Attributes:

Name Type Description
__mapper__ Mapper[Any]

The mapper SQLAlchemy attaches to every declaratively mapped class.

UpsertSet module-attribute

UpsertSet: TypeAlias = (
    Mapping[str, Any]
    | Callable[[ReadOnlyColumnCollection[str, Any]], Mapping[str, Any]]
)

The set_ of :meth:BaseRepository.bulk_upsert.

Either the SET mapping itself (column to value or SQL expression) or a callable that receives stmt.excluded — the row the statement tried to insert — and returns that mapping, since excluded only exists once the statement does.

dialect_insert

dialect_insert(
    session_or_bind: SessionOrBind, model: type[object] | TableClause
) -> DialectInsert

Return the insert of the session's dialect, ready for ON CONFLICT.

The same repository code runs on PostgreSQL in production and SQLite under test, and the two ship their ON CONFLICT support on different insert constructs. This picks the right one from the bound dialect, so on_conflict_do_nothing, on_conflict_do_update(set_=...) with expressions over stmt.excluded and .returning(Model) read the same on both.

The statement is not executed: it runs in whatever transaction the caller has open, and committing is the caller's decision.

Parameters:

Name Type Description Default
session_or_bind SessionOrBind

Where the dialect is read from.

required
model type[object] | TableClause

The mapped class or table to insert into.

required

Returns:

Name Type Description
DialectInsert DialectInsert

A postgresql.insert or sqlite.insert.

Raises:

Type Description
NotImplementedError

When the dialect is neither PostgreSQL nor SQLite.

DialectInsert module-attribute

DialectInsert: TypeAlias = PostgreSQLInsert | SQLiteInsert

The insert construct :func:dialect_insert returns.

Both members expose on_conflict_do_nothing, on_conflict_do_update (with index_elements, index_where, set_ and where) and excluded, so code written against the union runs on either database.

SessionOrBind module-attribute

SessionOrBind: TypeAlias = (
    AsyncSession | Session | AsyncConnection | Connection | AsyncEngine | Engine
)

Anything :func:dialect_insert can read the dialect from.

DEFAULT_SYNC_WATERMARK_LAG module-attribute

DEFAULT_SYNC_WATERMARK_LAG: timedelta = timedelta(seconds=5)

How far :meth:BaseRepository.changes_since sets its mark behind "now".

updated_at is stamped at flush time and becomes visible at commit, so a write whose transaction is still open when a pull runs carries an updated_at older than the pull. A mark taken at "now" would put that write behind every later since, and no incremental pull would ever return it. Setting the mark this far back makes the next pull re-read the window, which catches any such write whose transaction lasted less than the lag, and any clock disagreement between replicas smaller than it.

The cost is that rows changed inside the window come back on the next pull too, so the client must apply items idempotently (upsert by id), which the offline-sync recipe already requires. Five seconds covers a request transaction with room to spare; a service with longer write transactions passes a larger watermark_lag.

parse_integrity_error

parse_integrity_error(error: BaseException) -> IntegrityFailure

Read a database integrity error into its constituent parts.

Example:

>>> from sqlalchemy.exc import IntegrityError
>>> from tempest_fastapi_sdk import parse_integrity_error
>>>
>>> def to_conflict(error: IntegrityError) -> dict[str, object]:
...     failure = parse_integrity_error(error)
...     return {"code": failure.kind.value, "field": failure.column}

Never raises: an unrecognized message comes back as :attr:IntegrityViolationEnum.UNKNOWN with the text in :attr:IntegrityFailure.message. A parser for error prose that raises on prose it does not know turns a handled 409 into an unhandled 500, which is worse than the generic conflict it was added to improve on.

Parameters:

Name Type Description Default
error BaseException

The error to read. Normally a sqlalchemy.exc.IntegrityError; any exception whose text carries a supported message works, which is what lets a caller pass a driver exception directly.

required

Returns:

Name Type Description
IntegrityFailure IntegrityFailure

What the server said. Fields the dialect does

IntegrityFailure

not report are None or empty — see the module docstring for

IntegrityFailure

which those are.

describe_database_error

describe_database_error(error: DBAPIError) -> str

Summarize a database error without the server's text.

What the SDK logs in place of str(error): the 5xx handlers through :func:~tempest_fastapi_sdk.redact_database_errors, and :class:~tempest_fastapi_sdk.BaseRepository when it turns an IntegrityError into a 409. Postgres's text quotes the row — DETAIL: Key (cpf)=(123.456.789-00) already exists. — so the value the client sent would reach warning.log on every duplicate.

An integrity error keeps what :func:parse_integrity_error reads out of it — the kind, the constraint, the table and the columns, which are schema names — and drops the DETAIL line, which is data. Every other DBAPIError keeps only the driver's exception type: a DataError quotes the rejected input too (invalid input for query argument $1: 'abc'), so no server text is safe by category.

The SQL statement goes too. What the ORM emits carries placeholders, but a statement built with text() and an f-string carries the literal, and the constraint plus the frames already say which write failed.

Parameters:

Name Type Description Default
error DBAPIError

The error to summarize.

required

Returns:

Name Type Description
str str

One line naming what failed and stating the omission.

WITHHELD_NOTICE module-attribute

WITHHELD_NOTICE: Final[str] = 'database message withheld from the log'

Suffix of every redacted database line.

Says outright that the server's text was dropped, so an operator reading the traceback does not mistake the summary for the whole message.

IntegrityFailure dataclass

IntegrityFailure(
    kind: IntegrityViolationEnum = UNKNOWN,
    constraint: str | None = None,
    table: str | None = None,
    columns: tuple[str, ...] = tuple(),
    message: str = "",
)

What a database said about the constraint it enforced.

Every field except :attr:kind is best-effort: which of them the server fills in depends on the dialect and on the constraint, and the module docstring lists where each one is simply absent. Treat an empty value as "this server did not say", never as "there is none".

Attributes:

Name Type Description
kind IntegrityViolationEnum

The constraint category.

constraint str | None

The constraint name, when the server named one. Postgres always does; SQLite only for CHECK, and then only when the DDL named it.

table str | None

The table, when the message identifies one.

columns tuple[str, ...]

The columns involved, in the order the server listed them. A composite unique yields more than one.

message str

The driver's own message, with the echoed SQL statement stripped — useful for logging the thing that was parsed when :attr:kind came back UNKNOWN.

column property

column: str | None

Return the single column involved, when there is exactly one.

The common case — a unique email, a not-null name — is one column, and a caller answering {"field": ...} wants it without unpacking a tuple. None for a composite constraint is deliberate: naming only the first would be a guess about which half the user got wrong.

Returns:

Type Description
str | None

str | None: The column name, or None when the server

str | None

named zero or more than one.

IntegrityViolationEnum

Bases: BaseStrEnum

Which kind of constraint refused the write.

Attributes:

Name Type Description
UNIQUE

A unique index or constraint already holds that value.

FOREIGN_KEY

The referenced row does not exist.

NOT_NULL

A column that forbids NULL received one.

CHECK

A CHECK expression evaluated false.

UNKNOWN

The message matched no known pattern.

legacy_constraint_renames

legacy_constraint_renames(
    metadata: MetaData, *, legacy: Mapping[str, str] = LEGACY_NAMING_CONVENTION
) -> list[ConstraintRename]

List the constraints whose convention name changed since legacy.

Example:

>>> from sqlalchemy.dialects import postgresql
>>> from tempest_fastapi_sdk import BaseModel, legacy_constraint_renames
>>> for rename in legacy_constraint_renames(BaseModel.metadata):
...     print(rename.statement(postgresql.dialect()))

A constraint is listed when it covers more than one column, its current name is the one metadata's convention produces (a constraint with an explicit name= is left alone), and the legacy convention names it differently. Primary keys and check constraints are never listed: their templates did not change.

Two entries can share an old_name: that is the legacy collision itself, and PostgreSQL refused the second CREATE, so a database holds at most one of them. Keep the entry whose columns match the constraint the database actually has.

Run it once, while writing the migration, and paste the statements into the revision. A migration that calls it at upgrade time would compute its renames from whatever the models look like on the day it runs, not on the day it was written.

Parameters:

Name Type Description Default
metadata MetaData

The metadata to inspect, normally BaseModel.metadata with every model imported.

required
legacy Mapping[str, str]

The convention the database was created under. Defaults to :data:LEGACY_NAMING_CONVENTION.

LEGACY_NAMING_CONVENTION

Returns:

Type Description
list[ConstraintRename]

list[ConstraintRename]: One entry per renamed constraint, sorted

list[ConstraintRename]

by schema, table, kind and new name — empty when nothing drifts,

list[ConstraintRename]

which is also what a metadata with no composite constraint gives.

ConstraintRename dataclass

ConstraintRename(
    kind: ConstraintKindEnum,
    table: str,
    schema: str | None,
    columns: tuple[str, ...],
    old_name: str,
    new_name: str,
)

One constraint whose convention name changed.

old_name and new_name are the names the convention produces before any dialect shortens them; :meth:statement applies the dialect's identifier limit, the way the DDL did.

Attributes:

Name Type Description
kind ConstraintKindEnum

What is being renamed.

table str

The table the constraint belongs to.

schema str | None

The table's schema, or None for the default one.

columns tuple[str, ...]

The constrained columns, in order.

old_name str

The name under the legacy convention — what a database created before the fix holds.

new_name str

The name under the current convention — what the metadata declares now.

inverse

inverse() -> ConstraintRename

Return the rename that undoes this one, for a downgrade().

Returns:

Name Type Description
ConstraintRename ConstraintRename

The same constraint with the two names

ConstraintRename

swapped.

statement

statement(dialect: Dialect) -> str

Render the SQL that renames the constraint in place.

Unique and foreign-key constraints use ALTER TABLE ... RENAME CONSTRAINT, which on PostgreSQL also renames the index behind a unique constraint; a plain index uses ALTER INDEX ... RENAME TO. Both names go through the dialect's identifier preparer, so a name past the 63-character limit is shortened and quoted exactly as CREATE shortened it.

Only PostgreSQL is supported. SQLite cannot rename a constraint at all — its name lives inside the CREATE TABLE text — so the Alembic batch migration --autogenerate renders, which rebuilds the table, is the path there.

Parameters:

Name Type Description Default
dialect Dialect

The target dialect, such as op.get_bind().dialect inside a migration or sqlalchemy.dialects.postgresql.dialect() in a script.

required

Returns:

Name Type Description
str str

One SQL statement.

Raises:

Type Description
ValueError

When dialect is not PostgreSQL.

ConstraintKindEnum

Bases: BaseStrEnum

Which kind of schema object a :class:ConstraintRename renames.

Attributes:

Name Type Description
UNIQUE

A UNIQUE constraint.

INDEX

A (non-constraint) index.

FOREIGN_KEY

A FOREIGN KEY constraint.

LEGACY_NAMING_CONVENTION module-attribute

LEGACY_NAMING_CONVENTION: Final[dict[str, str]] = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

The naming convention BaseModel.metadata used before the composite fix.

Every template that names a constraint after its columns read only the first one, so two composite constraints sharing a first column shared a name. Kept as the default legacy of :func:legacy_constraint_renames, and for a project that builds its own MetaData and needs the old names on purpose.

F

F(name: str, _builder: Callable[[type[Any]], SQLColumnExpression[Any]] | None = None)

A lazily-resolved reference to a model column, plus arithmetic.

F("stock") resolves to the model's stock column; F("stock") - 1 resolves to stock - 1. Arithmetic accepts plain values or other F instances (F("price") * F("qty")) and works from either side (10 - F("stock")). Pass the result as a value in :meth:BaseRepository.bulk_update to compute the new value in the database.

Initialize a column reference.

Parameters:

Name Type Description Default
name str

The column name on the target model.

required
_builder Callable[[type[Any]], SQLColumnExpression[Any]] | None

Internal — the expression builder; defaults to reading the column.

None

resolve

resolve(model: type[Any]) -> SQLColumnExpression[Any]

Resolve to a SQLAlchemy column expression against model.

Parameters:

Name Type Description Default
model type[Any]

The model class to bind the column to.

required

Returns:

Type Description
SQLColumnExpression[Any]

SQLColumnExpression[Any]: The mapped attribute for a bare

SQLColumnExpression[Any]

F("name"), or the arithmetic expression built on it. Both

SQLColumnExpression[Any]

the ORM attribute and a core ColumnElement are

SQLColumnExpression[Any]

SQLColumnExpression.

Q

Q(**conditions: Any)

A composable set of filter conditions.

Q(status="open", priority__gte=5) is the AND of those two conditions (same conventions as a repository filter dict). Combine with & / | and negate with ~ to build arbitrary boolean trees:

Q(status="open") | Q(status="pending")   # OR
Q(active=True) & ~Q(role="guest")         # AND NOT

Pass the tree as where= to a repository read; it resolves to a single SQLAlchemy clause against the repository's model.

Build a leaf node from keyword conditions.

Parameters:

Name Type Description Default
**conditions Any

Filter key/value pairs, ANDed together.

{}

resolve

resolve(model: type[Any]) -> ColumnElement[bool] | None

Resolve the tree to a SQLAlchemy clause against model.

Every condition goes through :func:build_filter_condition, so a Q tree reads exactly like the repository's filter dict: None on a bare column is col IS NULL and on __ne is col IS NOT NULL.

An unknown column or an unknown operator raises :class:UnknownFilterKeyException — on ~Q(usr_id=1) a dropped condition would otherwise have negated nothing. A value that cannot express its operator raises :class:InvalidFilterValueException. What is still skipped is a None given to an operator that cannot express it (__gt, __between, __in and friends), with a :class:DroppedFilterWarning naming the key. A node whose conditions all resolve to nothing returns None.

Parameters:

Name Type Description Default
model type[Any]

The model class to bind columns to.

required

Returns:

Type Description
ColumnElement[bool] | None

ColumnElement[bool] | None: The combined clause, or None

ColumnElement[bool] | None

when the node carries no usable condition.

Raises:

Type Description
UnknownFilterKeyException

When a condition names a column model does not have, or an unknown operator.

InvalidFilterValueException

When a condition's value does not have the shape its operator requires.

build_filter_condition

build_filter_condition(
    model: type[Any], field: str, value: object
) -> ColumnElement[bool] | None

Build one WHERE condition from a field/value pair.

Implements the shared filter conventions used by both BaseRepository dict filters and :class:Q:

  • <column>__<op> suffix operator, one of: gt / gte / lt / lte / ne (comparison), in / notin / not_in (membership; value is any non-string iterable — list / set / tuple / generator — not_in is an alias of notin; a bare scalar is wrapped in a one-item list), between (col BETWEEN lo AND hi; value is an ordered two-item (lo, hi) list / tuple), iexact (case-insensitive equality), like / ilike (raw, un-escaped LIKE with caller wildcards), isnull (IS NULL when truthy, IS NOT NULL when falsy), contains / icontains / startswith / endswith (case-insensitive ILIKE substring / prefix / suffix, escaped).
  • None on a bare column → col IS NULL; on __ne → col IS NOT NULL.
  • name (string) → case-insensitive ILIKE %value%.
  • bool → .is_(value).
  • date → func.date(column) == value whole-day match.
  • non-string iterable (list / set / tuple / frozenset / range / generator / dict view) → .in_(value).
  • otherwise → equality.

An unknown column or an unknown operator raises :class:UnknownFilterKeyException naming the key. Both used to yield None, which the caller skipped: {"usr_id": 1234} matched every row on a read, and every row in the table on bulk_update / delete_many (measured on SQLite, #465). A typo has no safe reading, so it is refused before any statement is built.

A value that cannot express its operator raises :class:InvalidFilterValueException for the same reason: a malformed between pair used to be dropped, so {"created_at__between": x} with the wrong shape widened bulk_update / delete_many / update_returning to every row the filter did not name (measured on SQLite, #484). A shape error is refused before any statement is built.

None used to be dropped the same way, which was the wrong default in the worst direction: {"left_at": None} — the obvious spelling of "still a member" — silently matched every row, so the query returned more than asked for. Measured in a consumer, that meant someone who had left a group kept receiving its messages. A filter that errs toward fewer rows shows up as an empty screen on the first manual test; this one shows up as data nobody looks at twice.

None now means IS NULL, as in any ORM. Where it has no reading at all — __gt, __between, __in and friends — the condition is still dropped, but with a :class:DroppedFilterWarning naming the key, because silence is what made the original defect expensive.

Parameters:

Name Type Description Default
model type[Any]

The model class the field belongs to.

required
field str

The filter key, optionally <column>__<op>.

required
value object

The value to compare against.

required

Returns:

Type Description
ColumnElement[bool] | None

ColumnElement[bool] | None: The condition, or None to skip — only for None on an operator that cannot express it.

Raises:

Type Description
UnknownFilterKeyException

When the column (the part before __) is not an SQL-expressible attribute of model, or the suffix is not in :data:FILTER_OPERATORS.

InvalidFilterValueException

When the value does not have the shape the operator requires (in without an iterable, between without a two-item pair).

Notes

isnull is handled first, because it legitimately carries a boolean that may be False — and {"col__isnull": False} must stay IS NOT NULL rather than being read as "no filter".

resolve_filter_key

resolve_filter_key(model: type[Any], field: str) -> tuple[Any, str | None]

Split a filters key into its model attribute and operator.

"user_id" resolves to (Model.user_id, None) and "user_id__gte" to (Model.user_id, "gte"). The attribute must be SQL-expressible: a mapped column, a relationship, a column_property or the class-level expression of a hybrid_property. A plain Python attribute — a method, a @property, a class constant — does not qualify, because comparing it to a value has no SQL reading.

This is the check :func:build_filter_condition runs on every key, so configuration that carries filter keys (an admin Lens, say) can run it once at startup instead of on the first request.

Parameters:

Name Type Description Default
model type[Any]

The model class the key belongs to.

required
field str

The filter key, optionally <column>__<op>.

required

Returns:

Type Description
tuple[Any, str | None]

tuple[Any, str | None]: The resolved attribute and the operator suffix, or None as the suffix for a bare column.

Raises:

Type Description
UnknownFilterKeyException

When the column part names no SQL-expressible attribute of model, or the suffix is not in :data:FILTER_OPERATORS. filter_key is the full key.

FILTER_OPERATORS module-attribute

FILTER_OPERATORS: frozenset[str] = frozenset(
    {
        *COMPARISON_OPS,
        "in",
        "notin",
        "not_in",
        "between",
        "iexact",
        "like",
        "ilike",
        "isnull",
        "contains",
        "icontains",
        "startswith",
        "endswith",
    }
)

DroppedFilterWarning

Bases: UserWarning

Warns that a filter key was ignored instead of applied.

Raised when a None reaches an operator that cannot express it — {"price__gt": None}, {"id__in": None} — so the condition is dropped and the query answers with more rows than the caller asked for. That silent widening is the shape the old None handling had everywhere, and it is expensive precisely because the result still looks plausible.

Silence it per-project when a dict is deliberately built with optional keys::

import warnings

from tempest_fastapi_sdk import DroppedFilterWarning

warnings.filterwarnings("ignore", category=DroppedFilterWarning)

RepositorySignalEnum

Bases: BaseStrEnum

The lifecycle moments a :class:BaseRepository emits.

connect

connect(model: type[Any], signal: RepositorySignalEnum, handler: SignalHandler) -> None

Register handler to fire on signal for model.

Registering the same handler twice for the same (model, signal) is a no-op, so idempotent module-import wiring is safe.

Parameters:

Name Type Description Default
model type[Any]

The SQLAlchemy model class to watch. A base class also matches its subclasses.

required
signal RepositorySignalEnum

The lifecycle moment to hook.

required
handler SignalHandler

The sync or async callable invoked with the ORM instance.

required

on_signal

on_signal(
    model: type[Any], signal: RepositorySignalEnum
) -> Callable[[SignalHandler], SignalHandler]

Decorator form of :func:connect.

Parameters:

Name Type Description Default
model type[Any]

The model class to watch.

required
signal RepositorySignalEnum

The lifecycle moment to hook.

required

Returns:

Type Description
Callable[[SignalHandler], SignalHandler]

Callable[[SignalHandler], SignalHandler]: A decorator that

Callable[[SignalHandler], SignalHandler]

registers the wrapped function and returns it unchanged.

TenantScopedRepository

TenantScopedRepository(
    session: AsyncSession,
    *,
    model: type[TenantModelType],
    tenant_id: UUID,
    tenant_field: str = "tenant_id",
    not_found_exception: type[AppException] = NotFoundException,
    not_found_message: str | None = None,
    create_conflict_message: str | None = None,
    update_conflict_message: str | None = None,
    bulk_create_conflict_message: str | None = None,
    bulk_update_conflict_message: str | None = None,
)

Bases: BaseRepository[TenantModelType, TenantResponseT, TenantPrimaryKeyT]

A :class:BaseRepository locked to a single tenant.

Every read is filtered by tenant_id and every write is stamped with it, so no query site can leak across tenants. Use it exactly like :class:BaseRepository — the tenant scoping is invisible to callers.

Generic parameters

TenantModelType: The SQLAlchemy ORM model managed by the repository (:class:RepositoryModelProtocol). TenantResponseT: Optional API response schema returned by :meth:map_to_response. Defaults to Any. TenantPrimaryKeyT: Optional primary-key type used by :meth:delete, :meth:delete_batch and every key-taking method inherited from :class:BaseRepository. Defaults to UUID. The bound tenant_id stays UUID.

Example

repo = TenantScopedRepository( ... session, model=OrderModel, tenant_id=current_tenant ... ) await repo.list() # WHERE tenant_id = current_tenant await repo.add(OrderModel(...)) # tenant_id stamped automatically

Attributes:

Name Type Description
tenant_id UUID

The tenant this repository is bound to.

tenant_field str

The column name carrying the tenant id.

Initialize the tenant-scoped repository.

Parameters:

Name Type Description Default
session AsyncSession

The async database session.

required
model type[TenantModelType]

The model class. It MUST declare the tenant_field column.

required
tenant_id UUID

The tenant to scope every operation to.

required
tenant_field str

Name of the tenant column. Defaults to "tenant_id".

'tenant_id'
not_found_exception type[AppException]

As in :class:BaseRepository.

NotFoundException
not_found_message str | None

As in :class:BaseRepository.

None
create_conflict_message str | None

As in :class:BaseRepository.

None
update_conflict_message str | None

As in :class:BaseRepository.

None
bulk_create_conflict_message str | None

As in :class:BaseRepository.

None
bulk_update_conflict_message str | None

As in :class:BaseRepository.

None

Raises:

Type Description
TypeError

When model is not a mapped SQLAlchemy class, or does not map id and created_at.

AttributeError

When model has no tenant_field column.

tenant_column property

tenant_column: InstrumentedAttribute[Any]

Return the mapped tenant column for raw query building.

Returns:

Type Description
InstrumentedAttribute[Any]

InstrumentedAttribute[Any]: The model's tenant column, e.g.

InstrumentedAttribute[Any]

for .where(repo.tenant_column == repo.tenant_id) in a

InstrumentedAttribute[Any]

custom query.

get async

get(
    filters: dict[str, Any],
    for_update: bool = False,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> TenantModelType

See :meth:BaseRepository.get — scoped to the tenant.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

required
for_update bool

Whether to lock the selected rows.

False
with_ list[str] | None

Relationship names to eager- load.

None
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Name Type Description
TenantModelType TenantModelType

The row.

get_or_none async

get_or_none(
    filters: dict[str, Any],
    for_update: bool = False,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> TenantModelType | None

See :meth:BaseRepository.get_or_none — scoped to the tenant.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

required
for_update bool

Whether to lock the selected rows.

False
with_ list[str] | None

Relationship names to eager- load.

None
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Type Description
TenantModelType | None

TenantModelType | None: The row, or None when absent or owned by another tenant.

exists async

exists(filters: dict[str, Any], where: WhereClause | None = None) -> bool

See :meth:BaseRepository.exists — scoped to the tenant.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

required
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Name Type Description
bool bool

Whether any row matched.

first async

first(
    filters: dict[str, Any] | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> TenantModelType | None

See :meth:BaseRepository.first — scoped to the tenant.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

None
order_by Any | None

Column to sort by; None keeps the repository default.

None
ascending bool

Whether to sort ascending.

True
with_ list[str] | None

Relationship names to eager- load.

None
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Type Description
TenantModelType | None

TenantModelType | None: The row, or None when absent or owned by another tenant.

list async

list(
    filters: dict[str, Any] | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
    with_: list[str] | None = None,
    where: WhereClause | None = None,
) -> list[TenantModelType]

See :meth:BaseRepository.list — scoped to the tenant.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

None
order_by Any | None

Column to sort by; None keeps the repository default.

None
ascending bool

Whether to sort ascending.

True
with_ list[str] | None

Relationship names to eager- load.

None
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Type Description
list[TenantModelType]

builtins.list[TenantModelType]: Matching rows, scoped to the tenant.

count async

count(filters: dict[str, Any] | None = None, where: WhereClause | None = None) -> int

See :meth:BaseRepository.count — scoped to the tenant.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

None
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Name Type Description
int int

How many rows matched.

paginate async

paginate(
    filters: dict[str, Any] | None = None,
    order_by: str | None = None,
    page: int = 1,
    page_size: int = 20,
    ascending: bool = True,
    query: Any | None = None,
    where: WhereClause | None = None,
) -> dict[str, Any]

See :meth:BaseRepository.paginate — scoped to the tenant.

When a pre-built query is passed, scope it yourself with .where(self.tenant_column == self.tenant_id) — the override only auto-scopes the default select(self.model) path.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

None
order_by str | None

Column to sort by; None keeps the repository default.

None
page int

1-indexed page number.

1
page_size int

Rows per page.

20
ascending bool

Whether to sort ascending.

True
query Any | None

A pre-built query to scope; None starts a fresh one.

None
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The pagination envelope.

cursor_paginate async

cursor_paginate(
    filters: dict[str, Any] | None = None,
    cursor: str | None = None,
    limit: int = 20,
    order_by: str = "created_at",
    ascending: bool = False,
    query: Any | None = None,
) -> dict[str, Any]

See :meth:BaseRepository.cursor_paginate — scoped to the tenant.

The tenant predicate is always appended via filters, so it applies even when a pre-built query is passed. As with :meth:paginate, joins/predicates inside that query are the caller's responsibility.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

None
cursor str | None

Opaque cursor from a previous page.

None
limit int

Maximum rows to return.

20
order_by str

Column to sort by; None keeps the repository default.

'created_at'
ascending bool

Whether to sort ascending.

False
query Any | None

A pre-built query to scope; None starts a fresh one.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The pagination envelope.

delete_many async

delete_many(filters: dict[str, Any], where: WhereClause | None = None) -> int

See :meth:BaseRepository.delete_many — scoped to the tenant.

Because the tenant predicate is always added, an empty filters deletes only this tenant's rows, never the whole table.

Parameters:

Name Type Description Default
filters dict[str, Any]

Column name to the value it must match, ANDed with the tenant scope, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator raises UnknownFilterKeyException.

required
where WhereClause | None

Extra filter narrowing the tenant-scoped query.

None

Returns:

Name Type Description
int int

How many rows matched.

delete async

delete(id: TenantPrimaryKeyT) -> None

Delete a row by id within this tenant.

An id belonging to another tenant matches nothing and raises the not-found exception, so it is indistinguishable from a row that never existed — no cross-tenant probing.

Parameters:

Name Type Description Default
id TenantPrimaryKeyT

The primary key.

required

Raises:

Type Description
AppException

self.not_found_exception when no row in this tenant has that id.

delete_batch async

delete_batch(ids: list[TenantPrimaryKeyT]) -> int

Delete several rows by id within this tenant.

Parameters:

Name Type Description Default
ids list[TenantPrimaryKeyT]

The primary keys.

required

Returns:

Name Type Description
int int

The number of rows deleted (rows from other tenants are

int

never touched).

SoftDeleteMixin

Add a deleted_at timestamp for non-destructive deletes.

Pairs with the canonical is_active flag on :class:tempest_fastapi_sdk.BaseModel: is_active toggles visibility quickly while deleted_at records when the soft delete happened (useful for audit and retention policies).

A row is considered "alive" when deleted_at IS NULL. Filtering is the caller's responsibility — the mixin keeps the column declarative-only so it composes with arbitrary query strategies (global filters, partial indexes, repository hooks).

Attributes:

Name Type Description
deleted_at datetime | None

Timestamp of the soft delete, or None while the row is alive.

is_deleted property

is_deleted: bool

Whether the row is currently soft-deleted.

Returns:

Name Type Description
bool bool

True when deleted_at is non-null.

mark_deleted

mark_deleted() -> None

Stamp deleted_at with the current UTC instant.

mark_restored

mark_restored() -> None

Clear deleted_at to mark the row alive again.

UtcDateTime

Bases: TypeDecorator[datetime]

TIMESTAMP(timezone=True) that hands back UTC-aware values.

The DDL is unchanged — this emits exactly the same column type — but the value that comes back from a SELECT is normalized, because the engines disagree and the disagreement is invisible until it isn't.

Measured on this suite, same row and same process: right after session.commit() the Python-side default makes created_at aware, and after a SELECT on SQLite the very same column reads back naive::

after commit (python default): datetime(..., tzinfo=timezone.utc)
after SELECT (from sqlite)   : datetime(...)
datetime.now(UTC) - row.created_at
TypeError: can't subtract offset-naive and offset-aware datetimes

PostgreSQL returns it aware. So code written against one engine raises TypeError on the other — in the suite or in production, depending on which side you wrote it against, and never in both. Every service was expected to remember to_utc at each read boundary; forgetting it is silent until an arithmetic or a comparison runs.

Binding normalizes too, so a naive value handed in is stored as UTC rather than as whatever the driver's session zone makes of it. Naive input is read as UTC, which is the contract :func:~tempest_fastapi_sdk.to_utc already documents.

Attributes:

Name Type Description
impl TIMESTAMP

The wrapped type, declared as an instance with timezone=True rather than as the bare class. A decorator that writes impl = TIMESTAMP and adds the flag in load_dialect_impl emits the same DDL, but then impl_instance.timezone reads False — so anything asking the column whether it is aware (the cursor coercion, an admin widget) gets the wrong answer from a type that is in fact always aware.

cache_ok bool

Safe to cache in SQLAlchemy's compiled-statement cache — the type carries no per-instance state.

python_type property

python_type: type[datetime]

Return the Python type values of this column carry.

TypeDecorator does not forward this to the type it wraps — it raises NotImplementedError — and callers that ask before deciding how to treat a column then degrade silently: the admin form falls back to a text input for what is a datetime, and the cursor coercion leaves an ISO string unparsed.

Returns:

Type Description
type[datetime]

type[datetime]: Always :class:datetime.datetime.

process_bind_param

process_bind_param(value: datetime | None, dialect: Dialect) -> datetime | None

Normalize a value on its way into the database.

Parameters:

Name Type Description Default
value datetime | None

The value being bound.

required
dialect Dialect

The dialect in use.

required

Returns:

Type Description
datetime | None

datetime | None: The value in UTC, or None.

process_result_value

process_result_value(value: datetime | None, dialect: Dialect) -> datetime | None

Normalize a value on its way out of the database.

Parameters:

Name Type Description Default
value datetime | None

The value the driver returned.

required
dialect Dialect

The dialect in use.

required

Returns:

Type Description
datetime | None

datetime | None: An aware value in UTC, or None.

NaiveUtcDateTime

Bases: TypeDecorator[datetime]

TIMESTAMP(timezone=False) that stores and reads naive UTC values.

Built for existing databases whose schema convention is UTC without timezone (TIMESTAMP WITHOUT TIME ZONE). Binding strips tzinfo from aware UTC inputs (utcoffset() == timedelta(0)), passes naive inputs through as-is, and refuses any aware input whose offset is not UTC with ValueError — preventing silent zone drops or asyncpg errors when mixing aware and naive parameters. Reading always hands back a naive datetime.

Attributes:

Name Type Description
impl TIMESTAMP

The wrapped type, declared as an instance with timezone=False so impl_instance.timezone reports False to callers inspecting the column (cursor coercion, admin forms).

cache_ok bool

Safe to cache in SQLAlchemy's compiled-statement cache — the type carries no per-instance state.

python_type property

python_type: type[datetime]

Return the Python type values of this column carry.

Returns:

Type Description
type[datetime]

type[datetime]: Always :class:datetime.datetime.

process_bind_param

process_bind_param(value: datetime | None, dialect: Dialect) -> datetime | None

Validate and strip UTC tzinfo on the way into the database.

Parameters:

Name Type Description Default
value datetime | None

The value being bound.

required
dialect Dialect

The dialect in use.

required

Returns:

Type Description
datetime | None

datetime | None: A naive UTC datetime, or None.

Raises:

Type Description
ValueError

If value has a non-UTC timezone offset.

process_result_value

process_result_value(value: datetime | None, dialect: Dialect) -> datetime | None

Return a naive UTC value on the way out of the database.

Parameters:

Name Type Description Default
value datetime | None

The value the driver returned.

required
dialect Dialect

The dialect in use.

required

Returns:

Type Description
datetime | None

datetime | None: A naive UTC datetime, or None.

Raises:

Type Description
ValueError

If the driver returned an aware value whose offset is not UTC.

AuditMixin

Add created_by / updated_by foreign-key columns.

Tracks which user (by UUID) last touched a row. The mixin only declares the columns — populating them is the application's responsibility, typically inside the service layer (where the current user is in scope) right before calling the repository.

Attributes:

Name Type Description
created_by UUID | None

UUID of the user that created the row. Nullable for system-generated rows.

updated_by UUID | None

UUID of the user that last updated the row. Nullable until the first update.

stamp_created_by

stamp_created_by(user_id: UUID) -> None

Set both audit columns to user_id on initial insert.

Parameters:

Name Type Description Default
user_id UUID

The acting user's primary key.

required

stamp_updated_by

stamp_updated_by(user_id: UUID) -> None

Update updated_by to user_id ahead of an UPDATE.

Parameters:

Name Type Description Default
user_id UUID

The acting user's primary key.

required

MFAMixin

Add TOTP (2FA) columns to a user model.

Opt-in companion to :class:tempest_fastapi_sdk.BaseUserModel. Mix it into the concrete user model when the project enables the bundled MFA flow (AUTH_MFA_ENABLED=True) so the secret, the activation timestamp and the last accepted TOTP step live on the user row:

from tempest_fastapi_sdk import BaseUserModel, MFAMixin


class UserModel(MFAMixin, BaseUserModel):
    __tablename__ = "users"

Keeping these columns in a mixin (rather than on BaseUserModel) means projects that never enable MFA do not carry dead columns, and the migration only lands when the feature is actually adopted.

Attributes:

Name Type Description
totp_secret str | None

Base32 TOTP secret persisted by the MFA flow. NULL until enrollment. Consider storing it encrypted at rest (Postgres pgcrypto or an application-level Fernet wrapper).

totp_enabled_at datetime | None

Set by the MFA confirm step the first time the user supplies a valid TOTP code. NULL means MFA is not active yet — login skips the TOTP step entirely.

totp_last_step int | None

TOTP counter value of the last accepted code, written by every bundled path that accepts one (mfa_confirm, mfa_verify, mfa_disable and request_email_recovery). A code whose step is at or below this one is refused, so the same 6 digits cannot be spent twice inside their drift window. NULL until the first accepted code and again whenever the secret is replaced; rows created before 0.306.0 start NULL, which reads as "nothing spent yet".

is_mfa_active property

is_mfa_active: bool

Whether the user has completed MFA enrollment.

Returns:

Name Type Description
bool bool

True when totp_enabled_at is non-null. Does

bool

NOT account for the AUTH_MFA_ENABLED kill-switch — use

bool

meth:tempest_fastapi_sdk.UserAuthService.is_mfa_enrolled

bool

for the kill-switch-aware check.

NameMixin

Add a display-name column to a user model.

Opt-in companion to :class:tempest_fastapi_sdk.BaseUserModel, which ships no name column — the admin login flow it was built for needs an email and a password, not a greeting. Mix it in when the project wants one on the user row:

from tempest_fastapi_sdk import BaseUserModel, NameMixin


class UserModel(NameMixin, BaseUserModel):
    __tablename__ = "users"

Two bundled flows write it when it exists: :meth:~tempest_fastapi_sdk.UserAuthService.signup passes the name from the payload through, and :meth:~tempest_fastapi_sdk.UserAuthService.login_with_oauth stores what the identity provider reported (falling back to a localized placeholder when the provider reports nothing). Enabling the OAuth router without this mixin is refused at construction rather than at the first callback.

The column is NOT NULL with an empty-string default rather than nullable, so reading user.name never hands a template None to concatenate.

Attributes:

Name Type Description
name str

Display name. Empty string until something sets it.

LocaleColumnMixin

Add a nullable locale column for the row's preferred language.

Injects a BCP-47 locale tag column (e.g. "pt-BR", "en-US") so a model — typically a user — can carry the language its notifications and localized text should render in, without every project re-declaring the same column. Store a :class:tempest_fastapi_sdk.LocaleEnum member (it binds as its string value) or any raw tag.

NULL means "no preference": resolve it to your app's default locale (e.g. via :class:tempest_fastapi_sdk.MessageCatalog) rather than treating it as an error.

Attributes:

Name Type Description
locale str | None

The row's preferred BCP-47 locale tag, or None when unset.

AsyncDatabaseManager

AsyncDatabaseManager(
    db_url: str,
    *,
    echo: bool = False,
    pool_size: int = 10,
    max_overflow: int = 20,
    pool_recycle: int = 3600,
    connect_args: dict[str, Any] | None = None,
    poolclass: type[Pool] | None = None,
    sqlite_wal: bool = True,
    sqlite_busy_timeout: float = 30.0,
    sqlite_foreign_keys: bool = True,
    **engine_kwargs: Any,
)

Manage the async SQLAlchemy engine and session lifecycle.

Handles engine creation tailored to the database backend (SQLite gets check_same_thread=False by default, everything else gets a pooled config), session factory construction, and table create/drop helpers. Designed to be instantiated once per application and reused across requests.

Backend detection uses sqlalchemy.engine.make_url so URLs like sqlite+aiosqlite://... are matched precisely without relying on substring tricks.

SQLite engines are additionally put in WAL mode with a 30-second busy timeout, which is what makes "web process plus worker on the same file" work at all — see :func:enable_sqlite_wal for the measurement and for the one contention WAL does not fix. They also enforce foreign keys (:func:enable_sqlite_foreign_keys), so an orphan row or a missing ON DELETE CASCADE fails the way it does on PostgreSQL.

Attributes:

Name Type Description
is_sqlite bool

Whether the URL targets a SQLite backend.

The connection URL itself is stored on a private attribute so it never leaks through repr() or accidental logging. Use the :attr:db_url_safe property when a redacted form is needed.

Initialize the manager (does not open connections yet).

Parameters:

Name Type Description Default
db_url str

The database connection URL.

required
echo bool

Whether to emit SQL to stdout.

False
pool_size int

Number of permanent connections in the pool. Ignored for SQLite URLs.

10
max_overflow int

Extra connections allowed above the pool size. Ignored for SQLite URLs.

20
pool_recycle int

Recycle connections older than this many seconds. Ignored for SQLite URLs.

3600
connect_args dict[str, Any] | None

Driver-level arguments forwarded to create_async_engine (e.g. {"ssl": "require"} for asyncpg). SQLite always receives check_same_thread=False unless explicitly overridden here.

None
poolclass type[Pool] | None

Override SQLAlchemy's default pool class. Useful for tests (poolclass=NullPool) or specialized topologies.

None
sqlite_wal bool

Whether SQLite engines are put in WAL mode (see :func:enable_sqlite_wal). Ignored on every other backend. Turn it off only for a file on a filesystem without working shared memory — WAL needs mmap, so some network mounts reject it.

True
sqlite_busy_timeout float

Seconds a SQLite connection waits for a lock held by another connection before giving up with database is locked. Forwarded to the driver as connect_args["timeout"]; the driver's own default is 5 seconds, which is short for a worker that writes in bursts. Ignored on every other backend, and ignored here when connect_args already carries a timeout.

30.0
sqlite_foreign_keys bool

Whether SQLite engines enforce FOREIGN KEY constraints and their ON DELETE actions (see :func:enable_sqlite_foreign_keys). Ignored on every other backend. Turn it off only for a database that already holds orphan rows you cannot clean up yet.

True
**engine_kwargs Any

Any additional keyword arguments are passed through to create_async_engine verbatim.

{}

db_url_safe property

db_url_safe: str

Return the URL with the password masked.

Useful for diagnostics, health payloads or log lines — postgresql+asyncpg://user:pass@host:5432/db becomes postgresql+asyncpg://user:***@host:5432/db. Only the password is replaced (SQLAlchemy's render_as_string(hide_password=True)): the username, host, port, database and query string are kept, so treat the result as internal-facing if the username is itself sensitive. A URL without a password (SQLite) comes back unchanged.

Returns:

Name Type Description
str str

The URL safe to surface outside the manager.

engine property

engine: AsyncEngine

Return the live async engine.

Useful for instrumentation that attaches to the engine directly — e.g. :class:~tempest_fastapi_sdk.db.slow_query.SlowQueryLogger or OpenTelemetry's SQLAlchemy instrumentor.

Returns:

Name Type Description
AsyncEngine AsyncEngine

The initialized engine.

Raises:

Type Description
RuntimeError

If :meth:connect has not run yet.

is_connected property

is_connected: bool

Whether the engine is currently initialized.

Returns:

Name Type Description
bool bool

True if :meth:connect has been called and

bool

meth:disconnect has not.

connect async

connect() -> None

Create the engine and session factory if they don't exist.

Idempotent — calling twice is a no-op.

disconnect async

disconnect() -> None

Dispose the engine and clear the session factory.

Safe to call multiple times.

get_session async

get_session() -> AsyncSession

Return a new AsyncSession bound to the engine.

Lazy-connects on first use. The caller is responsible for closing the session (use :meth:get_session_context for managed lifecycle).

Returns:

Name Type Description
AsyncSession AsyncSession

A new session.

get_session_context async

get_session_context() -> AsyncGenerator[AsyncSession]

Yield a session that commits on exit and rolls back on error.

This is a unit of work, not a plain session scope: a clean exit from the async with block runs session.commit(), an exception runs session.rollback() and re-raises, and the session is closed either way. :meth:transaction is the same context manager under a name that says so.

Use it where the block is the unit of work: scripts, TaskIQ tasks, FastStream consumers, agent tools. Do not wrap it in a FastAPI dependency. The exit code of a yield dependency runs after the response has been sent — measured on FastAPI 0.141.1, the ASGI http.response.start and http.response.body messages go out before the COMMIT — so the client can act on a 204 before the write is durable, and a commit that fails there cannot change the status code the client already received. For a request-scoped session use :meth:session_dependency (or :func:session_dependency_for when the manager is built lazily) and commit in the service or repository layer.

Yields:

Name Type Description
AsyncSession AsyncGenerator[AsyncSession]

A managed session.

Raises:

Type Description
Exception

Re-raises whatever the caller raised inside the async with block, after rolling back.

transaction

transaction() -> AbstractAsyncContextManager[AsyncSession]

Open a session that commits on exit and rolls back on error.

Explicit-name alias of :meth:get_session_context, with the same behaviour and the same caveat: never wrap it in a FastAPI dependency, because the commit would run after the response is sent.

Not to be confused with :func:tempest_fastapi_sdk.db.transaction.transaction, which takes a session that already exists and groups several repository writes into one COMMIT. This method opens a new session; the function scopes writes on one you already hold.

Returns:

Name Type Description
AbstractAsyncContextManager[AsyncSession]

AbstractAsyncContextManager[AsyncSession]: The same context

manager AbstractAsyncContextManager[AsyncSession]

meth:get_session_context returns.

session_dependency async

session_dependency() -> AsyncGenerator[AsyncSession]

FastAPI dependency yielding one session per request.

Use as Depends(db.session_dependency). Differs from :meth:get_session_context in that it does not commit on success — commits are the responsibility of the service / repository layer. The session is closed when the request scope ends; failures bubble up unchanged.

Binding db.session_dependency requires the manager to exist when the module is imported. When it is built on demand (an @lru_cache factory that reads settings after a boot guard), use :func:session_dependency_for instead.

Yields:

Name Type Description
AsyncSession AsyncGenerator[AsyncSession]

A request-scoped session.

health_check async

health_check() -> bool

Return whether a trivial SELECT 1 succeeds.

Suitable for /health endpoints. Swallows every exception and returns False so callers can branch on the result without dealing with driver-specific error types.

Returns:

Name Type Description
bool bool

True when the database responded with 1,

bool

False on any failure.

create_tables async

create_tables(metadata: MetaData | None = None) -> None

Issue CREATE TABLE for every table registered on metadata.

Without an argument only the models that inherit the SDK's :class:~tempest_fastapi_sdk.db.model.BaseModel are created. A service that declares its own DeclarativeBase passes that base's metadata; otherwise nothing of its schema is created and the first query fails with a missing table.

Connects lazily when :meth:connect has not run yet. Intended for tests and local development. Production schemas should be managed by Alembic (see :class:tempest_fastapi_sdk.db.migrations.AlembicHelper).

Parameters:

Name Type Description Default
metadata MetaData | None

The metadata whose tables are created. Defaults to BaseModel.metadata.

None

drop_tables async

drop_tables(metadata: MetaData | None = None) -> None

Issue DROP TABLE for every table registered on metadata.

Without an argument only the tables of the SDK's :class:~tempest_fastapi_sdk.db.model.BaseModel are dropped; pass the metadata of your own DeclarativeBase to drop its tables. Connects lazily when :meth:connect has not run yet. Intended for tests and local development.

Parameters:

Name Type Description Default
metadata MetaData | None

The metadata whose tables are dropped. Defaults to BaseModel.metadata.

None

session_dependency_for

session_dependency_for(
    get_db: Callable[[], AsyncDatabaseManager],
) -> Callable[[], AsyncGenerator[AsyncSession]]

Build a request-session dependency for a manager built on demand.

Depends(db.session_dependency) needs db at import time. A service that builds the manager lazily — an @lru_cache factory that reads settings only after a boot guard, and that tests swap for a test database — passes the factory here instead. get_db is called once per request, never at import.

The returned dependency has the semantics of :meth:AsyncDatabaseManager.session_dependency: one session per request, no commit on success, the session closed when the request scope ends — also when the endpoint raises. It opens the session itself instead of iterating the manager's generator, so there is no inner generator left suspended for the garbage collector when FastAPI throws into the dependency.

Build it once, at module level (get_session = session_dependency_for(get_db)). FastAPI caches a dependency per request by callable identity, so two separate calls produce two functions and, used in one request, two sessions.

Parameters:

Name Type Description Default
get_db Callable[[], AsyncDatabaseManager]

Zero-argument factory returning the manager, typically @lru_cache-d.

required

Returns:

Type Description
Callable[[], AsyncGenerator[AsyncSession]]

Callable[[], AsyncGenerator[AsyncSession]]: The dependency, for

Callable[[], AsyncGenerator[AsyncSession]]

Depends(...).

AlembicHelper

AlembicHelper(config_path: str = 'alembic.ini', *, db_url: str | None = None)

High-level wrapper around the Alembic command surface.

Encapsulates a single alembic.ini configuration and exposes the operations that matter for day-to-day work — upgrade, downgrade, revision authoring, schema-vs-models check — without leaking Alembic internals into application code.

Alembic itself is synchronous, and the SDK's env.py drives the async engine with asyncio.run, so the plain methods are for CLI scripts and other code with no event loop running. Code that already runs on a loop — a FastAPI lifespan, an admin endpoint — awaits the *_async counterpart instead (:meth:upgrade_async, :meth:sync_schema_async, ...). Each one runs the sync method in a worker thread, which has no loop of its own, so asyncio.run inside env.py works there and the caller's loop keeps serving while the migration runs. A sync method that would execute env.py called from a running loop raises a RuntimeError naming its _async counterpart, instead of failing inside Alembic.

The worker thread is chosen over running the migration on the caller's loop through AsyncConnection.run_sync (Alembic's connection-sharing recipe) because it works with every env.py already generated: that recipe needs an env.py that reads config.attributes["connection"], and the template only learned to in the release that added these methods. The template now supports both, so code that must reuse its own connection still can — see the migrations recipe.

Attributes:

Name Type Description
config_path str

Path to the alembic.ini configuration.

Initialize the helper.

Parameters:

Name Type Description Default
config_path str

Path to alembic.ini. Resolved relative to the current working directory.

'alembic.ini'
db_url str | None

If provided, overrides sqlalchemy.url from the .ini file. Useful when the URL must come from settings/environment rather than the ini.

None

config property

config: Config

Return a fresh :class:alembic.config.Config instance.

A new instance is built on every access so the helper stays stateless and safe to share across threads — Alembic mutates the config object during command execution.

sqlalchemy.url resolution order:

  1. db_url passed on the constructor (explicit override).
  2. The value already on the ini file.
  3. The DATABASE_URL environment variable (loaded from .env before invoking the helper).
  4. src.core.settings.settings.DATABASE_URL when the scaffolded layout is detected.

The SDK-generated ini ships with sqlalchemy.url = empty on purpose so secrets never enter version control — the resolution chain above fills it at runtime. That empty default has been the SDK's shape since v0.30.2, which is why steps 3 and 4 exist at all: on a project generated before then the ini still carries a URL and step 2 wins.

Returns:

Name Type Description
Config Config

The configured Alembic config.

init

init(
    directory: str = "alembic",
    *,
    metadata_module: str | None = None,
    metadata_attr: str = "BaseModel",
    db_url: str = "sqlite+aiosqlite:///./app.db",
) -> None

Scaffold a new Alembic environment in directory.

Wraps alembic init -t async and then overwrites the generated env.py with the SDK's template: the metadata import and one call to :func:~tempest_fastapi_sdk.db.alembic_env.run_alembic_env, which sets compare_type / compare_server_default, batch mode for SQLite and the revision hooks. The file carries no alembic import, so it sorts the same under any ruff first-party configuration.

Four details of the scaffold are deliberate:

  • The ini is pre-seeded at :attr:config_path before calling command.init, because Alembic writes it wherever config.config_file_name points — seeding is what makes the file land where this helper later expects to find it.
  • The ini Alembic wrote is then replaced by the SDK layout (logger sections, file_template, UTC timestamps), with sqlalchemy.url left empty so credentials never enter version control. The companion env.py template resolves the URL at runtime from DATABASE_URL (or src.core.settings) and injects it back into the config before the engine is built; pass db_url= on the constructor to override for a one-off (CI smoke, scripted migrations).
  • Both paths in the ini are anchored on %(here)s, the directory holding the ini: script_location = %(here)s/alembic and prepend_sys_path = %(here)s. The bare alembic CLI (uv run alembic downgrade -1) imports the project's metadata module without the tempest CLI, and a lifespan that passes the ini's absolute path works whatever directory the process was started from — with alembic and . (up to v0.312.x) it only worked from the project root (#519). An absolute directory is written as given. path_separator = os comes with it: without it Alembic 1.19.1 emits a DeprecationWarning about the legacy splitting of prepend_sys_path, which a -W error run turns into a failure.
  • [post_write_hooks] runs ruff format then ruff check --fix over every generated revision, so the files autogenerate emits — long sa.Column lines, trailing whitespace in the header when down_revision is None — are lint-clean out of the box. The order matters: the formatter wraps over-length lines (E501) and strips trailing whitespace (W291), so running the linter first would report errors the formatter is about to fix on the next hook. --quiet keeps the second pass silent when nothing actionable remains. The hook is Alembic's module type pointing at tempest_fastapi_sdk.db._ruff_post_write, which looks ruff up first (next to the interpreter, then on PATH) and skips silently without one, so a [cli-ops] install without ruff creates the revision unformatted instead of printing ruff: command not found (#883).

The generated ini also carries no [loggers]/[handlers]/[formatters] sections, which is the one omission worth explaining. env.py runs inside the host application process, where configure_logging has already set up Python's logging tree. Shipping the stock [logger_root] level = WARN handlers = console block would make fileConfig(alembic.ini) reset the root logger to WARN plus a stderr handler, silencing the SDK's 500 handler, the /logs writer and every JSON record the app emits. The companion env.py still calls fileConfig — guarded on the section being present — so a project that deliberately re-adds a [loggers] block keeps working.

Parameters:

Name Type Description Default
directory str

Target directory for versions/ and env.py. Created if missing.

'alembic'
metadata_module str | None

Dotted module path that exposes the SQLAlchemy metadata (e.g. "app.db"). When None, the env.py is left with target_metadata = None so the user can wire it manually.

None
metadata_attr str

Name of the attribute inside metadata_module whose .metadata is used as the autogenerate target. Defaults to "BaseModel".

'BaseModel'
db_url str

Value to write under sqlalchemy.url in the generated alembic.ini. Replace later via env-var injection or by passing db_url to the constructor.

'sqlite+aiosqlite:///./app.db'

upgrade

upgrade(revision: str = 'head') -> None

Apply migrations up to revision (default: head).

Parameters:

Name Type Description Default
revision str

Target revision identifier or relative spec ("+1"). "head" runs every pending migration.

'head'

Raises:

Type Description
RuntimeError

When called from a running event loop; await :meth:upgrade_async there instead.

upgrade_async async

upgrade_async(revision: str = 'head') -> None

Run :meth:upgrade in a worker thread, for async callers.

Parameters:

Name Type Description Default
revision str

Target revision identifier or relative spec.

'head'

pending_destructive_ops

pending_destructive_ops(revision: str = 'head') -> list[tuple[str, str]]

Scan migrations pending up to revision for destructive ops.

Walks the revisions between the database's current revision and revision and inspects each migration module's source for data-destroying Alembic calls (op.drop_table / op.drop_column / op.drop_constraint and their batch_op variants). Source scanning is dialect-agnostic, so it never trips on SQLite's batch table-rebuild SQL the way offline-SQL scanning would.

Parameters:

Name Type Description Default
revision str

The target revision (default "head").

'head'

Returns:

Type Description
list[tuple[str, str]]

list[tuple[str, str]]: (revision_id, operation) pairs for

list[tuple[str, str]]

every destructive call found. Empty when the pending range is

list[tuple[str, str]]

clean.

pending_destructive_ops_async async

pending_destructive_ops_async(revision: str = 'head') -> list[tuple[str, str]]

Run :meth:pending_destructive_ops in a worker thread.

Parameters:

Name Type Description Default
revision str

The target revision (default "head").

'head'

Returns:

Type Description
list[tuple[str, str]]

list[tuple[str, str]]: (revision_id, operation) pairs.

safe_upgrade

safe_upgrade(revision: str = 'head', *, force: bool = False) -> None

Upgrade, but refuse destructive migrations unless forced.

Runs :meth:pending_destructive_ops first. If any pending migration would drop a table, column or constraint, raises :class:DestructiveMigrationError and does not touch the database — unless force=True, which logs the offences and proceeds. Use this in automated deploy pipelines so an accidental DROP COLUMN can't silently delete production data.

Parameters:

Name Type Description Default
revision str

The target revision (default "head").

'head'
force bool

When True, run even if destructive ops are present (after logging them). Defaults to False.

False

Raises:

Type Description
DestructiveMigrationError

When destructive ops are pending and force is False.

RuntimeError

When called from a running event loop; await :meth:safe_upgrade_async there instead.

safe_upgrade_async async

safe_upgrade_async(revision: str = 'head', *, force: bool = False) -> None

Run :meth:safe_upgrade in a worker thread, for async callers.

Parameters:

Name Type Description Default
revision str

The target revision (default "head").

'head'
force bool

Run even if destructive ops are pending.

False

Raises:

Type Description
DestructiveMigrationError

When destructive ops are pending and force is False.

squash

squash(message: str = 'squash', *, force: bool = False, backup: bool = True) -> str

Collapse the whole migration history into one fresh root revision.

Migration files accumulate without bound as a project evolves — every schema tweak adds another file under versions/ that Alembic must walk on every upgrade. This routine resets that history to a single root revision describing the current schema, so the tree stops growing while existing databases stay usable via :meth:stamp.

The flow is destructive to the configured database and is meant to run against a development database:

  1. Capture the current head (used to name the backup directory).
  2. downgrade base — drop every table and clear alembic_version so autogenerate sees an empty schema.
  3. Move (backup=True) or delete the old revision files out of versions/.
  4. Autogenerate one root revision from BaseModel.metadata — the full schema as a single upgrade().
  5. upgrade head to recreate the schema and stamp the new revision.

Existing production databases are not touched. After deploying the squashed tree, mark them as migrated without recreating tables: tempest db stamp head.

Parameters:

Name Type Description Default
message str

Slug/message for the new root revision.

'squash'
force bool

Must be True to proceed — step 2 drops every table in the configured database, so this guards against running against the wrong (e.g. production) URL.

False
backup bool

When True (default), move the old revision files into versions/_squashed_<oldhead>/ (a non-recursive subdirectory Alembic ignores) instead of deleting them outright.

True

Returns:

Name Type Description
str str

The revision id of the new root migration.

Raises:

Type Description
RuntimeError

When force is False, when there are no revisions to squash, when the migration graph has multiple heads (run a merge revision first), or when called from a running event loop (await :meth:squash_async).

squash_async async

squash_async(
    message: str = "squash", *, force: bool = False, backup: bool = True
) -> str

Run :meth:squash in a worker thread, for async callers.

Parameters:

Name Type Description Default
message str

Slug/message for the new root revision.

'squash'
force bool

Must be True to proceed.

False
backup bool

Move the old revision files aside instead of deleting them.

True

Returns:

Name Type Description
str str

The revision id of the new root migration.

Raises:

Type Description
RuntimeError

When force is False, when there are no revisions to squash, or when the graph has multiple heads.

downgrade

downgrade(revision: str = '-1') -> None

Revert migrations down to revision (default: one step back).

Parameters:

Name Type Description Default
revision str

Target revision identifier or relative spec. "base" rolls everything back.

'-1'

Raises:

Type Description
RuntimeError

When called from a running event loop; await :meth:downgrade_async there instead.

downgrade_async async

downgrade_async(revision: str = '-1') -> None

Run :meth:downgrade in a worker thread, for async callers.

Parameters:

Name Type Description Default
revision str

Target revision identifier or relative spec.

'-1'

current

current(*, bind: Engine | Connection | None = None) -> str | None

Return the revision the database is currently stamped at.

Reads alembic_version with a plain SELECT, without building an Alembic MigrationContext, so the call logs nothing: MigrationContext.configure would log Context impl ... and Will assume ... DDL. at INFO on every read, which is noise once this backs a readiness probe. upgrade/downgrade/stamp still go through Alembic and keep logging Running upgrade ....

Without bind, opens a short-lived engine from the configured URL and disposes of it afterwards. Works from a running event loop whenever a sync driver for the backend is installed. On an async-only install (asyncpg without a sync PostgreSQL driver) the read goes through asyncio.run and therefore raises there; await :meth:current_async instead.

Parameters:

Name Type Description Default
bind Engine | Connection | None

A sync engine or connection the caller already owns. When given, the read runs on it and no engine is created or disposed; sqlalchemy.url is not consulted.

None

Returns:

Type Description
str | None

str | None: The revision identifier, or None when the

str | None

alembic_version table is missing/empty.

Raises:

Type Description
CommandError

When alembic_version holds more than one row (unmerged branches stamped in the database), as Alembic's get_current_revision does.

RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE) and no bind was passed, so there is no database to read the revision from, or when the async-only fallback is needed inside a running loop.

current_async async

current_async(*, bind: AsyncEngine | AsyncConnection | None = None) -> str | None

Return the stamped revision from async code.

With bind — typically db.engine of the app's :class:~tempest_fastapi_sdk.db.connection.AsyncDatabaseManager — the SELECT runs on the caller's event loop over that pool: no worker thread, no engine created and none disposed. Without it, runs :meth:current in a worker thread, unchanged.

Parameters:

Name Type Description Default
bind AsyncEngine | AsyncConnection | None

An async engine or connection the caller already owns. An AsyncConnection is used as is, so the read joins its open transaction.

None

Returns:

Type Description
str | None

str | None: The revision identifier, or None when the

str | None

database is not stamped.

Raises:

Type Description
CommandError

When alembic_version holds more than one row.

RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE) and no bind was passed.

has_existing_schema

has_existing_schema(*, bind: Engine | Connection | None = None) -> bool

Report whether the database holds tables Alembic did not create.

This is the question that separates "empty database, run the migrations" from "database that predates Alembic, adopt it first", and it is the one a hand-rolled bootstrap usually forgets to ask. alembic_version is excluded because Alembic writes it itself, so its presence says nothing about the application schema.

Parameters:

Name Type Description Default
bind Engine | Connection | None

A sync engine or connection the caller already owns. When given, the read runs on it and no engine is created or disposed.

None

Returns:

Name Type Description
bool bool

True when at least one non-Alembic table exists.

Raises:

Type Description
RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE) and no bind was passed, or when the async-only fallback is needed inside a running loop.

has_existing_schema_async async

has_existing_schema_async(*, bind: AsyncEngine | AsyncConnection | None = None) -> bool

Report :meth:has_existing_schema from async code.

Parameters:

Name Type Description Default
bind AsyncEngine | AsyncConnection | None

An async engine or connection the caller already owns. When given, the read runs on the caller's loop over it, with no worker thread and no engine created or disposed; otherwise :meth:has_existing_schema runs in a worker thread.

None

Returns:

Name Type Description
bool bool

True when at least one non-Alembic table exists.

Raises:

Type Description
RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE) and no bind was passed.

schema_at_head_check

schema_at_head_check(db: AsyncDatabaseManager) -> Callable[[], Awaitable[bool]]

Build a readiness check: is the database stamped at the head?

The returned callable fits make_health_router(checks=...). Each call reads the stamp with :meth:current_async over db.engine (the app's pool, resolved per call so the check can be built before the lifespan connects) and the head with :meth:heads in a worker thread, since that walks the migration files on disk.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The app's database manager. It must be connected by the time the probe runs.

required

Returns:

Type Description
Callable[[], Awaitable[bool]]

Callable[[], Awaitable[bool]]: A check that answers True

Callable[[], Awaitable[bool]]

when the migration tree has exactly one head and the database

Callable[[], Awaitable[bool]]

is stamped at it, and False otherwise — including an empty

Callable[[], Awaitable[bool]]

tree, an unstamped database, or one behind the head. A

Callable[[], Awaitable[bool]]

database with several stamped heads raises CommandError,

Callable[[], Awaitable[bool]]

which the health router counts as failed.

base_revision

base_revision() -> str

Return the root revision of the migration tree.

This is the revision to stamp when adopting a schema that already exists — never head, which is :meth:stamp's default and the wrong answer for adoption.

Returns:

Name Type Description
str str

The single root revision identifier.

Raises:

Type Description
AmbiguousBaseRevisionError

When the tree has no revisions, or more than one root.

adopt

adopt() -> bool

Bring a pre-Alembic database under Alembic, without upgrading.

Stamps the base revision when the database holds application tables but no alembic_version row — the state a project reaches by creating its schema with create_all before it had migrations. Stamping the base says "the baseline is already applied", which is true, and leaves every revision after it pending, which is also true.

Does nothing when the database is already stamped (there is nothing to adopt) or when it is empty (the baseline will create the tables itself, so stamping would skip the work).

Returns:

Name Type Description
bool bool

True when a stamp was written.

Raises:

Type Description
AmbiguousBaseRevisionError

When adoption is needed but the tree has no single root to stamp.

RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE), or when called from a running event loop (await :meth:adopt_async).

adopt_async async

adopt_async() -> bool

Run :meth:adopt in a worker thread, for async callers.

Returns:

Name Type Description
bool bool

True when a stamp was written.

Raises:

Type Description
AmbiguousBaseRevisionError

When adoption is needed but the tree has no single root to stamp.

RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE).

sync_schema

sync_schema(*, force: bool = False) -> SchemaSyncOutcomeEnum

Bring the schema in line with the migration tree, from any state.

This is the whole first-boot bootstrap, and it exists because the obvious hand-written version is wrong in a way that stays invisible for weeks. That version calls create_tables() and then stamp("head"): create_all is CREATE TABLE IF NOT EXISTS, so against a schema that already exists it adds no column, and the stamp then records every revision as applied. alembic current answers head, alembic upgrade head has nothing to do, alembic history looks clean — and the first query touching a column a migration was supposed to add fails in production, far from the cause.

The three states this distinguishes:

  • Empty database — no stamp and no application table; upgrade runs the whole tree, and the schema the baseline builds is by construction the one later revisions expect to alter. The destructive guard is skipped here: every revision is pending, so a drop_column anywhere in the project's history would otherwise refuse the very first boot, and there is no row for it to destroy.
  • Database that predates Alembic — :meth:adopt stamps the base, then safe_upgrade runs everything after it.
  • Database already under Alembic — safe_upgrade alone.

From a lifespan hook, await :meth:sync_schema_async — this method raises when an event loop is already running.

Parameters:

Name Type Description Default
force bool

Passed to :meth:safe_upgrade. Destructive migrations are refused without it, except on an empty database.

False

Returns:

Name Type Description
SchemaSyncOutcomeEnum SchemaSyncOutcomeEnum

Which of the three paths ran.

Raises:

Type Description
DestructiveMigrationError

When a pending migration drops a table, column or constraint, the database already holds application tables and force is False.

AmbiguousBaseRevisionError

When adoption is needed but the tree has no single root to stamp.

RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE), or when called from a running event loop (await :meth:sync_schema_async).

sync_schema_async async

sync_schema_async(*, force: bool = False) -> SchemaSyncOutcomeEnum

Run :meth:sync_schema in a worker thread, for async callers.

The call to make from a FastAPI lifespan: the worker thread has no event loop, so the asyncio.run inside env.py works there.

Parameters:

Name Type Description Default
force bool

Passed to :meth:safe_upgrade.

False

Returns:

Name Type Description
SchemaSyncOutcomeEnum SchemaSyncOutcomeEnum

Which of the three paths ran.

Raises:

Type Description
DestructiveMigrationError

When a pending migration drops a table, column or constraint, the database already holds application tables and force is False.

AmbiguousBaseRevisionError

When adoption is needed but the tree has no single root to stamp.

RuntimeError

When no source resolves the database URL (:data:MISSING_DATABASE_URL_MESSAGE).

heads

heads() -> list[str]

Return every head revision known to the script directory.

Multiple heads indicate divergent branches in the migration graph — usually a sign that a merge migration is needed.

Returns:

Type Description
list[str]

list[str]: The head revision identifiers.

history

history(*, verbose: bool = False) -> str

Return the migration history as a printable string.

Wraps alembic history and captures stdout so the result can be logged or returned from an admin endpoint.

Parameters:

Name Type Description Default
verbose bool

Forward --verbose to Alembic.

False

Returns:

Name Type Description
str str

The captured output.

revision

revision(
    message: str, *, autogenerate: bool = True, sql: bool = False, head: str = "head"
) -> Script | list[Script | None] | None

Create a new revision file.

Parameters:

Name Type Description Default
message str

Description of the change (becomes the migration slug).

required
autogenerate bool

Run autogenerate against the live schema. When False, an empty revision is created for the user to fill in.

True
sql bool

Emit SQL to stdout instead of executing.

False
head str

Parent revision; defaults to the current head.

'head'

Returns:

Type Description
Script | list[Script | None] | None

Script | list[Script | None] | None: What

Script | list[Script | None] | None

alembic.command.revision returned — the Script created,

Script | list[Script | None] | None

a list of them when the environment emits one per database, or

Script | list[Script | None] | None

None under sql=True.

Raises:

Type Description
RuntimeError

When called from a running event loop; await :meth:revision_async there instead. Refused even with autogenerate=False, because revision_environment in the ini makes that path execute env.py too.

The file name is built from the message folded to ASCII ("Cria tabela de anotações" → ..._cria_tabela_de_anotacoes.py), so alembic/versions/ holds no non-ASCII module name; the file's docstring keeps the message as written. The comment lines autogenerate wraps around the operations (:data:AUTOGENERATE_MARKERS) are removed from the written file.

revision_async async

revision_async(
    message: str, *, autogenerate: bool = True, sql: bool = False, head: str = "head"
) -> Script | list[Script | None] | None

Run :meth:revision in a worker thread, for async callers.

Parameters:

Name Type Description Default
message str

Description of the change.

required
autogenerate bool

Run autogenerate against the live schema.

True
sql bool

Emit SQL to stdout instead of executing.

False
head str

Parent revision; defaults to the current head.

'head'

Returns:

Type Description
Script | list[Script | None] | None

Script | list[Script | None] | None: What :meth:revision

Script | list[Script | None] | None

returned.

stamp

stamp(revision: str = 'head', *, purge: bool = False) -> None

Stamp the database with revision without running migrations.

Useful after a manual squash where alembic_version still points at a revision that no longer exists in the tree.

.. danger:: The default is "head", and "head" is the wrong answer when importing an existing schema into Alembic for the first time. Stamping head on a schema Alembic did not build records every revision as applied when none of them ran: the database keeps the old columns while alembic current, upgrade and history all report it up to date, and the failure surfaces weeks later as no such column in production. The revision to stamp when adopting is the base — use :meth:adopt, or :meth:sync_schema for the whole first-boot path, rather than choosing by hand.

Parameters:

Name Type Description Default
revision str

The revision to stamp.

'head'
purge bool

When True, delete the existing alembic_version rows before stamping. Required when the recorded revision is no longer in the script directory — a plain stamp would fail with Can't locate revision because Alembic cannot resolve the stale pointer. Defaults to False.

False

Raises:

Type Description
RuntimeError

When called from a running event loop; await :meth:stamp_async there instead.

stamp_async async

stamp_async(revision: str = 'head', *, purge: bool = False) -> None

Run :meth:stamp in a worker thread, for async callers.

Parameters:

Name Type Description Default
revision str

The revision to stamp.

'head'
purge bool

Delete the existing alembic_version rows before stamping.

False

check

check() -> bool

Return True if no autogenerate diff would be produced.

Wraps alembic check (added in Alembic 1.9). Suitable for CI to fail when models drift from the migration tree.

The running-loop refusal sits outside the except that maps every Alembic failure to False: before it, a call from async code swallowed the asyncio.run error and reported drift that was never measured.

Returns:

Name Type Description
bool bool

True if the schema matches the models.

Raises:

Type Description
RuntimeError

When called from a running event loop; await :meth:check_async there instead.

check_async async

check_async() -> bool

Run :meth:check in a worker thread, for async callers.

Returns:

Name Type Description
bool bool

True if the schema matches the models.

show

show(revision: str = 'head') -> str

Return the details of a single revision.

Parameters:

Name Type Description Default
revision str

The revision to inspect.

'head'

Returns:

Name Type Description
str str

Multi-line description (id, parent, doc, path).

SlowQueryLogger

SlowQueryLogger(
    engine: Engine | AsyncEngine,
    *,
    threshold_ms: float = 500.0,
    level: int = WARNING,
    log_parameters: bool = False,
    explain: bool = False,
)

Emit a log line for every SQL statement slower than a threshold.

Attach once per engine at application boot, before the engine serves traffic. The listeners stay registered until :meth:detach is called (or the engine is disposed).

Example

from tempest_fastapi_sdk.db import AsyncDatabaseManager from tempest_fastapi_sdk.db.slow_query import SlowQueryLogger db = AsyncDatabaseManager("sqlite+aiosqlite://") await db.connect() slow = SlowQueryLogger(db.engine, threshold_ms=100.0) slow.attach()

Attributes:

Name Type Description
threshold_ms float

Statements at or above this wall-clock duration (in milliseconds) are logged.

level int

The logging level used for slow-query lines.

log_parameters bool

Whether to include bind parameters in the log line. Off by default (parameters may carry PII).

explain bool

Whether to run EXPLAIN and append the plan.

Initialize the logger (does not attach listeners yet).

Parameters:

Name Type Description Default
engine Engine | AsyncEngine

The engine to instrument. AsyncEngine is unwrapped to its .sync_engine.

required
threshold_ms float

Duration in milliseconds at or above which a statement is logged. Defaults to 500.0.

500.0
level int

Logging level for slow-query lines. Defaults to :data:logging.WARNING.

WARNING
log_parameters bool

When True, append the bind parameters to the log line. Development only — bind parameters may carry secrets / PII. Defaults to False.

False
explain bool

When True, run EXPLAIN <statement> on a fresh connection per slow query and append the plan. Adds a round-trip per slow query. Defaults to False.

False

Raises:

Type Description
ValueError

If threshold_ms is negative.

attach

attach() -> None

Register the timing listeners on the engine.

Idempotent — calling twice is a no-op.

detach

detach() -> None

Remove the timing listeners from the engine.

Idempotent — calling twice (or before :meth:attach) is a no-op.

BaseOutboxModel

Bases: BaseModel

Abstract outbox table — one row per event awaiting publication.

The consuming project subclasses this and picks a __tablename__ (outbox by convention), mirroring how :class:~tempest_fastapi_sdk.db.user_model.BaseUserModel is subclassed. The row carries everything the relay needs to publish and to retry with backoff.

Inherits the canonical four columns from :class:~tempest_fastapi_sdk.db.model.BaseModel (id, is_active, created_at, updated_at).

Attributes:

Name Type Description
topic str

Where the event goes — a queue name, routing key, exchange/topic, etc. Interpreted by the publish callable.

payload dict[str, Any]

The event body, stored as JSON.

status str

One of :class:OutboxStatusEnum. Indexed so the relay's WHERE status = 'pending' scan stays cheap.

attempts int

How many publish attempts have been made.

max_attempts int

Attempt budget; once attempts reaches it the row is marked FAILED instead of retried.

available_at datetime

Earliest time the relay may pick this row. Pushed into the future on each failure for backoff.

sent_at datetime | None

When the row was published, or None while pending/failed.

last_error str | None

The last publish error, for triage.

new_event classmethod

new_event(
    topic: str, payload: dict[str, Any], *, max_attempts: int = 5
) -> BaseOutboxModel

Build a fresh pending outbox row.

Convenience constructor so call sites read as OutboxModel.new_event("orders.created", {...}) instead of spelling out every default.

Parameters:

Name Type Description Default
topic str

Destination topic / queue / routing key.

required
payload dict[str, Any]

The event body (JSON-serializable).

required
max_attempts int

Attempt budget before the row fails. Defaults to 5.

5

Returns:

Name Type Description
BaseOutboxModel BaseOutboxModel

A new PENDING instance ready to add to

BaseOutboxModel

the session.

OutboxRelay

OutboxRelay(
    db: AsyncDatabaseManager,
    *,
    model: type[BaseOutboxModel],
    publish: Callable[[BaseOutboxModel], Awaitable[Any]],
    batch_size: int = 100,
    backoff_base_seconds: float = 2.0,
)

Drain pending outbox rows and publish them through a callable.

The relay is deliberately decoupled from any specific broker: it calls a caller-supplied async publish function with each event, so it works with :class:~tempest_fastapi_sdk.queue.AsyncBrokerManager, a raw FastStream broker, an HTTP webhook, or a test spy.

On a backend that supports it (PostgreSQL, MySQL), the relay locks the batch with FOR UPDATE SKIP LOCKED so several relay workers can run concurrently without two of them taking the same row. On SQLite (no row locks) it falls back to a plain select — fine for a single worker.

Delivery is at-least-once. Each event is published inside the drain's transaction and marked SENT only when that transaction commits at the end of the batch, so a drain interrupted after a publish (worker killed, task cancelled) leaves the row PENDING and the next drain publishes it again. Consumers deduplicate by the event id.

Example

relay = OutboxRelay( ... db, ... model=OutboxModel, ... publish=lambda e: broker.publish(e.topic, e.payload), ... ) await relay.run(poll_interval=1.0) # loops until cancelled

Attributes:

Name Type Description
batch_size int

Max rows drained per :meth:drain_once.

backoff_base_seconds float

Base for exponential retry backoff (base * 2 ** attempts seconds).

Initialize the relay.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager — the relay opens its own short transactions per drain.

required
model type[BaseOutboxModel]

The concrete outbox model.

required
publish Callable[[BaseOutboxModel], Awaitable[Any]]

Async callable that publishes one event. It receives the outbox row; raise to signal a failure (the row is retried with backoff).

required
batch_size int

Max rows drained per call. Defaults to 100.

100
backoff_base_seconds float

Base for the exponential retry backoff. Defaults to 2.0.

2.0

Raises:

Type Description
ValueError

If batch_size is not positive.

TypeError

If publish cannot be called with exactly one positional argument — e.g. a broker's bound publish(channel, message) passed without a wrapper, which would otherwise fail on every event and mark each one FAILED without publishing it.

drain_once async

drain_once() -> int

Publish one batch of due pending events.

Selects up to :attr:batch_size rows that are PENDING and whose available_at is in the past, publishes each, and marks it SENT — or, on failure, increments attempts, records the error, and either reschedules it (backoff) or marks it FAILED once the attempt budget is spent. All within one transaction.

Returns:

Name Type Description
int int

The number of events successfully published.

run async

run(*, poll_interval: float = 1.0, stop_event: Event | None = None) -> None

Loop :meth:drain_once forever (or until stop_event).

Sleeps poll_interval seconds between drains only when the last drain published nothing — a non-empty batch is followed by an immediate drain so a backlog clears fast.

Parameters:

Name Type Description Default
poll_interval float

Seconds to sleep when idle. Defaults to 1.0.

1.0
stop_event Event | None

When set, the loop exits after finishing the current drain. Wire it to your shutdown handler. When None, the loop runs until the task is cancelled.

None

OutboxStatusEnum

Bases: StrEnum

Lifecycle of an outbox event.

  • PENDING — written, not yet published. The relay picks these.
  • SENT — successfully published to the broker.
  • FAILED — exhausted max_attempts; needs manual attention (kept in the table for inspection, never auto-retried again).

BaseWebhookEventModel

Bases: BaseModel

Abstract inbox table — one row per distinct inbound event.

The consuming project subclasses this and picks a __tablename__ (webhook_events by convention). The unique constraint on (provider, external_id) is declared here rather than left to the subclass: it is the idempotency, and a subclass that forgot it would process every retry.

Inherits the canonical four columns from :class:~tempest_fastapi_sdk.db.model.BaseModel (id, is_active, created_at, updated_at), so created_at is when the delivery arrived.

Attributes:

Name Type Description
provider str

Who sent it ("revenuecat", "stripe", ...).

external_id str

The provider's event id — the value the provider promises is the same on every retry of one event.

event_type str

The provider's event type, as delivered. Indexed, because "every EXPIRATION that failed" is a real question.

payload dict[str, Any]

The event as JSON. Whatever the caller passes to :meth:WebhookInbox.record — strip personal data before that, not after.

status str

One of :class:WebhookEventStatusEnum. Indexed.

attempts int

Processing attempts so far, incremented by :meth:WebhookInbox.claim.

max_attempts int

Budget; reaching it makes a failure terminal.

available_at datetime

Earliest time the sweep may claim the row. Pushed forward on each failure.

started_at datetime | None

When the current attempt was claimed.

processed_at datetime | None

When the handler's transaction committed.

last_error str | None

The last failure, for triage.

WebhookInbox

WebhookInbox(
    db: AsyncDatabaseManager,
    *,
    model: type[EventT],
    max_attempts: int = DEFAULT_WEBHOOK_MAX_ATTEMPTS,
    backoff_base_seconds: float = DEFAULT_WEBHOOK_BACKOFF_SECONDS,
    stale_after: float | timedelta | None = 600.0,
)

Bases: Generic[EventT]

Record inbound events once and process each at most to its budget.

Like :class:~tempest_fastapi_sdk.tasks.JobStore, the inbox takes the :class:~tempest_fastapi_sdk.db.AsyncDatabaseManager and opens one short transaction per call, so neither the route nor the worker holds a session across the provider's wait or the handler's network calls.

Example

inbox = WebhookInbox(db, model=WebhookEventModel) event_id = await inbox.record( ... "revenuecat", event.id, event.type, payload ... )

in the worker or the scheduled sweep

await inbox.drain_once(apply_event)

Attributes:

Name Type Description
max_attempts int

Budget given to newly recorded events.

backoff_base_seconds float

Base of the exponential backoff.

stale_after timedelta | None

How long a claim may stay PROCESSING before :meth:reclaim_stale considers its worker dead. None disables reclaiming.

Initialize the inbox.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager; the inbox opens its own session per call.

required
model type[EventT]

The concrete inbox model.

required
max_attempts int

Attempt budget for new events. Defaults to 5.

DEFAULT_WEBHOOK_MAX_ATTEMPTS
backoff_base_seconds float

Base of the backoff between attempts, in seconds. 0 retries on the next sweep.

DEFAULT_WEBHOOK_BACKOFF_SECONDS
stale_after float | timedelta | None

Seconds (or a timedelta) a claim may last before :meth:reclaim_stale readmits it. Ten minutes by default — longer than any handler should take. None disables reclaiming.

600.0

Raises:

Type Description
ValueError

If max_attempts is below 1, the backoff is negative, or stale_after is not positive.

record async

record(
    provider: str, external_id: str, event_type: str, payload: Mapping[str, Any]
) -> UUID | None

Store one delivery unless the same event was already stored.

On PostgreSQL and SQLite this is INSERT ... ON CONFLICT DO NOTHING RETURNING id — no exception, no aborted transaction. Other dialects insert inside a savepoint and treat the IntegrityError as the duplicate.

Parameters:

Name Type Description Default
provider str

Who sent it.

required
external_id str

The provider's event id.

required
event_type str

The provider's event type.

required
payload Mapping[str, Any]

The event, JSON-serializable. Remove what you do not want stored before calling.

required

Returns:

Type Description
UUID | None

UUID | None: The new row's id, or None when

UUID | None

(provider, external_id) is already recorded — answer the

UUID | None

provider 200 either way.

Raises:

Type Description
ValueError

If provider or external_id is empty — an empty id would make every delivery a duplicate of the first.

get async

get(event_id: UUID) -> EventT | None

Return one recorded event.

Parameters:

Name Type Description Default
event_id UUID

The inbox row id.

required

Returns:

Type Description
EventT | None

EventT | None: The row, or None when no row has that id.

claim async

claim(event_id: UUID) -> EventT | None

Move a due RECEIVED event to PROCESSING and return it.

One conditional UPDATE: of two workers racing for the same id, exactly one sees a row change and the other gets None. A row whose backoff has not elapsed is not claimable either.

Parameters:

Name Type Description Default
event_id UUID

The inbox row id.

required

Returns:

Type Description
EventT | None

EventT | None: The claimed row, or None when it was not

EventT | None

claimable (claimed by someone else, finished, failed, in

EventT | None

backoff, or unknown).

fail async

fail(event_id: UUID, error: str) -> WebhookEventStatusEnum | None

Record a failed attempt: back to RECEIVED, or FAILED.

Two conditional UPDATE statements over disjoint conditions and no SELECT first (the read-then-write shape fails on SQLite against a concurrent writer). The first closes a row whose budget is spent; the second readmits the rest and returns attempts so the backoff can be computed, which a third UPDATE writes.

Parameters:

Name Type Description Default
event_id UUID

The claimed row.

required
error str

Why it failed. Truncated to 2000 characters.

required

Returns:

Type Description
WebhookEventStatusEnum | None

WebhookEventStatusEnum | None: FAILED when the budget is

WebhookEventStatusEnum | None

spent, RECEIVED when it will be retried, None when the

WebhookEventStatusEnum | None

row was not PROCESSING (already closed or reclaimed).

process async

process(
    event_id: UUID, handler: Callable[[EventT, AsyncSession], Awaitable[object]]
) -> WebhookEventStatusEnum | None

Claim one event, run handler and close the row.

The handler receives the claimed row and an open session, and the row is marked PROCESSED in that same transaction. Whatever the handler writes through the session commits together with the mark, or not at all — so a crash between the effect and the mark cannot apply the effect twice. Effects outside the database (an e-mail, a call to another API) are not covered by that transaction; make those idempotent on the event id.

If the handler raises, its transaction rolls back and :meth:fail records the attempt.

Parameters:

Name Type Description Default
event_id UUID

The inbox row id.

required
handler Callable[[EventT, AsyncSession], Awaitable[object]]

Applies the event. Its return value is ignored.

required

Returns:

Type Description
WebhookEventStatusEnum | None

WebhookEventStatusEnum | None: PROCESSED, RECEIVED (will

WebhookEventStatusEnum | None

be retried), FAILED (budget spent), or None when the row

WebhookEventStatusEnum | None

was not claimable.

due async

due(*, limit: int = 100) -> list[UUID]

List the ids of RECEIVED events whose backoff has elapsed.

Parameters:

Name Type Description Default
limit int

Maximum ids returned, oldest delivery first.

100

Returns:

Type Description
list[UUID]

list[UUID]: The ids, possibly empty.

reclaim_stale async

reclaim_stale() -> InboxDrainReport

Readmit events whose worker died holding the claim.

A PROCESSING row older than :attr:stale_after goes back to RECEIVED — unless its attempts are spent, in which case it is FAILED with :data:STALE_WEBHOOK_ERROR. Without the budget, an event that kills its worker would be readmitted forever.

Returns:

Name Type Description
InboxDrainReport InboxDrainReport

retrying holds the readmitted ids and

InboxDrainReport

failed the ones given up on. Empty when :attr:stale_after

InboxDrainReport

is None.

drain_once async

drain_once(
    handler: Callable[[EventT, AsyncSession], Awaitable[object]], *, limit: int = 100
) -> InboxDrainReport

Reclaim stale claims, then process every due event once.

This is the body of the scheduled sweep. Run it from a cron task (or any loop); several replicas running it at the same time is safe, because each event is claimed by exactly one of them.

Parameters:

Name Type Description Default
handler Callable[[EventT, AsyncSession], Awaitable[object]]

Applies one event; see :meth:process.

required
limit int

Maximum events processed in this pass.

100

Returns:

Name Type Description
InboxDrainReport InboxDrainReport

What happened to each event touched.

WebhookEventStatusEnum

Bases: BaseStrEnum

Lifecycle of a recorded webhook event.

  • RECEIVED — recorded, waiting for a worker (also where a failed attempt goes back to, until the budget is spent).
  • PROCESSING — a worker claimed it (see :meth:WebhookInbox.claim).
  • PROCESSED — the handler finished and its transaction committed.
  • FAILED — attempts reached max_attempts. Terminal: the sweep never picks it again, so it waits for a person.

InboxDrainReport dataclass

InboxDrainReport(
    processed: list[UUID] = list(),
    retrying: list[UUID] = list(),
    failed: list[UUID] = list(),
    skipped: list[UUID] = list(),
)

What one :meth:WebhookInbox.drain_once did.

Attributes:

Name Type Description
processed list[UUID]

Events whose handler committed.

retrying list[UUID]

Events that failed and went back to RECEIVED with backoff.

failed list[UUID]

Events that failed for the last time and are now FAILED — including stale claims given up on.

skipped list[UUID]

Events another worker claimed first.

make_webhook_event_model

make_webhook_event_model(
    *, tablename: str = "webhook_events", class_name: str = "WebhookEventModel"
) -> type[BaseWebhookEventModel]

Build a concrete inbox model bound to tablename.

For tests and lightweight scripts; production code should subclass :class:BaseWebhookEventModel by hand so Alembic picks it up statically.

Parameters:

Name Type Description Default
tablename str

The table name.

'webhook_events'
class_name str

The generated class name.

'WebhookEventModel'

Returns:

Type Description
type[BaseWebhookEventModel]

type[BaseWebhookEventModel]: The concrete model class.

DEFAULT_WEBHOOK_MAX_ATTEMPTS module-attribute

DEFAULT_WEBHOOK_MAX_ATTEMPTS: int = 5

Processing attempts a recorded event gets before it is FAILED.

DEFAULT_WEBHOOK_BACKOFF_SECONDS module-attribute

DEFAULT_WEBHOOK_BACKOFF_SECONDS: float = 60.0

Base of the exponential backoff between attempts (base * 2 ** (n - 1)).

One minute, then two, four, eight: a dependency that is down for a few minutes gets the time to come back before the budget is spent.

STALE_WEBHOOK_ERROR module-attribute

STALE_WEBHOOK_ERROR: str = "The worker stopped responding while processing this event, and the attempt budget is spent."

last_error written by :meth:WebhookInbox.reclaim_stale when it gives up.

BaseAuditLogModel

Bases: BaseModel

Abstract append-only audit-log table — one row per mutation.

The consuming project subclasses this and picks a __tablename__ (audit_log by convention), mirroring :class:~tempest_fastapi_sdk.db.outbox.BaseOutboxModel. Inherits the canonical four columns from :class:~tempest_fastapi_sdk.db.model.BaseModel.

Attributes:

Name Type Description
entity str

The changed model's name (self.model.__name__). Indexed for per-entity history queries.

entity_id str

The changed row's id, stored as text so any key type fits. Indexed.

action str

One of :class:AuditActionEnum.

actor str | None

Who performed the change (user id, e-mail, "system", ...). Indexed; None for anonymous/system.

changes dict[str, Any]

The diff. For create it is {"after": {...}}; for delete {"before": {...}}; for update {field: {"before": x, "after": y}}.

context dict[str, Any] | None

Optional extra metadata (request id, reason, ...). The event name, client IP and user agent get their own columns through :class:AuditRequestMixin.

new_entry classmethod

new_entry(
    *,
    entity: str,
    entity_id: str,
    action: AuditActionEnum,
    changes: dict[str, Any],
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    event: str | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> BaseAuditLogModel

Build an audit row (not yet added to a session).

The origin values (event, ip, user_agent, actor_id) go to columns of the same name. Each is optional and, when None, is not written at all — so an audit table without those columns keeps working. A value for a column the table lacks is refused rather than dropped, because silently losing an audit fact is worse than failing the call.

Author FK extension point. To link entries to a users table (and anonymize with ON DELETE SET NULL when an account is erased), declare the column on the subclass — actor_id: Mapped[UUID | None] = mapped_column(ForeignKey( "users.id", ondelete="SET NULL"), nullable=True, index=True) — and pass actor_id=. No override of this method is needed.

Any other domain column — the subject of the event, the tenant — goes the same way through columns={"subject_id": ...}. A key the table lacks is refused, and so is a key in :data:AUDIT_RESERVED_COLUMNS, which the entry fills itself or through a parameter of its own.

Parameters:

Name Type Description Default
entity str

The changed model name.

required
entity_id str

The changed row id (as text).

required
action AuditActionEnum

The mutation kind.

required
changes dict[str, Any]

The before/after diff.

required
actor str | None

Who performed the change.

None
context dict[str, Any] | None

Extra metadata.

None
event str | None

Domain event name; needs :class:AuditRequestMixin on the audit table.

None
ip str | None

Client IP; needs :class:AuditRequestMixin.

None
user_agent str | None

User agent; needs :class:AuditRequestMixin.

None
request_context AuditRequestContext | None

ip and user_agent together; mutually exclusive with both.

None
actor_id UUID | None

The author's id; needs an actor_id column on the audit table.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
BaseAuditLogModel BaseAuditLogModel

A new instance ready to add to a session.

Raises:

Type Description
ValueError

When a value is passed for a column the audit table does not have, when columns names a reserved column, when request_context is combined with ip / user_agent, or when event / ip exceed their column width.

for_create classmethod

for_create(
    instance: BaseModel,
    *,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    event: str | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> BaseAuditLogModel

Build a create entry snapshotting the new row.

Parameters:

Name Type Description Default
instance BaseModel

The created instance.

required
actor str | None

Who created it.

None
context dict[str, Any] | None

Extra metadata.

None
event str | None

Domain event name (see :meth:new_entry).

None
ip str | None

Client IP.

None
user_agent str | None

User agent.

None
request_context AuditRequestContext | None

ip and user_agent together.

None
actor_id UUID | None

The author's id.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
BaseAuditLogModel BaseAuditLogModel

The audit row with {"after": snapshot}.

Raises:

Type Description
ValueError

See :meth:new_entry.

for_update classmethod

for_update(
    instance: BaseModel,
    before: dict[str, Any],
    *,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    event: str | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> BaseAuditLogModel

Build an update entry diffing before against the row now.

The diff is computed on the raw snapshots and redacted afterwards, so rotating a secret listed in __audit_redact__ still yields {"before": "[redacted]", "after": "[redacted]"} — the change is recorded, the values are not.

Parameters:

Name Type Description Default
instance BaseModel

The instance after mutation.

required
before dict[str, Any]

A snapshot taken before the change (via :func:snapshot_model).

required
actor str | None

Who updated it.

None
context dict[str, Any] | None

Extra metadata.

None
event str | None

Domain event name (see :meth:new_entry).

None
ip str | None

Client IP.

None
user_agent str | None

User agent.

None
request_context AuditRequestContext | None

ip and user_agent together.

None
actor_id UUID | None

The author's id.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
BaseAuditLogModel BaseAuditLogModel

The audit row with the changed-field diff.

Raises:

Type Description
ValueError

See :meth:new_entry.

for_delete classmethod

for_delete(
    instance: BaseModel,
    *,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    event: str | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> BaseAuditLogModel

Build a delete entry snapshotting the row being removed.

Parameters:

Name Type Description Default
instance BaseModel

The instance about to be deleted.

required
actor str | None

Who deleted it.

None
context dict[str, Any] | None

Extra metadata.

None
event str | None

Domain event name (see :meth:new_entry).

None
ip str | None

Client IP.

None
user_agent str | None

User agent.

None
request_context AuditRequestContext | None

ip and user_agent together.

None
actor_id UUID | None

The author's id.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
BaseAuditLogModel BaseAuditLogModel

The audit row with {"before": snapshot}.

Raises:

Type Description
ValueError

See :meth:new_entry.

for_event classmethod

for_event(
    event: str,
    *,
    entity: str,
    entity_id: str = "",
    changes: dict[str, Any] | None = None,
    actor: str | None = None,
    context: dict[str, Any] | None = None,
    ip: str | None = None,
    user_agent: str | None = None,
    request_context: AuditRequestContext | None = None,
    actor_id: UUID | None = None,
    columns: Mapping[str, Any] | None = None,
) -> BaseAuditLogModel

Build an event entry — a domain event with no row mutation.

Requires :class:AuditRequestMixin on the audit table, since the event name is what the entry records. entity_id defaults to "" (the column is NOT NULL) for an event about no single row.

Parameters:

Name Type Description Default
event str

Domain event name ("export.requested").

required
entity str

The model the event concerns.

required
entity_id str

The concerned row id, or "" for none.

''
changes dict[str, Any] | None

Optional payload; stored as {} when None.

None
actor str | None

Who triggered the event.

None
context dict[str, Any] | None

Extra metadata.

None
ip str | None

Client IP.

None
user_agent str | None

User agent.

None
request_context AuditRequestContext | None

ip and user_agent together.

None
actor_id UUID | None

The author's id.

None
columns Mapping[str, Any] | None

Values for domain columns the audit subclass declares (subject_id, tenant_id), each written to the column of the same name.

None

Returns:

Name Type Description
BaseAuditLogModel BaseAuditLogModel

The audit row with action="event".

Raises:

Type Description
ValueError

See :meth:new_entry — including when the audit table lacks :class:AuditRequestMixin.

AuditActionEnum

Bases: StrEnum

The kind of change an audit entry records.

EVENT marks a domain event recorded without a row mutation ("consent.granted", "export.requested") — see :meth:BaseAuditLogModel.for_event.

AuditRequestMixin

Opt-in event / ip / user_agent columns for an audit table.

Mixed into a :class:BaseAuditLogModel subclass, it lets new_entry, the for_* factories and the repository's *_audited / record_event methods store the domain event name and the request origin in their own columns. It is a mixin, not part of :class:BaseAuditLogModel, so an audit table created before these columns existed keeps working without a migration; adding the mixin to an existing table is a schema change that needs one.

Attributes:

Name Type Description
event str | None

Domain event name ("consent.granted"). Indexed, so "every consent grant" is an index lookup.

ip str | None

Client IP of the request that caused the change.

user_agent str | None

The request's User-Agent, truncated to :data:AUDIT_USER_AGENT_MAX_LENGTH.

AuditRequestContext dataclass

AuditRequestContext(ip: str | None = None, user_agent: str | None = None)

The request origin an audit entry records: client IP and user agent.

Built once per request with :meth:from_request and handed to the audited repository methods as request_context=.

Attributes:

Name Type Description
ip str | None

The client IP, or None when unknown.

user_agent str | None

The User-Agent header, or None.

from_request classmethod

from_request(request: Request, *, trusted_ip_header: str | None) -> AuditRequestContext

Read the client IP and User-Agent from a request.

trusted_ip_header has no default on purpose: whether a proxy header is trustworthy is a deployment fact the caller has to state (see :func:~tempest_fastapi_sdk.utils.get_client_ip). Pass the single header your edge overwrites ("x-real-ip"), or None to use the transport peer.

A resolved value that is not an IP address (a misconfigured header, or no peer at all) is stored as None instead of as the raw string, so the column only ever holds addresses.

Parameters:

Name Type Description Default
request Request

The inbound Starlette/FastAPI request.

required
trusted_ip_header str | None

The edge-set header to trust, or None for the transport peer only.

required

Returns:

Name Type Description
AuditRequestContext AuditRequestContext

The resolved origin.

snapshot_model

snapshot_model(instance: BaseModel) -> dict[str, Any]

Capture a model's column values as a JSON-able dict.

Only mapped columns are read (no relationships), and the instance is not refreshed — pass an instance whose attributes are already loaded.

Parameters:

Name Type Description Default
instance BaseModel

The mapped instance to snapshot.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: {column_name: jsonable_value} for every

dict[str, Any]

mapped column.

diff_snapshots

diff_snapshots(
    before: dict[str, Any], after: dict[str, Any]
) -> dict[str, dict[str, Any]]

Return the changed fields between two snapshots.

Parameters:

Name Type Description Default
before dict[str, Any]

The pre-change snapshot.

required
after dict[str, Any]

The post-change snapshot.

required

Returns:

Type Description
dict[str, dict[str, Any]]

dict[str, dict[str, Any]]: {field: {"before": x, "after": y}}

dict[str, dict[str, Any]]

for every field whose value differs (the union of both key

dict[str, dict[str, Any]]

sets; a field absent on one side reads as None).

audit_redacted_columns

audit_redacted_columns(model: type[BaseModel]) -> frozenset[str]

Return the columns of model whose values the audit never stores.

model.__audit_redact__, plus the credential columns the model declares through __secret_columns__ (:meth:~tempest_fastapi_sdk.db.model.BaseModel.get_secret_columns, which covers MFAMixin.totp_secret and the push, refresh-token and recovery-code models without any project configuration), plus :data:DEFAULT_AUDIT_REDACT — the last two only where the model has the column.

Parameters:

Name Type Description Default
model type[BaseModel]

The audited model class.

required

Returns:

Type Description
frozenset[str]

frozenset[str]: The redacted column keys.

Raises:

Type Description
ValueError

When __audit_redact__ names a column the model does not map — a typo there would store the secret silently.

redact_snapshot

redact_snapshot(model: type[BaseModel], snapshot: dict[str, Any]) -> dict[str, Any]

Return snapshot with every redacted column's value replaced.

Parameters:

Name Type Description Default
model type[BaseModel]

The model the snapshot was taken from.

required
snapshot dict[str, Any]

A :func:snapshot_model result.

required

Returns:

Name Type Description
dict[str, Any]

dict[str, Any]: A new dict; a redacted column holding a value

reads dict[str, Any]

data:AUDIT_REDACTED, one holding None stays None.

AUDIT_REDACTED module-attribute

AUDIT_REDACTED: Final[str] = '[redacted]'

What an audit entry stores in place of a redacted column's value.

A constant rather than a digest on purpose: a short hash of a low-entropy secret is brute-forced offline, and a full one still says whether two rows share a value. None stays None, so the entry still tells "not set" from "set".

DEFAULT_AUDIT_REDACT module-attribute

DEFAULT_AUDIT_REDACT: Final[frozenset[str]] = frozenset({'hashed_password'})

Columns redacted on every model that has them, declared or not.

AUDIT_EVENT_MAX_LENGTH module-attribute

AUDIT_EVENT_MAX_LENGTH: Final[int] = 128

Width of :attr:AuditRequestMixin.event; longer names are refused.

AUDIT_RESERVED_COLUMNS module-attribute

AUDIT_RESERVED_COLUMNS: Final[frozenset[str]] = frozenset(
    {
        "action",
        "actor",
        "actor_id",
        "changes",
        "context",
        "created_at",
        "entity",
        "entity_id",
        "event",
        "id",
        "ip",
        "is_active",
        "updated_at",
        "user_agent",
    }
)

Audit columns columns= refuses to set.

The columns of :class:BaseAuditLogModel and :class:AuditRequestMixin, plus actor_id: the entry fills them itself, or takes them through a parameter of their own, so setting one through columns= would either be overwritten or bypass the validation that parameter applies.

AUDIT_IP_MAX_LENGTH module-attribute

AUDIT_IP_MAX_LENGTH: Final[int] = 64

Width of :attr:AuditRequestMixin.ip; longer values are refused.

AUDIT_USER_AGENT_MAX_LENGTH module-attribute

AUDIT_USER_AGENT_MAX_LENGTH: Final[int] = 512

Width of :attr:AuditRequestMixin.user_agent.

A longer User-Agent is truncated to this length rather than refused: the header is client-controlled, and an oversized one must not turn the audited business write into a database error.

DestructiveMigrationError

DestructiveMigrationError(offences: list[tuple[str, str]])

Bases: RuntimeError

Raised when a pending migration would drop a table/column/constraint.

:meth:AlembicHelper.safe_upgrade raises this instead of running the migration, unless the caller passes force=True. Carries the list of offending (revision, operation) pairs so the caller can log exactly what was blocked.

Attributes:

Name Type Description
offences list[tuple[str, str]]

(revision_id, operation) pairs that tripped the guard.

Initialize.

Parameters:

Name Type Description Default
offences list[tuple[str, str]]

The blocked operations as (revision_id, operation) pairs.

required

AmbiguousBaseRevisionError

AmbiguousBaseRevisionError(bases: list[str])

Bases: RuntimeError

Raised when a migration tree has no single root to adopt at.

:meth:AlembicHelper.base_revision needs exactly one base. Zero means the project has no revisions yet, so there is nothing to stamp; more than one means the tree was merged from independent roots and only a human knows which one describes the schema already on disk.

Attributes:

Name Type Description
bases list[str]

The roots Alembic reported.

Initialize.

Parameters:

Name Type Description Default
bases list[str]

The roots Alembic reported.

required

SchemaSyncOutcomeEnum

Bases: BaseStrEnum

What :meth:AlembicHelper.sync_schema did.

Attributes:

Name Type Description
NO_MIGRATIONS str

The project has no revisions yet, so the database was left alone.

ADOPTED str

A schema that predates Alembic was stamped at the base revision and then upgraded.

SYNCED str

The ordinary path — the database was already under Alembic (or empty) and was upgraded to head.

require_sqlite_foreign_keys_off

require_sqlite_foreign_keys_off(connection: Connection) -> None

Refuse to migrate SQLite on a connection that enforces foreign keys.

Alembic's batch mode is how a SQLite migration alters a table: it creates a copy with the new shape, copies the rows, drops the original and renames the copy. With PRAGMA foreign_keys=ON that DROP TABLE performs the foreign-key actions of the dropped table. Measured with Alembic 1.19.1 and SQLite 3.47.1: batch_alter_table("org", recreate="always") adding one nullable column to a parent whose children reference it with ON DELETE CASCADE took the child table from 3 rows to 0, and no statement raised.

The engines the generated env.py and :class:AlembicHelper build never turn enforcement on, so only a connection the caller hands over as config.attributes["connection"] can carry it — typically one taken from an :class:~tempest_fastapi_sdk.db.AsyncDatabaseManager, which enforces foreign keys by default. The generated env.py calls this before running migrations on such a connection.

Reads the pragma through the raw driver cursor, so the check neither opens a transaction nor changes how Alembic sees the connection. Any backend other than SQLite returns immediately.

Parameters:

Name Type Description Default
connection Connection

The connection migrations are about to run on.

required

Raises:

Type Description
RuntimeError

When connection is SQLite and PRAGMA foreign_keys answers 1.

run_alembic_env

run_alembic_env(
    target_metadata: MetaData | Sequence[MetaData] | None,
    *,
    process_revision_directives: ProcessRevisionDirectives | None = None,
) -> None

Run the current Alembic command the way the SDK configures it.

Call it as the last statement of alembic/env.py. It resolves the database URL, applies alembic.ini's logging sections only when they exist, and runs the migrations offline (--sql) or online with compare_type, compare_server_default, batch mode, :func:~tempest_fastapi_sdk.db.enum_migrations.render_enum_types as render_item, the enum-CHECK filter as include_object (so alembic check does not report drift on a clean SQLite schema) and the revision hooks.

The URL comes from, in order: the sqlalchemy.url already on the config (--database-url, or AlembicHelper(db_url=...)); the DATABASE_URL environment variable; a settings object on core/settings.py under either code root (src or app) — a BaseSettings instance or a zero-arg factory such as get_settings(); and finally DATABASE_URL in the project's .env. alembic.ini never has to hold a secret.

Online, three entry points are checked in order:

  1. A caller that already holds a connection hands it over as config.attributes["connection"] (Alembic's connection-sharing recipe, typically from inside AsyncConnection.run_sync), and the migrations run on it: no engine and no event loop of our own. A SQLite connection that enforces foreign keys is refused first (:func:~tempest_fastapi_sdk.db.migrations.require_sqlite_foreign_keys_off): batch mode recreates tables, and dropping a parent's old copy cascades to its children.
  2. No event loop is running in this thread (the CLI, the sync AlembicHelper methods, or its *_async methods, which run in a worker thread): build an async engine under asyncio.run.
  3. An event loop is running and no connection was handed over: raise before creating the coroutine, because asyncio.run cannot nest and would leave the migration coroutine un-awaited.

Parameters:

Name Type Description Default
target_metadata MetaData | Sequence[MetaData] | None

The autogenerate target, usually BaseModel.metadata. None disables autogenerate comparisons.

required
process_revision_directives ProcessRevisionDirectives | None

The hook every autogenerated revision goes through. None composes :data:DEFAULT_REVISION_HOOKS.

None

Raises:

Type Description
RuntimeError

When no source provides a database URL — the message is :data:~tempest_fastapi_sdk.db.migrations.MISSING_DATABASE_URL_MESSAGE, the same one the AlembicHelper reads raise, followed by the cause of every attempt that failed, so an import error inside core/settings.py reaches the operator instead of a bare "DATABASE_URL is empty"; in case 3; and in case 1 when the connection is SQLite with PRAGMA foreign_keys=ON.

DEFAULT_REVISION_HOOKS module-attribute

The process_revision_directives hooks every revision goes through.

In order:

  • reorder_base_columns_first: id, is_active, created_at and updated_at come first in every create_table.
  • backfill_non_nullable_defaults: a NOT NULL column added to a table with rows gets a server_default from its scalar Python default, so the migration backfills existing rows instead of raising NotNullViolationError.
  • sync_enum_types: a changed enum member list becomes a replace_enum operation. Alembic compares neither pg_enum (PostgreSQL) nor the CHECK constraint (SQLite), so without it, adding a member to a Python enum autogenerates an empty migration.
  • sqlite_enum_checks: every enum add_column gets its own, per-column CHECK on SQLite (two columns of one enum used to share a name, and the batch kept one), and every enum drop_column drops its CHECK first (the batch rebuilt the table with a check naming the dropped column). No-op on PostgreSQL.
  • create_enum_types_on_add_column: an enum column added to an existing table creates its PostgreSQL ENUM first — add_column never does, and the ALTER TABLE failed with type ... does not exist.
  • drop_enum_types_on_downgrade: the downgrade of a new table also drops the PostgreSQL ENUM types no surviving table uses, so a downgrade followed by an upgrade does not fail with type ... already exists.

Extend it with compose_hooks(*DEFAULT_REVISION_HOOKS, my_hook) and pass the result as process_revision_directives=.

enable_sqlite_foreign_keys

enable_sqlite_foreign_keys(engine: AsyncEngine) -> None

Make SQLite enforce FOREIGN KEY constraints on every connection.

SQLite parses REFERENCES clauses but only checks them on a connection that ran PRAGMA foreign_keys=ON — off is the compiled-in default, and the setting lives on the connection, not on the database file. Left off, three things pass on SQLite that PostgreSQL rejects or does differently. Measured on SQLAlchemy 2.0.52 and 2.1.3 with aiosqlite 0.22.1, SQLite 3.47.1:

======================================== =========== ============== Operation FK off FK on ======================================== =========== ============== insert a child pointing at no parent accepted IntegrityError delete a parent, ON DELETE CASCADE child stays child deleted add_all([child, parent]) with no accepted IntegrityError relationship() ordering the flush ======================================== =========== ==============

The pragma is emitted from a connect listener on engine.sync_engine, through the raw driver cursor, so it runs once per new connection and before any transaction opens. SQLite ignores PRAGMA foreign_keys inside a transaction: emitted after :func:enable_sqlite_savepoints has issued BEGIN it is a silent no-op and the pragma keeps answering 0.

Parameters:

Name Type Description Default
engine AsyncEngine

The SQLite engine to configure. Emitting this pragma against another backend would fail, so callers building their own engine must gate on the backend.

required
Notes

Do not run Alembic batch migrations on a connection with this on. Batch mode rebuilds a table by creating a copy and dropping the original, and with enforcement on the DROP TABLE runs the foreign-key actions: measured with Alembic 1.19.1, batch_alter_table("org", recreate="always") on a parent with ON DELETE CASCADE children deleted every child row without raising. :func:require_sqlite_foreign_keys_off is the check the generated env.py runs before migrating.

enable_sqlite_savepoints

enable_sqlite_savepoints(engine: AsyncEngine) -> None

Make SAVEPOINT behave on SQLite the way it does on PostgreSQL.

The pysqlite driver that aiosqlite builds on opens transactions implicitly and, by default, never emits a BEGIN. SQLite therefore sees the SAVEPOINT as the outermost transaction, and the matching RELEASE SAVEPOINT commits it. The damage is invisible on the failure path — a rollback to the savepoint still works — and only shows up when a nested block exits cleanly and the surrounding transaction is later rolled back: the supposedly pending rows are already durable.

That is the difference between the SDK's production backend and its test backend silently disagreeing about atomicity, so the manager applies SQLAlchemy's documented remedy to every SQLite engine it builds: turn off the driver's implicit transaction handling, then emit BEGIN explicitly when SQLAlchemy starts a transaction.

Idempotent per engine — re-registering the same handlers is harmless, and the listeners are attached to engine.sync_engine because the driver-level events fire there, not on the async facade.

Parameters:

Name Type Description Default
engine AsyncEngine

The SQLite engine to configure. Passing a non-SQLite engine would break its transaction handling, so callers building their own engine must gate on the backend.

required

A third listener closes the hole a failed COMMIT leaves behind. When SQLite refuses the COMMIT (database is locked), the transaction stays open on the driver connection, but SQLAlchemy has already marked its own transaction inactive: closing the :class:~sqlalchemy.engine.Connection neither rolls back nor lets the pool do it (the pool is told the transaction was reset). The connection goes back to the pool inside the open transaction, and its next user fails on BEGIN with cannot start a transaction within a transaction. The reset listener rolls back on check-in whenever the driver still reports in_transaction.

Measured with aiosqlite 0.22.1 and SQLite 3.47.1 in the rollback journal. A COMMIT forced to fail (another connection holding a read transaction, busy_timeout of 0.1 s) left the connection dirty every time on SQLAlchemy 2.0.52 and 2.1.3 without this listener, and clean with it. Two read-modify-write transactions racing on one file, on 2.0.52, had the first COMMIT refused in 8 to 11 of 200 trials per run, with busy_timeout unset, 0.1 s or 30 s alike, and every refusal left a dirty connection; with the listener, 6 of 200 refused and none dirty. In WAL mode a reader does not block COMMIT, and the same race refused 0 of 200.

Parameters:

Name Type Description Default
engine AsyncEngine

The SQLite engine to configure. Passing a non-SQLite engine would break its transaction handling, so callers building their own engine must gate on the backend.

required
Notes

tests/db/test_transaction.py pins the RELEASE path, which is the one that regressed silently before this existed. tests/db/test_sqlite_failed_commit.py pins the failed COMMIT path.

enable_sqlite_wal

enable_sqlite_wal(engine: AsyncEngine) -> None

Put every connection of a SQLite engine in WAL mode.

In the default rollback journal a reader and a writer exclude each other, so the moment an application grows a worker — web process and taskiq worker on one app.db — the second one fails. Measured across two processes, one holding a read transaction open while the other inserts:

================== ========================================== journal_mode Result for the writer ================== ========================================== delete waits the whole busy_timeout, then sqlite3.OperationalError: database is locked wal commits immediately ================== ==========================================

WAL is a property of the database file, not of the connection: setting it once is enough, it survives the process, and every later connection from any process opens the file already in WAL. Emitting the pragma per connection is therefore idempotent, and it is done per connection only so the very first connection of a brand-new file switches it too. On an in-memory database the pragma is a no-op — SQLite answers memory and keeps its own journal, without error.

Parameters:

Name Type Description Default
engine AsyncEngine

The SQLite engine to configure. Emitting this pragma against another backend would fail, so callers building their own engine must gate on the backend.

required
Notes

WAL admits one writer at a time; the others queue (see sqlite_busy_timeout). What no amount of waiting fixes is a transaction that reads first and writes later — promoting the lock fails at once when another connection wrote in between, and busy_timeout does not apply because there is nothing to wait for. Claim the row, do the long work with no session open, then persist.

is_memory_sqlite_url

is_memory_sqlite_url(db_url: str) -> bool

Whether a URL points at an in-memory SQLite database.

Parameters:

Name Type Description Default
db_url str

The connection URL.

required

Returns:

Name Type Description
bool bool

True for sqlite+aiosqlite:///:memory: and for the

bool

mode=memory URI form, False for a file or another backend.

shared_memory_url

shared_memory_url(name: str) -> str

Build a shared-cache in-memory SQLite URL.

Parameters:

Name Type Description Default
name str

Database name, unique per manager so two managers do not end up talking to the same in-memory database.

required

Returns:

Name Type Description
str str

A URL every connection of one engine resolves to the same

str

in-memory database, instead of the private one each connection

str

gets with plain :memory:.

transaction async

transaction(session: AsyncSession) -> AsyncGenerator[AsyncSession, None]

Group every write on session into a single commit.

While the block is open, repository writes flush instead of committing, so nothing is durable until the outermost block exits cleanly. An exception rolls the whole block back and propagates.

Nesting is re-entrant — an inner block joins the outer one and does not commit on its own exit. The depth is restored before the commit or rollback runs, so the repository is already back to its normal mode by the time that statement is issued.

Parameters:

Name Type Description Default
session AsyncSession

The session to bind the block to. Every repository sharing this session joins the same block.

required

Yields:

Name Type Description
AsyncSession AsyncGenerator[AsyncSession, None]

The same session, so ``async with transaction(s) as

session AsyncGenerator[AsyncSession, None]

`` reads naturally at the call site.

Raises:

Type Description
BaseException

Re-raises whatever the body raised, after rolling back at the outermost level.

Notes

Catching an exception inside the block and continuing leaves the session in a failed state — SQLAlchemy requires a rollback after a failed flush. Wrap the fallible part in :func:savepoint when you intend to recover from it.

savepoint async

savepoint(session: AsyncSession) -> AsyncGenerator[AsyncSession, None]

Run a nested, individually revertible unit of work.

Issues a real SAVEPOINT via session.begin_nested(). A failure inside the block rolls back to the savepoint and leaves the surrounding transaction usable, which is what lets a caller catch a :class:~tempest_fastapi_sdk.exceptions.conflict.ConflictException and carry on:

async with transaction(session):
    await accounts.add(account)
    try:
        async with savepoint(session):
            await nicknames.add(nickname)
    except ConflictException:
        pass  # the account survives, the nickname is rolled back

The block behaves like :func:transaction for repository writes — it bumps the same depth counter, so writes inside it flush rather than commit and the outer block still owns the final commit.

Parameters:

Name Type Description Default
session AsyncSession

The session to open the savepoint on.

required

Yields:

Name Type Description
AsyncSession AsyncGenerator[AsyncSession, None]

The same session.

Raises:

Type Description
BaseException

Re-raises whatever the body raised, after rolling back to the savepoint.

Notes

PostgreSQL supports SAVEPOINT unconditionally. SQLite needs :func:~tempest_fastapi_sdk.db.connection.enable_sqlite_savepoints, which :class:~tempest_fastapi_sdk.db.connection.AsyncDatabaseManager applies to every SQLite engine it builds — without it the driver's implicit transaction handling turns the closing RELEASE SAVEPOINT into a commit, so a nested block that exits cleanly becomes durable even when the outer block is later rolled back. A session built from a hand-rolled SQLite engine must call that function itself.

in_transaction

in_transaction(session: AsyncSession) -> bool

Report whether a :func:transaction block is open on session.

Repositories call this to decide between flush and commit: inside a block a write must stay uncommitted so the block owns the single commit at the end.

Parameters:

Name Type Description Default
session AsyncSession

The session to inspect.

required

Returns:

Name Type Description
bool bool

True when at least one block is open.

transaction_depth

transaction_depth(session: AsyncSession) -> int

Return how many :func:transaction blocks are open on session.

Parameters:

Name Type Description Default
session AsyncSession

The session to inspect.

required

Returns:

Name Type Description
int int

0 when no block is open, otherwise the nesting depth.

TextSearchLanguageEnum

Bases: BaseStrEnum

PostgreSQL text-search configuration used for stemming.

The configuration decides which stemmer and stop-word list apply, so it is what makes comprou match comprar in Portuguese and buying match buy in English. :attr:SIMPLE disables both — it lowercases and splits on non-word characters, nothing more, which is the right choice for identifiers, SKUs and tags.

Members cover the Snowball configurations shipped by every supported PostgreSQL release. A database with a custom configuration created through CREATE TEXT SEARCH CONFIGURATION is out of scope; the value reaches PostgreSQL as a regconfig, which rejects an unknown name with a clear error rather than silently matching nothing.

Ignored entirely on backends without full-text support, where the query degrades to the ILIKE layer.

TextSearchWeightEnum

Bases: BaseStrEnum

Relative importance of a column in the relevance score.

PostgreSQL ranks A highest and D lowest, so a term found in a title outranks the same term buried in a body. Only meaningful for :func:full_text_condition and :func:full_text_rank; the ILIKE layer has no score to weight.

TokenMatchEnum

Bases: BaseStrEnum

How the words of a search term combine.

Attributes:

Name Type Description
ALL

Every token must appear somewhere in the searched columns. Typing more words narrows the result — what a user expects from a search box, and the default.

ANY

One token is enough. Typing more words widens the result; useful for "related to any of these" lookups.

like_search_condition

like_search_condition(
    model: type[Any],
    term: str,
    fields: Sequence[ColumnRef],
    *,
    token_match: TokenMatchEnum = ALL,
    searchable: Collection[str] | None = None,
) -> ColumnElement[bool] | None

Build a portable substring-search condition.

Each token is matched case-insensitively against every listed column (OR across columns), and the tokens combine per token_match. Wildcards in the user's input are escaped, so a term containing % or _ searches for those characters literally instead of silently matching everything.

Parameters:

Name Type Description Default
model type[Any]

The model being searched.

required
term str

The raw search term.

required
fields Sequence[ColumnRef]

Columns to search, by name or as mapped attributes. Must not be empty.

required
token_match TokenMatchEnum

Whether every token must match or any single one is enough.

ALL
searchable Collection[str] | None

The columns fields may name (see :func:resolve_search_column). None accepts any mapped column that is not secret.

None

Returns:

Type Description
ColumnElement[bool] | None

ColumnElement[bool] | None: The condition, or None when the

ColumnElement[bool] | None

term holds no tokens — the caller then applies no filter, so a

ColumnElement[bool] | None

blank search box returns the unfiltered list rather than nothing.

Raises:

Type Description
ValidationException

When fields is empty or names a column that :func:resolve_search_column refuses.

full_text_condition

full_text_condition(
    model: type[Any],
    term: str,
    fields: Sequence[ColumnRef],
    *,
    language: TextSearchLanguageEnum = PORTUGUESE,
    weights: Mapping[str, TextSearchWeightEnum] | None = None,
    dialect: str = POSTGRESQL_DIALECT,
    token_match: TokenMatchEnum = ALL,
    searchable: Collection[str] | None = None,
) -> ColumnElement[bool] | None

Build a full-text match condition, or the portable fallback.

On PostgreSQL this compiles to to_tsvector(...) @@ websearch_to_tsquery(language, term). websearch_to_tsquery is what makes the term safe to take straight from a user: it accepts the search-engine syntax people already type — "exact phrase", -excluded, or — and never raises a syntax error on stray punctuation, unlike to_tsquery.

On any other dialect it delegates to :func:like_search_condition, so the same call site works against the SQLite test database.

Parameters:

Name Type Description Default
model type[Any]

The model being searched.

required
term str

The raw search term.

required
fields Sequence[ColumnRef]

Columns to search.

required
language TextSearchLanguageEnum

Stemming configuration.

PORTUGUESE
weights Mapping[str, TextSearchWeightEnum] | None

Per-column weight, keyed by column name. Columns left out default to D. Only affects :func:full_text_rank; supplying it changes how the vector is built, so the same mapping must be passed to both calls for the score to line up.

None
dialect str

The active SQLAlchemy dialect name. Compared against :data:POSTGRESQL_DIALECT.

POSTGRESQL_DIALECT
token_match TokenMatchEnum

Used only by the fallback path; PostgreSQL's websearch_to_tsquery already treats space-separated words as AND.

ALL
searchable Collection[str] | None

The columns fields may name (see :func:resolve_search_column).

None

Returns:

Type Description
ColumnElement[bool] | None

ColumnElement[bool] | None: The condition, or None for a

ColumnElement[bool] | None

blank term.

Raises:

Type Description
ValidationException

When fields is empty or names a column that :func:resolve_search_column refuses.

full_text_rank

full_text_rank(
    model: type[Any],
    term: str,
    fields: Sequence[ColumnRef],
    *,
    language: TextSearchLanguageEnum = PORTUGUESE,
    weights: Mapping[str, TextSearchWeightEnum] | None = None,
    dialect: str = POSTGRESQL_DIALECT,
    searchable: Collection[str] | None = None,
) -> ColumnElement[Any] | None

Build the relevance-score expression to order results by.

Parameters:

Name Type Description Default
model type[Any]

The model being searched.

required
term str

The raw search term.

required
fields Sequence[ColumnRef]

Columns to search.

required
language TextSearchLanguageEnum

Stemming configuration.

PORTUGUESE
weights Mapping[str, TextSearchWeightEnum] | None

Per-column weight; must match what was passed to :func:full_text_condition.

None
dialect str

The active SQLAlchemy dialect name.

POSTGRESQL_DIALECT
searchable Collection[str] | None

The columns fields may name (see :func:resolve_search_column).

None

Returns:

Type Description
ColumnElement[Any] | None

ColumnElement[Any] | None: The ts_rank expression, or

ColumnElement[Any] | None

None when the backend has no ranking to offer or the term is

ColumnElement[Any] | None

blank. A None return is the signal to leave the caller's own

ColumnElement[Any] | None

ordering in place rather than to order by nothing.

Raises:

Type Description
ValidationException

When fields is empty or names a column that :func:resolve_search_column refuses.

supports_full_text

supports_full_text(dialect: str) -> bool

Report whether dialect has a real full-text engine here.

Lets a caller tell a ranked result from an unranked one — a UI that shows a relevance bar needs to know it will be empty against SQLite.

Parameters:

Name Type Description Default
dialect str

The SQLAlchemy dialect name.

required

Returns:

Name Type Description
bool bool

True only for PostgreSQL.

TempestEnum

TempestEnum(*enums: Any, **kwargs: Any)

Bases: Enum

A SQLAlchemy Enum configured to be safe on PostgreSQL and SQLite.

Differs from sqlalchemy.Enum in exactly the three defaults described in the module docstring: the column stores member values, a CHECK constraint is emitted on backends without a native enum type, and the generated PostgreSQL type name carries a suffix.

Every default can still be overridden per column — passing name="legacy_status" keeps an existing type, and create_constraint=False opts a column out of the SQLite check (useful only when migrating a table that already holds invalid data you have not cleaned yet).

The resulting DDL:

-- PostgreSQL
CREATE TYPE order_status_enum AS ENUM ('open', 'in_progress');
status order_status_enum NOT NULL

-- SQLite
status VARCHAR(11) NOT NULL
CONSTRAINT ck_order_status CHECK (status IN ('open', 'in_progress'))

The CHECK name follows :data:~tempest_fastapi_sdk.db.model.NAMING_CONVENTION, so it is stable across machines and Alembic can address it by name.

Notes

That name is derived from the enum type, not the column, so two columns of the same enum in one table would produce two CHECK constraints sharing a name. SQLite accepts that in CREATE TABLE, but Alembic's batch mode keys constraints by name and keeps only one, so the other column silently accepted any value after the next rebuild (#526). The second and later columns of one enum in a table therefore get ck_<table>_<enum>_<column>; the first keeps ck_<table>_<enum>, as does every table with one column per enum, so no constraint already applied changes name. NAMING_CONVENTION itself is untouched.

The same holds for a migration written by alembic revision --autogenerate through the SDK's env.py: :func:~tempest_fastapi_sdk.db.enum_migrations.render_enum_types omits the CHECK the type attaches, and the sa.Enum(..., create_constraint=True) rendered on the column recreates it where it belongs. Without that, SQLAlchemy 2.1 with Alembic 1.20.0 rendered two explicit CheckConstraint per enum column, both named ck_<table>_<enum> by the convention, and PostgreSQL refused the second one.

Configure the enum type before handing off to SQLAlchemy.

Only fills in defaults the caller left out, so an explicit keyword always wins.

Parameters:

Name Type Description Default
*enums Any

Either a single enum.Enum subclass or a sequence of string values, exactly as sqlalchemy.Enum accepts.

()
**kwargs Any

Forwarded to sqlalchemy.Enum. name, native_enum, create_constraint and values_callable are defaulted when absent.

{}

enum_column

enum_column(enum_class: type[Enum], **kwargs: Any) -> Mapped[Any]

Declare a column backed by :class:TempestEnum.

Equivalent to what Mapped[MyEnum] produces on a :class:~tempest_fastapi_sdk.db.model.BaseModel, spelled out. Reach for it when the column needs arguments the bare annotation cannot carry — a default, a server default, an index, a custom type name:

status: Mapped[OrderStatus] = enum_column(
    OrderStatus, default=OrderStatus.OPEN, index=True
)

Parameters:

Name Type Description Default
enum_class type[Enum]

The enum backing the column.

required
**kwargs Any

Forwarded to mapped_column (default, nullable, index, server_default, …).

{}

Returns:

Type Description
Mapped[Any]

Mapped[Any]: The mapped column declaration.

enum_values

enum_values(enum_class: type[Enum]) -> list[str]

Return the member values of enum_class, in declaration order.

Used as SQLAlchemy's values_callable, which is what makes the column store "in_progress" rather than "IN_PROGRESS". Declaration order is preserved because it becomes the order of the PostgreSQL type's labels, and PostgreSQL sorts an ENUM column by that order — so ORDER BY status follows the workflow the enum describes instead of the alphabet.

Parameters:

Name Type Description Default
enum_class type[Enum]

The enum to read.

required

Returns:

Type Description
list[str]

list[str]: Each member's value, coerced to str.

enum_type_name

enum_type_name(enum_class: type[Enum]) -> str

Return the deterministic database type name for enum_class.

Deterministic because the name has to match across three places that never see each other: the model's DDL, the migration that creates the type, and the migration that later replaces it. OrderStatus becomes order_status_enum, and so does OrderStatusEnum: one trailing :data:ENUM_CLASS_SUFFIX is dropped before the suffix is appended, so the class suffix and the type suffix never stack into order_status_enum_enum. A class called exactly Enum keeps its name.

Notes

Until the suffix was dropped, a class ending in Enum produced the doubled name. A database created then still holds it, and PostgreSQL refuses every statement that casts to the new name (type "order_status_enum" does not exist) until the type is renamed. :func:~tempest_fastapi_sdk.db.enum_migrations.sync_enum_types detects the rename on autogenerate and emits :class:~tempest_fastapi_sdk.db.enum_migrations.RenameEnumTypeOp; a column that has to keep the old name passes it explicitly, mapped_column(TempestEnum(OrderStatusEnum, name="order_status_enum_enum")).

Parameters:

Name Type Description Default
enum_class type[Enum]

The enum to name.

required

Returns:

Name Type Description
str str

The snake-cased class name, without one trailing

str

data:ENUM_CLASS_SUFFIX, plus :data:ENUM_TYPE_SUFFIX.

ReplaceEnumOp

ReplaceEnumOp(
    name: str,
    *,
    new_values: Sequence[str],
    old_values: Sequence[str],
    columns: Sequence[EnumColumnRef],
    value_map: dict[str, str] | None = None,
)

Bases: MigrateOperation

Replace an enum type's members, on PostgreSQL or SQLite.

Handles additions, removals and reordering in one operation, because the PostgreSQL primitive that would handle additions alone (ALTER TYPE ... ADD VALUE) cannot run inside Alembic's transaction on older servers and cannot express the other two at all.

Reversible: :meth:reverse swaps the value lists, so downgrade is generated for free. A downgrade that would drop a member still held by a row fails loudly on the cast rather than corrupting data.

Attributes:

Name Type Description
name str

The enum type name.

new_values tuple[str, ...]

Members after the change.

old_values tuple[str, ...]

Members before it.

columns tuple[EnumColumnRef, ...]

Columns to migrate.

value_map dict[str, str]

Old-value to new-value renames applied while casting, so a renamed member keeps its rows.

Record what the operation should do.

Parameters:

Name Type Description Default
name str

The enum type name.

required
new_values Sequence[str]

Members after the change.

required
old_values Sequence[str]

Members before it, needed so the operation can reverse itself.

required
columns Sequence[EnumColumnRef]

Columns typed by the enum.

required
value_map dict[str, str] | None

Renames to apply to existing rows while casting.

None

replace_enum classmethod

replace_enum(
    operations: Operations,
    name: str,
    *,
    new_values: Sequence[str],
    old_values: Sequence[str],
    columns: Sequence[EnumColumnRef],
    value_map: dict[str, str] | None = None,
) -> None

Entry point registered as op.replace_enum(...).

Parameters:

Name Type Description Default
operations Operations

Alembic's operations proxy.

required
name str

The enum type name.

required
new_values Sequence[str]

Members after the change.

required
old_values Sequence[str]

Members before it.

required
columns Sequence[EnumColumnRef]

Columns typed by the enum.

required
value_map dict[str, str] | None

Renames applied to rows.

None

reverse

reverse() -> ReplaceEnumOp

Return the operation that undoes this one.

Returns:

Name Type Description
ReplaceEnumOp ReplaceEnumOp

The same replacement with the value lists and

ReplaceEnumOp

the rename map inverted.

to_diff_tuple

to_diff_tuple() -> tuple[Any, ...]

Describe the change so alembic check can report it.

Alembic's check command flattens the autogenerated operations with UpgradeOps.as_diffs, which calls this on every operation. The base :class:~alembic.operations.MigrateOperation raises NotImplementedError, so an enum whose members changed — the exact case :func:sync_enum_types exists to catch — crashed alembic check instead of reporting the pending change.

Returns:

Type Description
Any

tuple[Any, ...]: ("replace_enum", <name>, <new members>),

...

the shape Alembic expects from a diff.

RenameEnumTypeOp

RenameEnumTypeOp(
    old_name: str,
    new_name: str,
    *,
    columns: Sequence[EnumColumnRef] = (),
    schema: str | None = None,
)

Bases: MigrateOperation

Rename an enum type, keeping its members and every column's data.

alembic revision --autogenerate never notices a renamed type: on PostgreSQL the columns keep pointing at the old pg_type row and the model points at a name that does not exist, so every statement that casts to it fails with type "<new>" does not exist. :func:sync_enum_types detects the rename and emits this operation; it is also callable by hand as op.rename_enum_type("candidate_slug_enum_enum", "candidate_slug_enum", columns=[...]).

  • PostgreSQL: ALTER TYPE <old> RENAME TO <new>. The columns follow the type, so columns is not needed there.
  • SQLite: there is no type; the name lives in each column's CHECK (ck_<table>_<old>). Every listed column's table is rebuilt with the check renamed, so the name matches what the model declares and alembic check stops reporting it.

Reversible: :meth:reverse swaps the two names.

Attributes:

Name Type Description
old_name str

The type name the database holds today.

new_name str

The type name the model declares.

columns tuple[EnumColumnRef, ...]

Columns typed by the enum, read on SQLite only.

schema str | None

The PostgreSQL schema holding the type, or None for the connection's search path.

Record which type to rename.

Parameters:

Name Type Description Default
old_name str

The type name the database holds today.

required
new_name str

The type name the model declares.

required
columns Sequence[EnumColumnRef]

Columns typed by the enum.

()
schema str | None

The PostgreSQL schema holding the type.

None

rename_enum_type classmethod

rename_enum_type(
    operations: Operations,
    old_name: str,
    new_name: str,
    *,
    columns: Sequence[EnumColumnRef] = (),
    schema: str | None = None,
) -> None

Entry point registered as op.rename_enum_type(...).

Parameters:

Name Type Description Default
operations Operations

Alembic's operations proxy.

required
old_name str

The type name the database holds today.

required
new_name str

The type name the model declares.

required
columns Sequence[EnumColumnRef]

Columns typed by the enum.

()
schema str | None

The PostgreSQL schema holding the type.

None

reverse

reverse() -> RenameEnumTypeOp

Return the operation that undoes this one.

Returns:

Name Type Description
RenameEnumTypeOp RenameEnumTypeOp

The same rename with the names swapped.

to_diff_tuple

to_diff_tuple() -> tuple[Any, ...]

Describe the change so alembic check can report it.

Returns:

Type Description
tuple[Any, ...]

tuple[Any, ...]: ("rename_enum_type", <old>, <new>).

EnumColumnRef dataclass

EnumColumnRef(table: str, column: str)

A column that uses an enum type.

A named pair rather than a bare tuple so a migration file reads EnumColumnRef(table="order", column="status") and a swapped argument is a type error instead of a silent mis-migration.

Attributes:

Name Type Description
table str

The table holding the column.

column str

The column name.

EnumTypeState dataclass

EnumTypeState(name: str, values: tuple[str, ...], columns: tuple[EnumColumnRef, ...])

The members of one enum type, and where they are used.

Attributes:

Name Type Description
name str

The database type name (PostgreSQL) or the enum name carried by the CHECK constraint (SQLite).

values tuple[str, ...]

The members, in order.

columns tuple[EnumColumnRef, ...]

Columns typed by it.

render_enum_types

render_enum_types(
    type_: str, obj: object, autogen_context: AutogenContext
) -> str | Literal[False]

Render an SDK column type as a self-contained SQLAlchemy type.

Alembic's default renders a type it does not know as a dotted path into this package — tempest_fastapi_sdk.db.… — which the generated migration never imports, so the file raises NameError (or F821 under lint) the first time it runs. Two SDK types hit that path:

  • :class:TempestEnum renders as sa.Enum with the members spelled out, which avoids the import and freezes the members as they were when the migration was written — what a migration is supposed to record.
  • :class:~tempest_fastapi_sdk.UtcDateTime renders as sa.TIMESTAMP(timezone=True) and :class:~tempest_fastapi_sdk.NaiveUtcDateTime renders as sa.TIMESTAMP(timezone=False), the exact DDL they emit. The Python-side normalization they add is a runtime behaviour of the model, not of the schema, so a migration has no reason to carry it.

It also omits the CHECK constraint that an Enum (or a Boolean) column carries because of its type — the one SQLAlchemy marks _type_bound. The sa.Enum(..., create_constraint=True) rendered on the column already recreates that CHECK where the backend needs it (SQLite), and PostgreSQL uses the native type. Alembic means to skip it on its own, but recognizes it only through constraint._create_rule.target, which SQLAlchemy 2.1 no longer sets; there the migration came out with two explicit CheckConstraint per enum column, and PostgreSQL refused the second (check constraint "ck_<table>_<enum>" already exists). A CheckConstraint declared in __table_args__ is not type bound and keeps rendering.

Wire it into env.py as render_item=render_enum_types.

Parameters:

Name Type Description Default
type_ str

What Alembic is rendering ("type", "check", "column", …).

required
obj object

The object to render.

required
autogen_context AutogenContext

Alembic's rendering context.

required

Returns:

Type Description
str | Literal[False]

str | Literal[False]: The rendered expression; None (typed as

str | Literal[False]

Literal[False], see _OMIT_FROM_MIGRATION) to omit the

str | Literal[False]

object from the migration; or False to let Alembic render it

str | Literal[False]

its own way. The annotation is Alembic's RenderItemFn, so the

str | Literal[False]

function is assignable to render_item= under a type checker.

sync_enum_types

sync_enum_types(
    context: MigrationContext,
    revision: str | Iterable[str | None],
    directives: list[MigrationScript],
) -> None

Append :class:ReplaceEnumOp for every enum whose members changed.

An alembic revision --autogenerate hook. Reads the enum members the database currently enforces, compares them with the metadata, and emits a replacement for each difference — the gap that makes adding a member to a Python enum a silent no-op today.

Detection is best-effort by design: an enum the backend cannot report on is skipped rather than diffed against a guess, because emitting a wrong replace_enum would drop values from live rows. PostgreSQL is read from pg_enum; SQLite from the generated CHECK constraint, and only when it still has the generated shape.

A renamed type is detected too, and emitted as :class:RenameEnumTypeOp ahead of any replacement — the case :func:~tempest_fastapi_sdk.db.enums.enum_type_name creates for a class ending in Enum, whose type used to be <name>_enum_enum. On PostgreSQL the declared type is missing and every column it types is still typed by one other existing enum that the metadata no longer declares; on SQLite the column's enum CHECK carries a name that differs from the declared one only where the enum name sits.

Parameters:

Name Type Description Default
context MigrationContext

Alembic's MigrationContext.

required
revision str | Iterable[str | None]

The revision being generated.

required
directives list[MigrationScript]

The scripts to amend.

required

CreateEnumCheckOp

CreateEnumCheckOp(
    table_name: str,
    column_name: str,
    values: Sequence[str],
    *,
    name: str,
    schema: str | None = None,
)

Bases: MigrateOperation

Create the CHECK that enforces an enum column on SQLite.

SQLite has no enum type: the members live in a CHECK named by the naming convention. Left to sa.Enum(create_constraint=True) inside batch_alter_table, that check is named after the type, so two columns of one enum produce two checks under one name and the batch, which keys constraints by name, keeps only the last — the other column then accepts any value, with nothing reporting it. This operation names the check explicitly, per column.

It is a no-op on every other backend: PostgreSQL enforces the members through the native type and carries no CHECK.

:func:sqlite_enum_checks emits it after every enum add_column (and after a create_table whose columns share an enum); it is also callable by hand as op.create_enum_check(...) or, inside a batch, batch_op.create_enum_check(...).

Attributes:

Name Type Description
table_name str

The table holding the column.

column_name str

The enum column.

values tuple[str, ...]

The members the check allows.

name str

The constraint name, used as given.

schema str | None

The table's schema.

Record which check to create.

Parameters:

Name Type Description Default
table_name str

The table holding the column.

required
column_name str

The enum column.

required
values Sequence[str]

The members the check allows.

required
name str

The constraint name, used as given (the naming convention is not applied a second time).

required
schema str | None

The table's schema.

None

create_enum_check classmethod

create_enum_check(
    operations: Operations,
    table_name: str,
    column_name: str,
    values: Sequence[str],
    *,
    name: str,
    schema: str | None = None,
) -> None

Entry point registered as op.create_enum_check(...).

Parameters:

Name Type Description Default
operations Operations

Alembic's operations proxy.

required
table_name str

The table holding the column.

required
column_name str

The enum column.

required
values Sequence[str]

The members the check allows.

required
name str

The constraint name.

required
schema str | None

The table's schema.

None

batch_create_enum_check classmethod

batch_create_enum_check(
    operations: BatchOperations, column_name: str, values: Sequence[str], *, name: str
) -> None

Entry point registered as batch_op.create_enum_check(...).

Parameters:

Name Type Description Default
operations BatchOperations

Alembic's batch proxy.

required
column_name str

The enum column.

required
values Sequence[str]

The members the check allows.

required
name str

The constraint name.

required

reverse

reverse() -> DropEnumCheckOp

Return the operation that undoes this one.

Returns:

Name Type Description
DropEnumCheckOp DropEnumCheckOp

The drop of this column's enum check.

to_diff_tuple

to_diff_tuple() -> tuple[Any, ...]

Describe the change so alembic check can report it.

Returns:

Type Description
tuple[Any, ...]

tuple[Any, ...]: ("create_enum_check", <table>, <column>).

DropEnumCheckOp

DropEnumCheckOp(table_name: str, column_name: str, *, schema: str | None = None)

Bases: MigrateOperation

Drop the SQLite CHECK of an enum column, before dropping the column.

SQLite's batch mode copies every reflected CHECK into the rebuilt table and cannot tell which column a check text names, so batch_op.drop_column("age_range") rebuilt the table with CHECK (age_range IN (...)) still attached and failed with no such column: age_range — the downgrade of every enum add_column broke. This operation reads the table's checks, picks the ones in the generated <column> IN (...) shape for this column, and drops them by name, whatever name they carry.

It is a no-op on every other backend. :func:sqlite_enum_checks emits it before every enum drop_column.

Attributes:

Name Type Description
table_name str

The table holding the column.

column_name str

The enum column.

schema str | None

The table's schema.

Record which column's check to drop.

Parameters:

Name Type Description Default
table_name str

The table holding the column.

required
column_name str

The enum column.

required
schema str | None

The table's schema.

None

drop_enum_check classmethod

drop_enum_check(
    operations: Operations,
    table_name: str,
    column_name: str,
    *,
    schema: str | None = None,
) -> None

Entry point registered as op.drop_enum_check(...).

Parameters:

Name Type Description Default
operations Operations

Alembic's operations proxy.

required
table_name str

The table holding the column.

required
column_name str

The enum column.

required
schema str | None

The table's schema.

None

batch_drop_enum_check classmethod

batch_drop_enum_check(operations: BatchOperations, column_name: str) -> None

Entry point registered as batch_op.drop_enum_check(...).

Parameters:

Name Type Description Default
operations BatchOperations

Alembic's batch proxy.

required
column_name str

The enum column.

required

to_diff_tuple

to_diff_tuple() -> tuple[Any, ...]

Describe the change so alembic check can report it.

Returns:

Type Description
tuple[Any, ...]

tuple[Any, ...]: ("drop_enum_check", <table>, <column>).

sqlite_enum_checks

sqlite_enum_checks(
    context: MigrationContext,
    revision: str | Iterable[str | None],
    directives: list[MigrationScript],
) -> None

Give every enum column its own SQLite CHECK, and drop it with the column.

An alembic revision --autogenerate hook, for the two places where the CHECK an sa.Enum(create_constraint=True) carries goes wrong under the batch mode the SDK's env.py turns on:

  • Adding a column. The check is named after the enum type, so two columns of one enum get two checks under one name, and the batch keeps one. Every enum add_column is rewritten to create_constraint=False and followed by :class:CreateEnumCheckOp, named as the model's metadata names that column's check — ck_<table>_<enum>, or ck_<table>_<enum>_<column> for the second and later columns of one enum in a table (:class:~tempest_fastapi_sdk.db.enums.TempestEnum). A create_table whose columns share an enum gets the same treatment for those later columns.
  • Dropping a column. The batch copies the reflected check that names the column into the rebuilt table, which then fails with no such column. Every enum drop_column is preceded by :class:DropEnumCheckOp.

Both operations are no-ops outside SQLite, so the same migration runs on PostgreSQL with no CHECK at all. Both the upgrade and the downgrade are rewritten. Compose it with the other hooks through :func:~tempest_fastapi_sdk.db.alembic_hooks.compose_hooks.

Parameters:

Name Type Description Default
context MigrationContext

Alembic's MigrationContext.

required
revision str | Iterable[str | None]

The revision being generated.

required
directives list[MigrationScript]

The scripts to amend.

required

CreateEnumTypeOp

CreateEnumTypeOp(name: str, values: Sequence[str], *, schema: str | None = None)

Bases: MigrateOperation

Create a PostgreSQL ENUM type, and do nothing on other backends.

op.create_table creates the native type of its enum columns; op.add_column does not, so adding an enum column whose type is new to an existing table failed with type "<name>" does not exist. :func:create_enum_types_on_add_column puts this operation ahead of such an add_column; it is also callable by hand as op.create_enum_type("order_status_enum", ["open", "done"]).

Online, the type is created only when it does not exist yet, so a type another table already uses is left alone. In offline (--sql) mode there is no connection to ask, and a plain CREATE TYPE is written. SQLite has no type — the members live in a CHECK — so the operation is a no-op there.

Reversible: :meth:reverse is :class:DropEnumTypeOp.

Attributes:

Name Type Description
name str

The enum type name.

values tuple[str, ...]

The members, in order.

schema str | None

The schema holding the type, or None for the connection's search path.

Record which type to create.

Parameters:

Name Type Description Default
name str

The enum type name.

required
values Sequence[str]

The members, in order.

required
schema str | None

The schema holding the type.

None

create_enum_type classmethod

create_enum_type(
    operations: Operations,
    name: str,
    values: Sequence[str],
    *,
    schema: str | None = None,
) -> None

Entry point registered as op.create_enum_type(...).

Parameters:

Name Type Description Default
operations Operations

Alembic's operations proxy.

required
name str

The enum type name.

required
values Sequence[str]

The members, in order.

required
schema str | None

The schema holding the type.

None

reverse

reverse() -> DropEnumTypeOp

Return the operation that undoes this one.

Returns:

Name Type Description
DropEnumTypeOp DropEnumTypeOp

The drop of this type.

to_diff_tuple

to_diff_tuple() -> tuple[Any, ...]

Describe the change so alembic check can report it.

Returns:

Type Description
tuple[Any, ...]

tuple[Any, ...]: ("create_enum_type", <name>, <members>).

create_enum_types_on_add_column

create_enum_types_on_add_column(
    context: MigrationContext,
    revision: str | Iterable[str | None],
    directives: list[MigrationScript],
) -> None

Put :class:CreateEnumTypeOp ahead of an add_column with a new enum.

An alembic revision --autogenerate hook. Only create_table creates the PostgreSQL ENUM its columns use; adding an enum column whose type is new to an existing table rendered just ALTER TABLE ... ADD COLUMN age_source age_source_enum, which failed with type "age_source_enum" does not exist. For each native enum type an add_column uses, the hook inserts op.create_enum_type(name, values) before the operation (before the whole batch block, when there is one) — unless a create_table of the same revision creates it, or a column the revision does not touch already uses it. The upgrade and the downgrade are both handled: a downgrade that re-adds a dropped enum column recreates its type the same way.

The operation checks pg_type before creating, so a type that exists is never recreated, and it is a no-op outside PostgreSQL.

Parameters:

Name Type Description Default
context MigrationContext

Alembic's MigrationContext.

required
revision str | Iterable[str | None]

The revision being generated.

required
directives list[MigrationScript]

The scripts to amend.

required

DropEnumTypeOp

DropEnumTypeOp(name: str, *, schema: str | None = None)

Bases: MigrateOperation

Drop a PostgreSQL ENUM type, and do nothing on other backends.

op.drop_table removes the table but not the native type its create_table created, so a downgrade followed by an upgrade fails with type "<name>" already exists. This operation emits DROP TYPE IF EXISTS, which is safe to run when the type is already gone. SQLite has no type to drop — the enum lives in a CHECK that leaves with its table — so the operation is a no-op there and on every other backend.

:func:drop_enum_types_on_downgrade appends it to autogenerated downgrades; it is also callable by hand as op.drop_enum_type("order_status_enum").

Attributes:

Name Type Description
name str

The enum type name.

schema str | None

The schema holding the type, or None for the connection's search path.

Record which type to drop.

Parameters:

Name Type Description Default
name str

The enum type name.

required
schema str | None

The schema holding the type.

None

drop_enum_type classmethod

drop_enum_type(operations: Operations, name: str, *, schema: str | None = None) -> None

Entry point registered as op.drop_enum_type(...).

Parameters:

Name Type Description Default
operations Operations

Alembic's operations proxy.

required
name str

The enum type name.

required
schema str | None

The schema holding the type.

None

drop_enum_types_on_downgrade

drop_enum_types_on_downgrade(
    context: MigrationContext,
    revision: str | Iterable[str | None],
    directives: list[MigrationScript],
) -> None

Append :class:DropEnumTypeOp after the tables and columns a downgrade drops.

An alembic revision --autogenerate hook. The downgrade Alembic writes for a new table is only op.drop_table(...), and for a new column only drop_column(...); both leave the PostgreSQL ENUM type behind, so the next upgrade fails with type "<name>" already exists. For every native enum type used by a table or a column this downgrade drops, the hook appends op.drop_enum_type(name) at the end of the downgrade — but only when nothing that survives the downgrade still uses it: every column of the type in the metadata is dropped (with its table or on its own), and no table or column the downgrade recreates declares it. A type shared by two tables is therefore dropped by the revision that removes the last one.

The decision is made from the metadata alone, with no database connection, and the operation itself is a no-op outside PostgreSQL, so the same migration runs on SQLite. Compose it with the other hooks through :func:~tempest_fastapi_sdk.db.alembic_hooks.compose_hooks.

Parameters:

Name Type Description Default
context MigrationContext

Alembic's MigrationContext.

required
revision str | Iterable[str | None]

The revision being generated.

required
directives list[MigrationScript]

The scripts to amend.

required

type_bound_check_include_object

type_bound_check_include_object(
    metadata: MetaData | Sequence[MetaData] | None,
) -> Callable[[object, str | None, str, bool, object], bool]

Build the include_object filter that hides enum CHECK drift.

Alembic's CHECK comparison reads the constraint from the database but drops it from the metadata side: it collects metadata CHECKs through all_table_check_constraints, which skips the ones a column's type attaches (SQLAlchemy marks them _type_bound). On SQLite — where an Enum column is a VARCHAR plus a CHECK — the database therefore always shows one constraint the metadata does not, and alembic check fails on a clean upgrade head proposing remove_constraint for ck_<table>_<enum>.

A reflected CHECK whose name matches a type-bound CHECK declared in metadata on the same table is not drift: the column type recreates it. Returning False skips it; every other object is left to Alembic. The table is part of the key because two tables may carry a check of the same name under a project's own naming convention, and a match on the name alone would hide one table's drift behind the other's.

A reflected enum-shaped CHECK (<column> IN (...)) on a column the metadata types with a check-carrying enum is hidden too, whatever its name. Its name can legitimately differ from the declared one — after :func:~tempest_fastapi_sdk.db.enums.enum_type_name stopped doubling the _enum suffix, or in a table an older SDK rebuilt — and the name-only match then proposed remove_constraint for the check that enforces the column. Renames and member changes are :func:sync_enum_types' job, which reads the same check.

Pass it as include_object in context.configure; :func:~tempest_fastapi_sdk.db.alembic_env.run_alembic_env does.

Parameters:

Name Type Description Default
metadata MetaData | Sequence[MetaData] | None

The autogenerate target metadata, or a sequence of metadatas.

required

Returns:

Type Description
Callable[[object, str | None, str, bool, object], bool]

Callable[[object, str | None, str, bool, object], bool]: The

Callable[[object, str | None, str, bool, object], bool]

include_object callback Alembic expects.

explain_queries async

explain_queries(
    session: AsyncSession, *, analyze: bool = True
) -> AsyncGenerator[ExplainReport, None]

Record every statement the block runs, then explain each one.

Intended for development and for a deliberate profiling run — it doubles the work for each SELECT it analyzes, so it does not belong in a hot request path.

Parameters:

Name Type Description Default
session AsyncSession

The session whose statements to capture. Only this session is observed, so a concurrent request on another session does not pollute the report.

required
analyze bool

Whether SELECT statements may be executed a second time to collect measured timings. False keeps everything to planner estimates, which is the right choice when a statement is expensive enough that running it twice distorts the very thing being investigated.

True

Yields:

Name Type Description
ExplainReport AsyncGenerator[ExplainReport, None]

Empty while the block runs; filled on exit.

Raises:

Type Description
BaseException

Re-raises whatever the body raised. The plans captured before the failure are still in the report, which is what makes the tool usable on the query that is erroring.

Notes

Statements that are not SELECT are explained without ANALYZE on PostgreSQL and are therefore never re-executed; see the module docstring.

ExplainReport dataclass

ExplainReport(plans: list[QueryPlan] = list(), backend: str = '')

Every plan captured inside one :func:explain_queries block.

Populated when the block exits, not while it runs — the statements are recorded during the block and explained afterwards, so the explaining never interferes with what is being measured.

Attributes:

Name Type Description
plans list[QueryPlan]

One entry per captured statement, in execution order.

backend str

The dialect the plans came from.

slowest property

slowest: QueryPlan | None

Return the plan with the highest measured time, if any.

Falls back to the highest planner cost when nothing was measured, so the property still answers "which statement should I look at first?" on a backend that cannot time anything.

Returns:

Type Description
QueryPlan | None

QueryPlan | None: The costliest plan, or None when

QueryPlan | None

nothing was captured or nothing carries a comparable metric.

total_duration_ms property

total_duration_ms: float | None

Return the summed measured time across every analyzed plan.

Returns:

Type Description
float | None

float | None: The total, or None when nothing was timed.

report

report() -> str

Render every plan as one summary line each.

Returns:

Name Type Description
str str

The lines, newline-joined; a placeholder when empty.

QueryPlan dataclass

QueryPlan(
    sql: str,
    detail: ExplainDetailEnum,
    plan_text: str,
    total_cost: float | None = None,
    duration_ms: float | None = None,
    rows: int | None = None,
    raw: Any = None,
)

One statement's plan, as the database described it.

Attributes:

Name Type Description
sql str

The statement as compiled for the backend.

detail ExplainDetailEnum

How much the backend reported.

plan_text str

The plan, rendered for reading.

total_cost float | None

The planner's cost estimate for the whole statement. None when the backend has no cost model.

duration_ms float | None

Measured execution time. None unless the statement was analyzed.

rows int | None

Rows the top node actually produced (measured) or is expected to produce (estimated).

raw Any

The backend's untouched output, for anything the fields above do not carry.

summary

summary() -> str

Render a one-line summary suitable for a log or a console.

Returns:

Name Type Description
str str

The available metrics followed by the truncated SQL.

ExplainDetailEnum

Bases: BaseStrEnum

How much a backend was able to report.

Attributes:

Name Type Description
MEASURED

Costs and measured execution time — the statement was run under ANALYZE.

ESTIMATED

Planner costs only; the statement was not executed. This is what a write gets, deliberately.

PLAN_ONLY

Step descriptions with neither cost nor timing, which is everything SQLite offers.

BaseDeviceTokenModel

Bases: BaseModel

Abstract push device owned by one user.

Concrete subclasses pick the __tablename__ (device_tokens by convention) and add the FK to the project's UserModel. token is unique, so a device that re-registers updates its row instead of creating a duplicate — the token is the device identity, exactly as the endpoint is for Web Push.

Attributes:

Name Type Description
user_id UUID

FK to the owning user (target set by the subclass).

token str

Push endpoint URL (web) or FCM registration token (mobile). Unique + indexed.

platform str

"web", "ios" or "android" — the value of a :class:~tempest_fastapi_sdk.push.PushPlatformEnum.

p256dh str | None

Browser ECDH public key. Web rows only.

auth str | None

Browser auth secret. Web rows only.

expiration_time int | None

Browser expirationTime in milliseconds since epoch, when the subscription reported one.

app_version str | None

Optional client build identifier.

last_seen_at datetime | None

When the device last registered. Re-registration refreshes it, so a "devices" screen can show what is still in use and an operator can spot dormant rows.

make_device_token_model

make_device_token_model(
    *,
    user_table: str,
    tablename: str = "device_tokens",
    class_name: str = "DeviceTokenModel",
) -> type[BaseDeviceTokenModel]

Build a concrete DeviceTokenModel subclass at runtime.

Used by tests and small scripts. Production projects ship a hand-written src/db/models/device_token.py instead, so the FK column is editable and the class is importable for refactors.

Parameters:

Name Type Description Default
user_table str

Table name of the concrete UserModel the FK should reference (usually "users").

required
tablename str

__tablename__ for the generated class.

'device_tokens'
class_name str

Python class name; affects repr and Alembic identifiers.

'DeviceTokenModel'

Returns:

Type Description
type[BaseDeviceTokenModel]

type[BaseDeviceTokenModel]: A concrete mapped class.

reorder_base_columns_first

reorder_base_columns_first(
    context: MigrationContext,
    revision: str | Iterable[str | None],
    directives: list[MigrationScript],
) -> None

Reorder columns inside every autogenerated CreateTableOp.

SQLAlchemy stores columns in declaration order, which already matches what BaseModel defines (id → updated_at). Autogenerate normally honors that, but third-party mixins or class composition can flip the order in ways that leak into the migration. This hook normalizes it:

  • The four BaseModel columns (id, is_active, created_at, updated_at) come first, in that exact order.
  • Constraints stay where Alembic placed them (typically right after the columns they reference).
  • Every other column keeps its original relative position.

Parameters:

Name Type Description Default
context MigrationContext

The active Alembic context.

required
revision str | Iterable[str | None]

The new revision identifier — unused.

required
directives list[MigrationScript]

The list of MigrationScript directives Alembic will render. Modified in-place.

required
Notes

Nested directives (ModifyTableOps and friends) are recursed into, so the reorder applies inside a batch operation too.

backfill_non_nullable_defaults

backfill_non_nullable_defaults(
    context: MigrationContext,
    revision: str | Iterable[str | None],
    directives: list[MigrationScript],
) -> None

Give every added NOT NULL column a backfilling server_default.

Adding a NOT NULL column to a table that already has rows explodes on PostgreSQL with NotNullViolationError: column "x" contains null values — because a Python-side default= only fires on ORM inserts, never as DDL. Autogenerate therefore emits op.add_column(sa.Column("x", ..., nullable=False)) with no server_default, and the database has no value to backfill the existing rows with.

This hook closes that gap: for every autogenerated AddColumnOp whose column is nullable=False, carries no server_default already, and does declare a scalar Python default= (the value you intended new rows to get), it copies that default into a server_default so the generated migration backfills existing rows in the same statement. The column keeps the value as its DB default afterwards — harmless and matching the model's intent.

What it deliberately does not touch:

  • CreateTableOp columns — a brand-new table has no rows, so a bare NOT NULL is already safe.
  • Columns with a callable / SQL-expression default (uuid4, func.now()) or no default at all — those cannot be backfilled deterministically and need a hand-written data migration.
  • Columns that already carry a server_default.

Compose it after :func:reorder_base_columns_first::

process_revision_directives=compose_hooks(
    reorder_base_columns_first,
    backfill_non_nullable_defaults,
)

Parameters:

Name Type Description Default
context MigrationContext

The active Alembic context — unused.

required
revision str | Iterable[str | None]

The new revision identifier — unused.

required
directives list[MigrationScript]

The MigrationScript directives Alembic will render. Mutated in-place.

required

compose_hooks

compose_hooks(*hooks: ProcessRevisionDirectives) -> ProcessRevisionDirectives

Chain multiple process_revision_directives hooks.

Hooks run in the order they're passed and share the same directives list — each can mutate it before the next sees it.

Parameters:

Name Type Description Default
*hooks ProcessRevisionDirectives

Callables matching the Alembic signature.

()

Returns:

Name Type Description
ProcessRevisionDirectives ProcessRevisionDirectives

A single callable Alembic can

ProcessRevisionDirectives

register.

BaseWebPushSubscriptionModel

Bases: BaseModel

Abstract Web Push subscription owned by one user device.

Concrete subclasses pick the __tablename__ (web_push_subscriptions by convention) and add the FK to the project's concrete UserModel. endpoint is unique, so a device that re-subscribes updates its existing row instead of creating a duplicate (see :meth:~tempest_fastapi_sdk.webpush.WebPushSubscriptionService.subscribe).

Attributes:

Name Type Description
user_id UUID

FK to the user this device belongs to (the FK target is set by the subclass).

endpoint str

Push service endpoint URL — the per-device identity. Unique + indexed.

p256dh str

Client ECDH P-256 public key (URL-safe base64).

auth str

Client auth secret (URL-safe base64).

expiration_time int | None

Optional expiration timestamp in milliseconds since epoch (the browser's expirationTime).

user_agent str | None

Optional device/browser label, handy for a "your devices" management screen.

BASE_COLUMN_ORDER module-attribute

BASE_COLUMN_ORDER: tuple[str, ...] = ('id', 'is_active', 'created_at', 'updated_at')

Columns inherited from BaseModel — emitted in this exact order at the top of every op.create_table produced by autogenerate.

BackupToolMissingError

Bases: RuntimeError

Raised when a required CLI tool (pg_dump/pg_restore/psql) is absent.

DatabaseBackup

DatabaseBackup(database_url: str, *, docker_container: str | None = None)

Per-dialect database backup / restore over a single URL.

All methods are synchronous because the underlying tools are sync processes / file copies. Call them from a CLI command or, if needed from async code, via asyncio.to_thread.

Attributes:

Name Type Description
url str

The sync-flavored database URL (async driver stripped).

backend str

The detected backend ("postgresql" / "sqlite").

Initialize from a (possibly async) database URL.

Parameters:

Name Type Description Default
database_url str

The application's DATABASE_URL. The async driver suffix is stripped automatically.

required
docker_container str | None

Run the Postgres tooling inside this container via docker exec instead of on this host. Set it when the database runs as its own container: the image already carries the pg_dump that matches its server, so the application image does not need postgresql-client pinned to a compatible version just for a nightly job. Ignored for SQLite, which is a file copy either way.

None

backup

backup(output: Path | None = None, *, plain: bool | None = None) -> Path

Dump the database to output and return the written path.

Parameters:

Name Type Description Default
output Path | None

Destination file. When None, a timestamped path under backups/ is used. The parent directory is created if missing.

None
plain bool | None

Postgres format override. True forces a plain .sql dump, False forces custom -Fc. When None, the format is inferred from output's extension (.sql → plain, else custom). Ignored for SQLite.

None

Returns:

Name Type Description
Path Path

The path the backup was written to. The file is created

Path

owner-only (:data:BACKUP_FILE_MODE), and a directory this

Path

call creates for it is :data:BACKUP_DIR_MODE.

Raises:

Type Description
UnsupportedBackupBackendError

For an unsupported dialect.

BackupToolMissingError

When pg_dump is not installed.

RuntimeError

When the dump process fails or the SQLite file is missing / in-memory.

Notes

The dialect, the required tooling and the source are validated before the destination directory is created, so a failed backup never leaves an empty backups/ behind for someone to mistake for a successful run.

restore

restore(source: Path, *, clean: bool = True) -> None

Restore the database from source.

clean has no separate meaning for SQLite: the restore overwrites the database file, which is inherently a clean replacement.

Parameters:

Name Type Description Default
source Path

The backup file. For Postgres the format is inferred from the extension (.sql → psql, else pg_restore).

required
clean bool

When True (default), drop existing objects before recreating so the restore is a faithful copy. For Postgres custom this uses pg_restore --clean --if-exists; for plain it drops/recreates the public schema first; for SQLite the target file is overwritten.

True

Raises:

Type Description
FileNotFoundError

When source does not exist.

UnsupportedBackupBackendError

For an unsupported dialect.

BackupToolMissingError

When the required tool is absent.

RuntimeError

When the restore process fails.

UnsupportedBackupBackendError

Bases: RuntimeError

Raised when the database dialect has no backup strategy.

ENUM_CLASS_SUFFIX module-attribute

ENUM_CLASS_SUFFIX: Final[str] = 'Enum'

Class-name suffix :func:enum_type_name drops before naming the type.

A project that names its enums CandidateSlugEnum would otherwise get candidate_slug_enum_enum: the class suffix and :data:ENUM_TYPE_SUFFIX say the same thing twice. Dropping one trailing Enum makes CandidateSlugEnum and CandidateSlug produce the same type name, so adopting or dropping the suffix in a later refactor no longer renames the database type.

ENUM_TYPE_SUFFIX module-attribute

ENUM_TYPE_SUFFIX: Final[str] = '_enum'

Suffix appended to a generated PostgreSQL ENUM type name.

PostgreSQL keeps types and tables in the same namespace, so a type named after the enum class alone (status) collides with a table or column called status. The suffix makes OrderStatus become order_status_enum, which is unambiguous and still readable in \dT output and in a migration diff.

WhereClause module-attribute

WhereClause = Q | ColumnElement[bool]

What a repository's where= accepts.

Either a :class:Q tree, which resolves lazily against the repository's model, or a SQLAlchemy clause that is already bound to its columns. The second form is what lets a condition built elsewhere — a text search, a hand-written and_ — flow into list / paginate / cursor_paginate without being re-expressed as filter keywords.

NAMING_CONVENTION module-attribute

NAMING_CONVENTION: dict[str, str] = {
    "ix": "ix_%(column_0_N_label)s",
    "uq": "uq_%(table_name)s_%(column_0_N_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_N_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

Alembic-friendly naming convention applied to every constraint.

Constraint names become deterministic across machines and DB engines, so alembic revision --autogenerate only emits real schema diffs instead of churn from auto-generated identifiers.

Composite unique constraints, indexes and foreign keys are named after every column, joined with _: UniqueConstraint("title", "release_year") on books is uq_books_title_release_year. The column_0_N_* tokens SQLAlchemy expands render a one-column constraint exactly like the column_0_* tokens did, so a single-column name (uq_books_title, ix_books_title) is the same as before by construction.

Until the composite fix the templates read only the first column (:data:~tempest_fastapi_sdk.db.naming.LEGACY_NAMING_CONVENTION), so UniqueConstraint("title") and UniqueConstraint("title", "release_year") were both uq_books_title: PostgreSQL refuses the second with relation "uq_books_title" already exists while SQLite accepts both. A database created under that convention holds the old names for its composite constraints; :func:~tempest_fastapi_sdk.db.naming.legacy_constraint_renames lists them and writes the RENAME statements.

A name longer than the dialect's identifier limit (63 characters on PostgreSQL) is shortened by SQLAlchemy when it emits the DDL: the first 55 characters, _, and the last four hex digits of the full name's MD5 — the same on every run. SQLite has no limit and keeps the full name. Joining with _ leaves one ambiguity the convention cannot remove: columns ("a_b", "c") and ("a", "b_c") render the same name, and such a pair needs an explicit name=.

ColumnRef module-attribute

ColumnRef = str | InstrumentedAttribute[Any]

A searchable column: its name, or the mapped attribute itself.

BaseUserRefreshTokenModel

Bases: BaseModel

Abstract opaque-refresh-token row used by the bundled auth flow.

Concrete subclasses pick the __tablename__ (user_refresh_tokens by convention) and add the FK to the project's concrete UserModel. The SDK never sees the plaintext after the issuance response — only the hash is persisted.

Attributes:

Name Type Description
user_id UUID

Owner of the token. Concrete subclasses MUST declare this as a ForeignKey so cascading deletes wipe the tokens alongside the user.

token_hash str

SHA-256 hex digest of the plaintext refresh token. Indexed + unique so lookups by hash are fast and duplicates impossible.

family_id UUID

Rotation lineage. Every token minted by rotating an existing one inherits its family_id; a brand-new login starts a fresh family. Reuse detection and logout operate on the whole family at once.

expires_at datetime

UTC timestamp the token becomes invalid. Defaults to JWT_REFRESH_TTL_SECONDS after issuance.

used_at datetime | None

UTC timestamp the token was rotated (consumed by a successful refresh). Non-null means the token is spent — replaying it triggers reuse detection.

revoked_at datetime | None

UTC timestamp the token was explicitly revoked (logout or family-wide reuse kill). Non-null means the token is dead regardless of its expiry.

amr str | None

Space-separated RFC 8176 methods the family was authenticated with ("pwd", "pwd otp", "ext", "hwk"), copied onto every token minted by rotating it, so a refresh never promotes a session to MFA. NULL on a row written before the column existed: the access tokens it mints carry no amr and count as "no second factor".

make_user_refresh_token_model

make_user_refresh_token_model(
    *,
    user_table: str,
    tablename: str = "user_refresh_tokens",
    class_name: str = "UserRefreshTokenModel",
) -> type[BaseUserRefreshTokenModel]

Build a concrete refresh-token model bound to user_table.

Mirrors :func:tempest_fastapi_sdk.make_user_token_model — a one-call helper for projects that do not need to subclass the abstract base manually. Production projects should still ship a hand-written src/db/models/user_refresh_token.py so the FK column is editable and the class is importable for refactors.

Parameters:

Name Type Description Default
user_table str

Name of the project's concrete user table (e.g. "users") — used as the FK target.

required
tablename str

Name of the refresh-token table. Defaults to "user_refresh_tokens".

'user_refresh_tokens'
class_name str

Python class name. Defaults to "UserRefreshTokenModel".

'UserRefreshTokenModel'

Returns:

Type Description
type[BaseUserRefreshTokenModel]

type[BaseUserRefreshTokenModel]: Concrete SQLAlchemy

type[BaseUserRefreshTokenModel]

mapping with the FK + cascade set up correctly.

UserTokenPurposeEnum

Bases: StrEnum

What a token authorizes when redeemed.

Each value maps to a distinct flow exposed by :class:tempest_fastapi_sdk.auth.UserAuthService:

  • ACTIVATION — confirm the email address the user signed up with.
  • PASSWORD_RESET — let the user pick a new password without the old one.
  • EMAIL_VERIFICATION — re-verify the user's current email (resend the confirmation link).
  • EMAIL_CHANGE — confirm a move to a new email address. The pending new address travels in the token row's :attr:BaseUserTokenModel.payload.

BaseVoiceProfileModel

Bases: BaseModel

Abstract enrolled voiceprint belonging to one user.

Concrete subclasses pick the __tablename__ (user_voice_profiles by convention) and add the FK to the project's concrete UserModel.

Attributes:

Name Type Description
user_id UUID

Owner of the voiceprint. Concrete subclasses MUST declare this as a ForeignKey so a cascading delete takes the biometric data with the account.

label str | None

What this recording was — "cadastro no onboarding", "ligação de 12/08". A person may hold several profiles, and knowing which is which is what makes it possible to delete the bad one.

embedding bytes

The voiceprint, float32 little-endian. Stored as bytes rather than an array column so the table works on SQLite and Postgres alike; dimensions says how many values it holds.

dimensions int

Length of the vector. Checked on read — a profile written by a different model must not be silently compared against one from the current model, because the similarity would be a number without meaning.

model_name str

Which embedding model produced it. Swapping models invalidates every profile, and this column is how you find the ones that need re-enrolling.

consent_at datetime

When the person consented to voice biometrics. Required — the service refuses to write a row without it.

consent_reference str

What they consented to: a policy version, a signed document id, a ticket. Free text because what counts as evidence differs per product, but not nullable, because "we have consent" with nothing behind it is not a record.

last_matched_at datetime | None

Last time this profile matched a voice. NULL until it does.

make_voice_profile_model

make_voice_profile_model(
    *,
    user_table: str,
    tablename: str = "user_voice_profiles",
    class_name: str = "UserVoiceProfileModel",
) -> type[BaseVoiceProfileModel]

Build a concrete voice-profile model bound to user_table.

Parameters:

Name Type Description Default
user_table str

Name of the project's concrete user table.

required
tablename str

Name of the profile table.

'user_voice_profiles'
class_name str

Python class name.

'UserVoiceProfileModel'

Returns:

Type Description
type[BaseVoiceProfileModel]

type[BaseVoiceProfileModel]: Concrete SQLAlchemy mapping with the

type[BaseVoiceProfileModel]

FK and cascade set up, so deleting a user deletes their

type[BaseVoiceProfileModel]

biometric data rather than orphaning it.

make_web_push_subscription_model

make_web_push_subscription_model(
    *,
    user_table: str,
    tablename: str = "web_push_subscriptions",
    class_name: str = "WebPushSubscriptionModel",
) -> type[BaseWebPushSubscriptionModel]

Build a concrete WebPushSubscriptionModel subclass at runtime.

Used by tests and lightweight scripts. Production projects should instead ship a hand-written src/db/models/web_push_subscription.py so the FK column is editable and the class is importable for refactors.

Parameters:

Name Type Description Default
user_table str

Table name of the concrete UserModel the FK should reference (usually "users").

required
tablename str

__tablename__ for the generated class.

'web_push_subscriptions'
class_name str

Python class name; affects repr and Alembic identifiers.

'WebPushSubscriptionModel'

Returns:

Type Description
type[BaseWebPushSubscriptionModel]

type[BaseWebPushSubscriptionModel]: A concrete mapped class.