ddsqlmodel
SQLModel helpers: a base model with naming conventions, filter and update contracts, keyset pagination
Installation
Install the library using pip:
pip install ddsqlmodel
Development
The project runs entirely in Docker. Requires Docker and Fabric on the host:
fab build # build the dev image
fab tests # run pytest
fab linters # run ruff (with --fix), ty and complexipy
fab shell # IPython inside the container
fab bash # bash inside the container
This project was generated from dd-lib-stub;
run uvx copier update to pull in template updates.
Compatibility
Python 3.11 to 3.15. What changed in each release, breaking changes included, is in the GitHub releases.
Depends on sqlmodel>=0.0.37,<0.0.51, sqlalchemy[asyncio]>=2.0.14,<2.2, pydantic>=2.11,<3 and
ddutils>=0.4.0,<0.5.0. The SQL it builds is PostgreSQL's: row-value comparison, ILIKE, IS DISTINCT FROM,
FOR UPDATE SKIP LOCKED, JSONB. The driver is the application's choice. The tests run on an in-memory SQLite and
read the statements back as PostgreSQL, no server is needed.
| Package | What is in it |
|---|---|
ddsqlmodel.models |
base (BaseSQLModel, metadata), mixins.dates, types.datetime, types.json |
ddsqlmodel.filters |
lookups, filter_params, update_params are the contracts; filter_set runs them, with conditions, keyset and cursor behind it |
ddsqlmodel.pagination |
query_params and response, the HTTP side of a list |
Models
BaseSQLModel is the base of the table models. It is generic over the entity a row is read into, a pydantic
model: the table is named after the class in snake case (ProfileModel is profile_model), to_entity() and
from_entity() map a row to its entity and back by field name, and every model shares one metadata with a
naming convention for constraints and indexes, so Alembic autogenerate gives every one of them a stable name.
from datetime import datetime
from uuid import UUID
from pydantic import BaseModel
from sqlmodel import Field
from ddsqlmodel.models.base import BaseSQLModel
from ddsqlmodel.models.mixins.dates import DatesMixin
from ddsqlmodel.models.types.datetime import DATETIME_TZ
from ddsqlmodel.models.types.json import JSONB
class Profile(BaseModel):
profile_id: UUID
email: str
settings: dict | None = None
registered_at: datetime
created_at: datetime | None = None
updated_at: datetime | None = None
class ProfileModel(BaseSQLModel[Profile], DatesMixin, table=True):
profile_id: UUID = Field(primary_key=True)
email: str = Field(unique=True)
settings: dict | None = Field(default=None, sa_type=JSONB, nullable=True) # type: ignore[arg-type]
registered_at: datetime = Field(sa_type=DATETIME_TZ) # type: ignore[arg-type]
row = ProfileModel.from_entity(profile) # ProfileModel.model_validate(profile.model_dump(mode='json'))
profile = row.to_entity() # Profile, from the row's fields the entity declares
profile = row.to_entity(state=state) # plus entity fields that are not columns, e.g. a computed expression
- A model with
table=Truemust name its entity,BaseSQLModel[Profile]: without one the class raisesTypeError. - Override
to_entity/from_entitywhen the mapping is not one to one (renamed fields, wrapped value objects). ddsqlmodel.models.base.metadatais theMetaDataof every model: in Alembic'senv.pyit is thetarget_metadata. ItsNAMING_CONVENTION:
| Object | Name | Example |
|---|---|---|
| Primary key | pk__<table> |
pk__profile_model |
| Index | ix__<table>__<columns> |
ix__profile_model__project_id |
| Unique | uq__<table>__<columns> |
uq__profile_model__email |
| Foreign key | fk__<table>__<columns>__<referred table> |
fk__order_model__profile_id__profile_model |
| Check | ck__<table>__<constraint name> |
ck__order_model__positive_amount |
Types and mixins
ddsqlmodel.models.types.datetime.DATETIME_TZisDateTime(timezone=True):TIMESTAMP WITH TIME ZONE, not a naiveTIMESTAMP.ddsqlmodel.models.types.json.JSONBis PostgreSQL'sJSONBwithnone_as_null=True: PythonNoneis stored as SQLNULL, not as the JSON literalnull, whichWHERE column IS NULLdoes not match.ddsqlmodel.models.mixins.dates:CreatedDateMixinaddscreated_at,UpdatedDateMixinaddsupdated_at,DatesMixinboth. The columns areDATETIME_TZ,NOT NULL, defaulted by the server tonow();updated_atis refreshed on update.
Filtering
What can be asked of a model is declared once, as a FilterParams class: the filter fields with their lookups,
the fields a list can be ordered by and searched on. FilterSet runs an instance of it against the database:
a page of rows with keyset cursors, a count, a filtered update. The same contract becomes the query of an HTTP
list endpoint with QueryParams (see Pagination).
FilterParams
The filter fields are declared in a pydantic model; a field states its lookups with the FieldLookups marker, and
a field without one is compared for equality. FilterParams.build expands every lookup into a field of its own:
from typing import Annotated
from uuid import UUID
from pydantic import BaseModel
from ddsqlmodel.filters.filter_params import FilterParams
from ddsqlmodel.filters.lookups import FieldLookups, Lookup, SearchType
class CampaignFilters(BaseModel):
project_id: UUID | None = None
campaign_id: Annotated[UUID | None, FieldLookups(Lookup.IN)] = None
state: Annotated[str | None, FieldLookups(Lookup.EXACT, Lookup.IN)] = None
CampaignFilterParams = FilterParams.build(
'CampaignFilterParams',
filters=CampaignFilters,
ordering_fields=('created_at', 'name'),
default_ordering='-created_at',
search_fields={'name': SearchType.ILIKE, 'campaign_id': SearchType.EXACT},
)
params = CampaignFilterParams(project_id=project_id, state__in=['draft', 'live'], search='welcome', limit=50)
A lookup is the suffix of the generated field, <field>__<lookup>; EXACT is the bare field:
| Lookup | Generated field | SQL |
|---|---|---|
EXACT (no marker) |
kind: Kind | None |
kind = ... |
IEXACT |
email__iexact: str | None |
lower(email) = lower(...) |
NE |
segment_id__ne: UUID | None |
segment_id IS DISTINCT FROM ... |
IN |
state__in: list[State] | None |
state IN (...) |
NOT_IN |
state__not_in: list[State] | None |
state IS NULL OR state NOT IN (...) |
ISNULL |
email__isnull: bool | None |
email IS NULL for True, IS NOT NULL for False |
LT, LTE, GT, GTE |
paid_at__lt: datetime | None, ... |
paid_at < ..., <=, >, >= |
CONTAINS, STARTSWITH, ENDSWITH |
name__contains: str | None, ... |
name LIKE '%...%', '...%', '%...' |
ICONTAINS, ISTARTSWITH, IENDSWITH |
name__icontains: str | None, ... |
the same with ILIKE |
- A marked field gets only the listed lookups: add
Lookup.EXACTto keep the bare field. NEandNOT_INcount a row withNULLas different, as Python does; a plain<>orNOT INwould drop it.- The substring lookups match the value literally:
%and_in it are not wildcards. - A list is accepted only through
INandNOT_IN: a bare field given a list raisesValueError. ordering_fieldsneeds adefault_orderingamong them; a leading-is descending. Anorderingis taken only fromordering_fields, in either direction, or as thedefault_orderingitself: a contract that declares no ordering fields takes no other ordering.- Search is one term matched against every search field, joined with
OR:ILIKEis a case-insensitive substring, matched literally;EXACTcasts the term to the column type (a UUID, an integer) and skips the column when the term cannot be cast or, for an integer, is out of the range of the column. A term no column can take matches nothing.
Every instance also carries the query fields ordering, search, limit, page (from 1) and cursor;
page_size is limit or DEFAULT_LIMIT (20), offset is derived from page, and values are the filled filter
fields only.
An instance is changed in place, and what is assigned is validated like what it was built with: a caller narrows
the contract it was given (params.state__in = ['live']), a loop over the pages moves the cursor
(params.cursor = next_cursor), no copy needed.
FilterSet
from sqlmodel import select
from ddsqlmodel.filters.filter_set import FilterSet
filter_set = FilterSet(
session=session, # sqlmodel's AsyncSession
model=CampaignModel,
base_statement=select(CampaignModel).where(CampaignModel.is_deleted.is_(False)),
params=params,
)
rows, next_cursor, prev_cursor = await filter_set.select()
count = await filter_set.count()
| Parameter | Description |
|---|---|
session |
sqlmodel.ext.asyncio.session.AsyncSession the statements run in |
model |
The model whose columns the filter, ordering and search fields name |
base_statement |
The select (for select and count) or update (for update_by_filters) to extend |
params |
The FilterParams instance |
extra_columns |
Expressions by field name, for fields that are not columns of the model |
select()returns one page and both boundary cursors. The rows are model instances when the statement selects one entity, rows as SQLAlchemy returns them otherwise.count()is the number of rows the base statement, the filters and the search match; the range is ignored.update_by_filters(update_params)is described below.
A field that is not a column of the model, such as a computed state, is resolved through extra_columns:
state = case((CampaignModel.is_deleted.is_(True), literal('archived')), else_=literal('draft'))
filter_set = FilterSet(
session=session,
model=CampaignModel,
base_statement=select(CampaignModel, state.label('state')),
params=params, # CampaignFilterParams(state='archived')
extra_columns={'state': state},
)
rows, _, _ = await filter_set.select()
campaigns = [row.to_entity(state=state) for row, state in rows]
Keyset paging
Nothing extra is declared. The key of a page is always the effective ordering plus the model's primary key as a
unique tiebreaker, both running in the ordering's direction, so the anchor is one row-value comparison,
(created_at, campaign_id) < (..., ...), that an index on the ordering column serves.
- With
params.cursorthe page starts strictly after the row the cursor points at. A cursor isnext_cursororprev_cursorof an earlierselect(); a prev-cursor scans in reverse and the rows come back in display order. - Without a cursor the page is
OFFSET (page - 1) * page_size, for a jump to an arbitrary page. - One extra row is fetched to know whether the list goes on:
next_cursorisNoneon the last page,prev_cursorisNoneon the first. - The cursor is opaque and URL-safe. A malformed one, or one built for another ordering, raises
ValueError, and so does anorderingthe contract does not name. The cursor carries the values of the key of its row, the ordering column and the primary key, encoded but not encrypted: order by columns the client may see. ddsqlmodel.filters.keyset.Keysetis the key itself: it orders and anchors a statement, reads a cursor and writes one.FilterSetbuilds it from the params; it is there for a queryFilterSetdoes not cover.- The model needs a single-column primary key; keys may be datetimes, UUIDs, strings and numbers.
params = CampaignFilterParams(limit=500)
while True:
filter_set = FilterSet(session=session, model=CampaignModel, base_statement=select(CampaignModel), params=params)
rows, next_cursor, _ = await filter_set.select()
...
if next_cursor is None:
break
params.cursor = next_cursor
Filtered update
An UpdateParams subclass declares the columns that may be updated; the caller fills the ones to change, None
fields are skipped, and an update with nothing to set raises ValueError. The rows are chosen by the update
base statement and the filter fields of params.
from sqlmodel import update
from ddsqlmodel.filters.update_params import UpdateParams
class CampaignUpdateParams(UpdateParams):
state: str | None = None
filter_set = FilterSet(
session=session,
model=CampaignModel,
base_statement=update(CampaignModel).where(CampaignModel.project_id == project_id),
params=CampaignFilterParams(state='draft'),
)
updated, cursor = await filter_set.update_by_filters(CampaignUpdateParams(state='archived')) # (rows updated, None)
- A model with
UpdatedDateMixingetsupdated_atset to the current moment, unless the update params carry one. - Without
params.limiteverything matching is updated in one statement, and the cursor returned isNone. - With
params.limitthe update is one batch: thelimitrowsselect()would page first, in the keyset order and strictly afterparams.cursor, locked withFOR UPDATE SKIP LOCKEDand updated in place. The cursor returned is that page'snext_cursor. A mass update loops with it, each batch in a transaction of its own, until a batch updates no rows, so no transaction is held over the whole table. A prev-cursor is refused.
params = CampaignFilterParams(state='draft', limit=10_000)
while True:
async with session_factory() as session: # a transaction per batch
filter_set = FilterSet(
session=session, model=CampaignModel, base_statement=update(CampaignModel), params=params
)
updated, cursor = await filter_set.update_by_filters(CampaignUpdateParams(state='archived'))
if not updated:
break
params.cursor = cursor
Pagination
ddsqlmodel.pagination is the HTTP side of a list: QueryParams is the query of the endpoint built from a
FilterParams, PaginatedResponse its answer. Both are plain pydantic models; the example binds them with FastAPI.
from typing import Annotated
from fastapi import APIRouter, Query
from ddsqlmodel.pagination.query_params import QueryParams
from ddsqlmodel.pagination.response import PaginatedResponse, Pagination
router = APIRouter()
CampaignQueryParams = QueryParams.build('CampaignQueryParams', CampaignFilterParams)
@router.get('/campaigns/')
async def campaign_list(params: Annotated[CampaignQueryParams, Query()]) -> PaginatedResponse[Campaign]:
filter_params = params.filter_params # a CampaignFilterParams
campaigns, next_cursor, prev_cursor = await get_campaigns(filter_params)
count = await count_campaigns(filter_params)
pagination = Pagination.from_params(filter_params, count=count, next_cursor=next_cursor, prev_cursor=prev_cursor)
return PaginatedResponse.factory(items=campaigns, pagination=pagination)
QueryParams.build(name, filter_params) derives the query from the contract:
- The filter fields are read under
filter[...]:?filter[state__in]=draft&filter[state__in]=live. page(from 1, default 1),limit(1 toMAX_LIMIT, 100; default 20) andcursorare always there.orderingis an enum ofordering_fieldsin both directions,nameand-name, defaulting todefault_ordering; it exists only when the contract declares ordering fields.searchexists only when the contract declares search fields.params.filter_paramsis theFilterParamsinstance filled from the query, what the data access works with.
Pagination is one shape for both paging styles: page and limit always, count when the endpoint counts,
next_cursor / prev_cursor when it pages by keyset. A large list skips the COUNT, and a non-null next_cursor
is its "there is more". Pagination.from_params(params, ...) takes page and limit from the contract; limit=
overrides it for an endpoint with a fixed page size.
{"data": [...], "meta": {"pagination": {"page": 1, "limit": 20, "count": 42, "next_cursor": null, "prev_cursor": null}}}
{"data": [...], "meta": {"pagination": {"page": 1, "limit": 50, "count": null, "next_cursor": "n.f6...", "prev_cursor": null}}}
Metadata
Release files for ddsqlmodel 0.0.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ddsqlmodel-0.0.2.tar.gz | 21.5 kB | With provenance | Details for ddsqlmodel-0.0.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ddsqlmodel-0.0.2-py3-none-any.whl | Python 3 | none | any | Details for ddsqlmodel-0.0.2-py3-none-any.whl |
Total release size: 48.5 kB
Release files / ddsqlmodel-0.0.2.tar.gz
| Download URL | ddsqlmodel-0.0.2.tar.gz |
|---|---|
| Size | 21.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ac71b64049e75d6c55101a945df1ff86cc710b3a7f3938c0bad56ea3c5a36f73
|
|
BLAKE2b-256 checksum How to use checksums |
c380a95c4fc7dabc8ebf0b3b82fcdc98d04cde0e64a864dabd36201144054998
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logRelease files / ddsqlmodel-0.0.2-py3-none-any.whl
| Download URL | ddsqlmodel-0.0.2-py3-none-any.whl |
|---|---|
| Size | 27.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
08ba55e512db60ea4012a3bf5cfa8f94bd22657c73db147cb60721a256fac9c1
|
|
BLAKE2b-256 checksum How to use checksums |
1062ac43fb9a526b04ac7338f721df4e04186b9c2ebec925fca8ecb8160925d1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logSecurity for ddsqlmodel 0.0.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ddsqlmodel-0.0.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.