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.
- ddsqlmodel/__init__.py +3 -0
- ddsqlmodel/filters/__init__.py +3 -0
- ddsqlmodel/filters/conditions.py +78 -0
- ddsqlmodel/filters/cursor.py +32 -0
- ddsqlmodel/filters/filter_params.py +113 -0
- ddsqlmodel/filters/filter_set.py +158 -0
- ddsqlmodel/filters/keyset.py +136 -0
- ddsqlmodel/filters/lookups.py +59 -0
- ddsqlmodel/filters/update_params.py +20 -0
- ddsqlmodel/models/__init__.py +3 -0
- ddsqlmodel/models/base.py +70 -0
- ddsqlmodel/models/mixins/__init__.py +3 -0
- ddsqlmodel/models/mixins/dates.py +29 -0
- ddsqlmodel/models/types/__init__.py +3 -0
- ddsqlmodel/models/types/datetime.py +6 -0
- ddsqlmodel/models/types/json.py +6 -0
- ddsqlmodel/pagination/__init__.py +3 -0
- ddsqlmodel/pagination/query_params.py +85 -0
- ddsqlmodel/pagination/response.py +61 -0
- ddsqlmodel/py.typed +0 -0
- ddsqlmodel-0.0.1.dist-info/METADATA +372 -0
- ddsqlmodel-0.0.1.dist-info/RECORD +24 -0
- ddsqlmodel-0.0.1.dist-info/WHEEL +4 -0
- ddsqlmodel-0.0.1.dist-info/licenses/LICENSE +21 -0
ddsqlmodel/__init__.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import operator
|
|
2
|
+
from collections.abc import Iterable
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import TypeDecorator, false, func, or_
|
|
6
|
+
|
|
7
|
+
from ddsqlmodel.filters.lookups import Lookup, SearchType
|
|
8
|
+
|
|
9
|
+
_COMPARISONS = {Lookup.LT: operator.lt, Lookup.LTE: operator.le, Lookup.GT: operator.gt, Lookup.GTE: operator.ge}
|
|
10
|
+
# The name of the column method per substring lookup; the value is matched literally (`autoescape`)
|
|
11
|
+
_SUBSTRINGS = {
|
|
12
|
+
Lookup.CONTAINS: 'contains',
|
|
13
|
+
Lookup.ICONTAINS: 'icontains',
|
|
14
|
+
Lookup.STARTSWITH: 'startswith',
|
|
15
|
+
Lookup.ISTARTSWITH: 'istartswith',
|
|
16
|
+
Lookup.ENDSWITH: 'endswith',
|
|
17
|
+
Lookup.IENDSWITH: 'iendswith',
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_python_type(column: Any) -> type:
|
|
22
|
+
"""
|
|
23
|
+
The Python type of the values of a column. A `TypeDecorator` (SQLModel's `AutoString`, the type of a `str`
|
|
24
|
+
field, is one) does not report it, so the type it wraps is asked.
|
|
25
|
+
"""
|
|
26
|
+
column_type = column.type
|
|
27
|
+
if isinstance(column_type, TypeDecorator):
|
|
28
|
+
column_type = column_type.impl_instance
|
|
29
|
+
return column_type.python_type
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def build_lookup_condition(column: Any, lookup: Lookup, value: Any) -> Any:
|
|
33
|
+
"""
|
|
34
|
+
The condition of one filter field. ISNULL takes a flag: `True` is IS NULL, `False` is IS NOT NULL. NE and
|
|
35
|
+
NOT_IN count a row with no value as different too, as Python does: a plain `<>` or `NOT IN` would drop it.
|
|
36
|
+
The substring lookups match the value literally, `%` and `_` included.
|
|
37
|
+
"""
|
|
38
|
+
if lookup is Lookup.ISNULL:
|
|
39
|
+
return column.is_(None) if value else column.is_not(None)
|
|
40
|
+
if lookup is Lookup.IN:
|
|
41
|
+
return column.in_(value)
|
|
42
|
+
if lookup is Lookup.NOT_IN:
|
|
43
|
+
return or_(column.is_(None), column.not_in(value))
|
|
44
|
+
if lookup is Lookup.NE:
|
|
45
|
+
return column.is_distinct_from(value)
|
|
46
|
+
if lookup is Lookup.IEXACT:
|
|
47
|
+
return func.lower(column) == func.lower(value)
|
|
48
|
+
if lookup in _COMPARISONS:
|
|
49
|
+
return _COMPARISONS[lookup](column, value)
|
|
50
|
+
if lookup in _SUBSTRINGS:
|
|
51
|
+
return getattr(column, _SUBSTRINGS[lookup])(value, autoescape=True)
|
|
52
|
+
if isinstance(value, list):
|
|
53
|
+
raise ValueError("List values are only allowed with the 'in' and 'not_in' lookups")
|
|
54
|
+
return column == value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def build_search_condition(columns: Iterable[tuple[Any, SearchType]], term: str) -> Any:
|
|
58
|
+
"""
|
|
59
|
+
One term against every search column, joined with OR. ILIKE is a case-insensitive substring, matched
|
|
60
|
+
literally. EXACT casts the term to the column type (a UUID, an integer); a column that cannot take the term
|
|
61
|
+
is skipped, and a term no column can take matches nothing.
|
|
62
|
+
"""
|
|
63
|
+
conditions = []
|
|
64
|
+
for column, search_type in columns:
|
|
65
|
+
if search_type is SearchType.ILIKE:
|
|
66
|
+
conditions.append(column.icontains(term, autoescape=True))
|
|
67
|
+
elif search_type is SearchType.EXACT:
|
|
68
|
+
try:
|
|
69
|
+
value = get_python_type(column)(term)
|
|
70
|
+
except (ValueError, TypeError):
|
|
71
|
+
continue
|
|
72
|
+
conditions.append(column == value)
|
|
73
|
+
else:
|
|
74
|
+
raise ValueError(f"Search type '{search_type}' is not supported")
|
|
75
|
+
return or_(*conditions) if conditions else false()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
__all__ = ('build_lookup_condition', 'build_search_condition', 'get_python_type')
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
Direction = Literal['next', 'prev']
|
|
4
|
+
|
|
5
|
+
# Tokens are URL-safe by construction (digits, hex, unpadded base64url), so the cursor
|
|
6
|
+
# needs no envelope encoding; '.' never occurs inside a token.
|
|
7
|
+
SEPARATOR = '.'
|
|
8
|
+
_DIRECTIONS = {'n': 'next', 'p': 'prev'}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def encode_cursor(fingerprint: str, tokens: list[str], direction: Direction) -> str:
|
|
12
|
+
"""
|
|
13
|
+
Compact positional keyset cursor: `<n|p>.<key fingerprint>.<token>...`. Field names are not carried: the token
|
|
14
|
+
order is the keyset key order, and the fingerprint pins which key the cursor was built for.
|
|
15
|
+
"""
|
|
16
|
+
return SEPARATOR.join([direction[0], fingerprint, *tokens])
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def decode_cursor(raw: str, fingerprint: str, expected_tokens: int) -> tuple[list[str], Direction]:
|
|
20
|
+
"""
|
|
21
|
+
Decode an opaque cursor. Raises ValueError on malformed input or a cursor built for a different keyset key
|
|
22
|
+
(fingerprint/arity mismatch).
|
|
23
|
+
"""
|
|
24
|
+
direction_char, _, rest = raw.partition(SEPARATOR)
|
|
25
|
+
cursor_fingerprint, _, payload = rest.partition(SEPARATOR)
|
|
26
|
+
tokens = payload.split(SEPARATOR) if payload else []
|
|
27
|
+
if direction_char not in _DIRECTIONS or cursor_fingerprint != fingerprint or len(tokens) != expected_tokens:
|
|
28
|
+
raise ValueError('Cannot decode cursor')
|
|
29
|
+
return tokens, _DIRECTIONS[direction_char] # type: ignore[return-value]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
__all__ = ('Direction', 'decode_cursor', 'encode_cursor')
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from typing import Any, ClassVar
|
|
2
|
+
|
|
3
|
+
from ddutils.annotation_helpers import get_annotation_name, get_annotation_without_optional
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, create_model
|
|
5
|
+
|
|
6
|
+
from ddsqlmodel.filters.lookups import FLAG_LOOKUPS, LIST_LOOKUPS, LOOKUP_SEPARATOR, FieldLookups, Lookup, SearchType
|
|
7
|
+
|
|
8
|
+
DEFAULT_LIMIT = 20
|
|
9
|
+
|
|
10
|
+
# Instance fields of the query itself, not filter columns (see `values`).
|
|
11
|
+
QUERY_FIELDS = frozenset({'ordering', 'search', 'limit', 'page', 'cursor'})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FilterParams(BaseModel):
|
|
15
|
+
"""
|
|
16
|
+
Data-access query contract of a model: what can be filtered (and with which lookups), ordered by, searched on,
|
|
17
|
+
plus the range. One subclass per model, built with `build` and located next to the repository that consumes it.
|
|
18
|
+
|
|
19
|
+
`FilterSet` applies instances to SELECT/UPDATE statements. HTTP list endpoints wrap the same contract into a
|
|
20
|
+
`QueryParams` (see `ddsqlmodel.pagination`) and project it back via `QueryParams.filter_params`.
|
|
21
|
+
|
|
22
|
+
An instance can be changed in place, and what is assigned is validated: a loop over the pages of a list keeps
|
|
23
|
+
one object and moves its cursor, `params.cursor = next_cursor`.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
model_config = ConfigDict(validate_assignment=True)
|
|
27
|
+
|
|
28
|
+
ordering_fields: ClassVar[tuple[str, ...]] = ()
|
|
29
|
+
default_ordering: ClassVar[str | None] = None
|
|
30
|
+
search_fields: ClassVar[dict[str, SearchType]] = {}
|
|
31
|
+
|
|
32
|
+
ordering: str | None = None
|
|
33
|
+
search: str | None = None
|
|
34
|
+
limit: int | None = None
|
|
35
|
+
page: int = 1
|
|
36
|
+
# Opaque keyset cursor (see `FilterSet.select`); its composite key is always the effective ordering plus the
|
|
37
|
+
# model's primary key as tiebreaker.
|
|
38
|
+
cursor: str | None = None
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def build(
|
|
42
|
+
cls,
|
|
43
|
+
name: str,
|
|
44
|
+
filters: type[BaseModel] | None = None,
|
|
45
|
+
ordering_fields: tuple[str, ...] | None = None,
|
|
46
|
+
default_ordering: str | None = None,
|
|
47
|
+
search_fields: dict[str, SearchType] | None = None,
|
|
48
|
+
) -> type['FilterParams']: # noqa: UP037 # quoted so ty treats the dynamic model type as unknown
|
|
49
|
+
if ordering_fields:
|
|
50
|
+
if not default_ordering:
|
|
51
|
+
raise ValueError('default_ordering is required when ordering_fields is provided')
|
|
52
|
+
if default_ordering.lstrip('-') not in ordering_fields:
|
|
53
|
+
raise ValueError(f"default_ordering '{default_ordering}' must be one of {ordering_fields}")
|
|
54
|
+
|
|
55
|
+
field_definitions: dict[str, Any] = {
|
|
56
|
+
'ordering_fields': (ClassVar[tuple[str, ...]], tuple(ordering_fields or ())),
|
|
57
|
+
'default_ordering': (ClassVar[str | None], default_ordering),
|
|
58
|
+
'search_fields': (ClassVar[dict[str, SearchType]], search_fields or {}),
|
|
59
|
+
'ordering': (str | None, default_ordering),
|
|
60
|
+
}
|
|
61
|
+
if filters:
|
|
62
|
+
for field_name, field_info in filters.model_fields.items():
|
|
63
|
+
field_definitions.update(_expand_lookups(field_name, field_info))
|
|
64
|
+
return create_model(name, __base__=cls, **field_definitions)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def page_size(self) -> int:
|
|
68
|
+
return self.limit or DEFAULT_LIMIT
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def offset(self) -> int:
|
|
72
|
+
return (self.page - 1) * self.page_size
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def values(self) -> dict[str, Any]:
|
|
76
|
+
"""Non-empty filter fields only (query fields like ordering/search excluded)."""
|
|
77
|
+
return {field_name: value for field_name, value in self if field_name not in QUERY_FIELDS and value is not None}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _expand_lookups(field_name: str, field_info: Any) -> dict[str, Any]:
|
|
81
|
+
"""
|
|
82
|
+
One field per declared lookup. EXACT keeps the field as declared. IN and NOT_IN become `<field>__in` and
|
|
83
|
+
`<field>__not_in` of `list[...]`, ISNULL becomes `<field>__isnull: bool`. Every other lookup keeps the
|
|
84
|
+
declared type under `<field>__<lookup>`.
|
|
85
|
+
"""
|
|
86
|
+
field_lookups = next((meta for meta in field_info.metadata if isinstance(meta, FieldLookups)), None)
|
|
87
|
+
if field_lookups is None:
|
|
88
|
+
return {field_name: (field_info.annotation, field_info.default)}
|
|
89
|
+
|
|
90
|
+
definitions: dict[str, Any] = {}
|
|
91
|
+
for lookup in field_lookups.lookups:
|
|
92
|
+
if lookup is Lookup.EXACT:
|
|
93
|
+
definitions[field_name] = (field_info.annotation, field_info.default)
|
|
94
|
+
elif lookup in LIST_LOOKUPS:
|
|
95
|
+
item_type = _item_type(field_name, field_info.annotation)
|
|
96
|
+
definitions[f'{field_name}{LOOKUP_SEPARATOR}{lookup}'] = (list[item_type] | None, None) # type: ignore[valid-type]
|
|
97
|
+
elif lookup in FLAG_LOOKUPS:
|
|
98
|
+
definitions[f'{field_name}{LOOKUP_SEPARATOR}{lookup}'] = (bool | None, None)
|
|
99
|
+
else:
|
|
100
|
+
definitions[f'{field_name}{LOOKUP_SEPARATOR}{lookup}'] = (field_info.annotation, None)
|
|
101
|
+
return definitions
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _item_type(field_name: str, annotation: Any) -> Any:
|
|
105
|
+
try:
|
|
106
|
+
return get_annotation_without_optional(annotation)
|
|
107
|
+
except TypeError:
|
|
108
|
+
raise TypeError(
|
|
109
|
+
f"Field '{field_name}' needs a single type for a list lookup, got {get_annotation_name(annotation)}"
|
|
110
|
+
) from None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
__all__ = ('DEFAULT_LIMIT', 'QUERY_FIELDS', 'FilterParams')
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from ddutils.datetime_helpers import utc_now
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
6
|
+
from sqlalchemy import ScalarResult
|
|
7
|
+
from sqlmodel import SQLModel, func, select
|
|
8
|
+
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
9
|
+
|
|
10
|
+
from ddsqlmodel.filters.conditions import build_lookup_condition, build_search_condition
|
|
11
|
+
from ddsqlmodel.filters.filter_params import FilterParams
|
|
12
|
+
from ddsqlmodel.filters.keyset import Keyset
|
|
13
|
+
from ddsqlmodel.filters.lookups import LOOKUP_SEPARATOR, Lookup
|
|
14
|
+
from ddsqlmodel.filters.update_params import UpdateParams
|
|
15
|
+
from ddsqlmodel.models.mixins.dates import UpdatedDateMixin
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FilterSet(BaseModel):
|
|
19
|
+
"""
|
|
20
|
+
Executes a `FilterParams` contract against the database.
|
|
21
|
+
|
|
22
|
+
`select()` returns the page objects together with both boundary cursors, `count()` returns the number of
|
|
23
|
+
matching rows, `update_by_filters()` applies an `UpdateParams` contract. The statements are built from the
|
|
24
|
+
base statement: the filters (`ddsqlmodel.filters.conditions`), the search, and the keyset paging
|
|
25
|
+
(`ddsqlmodel.filters.keyset`) whose key is always the effective ordering plus the model's primary key.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
29
|
+
|
|
30
|
+
session: AsyncSession
|
|
31
|
+
model: type[SQLModel]
|
|
32
|
+
base_statement: Any
|
|
33
|
+
params: FilterParams
|
|
34
|
+
extra_columns: dict[str, Any] = Field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
def _resolve_column(self, field_name: str) -> Any:
|
|
37
|
+
return self.extra_columns[field_name] if field_name in self.extra_columns else getattr(self.model, field_name)
|
|
38
|
+
|
|
39
|
+
def _apply_filters(self, statement: Any) -> Any:
|
|
40
|
+
# Filter fields are `<column>` or `<column>__<lookup>`, see `FilterParams`
|
|
41
|
+
for field_name, value in self.params.values.items():
|
|
42
|
+
column_name, _, lookup_name = field_name.partition(LOOKUP_SEPARATOR)
|
|
43
|
+
column = self._resolve_column(column_name)
|
|
44
|
+
statement = statement.where(build_lookup_condition(column, Lookup(lookup_name or Lookup.EXACT), value))
|
|
45
|
+
return statement
|
|
46
|
+
|
|
47
|
+
def _apply_search(self, statement: Any) -> Any:
|
|
48
|
+
search_fields = type(self.params).search_fields
|
|
49
|
+
if not self.params.search or not search_fields:
|
|
50
|
+
return statement
|
|
51
|
+
columns = [(getattr(self.model, field_name), search_type) for field_name, search_type in search_fields.items()]
|
|
52
|
+
return statement.where(build_search_condition(columns, self.params.search))
|
|
53
|
+
|
|
54
|
+
def _build_keyset(self) -> Keyset:
|
|
55
|
+
return Keyset.build(self.model, self.params, self._resolve_column)
|
|
56
|
+
|
|
57
|
+
async def _exec(self, statement: Any) -> Any:
|
|
58
|
+
# SQLModel's session deprecates `execute`. Its `exec` returns the same result, except for a single-entity
|
|
59
|
+
# `sqlmodel.select`, which it hands back as scalars already.
|
|
60
|
+
return await self.session.exec(statement)
|
|
61
|
+
|
|
62
|
+
async def select(self) -> tuple[Sequence[Any], str | None, str | None]:
|
|
63
|
+
"""
|
|
64
|
+
One page of objects plus both boundary cursors.
|
|
65
|
+
|
|
66
|
+
With `params.cursor` the page is anchored by the fast keyset path (a prev-cursor scans in reverse and is
|
|
67
|
+
flipped back); without one it falls back to `OFFSET (page - 1) * page_size`. One extra row is over-fetched:
|
|
68
|
+
it signals continuation on the scan side, the other side is implied by how we got here (a cursor, or a jump
|
|
69
|
+
past page 1). Returns model instances when a single entity is selected, raw rows otherwise.
|
|
70
|
+
"""
|
|
71
|
+
keyset = self._build_keyset()
|
|
72
|
+
anchor, backwards = keyset.decode_cursor(self.params.cursor)
|
|
73
|
+
page_size = self.params.page_size
|
|
74
|
+
|
|
75
|
+
statement = self._apply_search(self._apply_filters(self.base_statement))
|
|
76
|
+
statement = keyset.apply(statement, anchor, backwards)
|
|
77
|
+
if anchor is None and self.params.page > 1:
|
|
78
|
+
statement = statement.offset(self.params.offset)
|
|
79
|
+
statement = statement.limit(page_size + 1)
|
|
80
|
+
|
|
81
|
+
result = await self._exec(statement)
|
|
82
|
+
single_entity = len(statement.column_descriptions) == 1
|
|
83
|
+
if isinstance(result, ScalarResult):
|
|
84
|
+
rows = list(result.all())
|
|
85
|
+
else:
|
|
86
|
+
rows = list(result.scalars().all() if single_entity else result.all())
|
|
87
|
+
|
|
88
|
+
overflow = len(rows) > page_size
|
|
89
|
+
rows = rows[:page_size]
|
|
90
|
+
if backwards:
|
|
91
|
+
rows.reverse()
|
|
92
|
+
if not rows:
|
|
93
|
+
return rows, None, None
|
|
94
|
+
|
|
95
|
+
next_exists = True if backwards else overflow
|
|
96
|
+
prev_exists = overflow if backwards else (anchor is not None or self.params.page > 1)
|
|
97
|
+
next_cursor = keyset.encode_cursor(rows[-1], 'next') if next_exists else None
|
|
98
|
+
prev_cursor = keyset.encode_cursor(rows[0], 'prev') if prev_exists else None
|
|
99
|
+
return rows, next_cursor, prev_cursor
|
|
100
|
+
|
|
101
|
+
async def count(self) -> int:
|
|
102
|
+
statement = self.base_statement.with_only_columns(func.count())
|
|
103
|
+
statement = self._apply_search(self._apply_filters(statement))
|
|
104
|
+
result = await self._exec(statement)
|
|
105
|
+
return (result.one() if isinstance(result, ScalarResult) else result.scalar()) or 0
|
|
106
|
+
|
|
107
|
+
async def update_by_filters(self, update_params: UpdateParams) -> tuple[int, str | None]:
|
|
108
|
+
"""
|
|
109
|
+
UPDATE from an Update base_statement: SET from the `UpdateParams` contract, WHERE from the filter fields of
|
|
110
|
+
`params` (same logic as `select`). Returns the rows updated and a cursor.
|
|
111
|
+
|
|
112
|
+
With `params.limit` the update is one batch: the `limit` rows that `select` would page first, in the keyset
|
|
113
|
+
order and strictly after `params.cursor`, locked with SKIP LOCKED and updated in place. The cursor returned
|
|
114
|
+
is the one `select` would call `next_cursor`: it points past the last row updated, so the caller loops with
|
|
115
|
+
it, each batch in a transaction of its own, until the update reports no rows. That is how a mass update
|
|
116
|
+
runs without holding one transaction over the whole table. A prev-cursor is refused.
|
|
117
|
+
|
|
118
|
+
Without `params.limit` everything matching is updated in one statement and the cursor is None.
|
|
119
|
+
"""
|
|
120
|
+
values = update_params.values
|
|
121
|
+
if not values:
|
|
122
|
+
raise ValueError('At least one update value must be provided')
|
|
123
|
+
if issubclass(self.model, UpdatedDateMixin):
|
|
124
|
+
values.setdefault('updated_at', utc_now())
|
|
125
|
+
|
|
126
|
+
if self.params.limit is None:
|
|
127
|
+
result = await self._exec(self._apply_filters(self.base_statement.values(**values)))
|
|
128
|
+
return result.rowcount, None
|
|
129
|
+
|
|
130
|
+
keyset = self._build_keyset()
|
|
131
|
+
anchor, backwards = keyset.decode_cursor(self.params.cursor)
|
|
132
|
+
if backwards:
|
|
133
|
+
raise ValueError('A limited update walks forward only')
|
|
134
|
+
|
|
135
|
+
# The batch is picked under the WHERE of the base statement too: picked from the whole table, it would
|
|
136
|
+
# count rows the UPDATE then leaves alone, and come back short or empty while matching rows remain.
|
|
137
|
+
batch_select = select(*keyset.columns)
|
|
138
|
+
if self.base_statement.whereclause is not None:
|
|
139
|
+
batch_select = batch_select.where(self.base_statement.whereclause)
|
|
140
|
+
batch = (
|
|
141
|
+
keyset.apply(self._apply_filters(batch_select), anchor, backwards)
|
|
142
|
+
.limit(self.params.limit)
|
|
143
|
+
.with_for_update(skip_locked=True)
|
|
144
|
+
.cte('batch')
|
|
145
|
+
)
|
|
146
|
+
# The primary key closes the key (see `Keyset`), and the batch carries it under its name
|
|
147
|
+
primary_key, primary_key_name = keyset.columns[-1], keyset.fields[-1]
|
|
148
|
+
statement = (
|
|
149
|
+
self.base_statement.where(primary_key == batch.c[primary_key_name]).values(**values).returning(*keyset.columns)
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
rows = (await self._exec(statement)).all()
|
|
153
|
+
if not rows:
|
|
154
|
+
return 0, None
|
|
155
|
+
return len(rows), keyset.encode_cursor(keyset.get_last_row(rows, backwards), 'next')
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
__all__ = ('FilterSet',)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
from collections.abc import Callable, Sequence
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
from hashlib import md5
|
|
5
|
+
from typing import Any, Self
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from sqlalchemy import inspect as sqlalchemy_inspect, tuple_
|
|
9
|
+
|
|
10
|
+
from ddsqlmodel.filters.conditions import get_python_type
|
|
11
|
+
from ddsqlmodel.filters.cursor import Direction, decode_cursor, encode_cursor
|
|
12
|
+
from ddsqlmodel.filters.filter_params import FilterParams
|
|
13
|
+
|
|
14
|
+
_MICROSECONDS = 1_000_000
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def value_to_token(column: Any, value: Any) -> str:
|
|
18
|
+
"""
|
|
19
|
+
Compact URL-safe token for a keyset value; `token_to_value` is the inverse and derives the type from the same
|
|
20
|
+
column.
|
|
21
|
+
"""
|
|
22
|
+
python_type = get_python_type(column)
|
|
23
|
+
if issubclass(python_type, datetime):
|
|
24
|
+
return str(int(value.timestamp() * _MICROSECONDS))
|
|
25
|
+
if issubclass(python_type, UUID):
|
|
26
|
+
return value.hex
|
|
27
|
+
if issubclass(python_type, str):
|
|
28
|
+
return base64.urlsafe_b64encode(str(value).encode()).decode().rstrip('=')
|
|
29
|
+
return str(value)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def token_to_value(column: Any, token: str) -> Any:
|
|
33
|
+
python_type = get_python_type(column)
|
|
34
|
+
if issubclass(python_type, datetime):
|
|
35
|
+
return datetime.fromtimestamp(int(token) / _MICROSECONDS, tz=UTC)
|
|
36
|
+
if issubclass(python_type, UUID):
|
|
37
|
+
return UUID(token)
|
|
38
|
+
if issubclass(python_type, str):
|
|
39
|
+
return base64.urlsafe_b64decode(token + '=' * (-len(token) % 4)).decode()
|
|
40
|
+
return python_type(token)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def get_row_value(row: Any, field: str) -> Any:
|
|
44
|
+
# A row is either a model instance / a Row with the column selected directly,
|
|
45
|
+
# or a composite Row (entity + extra columns) — then the entity carries the field.
|
|
46
|
+
if hasattr(row, field):
|
|
47
|
+
return getattr(row, field)
|
|
48
|
+
for item in row:
|
|
49
|
+
if hasattr(item, field):
|
|
50
|
+
return getattr(item, field)
|
|
51
|
+
raise ValueError(f"Keyset field '{field}' is not present in the selected row")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Keyset:
|
|
55
|
+
"""
|
|
56
|
+
The key a list is paged by: the effective ordering plus the model's primary key as a unique tiebreaker
|
|
57
|
+
(appended unless the ordering is the primary key itself). The tiebreaker runs in the ordering's direction, so
|
|
58
|
+
the whole key scans one way and the anchor of a page is a single row-value comparison.
|
|
59
|
+
|
|
60
|
+
It orders a statement and anchors it at a cursor (`apply`), reads a cursor into the values of its row
|
|
61
|
+
(`decode_cursor`) and writes the cursor of a row (`encode_cursor`).
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(self, fields: tuple[str, ...], columns: tuple[Any, ...], *, descending: bool) -> None:
|
|
65
|
+
self.fields = fields
|
|
66
|
+
self.columns = columns
|
|
67
|
+
self.descending = descending
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def build(cls, model: Any, params: FilterParams, resolve_column: Callable[[str], Any]) -> Self:
|
|
71
|
+
ordering = params.ordering or type(params).default_ordering
|
|
72
|
+
ordering_fields = type(params).ordering_fields
|
|
73
|
+
if ordering and ordering_fields and ordering.lstrip('-') not in ordering_fields:
|
|
74
|
+
raise ValueError(f"Ordering '{ordering}' is not one of {ordering_fields}")
|
|
75
|
+
primary_key = sqlalchemy_inspect(model).primary_key
|
|
76
|
+
if len(primary_key) != 1:
|
|
77
|
+
raise ValueError(f'Keyset paging requires a single-column primary key on {model.__name__}')
|
|
78
|
+
|
|
79
|
+
fields = [ordering.lstrip('-')] if ordering else []
|
|
80
|
+
if primary_key[0].name not in fields:
|
|
81
|
+
fields.append(primary_key[0].name)
|
|
82
|
+
return cls(
|
|
83
|
+
fields=tuple(fields),
|
|
84
|
+
columns=tuple(resolve_column(field) for field in fields),
|
|
85
|
+
descending=bool(ordering) and ordering.startswith('-'),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def fingerprint(self) -> str:
|
|
90
|
+
"""Pins the key a cursor was built for: the fields and their direction."""
|
|
91
|
+
signed_fields = (f'-{field}' if self.descending else field for field in self.fields)
|
|
92
|
+
return md5(','.join(signed_fields).encode(), usedforsecurity=False).hexdigest()[:2]
|
|
93
|
+
|
|
94
|
+
def scans_descending(self, backwards: bool) -> bool:
|
|
95
|
+
"""Whether the scan runs descending: a prev-cursor scans against the ordering."""
|
|
96
|
+
return self.descending != backwards
|
|
97
|
+
|
|
98
|
+
def apply(self, statement: Any, anchor: Sequence[Any] | None, backwards: bool) -> Any:
|
|
99
|
+
"""
|
|
100
|
+
Order the statement by the key and start it strictly after the anchor in scan order. The anchor is one
|
|
101
|
+
row-value comparison: Postgres turns it into a range condition on the index of the first key, so a page
|
|
102
|
+
starts where the last one ended instead of filtering its way there from the beginning of the range.
|
|
103
|
+
"""
|
|
104
|
+
descending = self.scans_descending(backwards)
|
|
105
|
+
if anchor is not None:
|
|
106
|
+
row = tuple_(*self.columns)
|
|
107
|
+
statement = statement.where(row < tuple_(*anchor) if descending else row > tuple_(*anchor))
|
|
108
|
+
return statement.order_by(*(column.desc() if descending else column.asc() for column in self.columns))
|
|
109
|
+
|
|
110
|
+
def decode_cursor(self, cursor: str | None) -> tuple[list[Any] | None, bool]:
|
|
111
|
+
"""
|
|
112
|
+
The key values of the row a cursor points at, and whether it is a prev-cursor. `ValueError` for a
|
|
113
|
+
malformed cursor or one built for another key.
|
|
114
|
+
"""
|
|
115
|
+
if cursor is None:
|
|
116
|
+
return None, False
|
|
117
|
+
tokens, direction = decode_cursor(cursor, self.fingerprint, len(self.fields))
|
|
118
|
+
try:
|
|
119
|
+
anchor = [token_to_value(column, token) for column, token in zip(self.columns, tokens, strict=True)]
|
|
120
|
+
except (ValueError, TypeError, OverflowError):
|
|
121
|
+
raise ValueError('Cannot decode cursor') from None
|
|
122
|
+
return anchor, direction == 'prev'
|
|
123
|
+
|
|
124
|
+
def encode_cursor(self, row: Any, direction: Direction) -> str:
|
|
125
|
+
tokens = [
|
|
126
|
+
value_to_token(column, get_row_value(row, field)) for field, column in zip(self.fields, self.columns, strict=True)
|
|
127
|
+
]
|
|
128
|
+
return encode_cursor(self.fingerprint, tokens, direction)
|
|
129
|
+
|
|
130
|
+
def get_last_row(self, rows: Sequence[Any], backwards: bool) -> Any:
|
|
131
|
+
"""The row a scan would have reached last, for rows that come back in no promised order (RETURNING)."""
|
|
132
|
+
pick = min if self.scans_descending(backwards) else max
|
|
133
|
+
return pick(rows, key=lambda row: tuple(get_row_value(row, field) for field in self.fields))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
__all__ = ('Keyset', 'get_row_value', 'token_to_value', 'value_to_token')
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from enum import StrEnum
|
|
2
|
+
|
|
3
|
+
LOOKUP_SEPARATOR = '__'
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Lookup(StrEnum):
|
|
7
|
+
"""
|
|
8
|
+
What a filter field does with its value; the member's value is the suffix of the field, `<field>__<lookup>`
|
|
9
|
+
(`EXACT` is the bare field).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
EXACT = 'exact'
|
|
13
|
+
IEXACT = 'iexact'
|
|
14
|
+
NE = 'ne'
|
|
15
|
+
IN = 'in'
|
|
16
|
+
NOT_IN = 'not_in'
|
|
17
|
+
ISNULL = 'isnull'
|
|
18
|
+
LT = 'lt'
|
|
19
|
+
LTE = 'lte'
|
|
20
|
+
GT = 'gt'
|
|
21
|
+
GTE = 'gte'
|
|
22
|
+
CONTAINS = 'contains'
|
|
23
|
+
ICONTAINS = 'icontains'
|
|
24
|
+
STARTSWITH = 'startswith'
|
|
25
|
+
ISTARTSWITH = 'istartswith'
|
|
26
|
+
ENDSWITH = 'endswith'
|
|
27
|
+
IENDSWITH = 'iendswith'
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# Lookups that take a list of values, and the one that takes a flag instead of a value
|
|
31
|
+
LIST_LOOKUPS = frozenset({Lookup.IN, Lookup.NOT_IN})
|
|
32
|
+
FLAG_LOOKUPS = frozenset({Lookup.ISNULL})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SearchType(StrEnum):
|
|
36
|
+
ILIKE = 'ilike'
|
|
37
|
+
EXACT = 'exact'
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class FieldLookups:
|
|
41
|
+
"""
|
|
42
|
+
Annotated marker declaring which lookups a filter field allows:
|
|
43
|
+
|
|
44
|
+
class CampaignFilters(BaseModel):
|
|
45
|
+
campaign_id: Annotated[CampaignId | None, FieldLookups(Lookup.IN)] = None
|
|
46
|
+
email: Annotated[str | None, FieldLookups(Lookup.EXACT, Lookup.ISNULL)] = None
|
|
47
|
+
|
|
48
|
+
`FilterParams.build` expands each declared lookup into its own field (`campaign_id__in: list[CampaignId] | None`,
|
|
49
|
+
`email__isnull: bool | None`, `purchased_at__lt: datetime | None`, ...). Fields without the marker allow EXACT
|
|
50
|
+
only. List values are accepted only through the IN and NOT_IN lookups, never on the bare field.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, *lookups: Lookup) -> None:
|
|
54
|
+
if not lookups:
|
|
55
|
+
raise ValueError('At least one lookup must be declared')
|
|
56
|
+
self.lookups = tuple(lookups)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
__all__ = ('FLAG_LOOKUPS', 'LIST_LOOKUPS', 'LOOKUP_SEPARATOR', 'FieldLookups', 'Lookup', 'SearchType')
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class UpdateParams(BaseModel):
|
|
7
|
+
"""
|
|
8
|
+
Base contract of the columns a repository allows to update.
|
|
9
|
+
|
|
10
|
+
Subclass per model with optional fields; the caller fills the ones it wants to change, `None` fields are
|
|
11
|
+
skipped. The UPDATE counterpart of the `filters` contract passed to `FilterParams.build`, see
|
|
12
|
+
`FilterSet.update_by_filters`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def values(self) -> dict[str, Any]:
|
|
17
|
+
return {field_name: value for field_name, value in self if value is not None}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
__all__ = ('UpdateParams',)
|