ddsqlmodel 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,70 @@
1
+ from typing import Any, ClassVar, Generic, Self, TypeVar, cast
2
+
3
+ from ddutils.convertors import convert_camel_case_to_snake_case
4
+ from pydantic import BaseModel
5
+ from sqlalchemy.orm import declared_attr
6
+ from sqlmodel import MetaData, SQLModel
7
+ from sqlmodel.main import SQLModelMetaclass
8
+
9
+ EntityT = TypeVar('EntityT', bound=BaseModel)
10
+
11
+ # https://alembic.sqlalchemy.org/en/latest/naming.html
12
+ NAMING_CONVENTION = {
13
+ 'all_column_names': lambda constraint, _table: '_'.join([column.name for column in constraint.columns.values()]),
14
+ 'ix': 'ix__%(table_name)s__%(all_column_names)s',
15
+ 'uq': 'uq__%(table_name)s__%(all_column_names)s',
16
+ 'ck': 'ck__%(table_name)s__%(constraint_name)s',
17
+ 'fk': 'fk__%(table_name)s__%(all_column_names)s__%(referred_table_name)s',
18
+ 'pk': 'pk__%(table_name)s',
19
+ }
20
+
21
+
22
+ metadata = MetaData(naming_convention=NAMING_CONVENTION) # type: ignore
23
+
24
+
25
+ class BaseSQLModelMeta(SQLModelMetaclass):
26
+ def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs: Any) -> Any:
27
+ new_cls = super().__new__(cls, name, bases, namespace, **kwargs)
28
+ if kwargs.get('table') and not hasattr(new_cls, '_entity_class'):
29
+ raise TypeError(f'{name} must specify entity type: class {name}(BaseSQLModel[YourEntity], table=True)')
30
+ return new_cls
31
+
32
+
33
+ class BaseSQLModel(SQLModel, Generic[EntityT], metaclass=BaseSQLModelMeta):
34
+ """
35
+ Base of the table models, bound to the entity a row is read into: `class ProfileModel(BaseSQLModel[Profile],
36
+ table=True)`. The table is named after the class in snake case, every constraint and index after
37
+ `NAMING_CONVENTION`, and all models share `metadata` (what Alembic's `target_metadata` takes).
38
+
39
+ `to_entity` and `from_entity` map a row to its entity and back by field name; override them when the mapping
40
+ is not one to one.
41
+ """
42
+
43
+ metadata = metadata
44
+
45
+ _entity_class: ClassVar[type[BaseModel]]
46
+
47
+ @declared_attr # type: ignore
48
+ def __tablename__(cls) -> str:
49
+ return convert_camel_case_to_snake_case(cls.__name__)
50
+
51
+ def __class_getitem__(cls, params: type[Any] | tuple[type[Any], ...]) -> Any: # type: ignore[invalid-method-override]
52
+ result = super().__class_getitem__(params)
53
+ if not isinstance(params, TypeVar):
54
+ result._entity_class = params
55
+ return result
56
+
57
+ def to_entity(self, **extra_fields: Any) -> EntityT:
58
+ """
59
+ Entity from the model row; `extra_fields` carries entity fields that are not model columns (e.g. computed
60
+ SELECT expressions like a derived `state`).
61
+ """
62
+ data = {field: getattr(self, field) for field in self._entity_class.model_fields if hasattr(self, field)}
63
+ return cast('EntityT', self._entity_class(**{**data, **extra_fields}))
64
+
65
+ @classmethod
66
+ def from_entity(cls, entity: EntityT) -> Self:
67
+ return cls.model_validate(entity.model_dump(mode='json'))
68
+
69
+
70
+ __all__ = ('NAMING_CONVENTION', 'BaseSQLModel', 'metadata')
@@ -0,0 +1,3 @@
1
+ from . import dates
2
+
3
+ __all__ = ('dates',)
@@ -0,0 +1,29 @@
1
+ from datetime import datetime
2
+
3
+ from sqlalchemy import func
4
+ from sqlmodel import Field
5
+
6
+ from ddsqlmodel.models.types.datetime import DATETIME_TZ
7
+
8
+
9
+ class UpdatedDateMixin:
10
+ updated_at: datetime | None = Field(
11
+ default=None,
12
+ sa_type=DATETIME_TZ, # type: ignore[arg-type]
13
+ sa_column_kwargs={'nullable': False, 'server_default': func.now(), 'onupdate': func.current_timestamp()},
14
+ )
15
+
16
+
17
+ class CreatedDateMixin:
18
+ created_at: datetime | None = Field(
19
+ default=None,
20
+ sa_type=DATETIME_TZ, # type: ignore[arg-type]
21
+ sa_column_kwargs={'nullable': False, 'server_default': func.now()},
22
+ )
23
+
24
+
25
+ class DatesMixin(UpdatedDateMixin, CreatedDateMixin):
26
+ pass
27
+
28
+
29
+ __all__ = ('CreatedDateMixin', 'DatesMixin', 'UpdatedDateMixin')
@@ -0,0 +1,3 @@
1
+ from . import datetime, json
2
+
3
+ __all__ = ('datetime', 'json')
@@ -0,0 +1,6 @@
1
+ from sqlalchemy import DateTime
2
+
3
+ # `timezone=True`: stores values as PostgreSQL `TIMESTAMP WITH TIME ZONE` (tz-aware), not naive `TIMESTAMP`.
4
+ DATETIME_TZ = DateTime(timezone=True)
5
+
6
+ __all__ = ('DATETIME_TZ',)
@@ -0,0 +1,6 @@
1
+ from sqlalchemy.dialects.postgresql import JSONB as _JSONB
2
+
3
+ # `none_as_null=True`: Python `None` persists as SQL NULL, not the JSON literal `null` (`'null'::jsonb`).
4
+ JSONB = _JSONB(none_as_null=True)
5
+
6
+ __all__ = ('JSONB',)
@@ -0,0 +1,3 @@
1
+ from . import query_params, response
2
+
3
+ __all__ = ('query_params', 'response')
@@ -0,0 +1,85 @@
1
+ from enum import StrEnum
2
+ from typing import Any, ClassVar, cast
3
+
4
+ from pydantic import BaseModel, ConfigDict, Field, create_model
5
+
6
+ from ddsqlmodel.filters.filter_params import DEFAULT_LIMIT, QUERY_FIELDS, FilterParams
7
+
8
+ DEFAULT_PAGE = 1
9
+ MAX_LIMIT = 100
10
+
11
+ RESERVED_FIELDS = frozenset({'page', 'limit', 'search', 'ordering', 'cursor'})
12
+
13
+
14
+ def _alias_generator(field_name: str) -> str:
15
+ if field_name in RESERVED_FIELDS:
16
+ return field_name
17
+ return f'filter[{field_name}]'
18
+
19
+
20
+ def _build_ordering_enum(name: str, fields: tuple[str, ...]) -> type[StrEnum]:
21
+ members = {}
22
+ for field in fields:
23
+ key = field.upper()
24
+ members[key] = field
25
+ members[f'{key}_DESC'] = f'-{field}'
26
+ return cast('type[StrEnum]', StrEnum(f'{name}Ordering', members))
27
+
28
+
29
+ class QueryParams(BaseModel):
30
+ """
31
+ HTTP query contract of a list endpoint, built from a model's `FilterParams`:
32
+ pagination, search, ordering, and flat `filter[...]`-aliased filter fields. Defined
33
+ next to the route; the data-access side receives the `filter_params` projection.
34
+ """
35
+
36
+ model_config = ConfigDict(populate_by_name=True, alias_generator=_alias_generator)
37
+
38
+ filter_params_class: ClassVar[type[FilterParams]] = FilterParams
39
+
40
+ page: int = Field(DEFAULT_PAGE, ge=1)
41
+ limit: int = Field(DEFAULT_LIMIT, ge=1, le=MAX_LIMIT)
42
+ # Keyset-paginated endpoints echo the previous page's next_cursor here; page/limit
43
+ # endpoints simply never receive it.
44
+ cursor: str | None = None
45
+
46
+ @classmethod
47
+ def build(cls, name: str, filter_params: type[FilterParams]) -> type['QueryParams']: # noqa: UP037 # quoted so ty treats the dynamic model type as unknown
48
+ field_definitions: dict[str, Any] = {
49
+ 'filter_params_class': (ClassVar[type[FilterParams]], filter_params),
50
+ }
51
+
52
+ for field_name, field_info in filter_params.model_fields.items():
53
+ if field_name in QUERY_FIELDS:
54
+ continue
55
+ field_definitions[field_name] = (field_info.annotation, field_info.default)
56
+
57
+ if filter_params.ordering_fields:
58
+ ordering_enum = _build_ordering_enum(name, filter_params.ordering_fields)
59
+ field_definitions['ordering'] = (ordering_enum, filter_params.default_ordering)
60
+
61
+ if filter_params.search_fields:
62
+ field_definitions['search'] = (str | None, None)
63
+
64
+ return create_model(name, __base__=cls, **field_definitions)
65
+
66
+ @property
67
+ def filter_params(self) -> FilterParams:
68
+ """The data-access projection of this query — what repositories work with."""
69
+ filter_fields = {
70
+ name: getattr(self, name)
71
+ for name in self.filter_params_class.model_fields
72
+ if name not in QUERY_FIELDS and name in type(self).model_fields
73
+ }
74
+ ordering = getattr(self, 'ordering', None)
75
+ return self.filter_params_class(
76
+ **filter_fields,
77
+ ordering=str(ordering) if ordering else None,
78
+ search=getattr(self, 'search', None),
79
+ limit=self.limit,
80
+ page=self.page,
81
+ cursor=self.cursor,
82
+ )
83
+
84
+
85
+ __all__ = ('DEFAULT_PAGE', 'MAX_LIMIT', 'QueryParams')
@@ -0,0 +1,61 @@
1
+ from typing import Generic, Self, TypeVar
2
+
3
+ from pydantic import BaseModel
4
+
5
+ from ddsqlmodel.filters.filter_params import FilterParams
6
+
7
+ T = TypeVar('T')
8
+
9
+
10
+ class Pagination(BaseModel):
11
+ """
12
+ One pagination shape for both paging styles. The client always sends `page` and
13
+ echoes `next_cursor`/`prev_cursor` when it has one; the server serves cursor requests
14
+ via the fast keyset path and falls back to page/offset otherwise. `count` is
15
+ optional — large tables skip the expensive COUNT, and a non-null `next_cursor` is
16
+ the "there is more" signal.
17
+ """
18
+
19
+ page: int
20
+ limit: int
21
+ count: int | None = None
22
+ next_cursor: str | None = None
23
+ prev_cursor: str | None = None
24
+
25
+ @classmethod
26
+ def from_params(
27
+ cls,
28
+ params: FilterParams,
29
+ count: int | None = None,
30
+ next_cursor: str | None = None,
31
+ prev_cursor: str | None = None,
32
+ limit: int | None = None,
33
+ ) -> Self:
34
+ """
35
+ `limit` overrides the display limit for endpoints with a fixed page size.
36
+ A non-null `next_cursor` IS the "there is more" signal; page/limit endpoints
37
+ expose `count` and leave the cursors empty.
38
+ """
39
+ return cls(
40
+ page=params.page,
41
+ limit=limit or params.page_size,
42
+ count=count,
43
+ next_cursor=next_cursor,
44
+ prev_cursor=prev_cursor,
45
+ )
46
+
47
+
48
+ class Meta(BaseModel):
49
+ pagination: Pagination
50
+
51
+
52
+ class PaginatedResponse(BaseModel, Generic[T]):
53
+ data: list[T]
54
+ meta: Meta
55
+
56
+ @classmethod
57
+ def factory(cls, items: list[T], pagination: Pagination) -> Self:
58
+ return cls(data=items, meta=Meta(pagination=pagination))
59
+
60
+
61
+ __all__ = ('Meta', 'PaginatedResponse', 'Pagination')
ddsqlmodel/py.typed ADDED
File without changes
@@ -0,0 +1,372 @@
1
+ Metadata-Version: 2.4
2
+ Name: ddsqlmodel
3
+ Version: 0.0.1
4
+ Summary: SQLModel helpers: a base model with naming conventions, filter and update contracts, keyset pagination
5
+ Keywords: python,ddsqlmodel,sqlmodel,sqlalchemy,postgresql,asyncio,orm,filtering,lookups,pagination,keyset pagination,cursor,pydantic
6
+ Author: davyddd
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: ddutils>=0.4.0,<0.5.0
17
+ Requires-Dist: pydantic>=2.11,<3
18
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.14,<2.2
19
+ Requires-Dist: sqlmodel>=0.0.37,<0.0.51
20
+ Requires-Python: >=3.11, <3.16
21
+ Project-URL: Repository, https://github.com/davyddd/ddsqlmodel
22
+ Description-Content-Type: text/markdown
23
+
24
+ # ddsqlmodel
25
+
26
+ [![pypi](https://img.shields.io/pypi/v/ddsqlmodel.svg)](https://pypi.python.org/pypi/ddsqlmodel)
27
+ [![downloads](https://static.pepy.tech/badge/ddsqlmodel/month)](https://pepy.tech/project/ddsqlmodel)
28
+ [![versions](https://img.shields.io/pypi/pyversions/ddsqlmodel.svg)](https://github.com/davyddd/ddsqlmodel)
29
+ [![codecov](https://codecov.io/gh/davyddd/ddsqlmodel/branch/main/graph/badge.svg)](https://app.codecov.io/github/davyddd/ddsqlmodel)
30
+ [![license](https://img.shields.io/github/license/davyddd/ddsqlmodel.svg)](https://github.com/davyddd/ddsqlmodel/blob/main/LICENSE)
31
+
32
+ SQLModel helpers: a base model with naming conventions, filter and update contracts, keyset pagination
33
+
34
+ ## Installation
35
+
36
+ Install the library using pip:
37
+ ```bash
38
+ pip install ddsqlmodel
39
+ ```
40
+
41
+ ## Development
42
+
43
+ The project runs entirely in Docker. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:
44
+
45
+ ```bash
46
+ fab build # build the dev image
47
+ fab tests # run pytest
48
+ fab linters # run ruff (with --fix), ty and complexipy
49
+ fab shell # IPython inside the container
50
+ fab bash # bash inside the container
51
+ ```
52
+
53
+ This project was generated from [dd-lib-stub](https://github.com/davyddd/dd-lib-stub);
54
+ run `uvx copier update` to pull in template updates.
55
+
56
+ ## Compatibility
57
+
58
+ Python 3.11 to 3.15. What changed in each release, breaking changes included,
59
+ is in the [GitHub releases](https://github.com/davyddd/ddsqlmodel/releases).
60
+
61
+ <!-- The sections below are the library's own; copier update leaves them alone -->
62
+
63
+ Depends on `sqlmodel>=0.0.37,<0.0.51`, `sqlalchemy[asyncio]>=2.0.14,<2.2`, `pydantic>=2.11,<3` and
64
+ `ddutils>=0.4.0,<0.5.0`. The SQL it builds is PostgreSQL's: row-value comparison, `ILIKE`, `IS DISTINCT FROM`,
65
+ `FOR UPDATE SKIP LOCKED`, `JSONB`. The driver is the application's choice. The tests run on an in-memory SQLite and
66
+ read the statements back as PostgreSQL, no server is needed.
67
+
68
+ | Package | What is in it |
69
+ |---|---|
70
+ | `ddsqlmodel.models` | `base` (`BaseSQLModel`, `metadata`), `mixins.dates`, `types.datetime`, `types.json` |
71
+ | `ddsqlmodel.filters` | `lookups`, `filter_params`, `update_params` are the contracts; `filter_set` runs them, with `conditions`, `keyset` and `cursor` behind it |
72
+ | `ddsqlmodel.pagination` | `query_params` and `response`, the HTTP side of a list |
73
+
74
+ ## Models
75
+
76
+ `BaseSQLModel` is the base of the table models. It is generic over the entity a row is read into, a pydantic
77
+ model: the table is named after the class in snake case (`ProfileModel` is `profile_model`), `to_entity()` and
78
+ `from_entity()` map a row to its entity and back by field name, and every model shares one `metadata` with a
79
+ naming convention for constraints and indexes, so Alembic autogenerate gives every one of them a stable name.
80
+
81
+ ```python
82
+ from datetime import datetime
83
+ from uuid import UUID
84
+
85
+ from pydantic import BaseModel
86
+ from sqlmodel import Field
87
+
88
+ from ddsqlmodel.models.base import BaseSQLModel
89
+ from ddsqlmodel.models.mixins.dates import DatesMixin
90
+ from ddsqlmodel.models.types.datetime import DATETIME_TZ
91
+ from ddsqlmodel.models.types.json import JSONB
92
+
93
+
94
+ class Profile(BaseModel):
95
+ profile_id: UUID
96
+ email: str
97
+ settings: dict | None = None
98
+ registered_at: datetime
99
+ created_at: datetime | None = None
100
+ updated_at: datetime | None = None
101
+
102
+
103
+ class ProfileModel(BaseSQLModel[Profile], DatesMixin, table=True):
104
+ profile_id: UUID = Field(primary_key=True)
105
+ email: str = Field(unique=True)
106
+ settings: dict | None = Field(default=None, sa_type=JSONB, nullable=True) # type: ignore[arg-type]
107
+ registered_at: datetime = Field(sa_type=DATETIME_TZ) # type: ignore[arg-type]
108
+
109
+
110
+ row = ProfileModel.from_entity(profile) # ProfileModel.model_validate(profile.model_dump(mode='json'))
111
+ profile = row.to_entity() # Profile, from the row's fields the entity declares
112
+ profile = row.to_entity(state=state) # plus entity fields that are not columns, e.g. a computed expression
113
+ ```
114
+
115
+ - A model with `table=True` must name its entity, `BaseSQLModel[Profile]`: without one the class raises `TypeError`.
116
+ - Override `to_entity` / `from_entity` when the mapping is not one to one (renamed fields, wrapped value objects).
117
+ - `ddsqlmodel.models.base.metadata` is the `MetaData` of every model: in Alembic's `env.py` it is the
118
+ `target_metadata`. Its `NAMING_CONVENTION`:
119
+
120
+ | Object | Name | Example |
121
+ |---|---|---|
122
+ | Primary key | `pk__<table>` | `pk__profile_model` |
123
+ | Index | `ix__<table>__<columns>` | `ix__profile_model__project_id` |
124
+ | Unique | `uq__<table>__<columns>` | `uq__profile_model__email` |
125
+ | Foreign key | `fk__<table>__<columns>__<referred table>` | `fk__order_model__profile_id__profile_model` |
126
+ | Check | `ck__<table>__<constraint name>` | `ck__order_model__positive_amount` |
127
+
128
+ ### Types and mixins
129
+
130
+ - `ddsqlmodel.models.types.datetime.DATETIME_TZ` is `DateTime(timezone=True)`: `TIMESTAMP WITH TIME ZONE`, not a
131
+ naive `TIMESTAMP`.
132
+ - `ddsqlmodel.models.types.json.JSONB` is PostgreSQL's `JSONB` with `none_as_null=True`: Python `None` is stored as
133
+ SQL `NULL`, not as the JSON literal `null`, which `WHERE column IS NULL` does not match.
134
+ - `ddsqlmodel.models.mixins.dates`: `CreatedDateMixin` adds `created_at`, `UpdatedDateMixin` adds `updated_at`,
135
+ `DatesMixin` both. The columns are `DATETIME_TZ`, `NOT NULL`, defaulted by the server to `now()`; `updated_at`
136
+ is refreshed on update.
137
+
138
+ ## Filtering
139
+
140
+ What can be asked of a model is declared once, as a `FilterParams` class: the filter fields with their lookups,
141
+ the fields a list can be ordered by and searched on. `FilterSet` runs an instance of it against the database:
142
+ a page of rows with keyset cursors, a count, a filtered update. The same contract becomes the query of an HTTP
143
+ list endpoint with `QueryParams` (see [Pagination](#pagination)).
144
+
145
+ ### FilterParams
146
+
147
+ The filter fields are declared in a pydantic model; a field states its lookups with the `FieldLookups` marker, and
148
+ a field without one is compared for equality. `FilterParams.build` expands every lookup into a field of its own:
149
+
150
+ ```python
151
+ from typing import Annotated
152
+ from uuid import UUID
153
+
154
+ from pydantic import BaseModel
155
+
156
+ from ddsqlmodel.filters.filter_params import FilterParams
157
+ from ddsqlmodel.filters.lookups import FieldLookups, Lookup, SearchType
158
+
159
+
160
+ class CampaignFilters(BaseModel):
161
+ project_id: UUID | None = None
162
+ campaign_id: Annotated[UUID | None, FieldLookups(Lookup.IN)] = None
163
+ state: Annotated[str | None, FieldLookups(Lookup.EXACT, Lookup.IN)] = None
164
+
165
+
166
+ CampaignFilterParams = FilterParams.build(
167
+ 'CampaignFilterParams',
168
+ filters=CampaignFilters,
169
+ ordering_fields=('created_at', 'name'),
170
+ default_ordering='-created_at',
171
+ search_fields={'name': SearchType.ILIKE, 'campaign_id': SearchType.EXACT},
172
+ )
173
+
174
+ params = CampaignFilterParams(project_id=project_id, state__in=['draft', 'live'], search='welcome', limit=50)
175
+ ```
176
+
177
+ A lookup is the suffix of the generated field, `<field>__<lookup>`; `EXACT` is the bare field:
178
+
179
+ | Lookup | Generated field | SQL |
180
+ |---|---|---|
181
+ | `EXACT` (no marker) | `kind: Kind \| None` | `kind = ...` |
182
+ | `IEXACT` | `email__iexact: str \| None` | `lower(email) = lower(...)` |
183
+ | `NE` | `segment_id__ne: UUID \| None` | `segment_id IS DISTINCT FROM ...` |
184
+ | `IN` | `state__in: list[State] \| None` | `state IN (...)` |
185
+ | `NOT_IN` | `state__not_in: list[State] \| None` | `state IS NULL OR state NOT IN (...)` |
186
+ | `ISNULL` | `email__isnull: bool \| None` | `email IS NULL` for `True`, `IS NOT NULL` for `False` |
187
+ | `LT`, `LTE`, `GT`, `GTE` | `paid_at__lt: datetime \| None`, ... | `paid_at < ...`, `<=`, `>`, `>=` |
188
+ | `CONTAINS`, `STARTSWITH`, `ENDSWITH` | `name__contains: str \| None`, ... | `name LIKE '%...%'`, `'...%'`, `'%...'` |
189
+ | `ICONTAINS`, `ISTARTSWITH`, `IENDSWITH` | `name__icontains: str \| None`, ... | the same with `ILIKE` |
190
+
191
+ - A marked field gets only the listed lookups: add `Lookup.EXACT` to keep the bare field.
192
+ - `NE` and `NOT_IN` count a row with `NULL` as different, as Python does; a plain `<>` or `NOT IN` would drop it.
193
+ - The substring lookups match the value literally: `%` and `_` in it are not wildcards.
194
+ - A list is accepted only through `IN` and `NOT_IN`: a bare field given a list raises `ValueError`.
195
+ - `ordering_fields` needs a `default_ordering` among them; a leading `-` is descending.
196
+ - Search is one term matched against every search field, joined with `OR`: `ILIKE` is a case-insensitive
197
+ substring, matched literally; `EXACT` casts the term to the column type (a UUID, an integer) and skips the
198
+ column when the term cannot be cast. A term no column can take matches nothing.
199
+
200
+ Every instance also carries the query fields `ordering`, `search`, `limit`, `page` (from 1) and `cursor`;
201
+ `page_size` is `limit` or `DEFAULT_LIMIT` (20), `offset` is derived from `page`, and `values` are the filled filter
202
+ fields only.
203
+
204
+ An instance is changed in place, and what is assigned is validated like what it was built with: a caller narrows
205
+ the contract it was given (`params.state__in = ['live']`), a loop over the pages moves the cursor
206
+ (`params.cursor = next_cursor`), no copy needed.
207
+
208
+ ### FilterSet
209
+
210
+ ```python
211
+ from sqlmodel import select
212
+
213
+ from ddsqlmodel.filters.filter_set import FilterSet
214
+
215
+ filter_set = FilterSet(
216
+ session=session, # sqlmodel's AsyncSession
217
+ model=CampaignModel,
218
+ base_statement=select(CampaignModel).where(CampaignModel.is_deleted.is_(False)),
219
+ params=params,
220
+ )
221
+
222
+ rows, next_cursor, prev_cursor = await filter_set.select()
223
+ count = await filter_set.count()
224
+ ```
225
+
226
+ | Parameter | Description |
227
+ |---|---|
228
+ | `session` | `sqlmodel.ext.asyncio.session.AsyncSession` the statements run in |
229
+ | `model` | The model whose columns the filter, ordering and search fields name |
230
+ | `base_statement` | The `select` (for `select` and `count`) or `update` (for `update_by_filters`) to extend |
231
+ | `params` | The `FilterParams` instance |
232
+ | `extra_columns` | Expressions by field name, for fields that are not columns of the model |
233
+
234
+ - `select()` returns one page and both boundary cursors. The rows are model instances when the statement selects
235
+ one entity, rows as SQLAlchemy returns them otherwise.
236
+ - `count()` is the number of rows the base statement, the filters and the search match; the range is ignored.
237
+ - `update_by_filters(update_params)` is described [below](#filtered-update).
238
+
239
+ A field that is not a column of the model, such as a computed state, is resolved through `extra_columns`:
240
+
241
+ ```python
242
+ state = case((CampaignModel.is_deleted.is_(True), literal('archived')), else_=literal('draft'))
243
+
244
+ filter_set = FilterSet(
245
+ session=session,
246
+ model=CampaignModel,
247
+ base_statement=select(CampaignModel, state.label('state')),
248
+ params=params, # CampaignFilterParams(state='archived')
249
+ extra_columns={'state': state},
250
+ )
251
+ rows, _, _ = await filter_set.select()
252
+ campaigns = [row.to_entity(state=state) for row, state in rows]
253
+ ```
254
+
255
+ ### Keyset paging
256
+
257
+ Nothing extra is declared. The key of a page is always the effective ordering plus the model's primary key as a
258
+ unique tiebreaker, both running in the ordering's direction, so the anchor is one row-value comparison,
259
+ `(created_at, campaign_id) < (..., ...)`, that an index on the ordering column serves.
260
+
261
+ - With `params.cursor` the page starts strictly after the row the cursor points at. A cursor is `next_cursor` or
262
+ `prev_cursor` of an earlier `select()`; a prev-cursor scans in reverse and the rows come back in display order.
263
+ - Without a cursor the page is `OFFSET (page - 1) * page_size`, for a jump to an arbitrary page.
264
+ - One extra row is fetched to know whether the list goes on: `next_cursor` is `None` on the last page,
265
+ `prev_cursor` is `None` on the first.
266
+ - The cursor is opaque and URL-safe. A malformed one, or one built for another ordering, raises `ValueError`, and
267
+ so does an `ordering` outside `ordering_fields`.
268
+ - `ddsqlmodel.filters.keyset.Keyset` is the key itself: it orders and anchors a statement, reads a cursor and writes
269
+ one. `FilterSet` builds it from the params; it is there for a query `FilterSet` does not cover.
270
+ - The model needs a single-column primary key; keys may be datetimes, UUIDs, strings and numbers.
271
+
272
+ ```python
273
+ params = CampaignFilterParams(limit=500)
274
+ while True:
275
+ filter_set = FilterSet(session=session, model=CampaignModel, base_statement=select(CampaignModel), params=params)
276
+ rows, next_cursor, _ = await filter_set.select()
277
+ ...
278
+ if next_cursor is None:
279
+ break
280
+ params.cursor = next_cursor
281
+ ```
282
+
283
+ ### Filtered update
284
+
285
+ An `UpdateParams` subclass declares the columns that may be updated; the caller fills the ones to change, `None`
286
+ fields are skipped, and an update with nothing to set raises `ValueError`. The rows are chosen by the `update`
287
+ base statement and the filter fields of `params`.
288
+
289
+ ```python
290
+ from sqlmodel import update
291
+
292
+ from ddsqlmodel.filters.update_params import UpdateParams
293
+
294
+
295
+ class CampaignUpdateParams(UpdateParams):
296
+ state: str | None = None
297
+
298
+
299
+ filter_set = FilterSet(
300
+ session=session,
301
+ model=CampaignModel,
302
+ base_statement=update(CampaignModel).where(CampaignModel.project_id == project_id),
303
+ params=CampaignFilterParams(state='draft'),
304
+ )
305
+ updated, cursor = await filter_set.update_by_filters(CampaignUpdateParams(state='archived')) # (rows updated, None)
306
+ ```
307
+
308
+ - A model with `UpdatedDateMixin` gets `updated_at` set to the current moment, unless the update params carry one.
309
+ - Without `params.limit` everything matching is updated in one statement, and the cursor returned is `None`.
310
+ - With `params.limit` the update is one batch: the `limit` rows `select()` would page first, in the keyset
311
+ order and strictly after `params.cursor`, locked with `FOR UPDATE SKIP LOCKED` and updated in place. The cursor
312
+ returned is that page's `next_cursor`. A mass update loops with it, each batch in a transaction of its own,
313
+ until a batch updates no rows, so no transaction is held over the whole table. A prev-cursor is refused.
314
+
315
+ ```python
316
+ params = CampaignFilterParams(state='draft', limit=10_000)
317
+ while True:
318
+ async with session_factory() as session: # a transaction per batch
319
+ filter_set = FilterSet(
320
+ session=session, model=CampaignModel, base_statement=update(CampaignModel), params=params
321
+ )
322
+ updated, cursor = await filter_set.update_by_filters(CampaignUpdateParams(state='archived'))
323
+ if not updated:
324
+ break
325
+ params.cursor = cursor
326
+ ```
327
+
328
+ ## Pagination
329
+
330
+ `ddsqlmodel.pagination` is the HTTP side of a list: `QueryParams` is the query of the endpoint built from a
331
+ `FilterParams`, `PaginatedResponse` its answer. Both are plain pydantic models; the example binds them with FastAPI.
332
+
333
+ ```python
334
+ from typing import Annotated
335
+
336
+ from fastapi import APIRouter, Query
337
+
338
+ from ddsqlmodel.pagination.query_params import QueryParams
339
+ from ddsqlmodel.pagination.response import PaginatedResponse, Pagination
340
+
341
+ router = APIRouter()
342
+
343
+ CampaignQueryParams = QueryParams.build('CampaignQueryParams', CampaignFilterParams)
344
+
345
+
346
+ @router.get('/campaigns/')
347
+ async def campaign_list(params: Annotated[CampaignQueryParams, Query()]) -> PaginatedResponse[Campaign]:
348
+ filter_params = params.filter_params # a CampaignFilterParams
349
+ campaigns, next_cursor, prev_cursor = await get_campaigns(filter_params)
350
+ count = await count_campaigns(filter_params)
351
+ pagination = Pagination.from_params(filter_params, count=count, next_cursor=next_cursor, prev_cursor=prev_cursor)
352
+ return PaginatedResponse.factory(items=campaigns, pagination=pagination)
353
+ ```
354
+
355
+ `QueryParams.build(name, filter_params)` derives the query from the contract:
356
+
357
+ - The filter fields are read under `filter[...]`: `?filter[state__in]=draft&filter[state__in]=live`.
358
+ - `page` (from 1, default 1), `limit` (1 to `MAX_LIMIT`, 100; default 20) and `cursor` are always there.
359
+ - `ordering` is an enum of `ordering_fields` in both directions, `name` and `-name`, defaulting to
360
+ `default_ordering`; it exists only when the contract declares ordering fields.
361
+ - `search` exists only when the contract declares search fields.
362
+ - `params.filter_params` is the `FilterParams` instance filled from the query, what the data access works with.
363
+
364
+ `Pagination` is one shape for both paging styles: `page` and `limit` always, `count` when the endpoint counts,
365
+ `next_cursor` / `prev_cursor` when it pages by keyset. A large list skips the `COUNT`, and a non-null `next_cursor`
366
+ is its "there is more". `Pagination.from_params(params, ...)` takes `page` and `limit` from the contract; `limit=`
367
+ overrides it for an endpoint with a fixed page size.
368
+
369
+ ```json
370
+ {"data": [...], "meta": {"pagination": {"page": 1, "limit": 20, "count": 42, "next_cursor": null, "prev_cursor": null}}}
371
+ {"data": [...], "meta": {"pagination": {"page": 1, "limit": 50, "count": null, "next_cursor": "n.f6...", "prev_cursor": null}}}
372
+ ```
@@ -0,0 +1,24 @@
1
+ ddsqlmodel/__init__.py,sha256=Pl9SRMdAvhPOjphmtu9hsLyDqm-1CLHn8J7JKxrRP9g,89
2
+ ddsqlmodel/filters/__init__.py,sha256=kRWnN89m7xnVbY9q25ems5UTT5IISy8JhUlFLGBYUpI,197
3
+ ddsqlmodel/filters/conditions.py,sha256=KbFycoL1R1XkuJHxBZc6_R_1av_VtV02i3FlHT9EB_s,3203
4
+ ddsqlmodel/filters/cursor.py,sha256=JrrXMmD3n9PXWxbb3QBIEBrPX1ZKfAg5_Y6wYsC8R1c,1387
5
+ ddsqlmodel/filters/filter_params.py,sha256=UN757P3YuGml8mmSI8NvJShjcBcOqjdoB7LZRQm29cE,5050
6
+ ddsqlmodel/filters/filter_set.py,sha256=9ulZ1WmxECl4XyYCmqO_J2RDHDVTrzESnnp3XoC0eIg,7852
7
+ ddsqlmodel/filters/keyset.py,sha256=O992xmAmAyEhADLBvGiMQvdrjpt4I6Bxxch9ePmUJvo,6294
8
+ ddsqlmodel/filters/lookups.py,sha256=MQBVoNtLHWb4B33iXiURU1Wtuj7Kh4CAvomYCuCKUB0,1781
9
+ ddsqlmodel/filters/update_params.py,sha256=LemPDdJ6eV9Fm-34rwnUK80d35V6AqT-Z_ymg7HYXf0,582
10
+ ddsqlmodel/models/__init__.py,sha256=EuywMntZTpCMohXaoO51J953Zp1epRqZDjdYNGxoEfA,73
11
+ ddsqlmodel/models/base.py,sha256=FBd6djuG2JLTisFQXPa1U-QhbSYLd9E_xOb71ck8d6A,2983
12
+ ddsqlmodel/models/mixins/__init__.py,sha256=a4JvZymM0c57vLxzxEr8CCLMPPqYvYrErD1TDGmjR5o,42
13
+ ddsqlmodel/models/mixins/dates.py,sha256=B4KwxD9zNo0vBSQmHZbG8vD_OZrrcQRBc3whot0_ps0,766
14
+ ddsqlmodel/models/types/__init__.py,sha256=Tin66aDxHggO7n35xPpUYAydIxLerQGwa0yykZ9ewew,61
15
+ ddsqlmodel/models/types/datetime.py,sha256=MGp0KgBNnHVCMA1W2BImqknqMyyNfewuabzqE7EPC6o,208
16
+ ddsqlmodel/models/types/json.py,sha256=iW2QhxZgq3sp8CxtB0BEppK4zIUkWIYQacr-hmSgaJ4,222
17
+ ddsqlmodel/pagination/__init__.py,sha256=UxA8fusHiiXG-ppZeCacipbogVzlc4OtZMqfnVdv6hM,77
18
+ ddsqlmodel/pagination/query_params.py,sha256=-MYoH70n8UhtTohxU--Te-ZGq-CpuzDKECw7VXFL7tE,3178
19
+ ddsqlmodel/pagination/response.py,sha256=XZgsjfX3CxwBT3uFhZzO_Kx-54qoszlrsOMSDg3gl4I,1738
20
+ ddsqlmodel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
+ ddsqlmodel-0.0.1.dist-info/licenses/LICENSE,sha256=_DkcY418J4TyqQWxa0QjLzg1jCl1NiR-XE_UyK-Rv6g,1070
22
+ ddsqlmodel-0.0.1.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
23
+ ddsqlmodel-0.0.1.dist-info/METADATA,sha256=OeGZfpmTUI9-8KR73bHm4FfZCQtergUECWTS_W3JTuU,17855
24
+ ddsqlmodel-0.0.1.dist-info/RECORD,,