Metadata-Version: 2.4
Name: ddsqlmodel
Version: 0.0.2
Summary: SQLModel helpers: a base model with naming conventions, filter and update contracts, keyset pagination
Keywords: python,ddsqlmodel,sqlmodel,sqlalchemy,postgresql,asyncio,orm,filtering,lookups,pagination,keyset pagination,cursor,pydantic
Author: davyddd
License-Expression: MIT
License-File: LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Requires-Dist: ddutils>=0.4.0,<0.5.0
Requires-Dist: pydantic>=2.11,<3
Requires-Dist: sqlalchemy[asyncio]>=2.0.14,<2.2
Requires-Dist: sqlmodel>=0.0.37,<0.0.51
Requires-Python: >=3.11, <3.16
Project-URL: Repository, https://github.com/davyddd/ddsqlmodel
Description-Content-Type: text/markdown

# ddsqlmodel

[![pypi](https://img.shields.io/pypi/v/ddsqlmodel.svg)](https://pypi.python.org/pypi/ddsqlmodel)
[![downloads](https://static.pepy.tech/badge/ddsqlmodel/month)](https://pepy.tech/project/ddsqlmodel)
[![versions](https://img.shields.io/pypi/pyversions/ddsqlmodel.svg)](https://github.com/davyddd/ddsqlmodel)
[![codecov](https://codecov.io/gh/davyddd/ddsqlmodel/branch/main/graph/badge.svg)](https://app.codecov.io/github/davyddd/ddsqlmodel)
[![license](https://img.shields.io/github/license/davyddd/ddsqlmodel.svg)](https://github.com/davyddd/ddsqlmodel/blob/main/LICENSE)

SQLModel helpers: a base model with naming conventions, filter and update contracts, keyset pagination

## Installation

Install the library using pip:
```bash
pip install ddsqlmodel
```

## Development

The project runs entirely in Docker. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:

```bash
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](https://github.com/davyddd/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](https://github.com/davyddd/ddsqlmodel/releases).

<!-- The sections below are the library's own; copier update leaves them alone -->

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.

```python
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](#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:

```python
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. An `ordering` is taken
  only from `ordering_fields`, in either direction, or as the `default_ordering` itself: a contract that declares
  no ordering fields takes no other ordering.
- 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 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

```python
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](#filtered-update).

A field that is not a column of the model, such as a computed state, is resolved through `extra_columns`:

```python
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` the 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.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.

```python
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`.

```python
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.

```python
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.

```python
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.

```json
{"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}}}
```
