narabi-orm 0.1.0__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.
- narabi/__init__.py +27 -0
- narabi/__main__.py +5 -0
- narabi/cli.py +338 -0
- narabi/console.py +102 -0
- narabi/database.py +310 -0
- narabi/fields/__init__.py +13 -0
- narabi/fields/defaults.py +59 -0
- narabi/fields/markers.py +74 -0
- narabi/migrations/__init__.py +22 -0
- narabi/migrations/bootstrap.py +30 -0
- narabi/migrations/decorators.py +22 -0
- narabi/migrations/diff.py +96 -0
- narabi/migrations/dsl.py +255 -0
- narabi/migrations/errors.py +5 -0
- narabi/migrations/executor.py +299 -0
- narabi/migrations/generate.py +149 -0
- narabi/migrations/historical.py +158 -0
- narabi/migrations/history.py +160 -0
- narabi/migrations/models.py +57 -0
- narabi/migrations/postgres_executor.py +239 -0
- narabi/migrations/postgresql.py +268 -0
- narabi/migrations/preview.py +150 -0
- narabi/migrations/replay.py +40 -0
- narabi/migrations/reverse.py +127 -0
- narabi/migrations/schema.py +169 -0
- narabi/migrations/snapshot.py +52 -0
- narabi/migrations/sqlite.py +131 -0
- narabi/models/__init__.py +1 -0
- narabi/models/bulk.py +123 -0
- narabi/models/core.py +440 -0
- narabi/models/inflection.py +37 -0
- narabi/models/lifecycle.py +125 -0
- narabi/models/privacy.py +19 -0
- narabi/models/serialization.py +145 -0
- narabi/models/soft_delete.py +59 -0
- narabi/models/timestamps.py +47 -0
- narabi/models/validation.py +149 -0
- narabi/models/values.py +167 -0
- narabi/project.py +108 -0
- narabi/py.typed +0 -0
- narabi/pytest.py +11 -0
- narabi/query/__init__.py +7 -0
- narabi/query/expressions.py +180 -0
- narabi/query/relation.py +562 -0
- narabi/query/scopes.py +36 -0
- narabi/relations/__init__.py +6 -0
- narabi/relations/prefetch.py +66 -0
- narabi/relations/references.py +196 -0
- narabi/relations/relationships.py +185 -0
- narabi/schema.py +132 -0
- narabi/stubs.py +275 -0
- narabi_orm-0.1.0.dist-info/METADATA +104 -0
- narabi_orm-0.1.0.dist-info/RECORD +56 -0
- narabi_orm-0.1.0.dist-info/WHEEL +4 -0
- narabi_orm-0.1.0.dist-info/entry_points.txt +2 -0
- narabi_orm-0.1.0.dist-info/licenses/LICENSE +29 -0
narabi/query/relation.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
"""Lazy queries for persistent models."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Coroutine, Generator
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Generic, Self, TypeVar
|
|
6
|
+
|
|
7
|
+
import attrs
|
|
8
|
+
|
|
9
|
+
from ..database import Database, default_database, identifier
|
|
10
|
+
from ..models.serialization import from_values
|
|
11
|
+
from ..models.timestamps import encode_datetime
|
|
12
|
+
from ..relations.references import cached_relationship, clear_relationship_cache, reference_for, require_lazy_loading
|
|
13
|
+
from .expressions import Aggregate, Descending, Field, Operand, Predicate, _as_field, compile_predicate
|
|
14
|
+
from .scopes import Scope
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from ..relations.prefetch import Include
|
|
18
|
+
from ..relations.relationships import HasMany
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
S = TypeVar("S")
|
|
23
|
+
P = TypeVar("P")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@attrs.frozen
|
|
27
|
+
class _Scalar(Generic[S]):
|
|
28
|
+
fetch: Callable[[], Coroutine[Any, Any, S]]
|
|
29
|
+
|
|
30
|
+
def __await__(self) -> Generator[Any, None, S]:
|
|
31
|
+
return self.fetch().__await__()
|
|
32
|
+
|
|
33
|
+
def __call__(self) -> Coroutine[Any, Any, S]:
|
|
34
|
+
return self.fetch()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@attrs.frozen
|
|
38
|
+
class _Association:
|
|
39
|
+
parent: Any
|
|
40
|
+
relationship: "HasMany"
|
|
41
|
+
field: str
|
|
42
|
+
key: object
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@attrs.frozen
|
|
46
|
+
class _Through:
|
|
47
|
+
model: type
|
|
48
|
+
source: str
|
|
49
|
+
target: str
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@attrs.frozen
|
|
53
|
+
class _Join:
|
|
54
|
+
name: str
|
|
55
|
+
target: type
|
|
56
|
+
source_field: str
|
|
57
|
+
target_field: str
|
|
58
|
+
kind: str
|
|
59
|
+
through: _Through | None = None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_LINK = "@link"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@attrs.frozen
|
|
66
|
+
class Relation(Generic[T]):
|
|
67
|
+
"""An immutable query that fetches rows when awaited."""
|
|
68
|
+
|
|
69
|
+
model: type[T]
|
|
70
|
+
database: Database | None = None
|
|
71
|
+
filters: tuple[tuple[str, object], ...] = ()
|
|
72
|
+
ordering: tuple[Operand, bool] | None = None
|
|
73
|
+
maximum: int | None = None
|
|
74
|
+
offset: int = 0
|
|
75
|
+
expressions: tuple[Predicate, ...] = ()
|
|
76
|
+
_association: _Association | None = attrs.field(default=None, repr=False, kw_only=True)
|
|
77
|
+
_membership: tuple[str, tuple[object, ...]] | None = attrs.field(default=None, repr=False, kw_only=True)
|
|
78
|
+
_includes: tuple["Include", ...] = ()
|
|
79
|
+
_show_deleted: bool = False
|
|
80
|
+
_joins: tuple[_Join, ...] = ()
|
|
81
|
+
_groups: tuple[str, ...] = ()
|
|
82
|
+
_having: tuple[Predicate, ...] = ()
|
|
83
|
+
_strict_loading: bool = False
|
|
84
|
+
|
|
85
|
+
def strict_loading(self) -> Self:
|
|
86
|
+
"""Require eager loading for associations on the returned records."""
|
|
87
|
+
return attrs.evolve(self, strict_loading=True)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def with_deleted(self) -> Self:
|
|
91
|
+
"""Include rows hidden by a soft-delete table's default filter."""
|
|
92
|
+
return attrs.evolve(self, show_deleted=True)
|
|
93
|
+
|
|
94
|
+
def include(self, *names: str) -> Self:
|
|
95
|
+
"""Preload the named relationships of the returned rows."""
|
|
96
|
+
from ..relations.prefetch import describe_include
|
|
97
|
+
|
|
98
|
+
includes = {item.name: item for item in self._includes}
|
|
99
|
+
for name in names:
|
|
100
|
+
if not isinstance(name, str) or name not in includes:
|
|
101
|
+
item = describe_include(self.model, name)
|
|
102
|
+
includes[item.name] = item
|
|
103
|
+
return attrs.evolve(self, includes=tuple(includes.values()))
|
|
104
|
+
|
|
105
|
+
def _prefetched_collection(self) -> tuple[T, ...] | None:
|
|
106
|
+
association = self._association
|
|
107
|
+
if association is None or (
|
|
108
|
+
self._includes or any(join.name != _LINK for join in self._joins)
|
|
109
|
+
or self._groups or self._show_deleted
|
|
110
|
+
or self.expressions or self.ordering is not None
|
|
111
|
+
or self.maximum is not None or self.offset
|
|
112
|
+
or self.filters != ((association.field, association.key),)
|
|
113
|
+
):
|
|
114
|
+
return None
|
|
115
|
+
cached = cached_relationship(association.parent, association.relationship, association.key, self.database)
|
|
116
|
+
return cached.value if cached is not None else None
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def _unbound(self) -> bool:
|
|
120
|
+
return self._association is not None and self._association.key is None
|
|
121
|
+
|
|
122
|
+
async def create(self, **values: object) -> T:
|
|
123
|
+
"""Create a row linked to the saved record that owns this relationship."""
|
|
124
|
+
association = self._association
|
|
125
|
+
if association is None:
|
|
126
|
+
raise TypeError("Relation.create() requires a relationship")
|
|
127
|
+
if association.field.startswith(f"{_LINK}."):
|
|
128
|
+
raise TypeError("Create the link through its model")
|
|
129
|
+
state = getattr(association.parent, "_record_state", None)
|
|
130
|
+
if self._unbound or state is None or state.key != association.key or state.database is not self.database:
|
|
131
|
+
raise ValueError("Relationship creation requires a saved parent")
|
|
132
|
+
alias = attrs.fields_dict(self.model)[association.field].alias
|
|
133
|
+
if alias in values:
|
|
134
|
+
raise ValueError(f"The relationship sets {alias}")
|
|
135
|
+
result = await self.model.create(db=self.database, **{alias: association.key, **values})
|
|
136
|
+
clear_relationship_cache(association.parent)
|
|
137
|
+
return result
|
|
138
|
+
|
|
139
|
+
def __getattr__(self, name: str) -> Any:
|
|
140
|
+
model = object.__getattribute__(self, "model")
|
|
141
|
+
for base in model.__mro__:
|
|
142
|
+
if name in vars(base):
|
|
143
|
+
member = vars(base)[name]
|
|
144
|
+
if isinstance(member, Scope):
|
|
145
|
+
return member.bind(self)
|
|
146
|
+
break
|
|
147
|
+
raise AttributeError(name)
|
|
148
|
+
|
|
149
|
+
def join(self, *names: str, kind: str = "inner") -> Self:
|
|
150
|
+
"""Join associations so their fields can be used in queries."""
|
|
151
|
+
from ..relations.relationships import describe_join
|
|
152
|
+
|
|
153
|
+
if kind not in ("inner", "left"):
|
|
154
|
+
raise ValueError("Join kind must be 'inner' or 'left'")
|
|
155
|
+
joins = {join.name: join for join in self._joins}
|
|
156
|
+
for name in names:
|
|
157
|
+
if not isinstance(name, str):
|
|
158
|
+
raise TypeError("join() expects relationship names")
|
|
159
|
+
if name in joins:
|
|
160
|
+
if joins[name].kind != kind:
|
|
161
|
+
raise ValueError(f"Conflicting join kinds for {name!r}")
|
|
162
|
+
continue
|
|
163
|
+
target, source_field, target_field, through = describe_join(self.model, name)
|
|
164
|
+
joins[name] = _Join(name, target, source_field, target_field, kind, through)
|
|
165
|
+
return attrs.evolve(self, joins=tuple(joins.values()))
|
|
166
|
+
|
|
167
|
+
def _through(self, link: _Through) -> Self:
|
|
168
|
+
join = _Join(_LINK, link.model, self.model._record_key, link.target, "inner")
|
|
169
|
+
return attrs.evolve(self, joins=(join,))
|
|
170
|
+
|
|
171
|
+
async def _through_records(self, link: _Through, keys, database: Database):
|
|
172
|
+
field = f"{_LINK}.{link.source}"
|
|
173
|
+
relation = attrs.evolve(self._through(link), membership=(field, keys))
|
|
174
|
+
columns = ", ".join(map(relation._field, (field, *self.model._record_columns)))
|
|
175
|
+
sql, params = relation._select(database, columns)
|
|
176
|
+
rows = await database.execute(sql, params, fetch=True)
|
|
177
|
+
return [(key, self.model._record_from_row(row, database)) for key, *row in rows]
|
|
178
|
+
|
|
179
|
+
def _field_owner(self, path):
|
|
180
|
+
association, dot, name = path.partition(".")
|
|
181
|
+
if (
|
|
182
|
+
not dot or association in self.model._record_value_fields
|
|
183
|
+
or path in self.model._record_columns.values()
|
|
184
|
+
):
|
|
185
|
+
return self.model, path, "_narabi_root" if self._joins else None
|
|
186
|
+
for index, join in enumerate(self._joins):
|
|
187
|
+
if join.name == association:
|
|
188
|
+
return join.target, name, f"_narabi_join_{index}"
|
|
189
|
+
raise ValueError(f"Unknown joined association: {association}")
|
|
190
|
+
|
|
191
|
+
def _field(self, path):
|
|
192
|
+
model, name, alias = self._field_owner(path)
|
|
193
|
+
columns = model._record_columns
|
|
194
|
+
if name in columns:
|
|
195
|
+
name = columns[name]
|
|
196
|
+
elif name not in columns.values():
|
|
197
|
+
raise ValueError(f"Unknown field: {path}")
|
|
198
|
+
column = identifier(name)
|
|
199
|
+
return f"{identifier(alias)}.{column}" if alias else column
|
|
200
|
+
|
|
201
|
+
def _operand(self, operand: Operand, *, aggregates: bool = False) -> str:
|
|
202
|
+
if isinstance(operand, Field):
|
|
203
|
+
return self._field(operand._path)
|
|
204
|
+
if isinstance(operand, Aggregate) and aggregates:
|
|
205
|
+
if operand._function not in ("COUNT", "SUM", "AVG"):
|
|
206
|
+
raise ValueError("Unknown aggregate function")
|
|
207
|
+
column = self._field(operand._field._path) if operand._field is not None else "*"
|
|
208
|
+
return f"{operand._function}({column})"
|
|
209
|
+
raise ValueError("Aggregate expressions require rows(), grouped ordering, or HAVING")
|
|
210
|
+
|
|
211
|
+
def _field_value(self, name, value):
|
|
212
|
+
model, name, _ = self._field_owner(name)
|
|
213
|
+
reference = reference_for(model, name)
|
|
214
|
+
if reference is None and name in model._record_columns.values():
|
|
215
|
+
name = next(path for path, column in model._record_columns.items() if column == name)
|
|
216
|
+
reference = model._record_references.get(name)
|
|
217
|
+
return reference.key(value) if reference is not None else value
|
|
218
|
+
|
|
219
|
+
def _value_columns(self, path):
|
|
220
|
+
model, name, _ = self._field_owner(path)
|
|
221
|
+
return model._record_value_fields.get(name)
|
|
222
|
+
|
|
223
|
+
def where(self, *predicates: Predicate, **values: object) -> Self:
|
|
224
|
+
filters = []
|
|
225
|
+
for name, value in values.items():
|
|
226
|
+
if self._value_columns(name) is None:
|
|
227
|
+
self._field(name)
|
|
228
|
+
value = self._field_value(name, value)
|
|
229
|
+
filters.append((name, value))
|
|
230
|
+
if any(not isinstance(predicate, Predicate) for predicate in predicates):
|
|
231
|
+
raise TypeError("where() expects query predicates")
|
|
232
|
+
return attrs.evolve(
|
|
233
|
+
self, filters=self.filters + tuple(filters),
|
|
234
|
+
expressions=self.expressions + predicates,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
def order_by(self, name: str | Field | Aggregate | Descending, *, descending: bool = False) -> Self:
|
|
238
|
+
if isinstance(name, Descending):
|
|
239
|
+
name, descending = name.field, True
|
|
240
|
+
operand = Field(name) if isinstance(name, str) else name
|
|
241
|
+
self._operand(operand, aggregates=True)
|
|
242
|
+
return attrs.evolve(self, ordering=(operand, descending))
|
|
243
|
+
|
|
244
|
+
def group_by(self, *fields: str | Field) -> Self:
|
|
245
|
+
"""Group rows by the given fields."""
|
|
246
|
+
groups = (*self._groups, *(_as_field(field)._path for field in fields))
|
|
247
|
+
for name in groups:
|
|
248
|
+
self._field(name)
|
|
249
|
+
return attrs.evolve(self, groups=tuple(dict.fromkeys(groups)))
|
|
250
|
+
|
|
251
|
+
def having(self, *predicates: Predicate) -> Self:
|
|
252
|
+
"""Filter groups after aggregation."""
|
|
253
|
+
if not self._groups:
|
|
254
|
+
raise ValueError("having() requires group_by()")
|
|
255
|
+
if any(not isinstance(predicate, Predicate) for predicate in predicates):
|
|
256
|
+
raise TypeError("having() expects query predicates")
|
|
257
|
+
return attrs.evolve(self, having=self._having + predicates)
|
|
258
|
+
|
|
259
|
+
def limit(self, amount: int) -> Self:
|
|
260
|
+
if type(amount) is not int or amount < 0:
|
|
261
|
+
raise ValueError("Limit must be a nonnegative integer")
|
|
262
|
+
return attrs.evolve(self, maximum=amount)
|
|
263
|
+
|
|
264
|
+
def __getitem__(self, selection: slice) -> Self:
|
|
265
|
+
if not isinstance(selection, slice):
|
|
266
|
+
raise TypeError("Relations support slicing with start and stop")
|
|
267
|
+
if selection.step is not None and (type(selection.step) is not int or selection.step != 1):
|
|
268
|
+
raise ValueError("Relation slice step must be 1")
|
|
269
|
+
for bound in (selection.start, selection.stop):
|
|
270
|
+
if bound is not None and (type(bound) is not int or bound < 0):
|
|
271
|
+
raise ValueError("Relation slice bounds must be nonnegative integers")
|
|
272
|
+
start = selection.start if selection.start is not None else 0
|
|
273
|
+
stop = selection.stop
|
|
274
|
+
if self.maximum is not None:
|
|
275
|
+
start = min(start, self.maximum)
|
|
276
|
+
stop = self.maximum if stop is None else min(stop, self.maximum)
|
|
277
|
+
maximum = None if stop is None else max(0, stop - start)
|
|
278
|
+
return attrs.evolve(self, offset=self.offset + start, maximum=maximum)
|
|
279
|
+
|
|
280
|
+
def _select(self, database: Database, columns: str | None = None, *, aggregate_rows=False, generic_plan=False):
|
|
281
|
+
if self._association is not None:
|
|
282
|
+
require_lazy_loading(self._association.parent, self._association.relationship.name)
|
|
283
|
+
if columns is None:
|
|
284
|
+
columns = ", ".join(map(self._field, self.model._record_columns))
|
|
285
|
+
sql = f"SELECT {columns} FROM {self.model._record_table}"
|
|
286
|
+
if self._joins:
|
|
287
|
+
sql += ' AS "_narabi_root"'
|
|
288
|
+
join_keys = []
|
|
289
|
+
for index, join in enumerate(self._joins):
|
|
290
|
+
alias = identifier(f"_narabi_join_{index}")
|
|
291
|
+
source = self._field(join.source_field)
|
|
292
|
+
target = self._field(f"{join.name}.{join.target_field}")
|
|
293
|
+
target_table = f"{join.target._record_table} AS {alias}"
|
|
294
|
+
target_deleted = self._visible_join(join.target, alias)
|
|
295
|
+
if join.through is None:
|
|
296
|
+
condition = f"{source} = {target}{target_deleted}"
|
|
297
|
+
else:
|
|
298
|
+
link = join.through
|
|
299
|
+
link_alias = identifier(f"_narabi_link_{index}")
|
|
300
|
+
link_source = identifier(link.model._record_columns[link.source])
|
|
301
|
+
link_target = identifier(link.model._record_columns[link.target])
|
|
302
|
+
link_table = f"{link.model._record_table} AS {link_alias}"
|
|
303
|
+
target_table = (
|
|
304
|
+
f"({link_table} INNER JOIN {target_table} "
|
|
305
|
+
f"ON {link_alias}.{link_target} = {target}{target_deleted})"
|
|
306
|
+
)
|
|
307
|
+
condition = f"{source} = {link_alias}.{link_source}{self._visible_join(link.model, link_alias)}"
|
|
308
|
+
join_keys.append(f"{link_alias}.{identifier(link.model._record_columns[link.model._record_key])}")
|
|
309
|
+
sql += f" {join.kind.upper()} JOIN {target_table} ON {condition}"
|
|
310
|
+
join_keys.append(self._field(f"{join.name}.{join.target._record_key}"))
|
|
311
|
+
params = []
|
|
312
|
+
|
|
313
|
+
def bind(value):
|
|
314
|
+
params.append(value)
|
|
315
|
+
return f"${len(params)}" if generic_plan else database.placeholder
|
|
316
|
+
|
|
317
|
+
def field_parameter(name, value):
|
|
318
|
+
value = self._field_value(name, value)
|
|
319
|
+
model, field, _ = self._field_owner(name)
|
|
320
|
+
if field in model._record_columns.values() and field not in model._record_columns:
|
|
321
|
+
field = next(path for path, column in model._record_columns.items() if column == field)
|
|
322
|
+
parent, dot, component = field.partition(".")
|
|
323
|
+
if dot and parent in model._record_value_fields:
|
|
324
|
+
return model._record_value_fields[parent].unpack_component(component, value, database.backend)
|
|
325
|
+
if field in model._record_managed_fields:
|
|
326
|
+
value = encode_datetime(value, database.backend)
|
|
327
|
+
return value
|
|
328
|
+
|
|
329
|
+
def compare_value(path, operator, value):
|
|
330
|
+
mapping = self._value_columns(path)
|
|
331
|
+
if mapping is None:
|
|
332
|
+
return None
|
|
333
|
+
if operator not in ("=", "<>") or isinstance(value, Operand):
|
|
334
|
+
raise ValueError("Whole-value predicates require equality or inequality with a value or None")
|
|
335
|
+
qualifier = path[:-len(mapping.name)]
|
|
336
|
+
if value is None:
|
|
337
|
+
parts = [f"{self._field(qualifier + name)} IS NULL" for name in mapping.paths]
|
|
338
|
+
else:
|
|
339
|
+
parts = [
|
|
340
|
+
f"{self._field(qualifier + name)} = {bind(component)}"
|
|
341
|
+
for name, component in mapping.unpack(value, database.backend).items()
|
|
342
|
+
]
|
|
343
|
+
combined = "(" + " AND ".join(parts) + ")"
|
|
344
|
+
return combined if operator == "=" else f"NOT {combined}"
|
|
345
|
+
|
|
346
|
+
predicates = []
|
|
347
|
+
for name, value in self.filters:
|
|
348
|
+
expanded = compare_value(name, "=", value)
|
|
349
|
+
if expanded is not None:
|
|
350
|
+
predicates.append(expanded)
|
|
351
|
+
elif value is None:
|
|
352
|
+
predicates.append(f"{self._field(name)} IS NULL")
|
|
353
|
+
else:
|
|
354
|
+
predicates.append(f"{self._field(name)} = {bind(field_parameter(name, value))}")
|
|
355
|
+
predicates.extend(
|
|
356
|
+
compile_predicate(expression, self._operand, bind, database.backend, field_parameter, compare_value)
|
|
357
|
+
for expression in self.expressions
|
|
358
|
+
)
|
|
359
|
+
if self._membership is not None:
|
|
360
|
+
name, values = self._membership
|
|
361
|
+
placeholders = ", ".join(map(bind, values))
|
|
362
|
+
predicates.append(f"{self._field(name)} IN ({placeholders})")
|
|
363
|
+
if getattr(self.model, "_record_soft_delete", False) and not self._show_deleted:
|
|
364
|
+
predicates.append(f"{self._field('deleted_at')} IS NULL")
|
|
365
|
+
if predicates:
|
|
366
|
+
sql += " WHERE " + " AND ".join(predicates)
|
|
367
|
+
group_columns = tuple(dict.fromkeys(map(self._field, self._groups)))
|
|
368
|
+
if group_columns:
|
|
369
|
+
sql += " GROUP BY " + ", ".join(group_columns)
|
|
370
|
+
if self._having:
|
|
371
|
+
sql += " HAVING " + " AND ".join(
|
|
372
|
+
compile_predicate(expression, self._group_operand, bind, database.backend, field_parameter,
|
|
373
|
+
self._group_value_comparison)
|
|
374
|
+
for expression in self._having
|
|
375
|
+
)
|
|
376
|
+
ordering = []
|
|
377
|
+
explicit = None
|
|
378
|
+
if self.ordering is not None:
|
|
379
|
+
operand, descending = self.ordering
|
|
380
|
+
if group_columns or aggregate_rows:
|
|
381
|
+
explicit = self._group_operand(operand)
|
|
382
|
+
else:
|
|
383
|
+
explicit = self._operand(operand)
|
|
384
|
+
ordering.append(f"{explicit} " + ("DESC" if descending else "ASC"))
|
|
385
|
+
defaults = group_columns
|
|
386
|
+
if not group_columns and not aggregate_rows:
|
|
387
|
+
defaults = (self._field(self.model._record_key), *join_keys)
|
|
388
|
+
ordering.extend(f"{name} ASC" for name in defaults if name != explicit)
|
|
389
|
+
if ordering:
|
|
390
|
+
sql += " ORDER BY " + ", ".join(ordering)
|
|
391
|
+
if self.maximum is not None:
|
|
392
|
+
sql += f" LIMIT {bind(self.maximum)}"
|
|
393
|
+
elif self.offset and database.backend == "sqlite":
|
|
394
|
+
sql += " LIMIT -1"
|
|
395
|
+
if self.offset:
|
|
396
|
+
sql += f" OFFSET {bind(self.offset)}"
|
|
397
|
+
return sql, params
|
|
398
|
+
|
|
399
|
+
def _visible_join(self, model, alias):
|
|
400
|
+
if getattr(model, "_record_soft_delete", False) and not self._show_deleted:
|
|
401
|
+
return f" AND {alias}.{identifier(model._record_columns['deleted_at'])} IS NULL"
|
|
402
|
+
return ""
|
|
403
|
+
|
|
404
|
+
def _group_operand(self, operand: Operand) -> str:
|
|
405
|
+
sql = self._operand(operand, aggregates=True)
|
|
406
|
+
if isinstance(operand, Field) and sql not in map(self._field, self._groups):
|
|
407
|
+
raise ValueError(f"Field must appear in group_by(): {operand._path}")
|
|
408
|
+
return sql
|
|
409
|
+
|
|
410
|
+
def _group_value_comparison(self, path, operator, value):
|
|
411
|
+
if self._value_columns(path) is not None:
|
|
412
|
+
raise ValueError("Use component predicates in having()")
|
|
413
|
+
return None
|
|
414
|
+
|
|
415
|
+
def _inspection_query(self, *, explain=False):
|
|
416
|
+
if self._groups:
|
|
417
|
+
raise ValueError("Grouped relations require a rows() projection")
|
|
418
|
+
if self._unbound:
|
|
419
|
+
raise ValueError("An unbound relation has no SQL query")
|
|
420
|
+
database = self.database if self.database is not None else default_database()
|
|
421
|
+
sql, params = self._select(database, generic_plan=explain and database.backend == "postgresql")
|
|
422
|
+
return database, sql, params
|
|
423
|
+
|
|
424
|
+
def to_sql(self) -> str:
|
|
425
|
+
"""Return the relation's SELECT with backend placeholders."""
|
|
426
|
+
_, sql, _ = self._inspection_query()
|
|
427
|
+
return sql
|
|
428
|
+
|
|
429
|
+
async def explain(self):
|
|
430
|
+
"""Return the estimated plan. PostgreSQL requires version 16 or newer."""
|
|
431
|
+
database, sql, params = self._inspection_query(explain=True)
|
|
432
|
+
if database.backend == "postgresql":
|
|
433
|
+
return await database.execute(f"EXPLAIN (GENERIC_PLAN TRUE) {sql}", fetch=True)
|
|
434
|
+
return await database.execute(f"EXPLAIN QUERY PLAN {sql}", params, fetch=True)
|
|
435
|
+
|
|
436
|
+
def __await__(self) -> Generator[Any, None, list[T]]:
|
|
437
|
+
return self.all().__await__()
|
|
438
|
+
|
|
439
|
+
def _mark_strict(self, records):
|
|
440
|
+
if self._strict_loading:
|
|
441
|
+
for record in records:
|
|
442
|
+
record._record_strict_loading = True
|
|
443
|
+
|
|
444
|
+
async def all(self) -> list[T]:
|
|
445
|
+
if self._groups:
|
|
446
|
+
raise ValueError("Use rows() to fetch grouped results")
|
|
447
|
+
if self._unbound:
|
|
448
|
+
return []
|
|
449
|
+
prefetched = self._prefetched_collection()
|
|
450
|
+
if prefetched is not None:
|
|
451
|
+
self._mark_strict(prefetched)
|
|
452
|
+
return list(prefetched)
|
|
453
|
+
database = self.database if self.database is not None else default_database()
|
|
454
|
+
sql, params = self._select(database)
|
|
455
|
+
rows = await database.execute(sql, params, fetch=True)
|
|
456
|
+
records = [self.model._record_from_row(row, database) for row in rows]
|
|
457
|
+
self._mark_strict(records)
|
|
458
|
+
for include in self._includes:
|
|
459
|
+
await include.load(records, database, strict=self._strict_loading)
|
|
460
|
+
return records
|
|
461
|
+
|
|
462
|
+
async def select(self, target: type[P]) -> list[P]:
|
|
463
|
+
"""Fetch just the columns declared by a data record."""
|
|
464
|
+
if self._groups:
|
|
465
|
+
raise ValueError("Use rows() to fetch grouped results")
|
|
466
|
+
if not isinstance(target, type) or "_record_metadata" not in vars(target) or hasattr(target, "_record_key"):
|
|
467
|
+
raise TypeError("select() expects a non-persistent @record class")
|
|
468
|
+
names = tuple(field.name for field in attrs.fields(target) if field.init)
|
|
469
|
+
mappings = self.model._record_value_fields
|
|
470
|
+
paths = tuple(path for name in names for path in (mappings[name].paths if name in mappings else (name,)))
|
|
471
|
+
columns = ", ".join(map(self._field, paths)) or "1"
|
|
472
|
+
if self._unbound:
|
|
473
|
+
return []
|
|
474
|
+
database = self.database if self.database is not None else default_database()
|
|
475
|
+
sql, params = self._select(database, columns)
|
|
476
|
+
rows = await database.execute(sql, params, fetch=True)
|
|
477
|
+
results = []
|
|
478
|
+
for row in rows:
|
|
479
|
+
values = dict(zip(paths, row))
|
|
480
|
+
for name in names:
|
|
481
|
+
if name in mappings:
|
|
482
|
+
mapping = mappings[name]
|
|
483
|
+
values[name] = mapping.load({path: values.pop(path) for path in mapping.paths})
|
|
484
|
+
results.append(from_values(target, values))
|
|
485
|
+
return results
|
|
486
|
+
|
|
487
|
+
async def rows(self, **expressions: str | Field | Aggregate) -> list[dict[str, Any]]:
|
|
488
|
+
"""Fetch named SQL expressions as dictionaries."""
|
|
489
|
+
if not expressions:
|
|
490
|
+
raise ValueError("rows() requires at least one named expression")
|
|
491
|
+
operands = tuple(Field(value) if isinstance(value, str) else value for value in expressions.values())
|
|
492
|
+
aggregate_rows = any(isinstance(operand, Aggregate) for operand in operands)
|
|
493
|
+
render = self._group_operand if self._groups or aggregate_rows else self._operand
|
|
494
|
+
columns = ", ".join(map(render, operands))
|
|
495
|
+
if self._unbound:
|
|
496
|
+
return []
|
|
497
|
+
database = self.database if self.database is not None else default_database()
|
|
498
|
+
sql, params = self._select(database, columns, aggregate_rows=aggregate_rows)
|
|
499
|
+
rows = await database.execute(sql, params, fetch=True)
|
|
500
|
+
return [dict(zip(expressions, row)) for row in rows]
|
|
501
|
+
|
|
502
|
+
async def first(self) -> T | None:
|
|
503
|
+
prefetched = self._prefetched_collection()
|
|
504
|
+
if prefetched is not None:
|
|
505
|
+
rows = prefetched[:1]
|
|
506
|
+
self._mark_strict(rows)
|
|
507
|
+
else:
|
|
508
|
+
rows = await self.limit(0 if self.maximum == 0 else 1).all()
|
|
509
|
+
return rows[0] if rows else None
|
|
510
|
+
|
|
511
|
+
@property
|
|
512
|
+
def count(self) -> _Scalar[int]:
|
|
513
|
+
return _Scalar(self._count)
|
|
514
|
+
|
|
515
|
+
@property
|
|
516
|
+
def exists(self) -> _Scalar[bool]:
|
|
517
|
+
return _Scalar(self._exists)
|
|
518
|
+
|
|
519
|
+
async def _count(self) -> int:
|
|
520
|
+
if self._unbound:
|
|
521
|
+
return 0
|
|
522
|
+
prefetched = self._prefetched_collection()
|
|
523
|
+
return len(prefetched) if prefetched is not None else await self._aggregate("COUNT(*)")
|
|
524
|
+
|
|
525
|
+
async def _exists(self) -> bool:
|
|
526
|
+
if self._unbound:
|
|
527
|
+
return False
|
|
528
|
+
prefetched = self._prefetched_collection()
|
|
529
|
+
if prefetched is not None:
|
|
530
|
+
return bool(prefetched)
|
|
531
|
+
database = self.database if self.database is not None else default_database()
|
|
532
|
+
sql, params = self._select(database, "1")
|
|
533
|
+
rows = await database.execute(f"SELECT EXISTS ({sql})", params, fetch=True)
|
|
534
|
+
return bool(rows[0][0])
|
|
535
|
+
|
|
536
|
+
async def avg(self, field: str | Field) -> float | Decimal | None:
|
|
537
|
+
if self._groups:
|
|
538
|
+
raise ValueError("Use rows() to fetch grouped aggregates")
|
|
539
|
+
column = self._field(_as_field(field)._path)
|
|
540
|
+
return await self._aggregate("AVG", column)
|
|
541
|
+
|
|
542
|
+
async def sum(self, field: str | Field) -> int | float | Decimal | None:
|
|
543
|
+
if self._groups:
|
|
544
|
+
raise ValueError("Use rows() to fetch grouped aggregates")
|
|
545
|
+
column = self._field(_as_field(field)._path)
|
|
546
|
+
return await self._aggregate("SUM", column)
|
|
547
|
+
|
|
548
|
+
async def _aggregate(self, expression: str, column: str = "1") -> Any:
|
|
549
|
+
if self._unbound:
|
|
550
|
+
return None
|
|
551
|
+
database = self.database if self.database is not None else default_database()
|
|
552
|
+
if column != "1":
|
|
553
|
+
if self._joins:
|
|
554
|
+
column += ' AS "_narabi_value"'
|
|
555
|
+
expression = f'{expression}("_narabi_value")'
|
|
556
|
+
else:
|
|
557
|
+
expression = f"{expression}({column})"
|
|
558
|
+
sql, params = self._select(database, column)
|
|
559
|
+
rows = await database.execute(
|
|
560
|
+
f"SELECT {expression} FROM ({sql}) AS records", params, fetch=True,
|
|
561
|
+
)
|
|
562
|
+
return rows[0][0]
|
narabi/query/scopes.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Reusable transformations of model relations."""
|
|
2
|
+
|
|
3
|
+
from functools import partial
|
|
4
|
+
from inspect import Parameter, iscoroutinefunction, signature
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Scope:
|
|
8
|
+
def __init__(self, function):
|
|
9
|
+
parameters = tuple(signature(function).parameters.values())
|
|
10
|
+
if iscoroutinefunction(function) or not parameters or parameters[0].kind not in (
|
|
11
|
+
Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD,
|
|
12
|
+
):
|
|
13
|
+
raise TypeError("@scope expects a synchronous function with a relation parameter")
|
|
14
|
+
self.function = function
|
|
15
|
+
self.is_property = len(parameters) == 1
|
|
16
|
+
|
|
17
|
+
def bind(self, relation):
|
|
18
|
+
if self.is_property:
|
|
19
|
+
return self.apply(relation)
|
|
20
|
+
return partial(self.apply, relation)
|
|
21
|
+
|
|
22
|
+
def apply(self, relation, /, *args, **kwargs):
|
|
23
|
+
result = self.function(relation, *args, **kwargs)
|
|
24
|
+
if not isinstance(result, type(relation)) or result.model is not relation.model:
|
|
25
|
+
raise TypeError(f"Scope {self.function.__name__} must return a relation for the same model")
|
|
26
|
+
return result
|
|
27
|
+
|
|
28
|
+
def __get__(self, instance, owner):
|
|
29
|
+
from .relation import Relation
|
|
30
|
+
|
|
31
|
+
return self.bind(Relation(owner))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def scope(function):
|
|
35
|
+
"""Expose a synchronous relation transform on its model and relations."""
|
|
36
|
+
return Scope(function)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Fetch relationships in batches for a set of loaded records."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from inspect import getattr_static
|
|
7
|
+
from itertools import batched
|
|
8
|
+
|
|
9
|
+
from .references import ReferenceField, cache_relationship, field_value
|
|
10
|
+
from ..query.relation import Relation, _Through
|
|
11
|
+
from .relationships import HasMany
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Include:
|
|
16
|
+
name: str
|
|
17
|
+
descriptor: ReferenceField | HasMany | Callable
|
|
18
|
+
target: type
|
|
19
|
+
link: str
|
|
20
|
+
through: _Through | None = None
|
|
21
|
+
source: str | None = None
|
|
22
|
+
|
|
23
|
+
async def load(self, records, database, *, strict=False):
|
|
24
|
+
if self.source is not None:
|
|
25
|
+
keys = [field_value(record, self.source) for record in records]
|
|
26
|
+
else:
|
|
27
|
+
keys = [record._record_state.key for record in records]
|
|
28
|
+
|
|
29
|
+
groups = defaultdict(list)
|
|
30
|
+
unique_keys = dict.fromkeys(key for key in keys if key is not None)
|
|
31
|
+
# Stay under the parameter limit of older SQLite builds.
|
|
32
|
+
for batch in batched(unique_keys, 500):
|
|
33
|
+
if self.through is not None:
|
|
34
|
+
for key, related in await Relation(self.target, database)._through_records(
|
|
35
|
+
self.through, batch, database,
|
|
36
|
+
):
|
|
37
|
+
groups[key].append(related)
|
|
38
|
+
else:
|
|
39
|
+
for related in await Relation(self.target, database, membership=(self.link, batch)):
|
|
40
|
+
groups[field_value(related, self.link)].append(related)
|
|
41
|
+
|
|
42
|
+
for record, key in zip(records, keys):
|
|
43
|
+
matches = groups.get(key, ())
|
|
44
|
+
if strict:
|
|
45
|
+
for match in matches:
|
|
46
|
+
match._record_strict_loading = True
|
|
47
|
+
related = next(iter(matches), None) if self.source is not None else tuple(matches)
|
|
48
|
+
cache_relationship(record, self.descriptor, key, database, related)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def describe_include(model, name: str) -> Include:
|
|
52
|
+
if not isinstance(name, str):
|
|
53
|
+
raise TypeError("include() expects relationship names")
|
|
54
|
+
descriptor = getattr_static(model, name, None)
|
|
55
|
+
if isinstance(descriptor, ReferenceField):
|
|
56
|
+
target = descriptor.target()
|
|
57
|
+
return Include(name, descriptor, target, target._record_key, source=descriptor.name)
|
|
58
|
+
if isinstance(descriptor, HasMany):
|
|
59
|
+
_, target = descriptor.signature(model)
|
|
60
|
+
through = descriptor._link(model, target)
|
|
61
|
+
link = through.source if through is not None else descriptor._field(model, target)
|
|
62
|
+
return Include(name, descriptor, target, link, through)
|
|
63
|
+
if resolver := getattr(descriptor, "_record_join", None):
|
|
64
|
+
target, source = resolver(model)
|
|
65
|
+
return Include(name, descriptor, target, target._record_key, source=source)
|
|
66
|
+
raise ValueError(f"Unknown relationship {model.__name__}.{name}")
|