Skip to main content

ddsqlmodel

pypi downloads versions codecov license

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=True must name its entity, BaseSQLModel[Profile]: without one the class raises TypeError.
  • Override to_entity / from_entity when the mapping is not one to one (renamed fields, wrapped value objects).
  • ddsqlmodel.models.base.metadata is the MetaData of every model: in Alembic's env.py it is the target_metadata. Its NAMING_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_TZ is DateTime(timezone=True): TIMESTAMP WITH TIME ZONE, not a naive TIMESTAMP.
  • ddsqlmodel.models.types.json.JSONB is PostgreSQL's JSONB with none_as_null=True: Python None is stored as SQL NULL, not as the JSON literal null, which WHERE column IS NULL does not match.
  • ddsqlmodel.models.mixins.dates: CreatedDateMixin adds created_at, UpdatedDateMixin adds updated_at, DatesMixin both. The columns are DATETIME_TZ, NOT NULL, defaulted by the server to now(); updated_at is 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.EXACT to keep the bare field.
  • NE and NOT_IN count a row with NULL as different, as Python does; a plain <> or NOT IN would drop it.
  • The substring lookups match the value literally: % and _ in it are not wildcards.
  • A list is accepted only through IN and NOT_IN: a bare field given a list raises ValueError.
  • ordering_fields needs a default_ordering among them; a leading - is descending.
  • Search is one term matched against every search field, joined with OR: ILIKE is a case-insensitive substring, matched literally; EXACT casts the term to the column type (a UUID, an integer) and skips the column when the term cannot be cast. 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.cursor the page starts strictly after the row the cursor points at. A cursor is next_cursor or prev_cursor of an earlier select(); 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_cursor is None on the last page, prev_cursor is None on the first.
  • The cursor is opaque and URL-safe. A malformed one, or one built for another ordering, raises ValueError, and so does an ordering outside ordering_fields.
  • ddsqlmodel.filters.keyset.Keyset is the key itself: it orders and anchors a statement, reads a cursor and writes one. FilterSet builds it from the params; it is there for a query FilterSet does 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 UpdatedDateMixin gets updated_at set to the current moment, unless the update params carry one.
  • Without params.limit everything matching is updated in one statement, and the cursor returned is None.
  • With params.limit the update is one batch: the limit rows select() would page first, in the keyset order and strictly after params.cursor, locked with FOR UPDATE SKIP LOCKED and updated in place. The cursor returned is that page's next_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 to MAX_LIMIT, 100; default 20) and cursor are always there.
  • ordering is an enum of ordering_fields in both directions, name and -name, defaulting to default_ordering; it exists only when the contract declares ordering fields.
  • search exists only when the contract declares search fields.
  • params.filter_params is the FilterParams instance 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.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ddsqlmodel 0.0.1
File Size Uploaded Provenance Actions
ddsqlmodel-0.0.1.tar.gz 21.0 kB With provenance Details for ddsqlmodel-0.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ddsqlmodel 0.0.1
File Interpreter ABI Platform Actions
ddsqlmodel-0.0.1-py3-none-any.whl Python 3 none any Details for ddsqlmodel-0.0.1-py3-none-any.whl

Total release size: 47.5 kB

Release files / ddsqlmodel-0.0.1.tar.gz

Download URL ddsqlmodel-0.0.1.tar.gz
Size 21.0 kB
Tags Source
SHA-256 checksum
How to use checksums
d2cd1e0bf0bbe02718acb320b8b4a3050da2d089f7e62025469a78fe55c9862b
BLAKE2b-256 checksum
How to use checksums
fa6f7fd997626d074a710e517596f122b4ab627010cb4b59f6e813f065cd9d16
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 28, 2026.

Transparency log

Release files / ddsqlmodel-0.0.1-py3-none-any.whl

Download URL ddsqlmodel-0.0.1-py3-none-any.whl
Size 26.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a9fe09dba8864d00ac16e443318d0c412a04719196d57191ebae2986c31ea7b1
BLAKE2b-256 checksum
How to use checksums
5e593d63620718b002f2bedbaf535588e2459834729d3ab85005bd7aef2c339a
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 28, 2026.

Transparency log

Security for ddsqlmodel 0.0.1

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.

Select from 2 files

Attestation for ddsqlmodel-0.0.1.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 28, 2026.

Transparency log

A 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.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page