ddsqlmodel 0.0.1__tar.gz
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.
- ddsqlmodel-0.0.1/LICENSE +21 -0
- ddsqlmodel-0.0.1/PKG-INFO +372 -0
- ddsqlmodel-0.0.1/README.md +349 -0
- ddsqlmodel-0.0.1/ddsqlmodel/__init__.py +3 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/__init__.py +3 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/conditions.py +78 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/cursor.py +32 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/filter_params.py +113 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/filter_set.py +158 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/keyset.py +136 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/lookups.py +59 -0
- ddsqlmodel-0.0.1/ddsqlmodel/filters/update_params.py +20 -0
- ddsqlmodel-0.0.1/ddsqlmodel/models/__init__.py +3 -0
- ddsqlmodel-0.0.1/ddsqlmodel/models/base.py +70 -0
- ddsqlmodel-0.0.1/ddsqlmodel/models/mixins/__init__.py +3 -0
- ddsqlmodel-0.0.1/ddsqlmodel/models/mixins/dates.py +29 -0
- ddsqlmodel-0.0.1/ddsqlmodel/models/types/__init__.py +3 -0
- ddsqlmodel-0.0.1/ddsqlmodel/models/types/datetime.py +6 -0
- ddsqlmodel-0.0.1/ddsqlmodel/models/types/json.py +6 -0
- ddsqlmodel-0.0.1/ddsqlmodel/pagination/__init__.py +3 -0
- ddsqlmodel-0.0.1/ddsqlmodel/pagination/query_params.py +85 -0
- ddsqlmodel-0.0.1/ddsqlmodel/pagination/response.py +61 -0
- ddsqlmodel-0.0.1/ddsqlmodel/py.typed +0 -0
- ddsqlmodel-0.0.1/pyproject.toml +68 -0
- ddsqlmodel-0.0.1/pyproject.toml.orig +53 -0
ddsqlmodel-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Artem Davydov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -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
|
+
[](https://pypi.python.org/pypi/ddsqlmodel)
|
|
27
|
+
[](https://pepy.tech/project/ddsqlmodel)
|
|
28
|
+
[](https://github.com/davyddd/ddsqlmodel)
|
|
29
|
+
[](https://app.codecov.io/github/davyddd/ddsqlmodel)
|
|
30
|
+
[](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
|
+
```
|