chickinfry 0.5.0.dev1__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.
- chickinfry/__init__.py +18 -0
- chickinfry/_auth_database.py +765 -0
- chickinfry/_conformance.py +208 -0
- chickinfry/_device.py +1405 -0
- chickinfry/_device_windows.py +250 -0
- chickinfry/_error_details.py +76 -0
- chickinfry/_http_common.py +165 -0
- chickinfry/_input.py +129 -0
- chickinfry/_origin.py +60 -0
- chickinfry/_password.py +38 -0
- chickinfry/_request_logs.py +66 -0
- chickinfry/_request_state.py +32 -0
- chickinfry/_sync_http.py +546 -0
- chickinfry/_sync_network.py +288 -0
- chickinfry/_workerd.py +731 -0
- chickinfry/auth.py +1227 -0
- chickinfry/errors.py +101 -0
- chickinfry/http.py +427 -0
- chickinfry/orm.py +506 -0
- chickinfry/postgres.py +281 -0
- chickinfry/py.typed +0 -0
- chickinfry/realtime.py +522 -0
- chickinfry/server.py +540 -0
- chickinfry/session.py +465 -0
- chickinfry/signup.py +134 -0
- chickinfry/wire.py +23 -0
- chickinfry-0.5.0.dev1.dist-info/METADATA +375 -0
- chickinfry-0.5.0.dev1.dist-info/RECORD +30 -0
- chickinfry-0.5.0.dev1.dist-info/WHEEL +4 -0
- chickinfry-0.5.0.dev1.dist-info/licenses/LICENSE +202 -0
chickinfry/orm.py
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
"""Generated databases connect table definitions and row decoders to repositories.
|
|
2
|
+
|
|
3
|
+
The generator owns the immutable Row/PrimaryKey dataclasses, Insert/Update
|
|
4
|
+
TypedDicts, typed columns, and repositories; this module owns SQL generation
|
|
5
|
+
and execution.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from datetime import date, datetime, timezone
|
|
13
|
+
from types import MappingProxyType
|
|
14
|
+
from typing import Generic, Literal, Protocol, TypeVar
|
|
15
|
+
from uuid import UUID
|
|
16
|
+
|
|
17
|
+
from .server import OperationError
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T")
|
|
20
|
+
R = TypeVar("R")
|
|
21
|
+
ScalarKind = Literal["id", "string", "integer", "date", "timestamp"]
|
|
22
|
+
_DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
|
|
23
|
+
_STAMP = re.compile(
|
|
24
|
+
r"[0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9]{2}:[0-9]{2}:[0-9]{2}"
|
|
25
|
+
r"(?:\.[0-9]{1,6})?(?:Z|[+-][0-9]{2}(?::[0-9]{2})?)"
|
|
26
|
+
)
|
|
27
|
+
_UUID = re.compile(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_date(value: str) -> date:
|
|
31
|
+
if not _DATE.fullmatch(value):
|
|
32
|
+
raise ValueError("Date values must use YYYY-MM-DD.")
|
|
33
|
+
return date.fromisoformat(value)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def parse_timestamp(value: str) -> datetime:
|
|
37
|
+
if not _STAMP.fullmatch(value):
|
|
38
|
+
raise ValueError("Timestamp must include a valid time and timezone.")
|
|
39
|
+
normalized = value.replace(" ", "T")
|
|
40
|
+
normalized = re.sub(r"([+-][0-9]{2})$", r"\1:00", normalized)
|
|
41
|
+
# The standard parser accepts overflowing offset minutes, so reject them here first.
|
|
42
|
+
if normalized[-6:-5] in ("+", "-") and (
|
|
43
|
+
int(normalized[-5:-3]) > 23 or int(normalized[-2:]) > 59
|
|
44
|
+
):
|
|
45
|
+
raise ValueError("Invalid timestamp offset.")
|
|
46
|
+
return datetime.fromisoformat(normalized.replace("Z", "+00:00")).astimezone(
|
|
47
|
+
timezone.utc
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def format_timestamp(value: datetime) -> str:
|
|
52
|
+
if value.tzinfo is None or value.utcoffset() is None:
|
|
53
|
+
raise ValueError("Database timestamps must have a timezone.")
|
|
54
|
+
utc = value.astimezone(timezone.utc)
|
|
55
|
+
fraction = f"{utc.microsecond:06d}".rstrip("0").ljust(3, "0")
|
|
56
|
+
return (
|
|
57
|
+
f"{utc.year:04d}-{utc.month:02d}-{utc.day:02d}T"
|
|
58
|
+
f"{utc.hour:02d}:{utc.minute:02d}:{utc.second:02d}.{fraction}Z"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def encode_value(kind: ScalarKind, nullable: bool, value: object) -> object:
|
|
63
|
+
if value is None:
|
|
64
|
+
if nullable:
|
|
65
|
+
return None
|
|
66
|
+
raise ValueError("A non-null column cannot accept null.")
|
|
67
|
+
if kind == "integer":
|
|
68
|
+
if type(value) is not int or not -2147483648 <= value <= 2147483647:
|
|
69
|
+
raise ValueError("Integer values must be signed 32-bit integers.")
|
|
70
|
+
return value
|
|
71
|
+
if not isinstance(value, str):
|
|
72
|
+
raise ValueError("A string value is required.")
|
|
73
|
+
if kind == "string":
|
|
74
|
+
if "\0" in value:
|
|
75
|
+
raise ValueError("A text column cannot contain NUL.")
|
|
76
|
+
return value
|
|
77
|
+
if kind == "id":
|
|
78
|
+
if not _UUID.fullmatch(value):
|
|
79
|
+
raise ValueError("An ID column requires a UUID.")
|
|
80
|
+
return UUID(value)
|
|
81
|
+
if kind == "date":
|
|
82
|
+
return parse_date(value)
|
|
83
|
+
if kind == "timestamp":
|
|
84
|
+
return parse_timestamp(value)
|
|
85
|
+
raise ValueError("Unsupported scalar kind.")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def decode_value(kind: ScalarKind, nullable: bool, value: object) -> object:
|
|
89
|
+
if (
|
|
90
|
+
sys.platform == "emscripten"
|
|
91
|
+
and isinstance(value, str)
|
|
92
|
+
and kind in ("id", "date", "timestamp")
|
|
93
|
+
):
|
|
94
|
+
value = encode_value(kind, nullable, value)
|
|
95
|
+
if value is None:
|
|
96
|
+
return encode_value(kind, nullable, value)
|
|
97
|
+
if kind == "date":
|
|
98
|
+
if type(value) is not date:
|
|
99
|
+
raise ValueError("Database dates must decode to dates.")
|
|
100
|
+
return value.isoformat()
|
|
101
|
+
if kind == "timestamp":
|
|
102
|
+
if not isinstance(value, datetime):
|
|
103
|
+
raise ValueError("Database timestamps must decode to datetimes.")
|
|
104
|
+
return format_timestamp(value)
|
|
105
|
+
if kind == "id":
|
|
106
|
+
if not isinstance(value, UUID):
|
|
107
|
+
raise ValueError("Database IDs must decode to UUIDs.")
|
|
108
|
+
return str(value)
|
|
109
|
+
return encode_value(kind, nullable, value)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class DatabasePort(Protocol):
|
|
113
|
+
async def query(
|
|
114
|
+
self, sql: str, parameters: Sequence[object]
|
|
115
|
+
) -> Sequence[Mapping[str, object]]: ...
|
|
116
|
+
|
|
117
|
+
async def transaction(
|
|
118
|
+
self, work: Callable[["DatabasePort"], Awaitable[T]]
|
|
119
|
+
) -> T: ...
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Database(Generic[T]):
|
|
123
|
+
"""Generated database subclasses pass their own constructor as the factory."""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self, port: DatabasePort, create_database: Callable[[DatabasePort], T]
|
|
127
|
+
) -> None:
|
|
128
|
+
self._port, self._create_database = port, create_database
|
|
129
|
+
|
|
130
|
+
async def transaction(self, work: Callable[[T], Awaitable[R]]) -> R:
|
|
131
|
+
async def run(port: DatabasePort) -> R:
|
|
132
|
+
return await work(self._create_database(port))
|
|
133
|
+
|
|
134
|
+
return await self._port.transaction(run)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True, slots=True, eq=False)
|
|
138
|
+
class ColumnBase:
|
|
139
|
+
name: str
|
|
140
|
+
kind: ScalarKind
|
|
141
|
+
nullable: bool = False
|
|
142
|
+
|
|
143
|
+
def encode(self, value: object) -> object:
|
|
144
|
+
return encode_value(self.kind, self.nullable, value)
|
|
145
|
+
|
|
146
|
+
def decode(self, value: object) -> object:
|
|
147
|
+
return decode_value(self.kind, self.nullable, value)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class Column(ColumnBase, Generic[T]):
|
|
151
|
+
"""Generated columns are declared as Column[scalar] to type-check condition values."""
|
|
152
|
+
|
|
153
|
+
def eq(self, value: T) -> "Filter":
|
|
154
|
+
return Filter("=", self, (value,))
|
|
155
|
+
|
|
156
|
+
def ne(self, value: T) -> "Filter":
|
|
157
|
+
return Filter("<>", self, (value,))
|
|
158
|
+
|
|
159
|
+
def gt(self, value: T) -> "Filter":
|
|
160
|
+
return Filter(">", self, (value,))
|
|
161
|
+
|
|
162
|
+
def gte(self, value: T) -> "Filter":
|
|
163
|
+
return Filter(">=", self, (value,))
|
|
164
|
+
|
|
165
|
+
def lt(self, value: T) -> "Filter":
|
|
166
|
+
return Filter("<", self, (value,))
|
|
167
|
+
|
|
168
|
+
def lte(self, value: T) -> "Filter":
|
|
169
|
+
return Filter("<=", self, (value,))
|
|
170
|
+
|
|
171
|
+
def is_in(self, values: Sequence[T]) -> "Filter":
|
|
172
|
+
if isinstance(values, (str, bytes)) or not isinstance(values, Sequence):
|
|
173
|
+
raise ValueError("IN values must be a sequence.")
|
|
174
|
+
return Filter("in", self, tuple(values))
|
|
175
|
+
|
|
176
|
+
def is_null(self) -> "Filter":
|
|
177
|
+
return Filter("is null", self)
|
|
178
|
+
|
|
179
|
+
def is_not_null(self) -> "Filter":
|
|
180
|
+
return Filter("is not null", self)
|
|
181
|
+
|
|
182
|
+
def asc(self) -> "Order":
|
|
183
|
+
return Order(self, "asc")
|
|
184
|
+
|
|
185
|
+
def desc(self) -> "Order":
|
|
186
|
+
return Order(self, "desc")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass(frozen=True, slots=True)
|
|
190
|
+
class Filter:
|
|
191
|
+
operator: str
|
|
192
|
+
column: ColumnBase | None = None
|
|
193
|
+
values: tuple[object, ...] = ()
|
|
194
|
+
children: tuple["Filter", ...] = ()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@dataclass(frozen=True, slots=True)
|
|
198
|
+
class Order:
|
|
199
|
+
column: ColumnBase
|
|
200
|
+
direction: Literal["asc", "desc"]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def and_(*filters: Filter) -> Filter:
|
|
204
|
+
if not filters:
|
|
205
|
+
raise ValueError("AND requires at least one condition.")
|
|
206
|
+
return Filter("and", children=filters)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def or_(*filters: Filter) -> Filter:
|
|
210
|
+
if not filters:
|
|
211
|
+
raise ValueError("OR requires at least one condition.")
|
|
212
|
+
return Filter("or", children=filters)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def not_(condition: Filter) -> Filter:
|
|
216
|
+
return Filter("not", children=(condition,))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def quote_identifier(value: str) -> str:
|
|
220
|
+
if not isinstance(value, str) or not value or "\0" in value:
|
|
221
|
+
raise ValueError("Invalid SQL identifier.")
|
|
222
|
+
return '"' + value.replace('"', '""') + '"'
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@dataclass(frozen=True, slots=True)
|
|
226
|
+
class Table:
|
|
227
|
+
name: str
|
|
228
|
+
columns: Mapping[str, ColumnBase]
|
|
229
|
+
primary_key: tuple[str, ...]
|
|
230
|
+
required_insert: tuple[str, ...] = ()
|
|
231
|
+
|
|
232
|
+
def __post_init__(self) -> None:
|
|
233
|
+
quote_identifier(self.name)
|
|
234
|
+
columns = dict(self.columns)
|
|
235
|
+
if not columns or not self.primary_key:
|
|
236
|
+
raise ValueError("Tables require columns and a primary key.")
|
|
237
|
+
for keys in (self.primary_key, self.required_insert):
|
|
238
|
+
if len(set(keys)) != len(keys) or any(key not in columns for key in keys):
|
|
239
|
+
raise ValueError("Invalid table column list.")
|
|
240
|
+
names = [column.name for column in columns.values()]
|
|
241
|
+
for name in names:
|
|
242
|
+
quote_identifier(name)
|
|
243
|
+
if len(set(names)) != len(names):
|
|
244
|
+
raise ValueError("Duplicate database column.")
|
|
245
|
+
object.__setattr__(self, "columns", MappingProxyType(columns))
|
|
246
|
+
|
|
247
|
+
def column(self, column: ColumnBase | None) -> ColumnBase:
|
|
248
|
+
if column is None or not any(column is item for item in self.columns.values()):
|
|
249
|
+
raise ValueError("Undeclared table columns cannot be used.")
|
|
250
|
+
return column
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _compile(condition: Filter, table: Table, params: list[object]) -> str:
|
|
254
|
+
if not isinstance(condition, Filter):
|
|
255
|
+
raise ValueError("A typed filter is required.")
|
|
256
|
+
op = condition.operator
|
|
257
|
+
if op in ("and", "or", "not"):
|
|
258
|
+
if not condition.children or (op == "not" and len(condition.children) != 1):
|
|
259
|
+
raise ValueError("Invalid logical filter.")
|
|
260
|
+
parts = [_compile(child, table, params) for child in condition.children]
|
|
261
|
+
return f"not ({parts[0]})" if op == "not" else "(" + f" {op} ".join(parts) + ")"
|
|
262
|
+
column = table.column(condition.column)
|
|
263
|
+
name = quote_identifier(column.name)
|
|
264
|
+
if op in ("is null", "is not null"):
|
|
265
|
+
return f"{name} {op}"
|
|
266
|
+
if op == "in":
|
|
267
|
+
values = [column.encode(value) for value in condition.values]
|
|
268
|
+
if not values:
|
|
269
|
+
return "1 = 0"
|
|
270
|
+
placeholders = []
|
|
271
|
+
for value in values:
|
|
272
|
+
if value is not None:
|
|
273
|
+
params.append(value)
|
|
274
|
+
placeholders.append(f"${len(params)}")
|
|
275
|
+
parts = [f"{name} in ({', '.join(placeholders)})"] if placeholders else []
|
|
276
|
+
if None in values:
|
|
277
|
+
parts.append(f"{name} is null")
|
|
278
|
+
return "(" + " or ".join(parts) + ")"
|
|
279
|
+
if op not in ("=", "<>", ">", ">=", "<", "<=") or len(condition.values) != 1:
|
|
280
|
+
raise ValueError("Unsupported comparison operator.")
|
|
281
|
+
value = column.encode(condition.values[0])
|
|
282
|
+
if value is None:
|
|
283
|
+
if op not in ("=", "<>"):
|
|
284
|
+
raise ValueError("NULL only supports equality comparisons.")
|
|
285
|
+
return f"{name} is {'not ' if op == '<>' else ''}null"
|
|
286
|
+
params.append(value)
|
|
287
|
+
return f"{name} {op} ${len(params)}"
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
class Repository(Generic[R]):
|
|
291
|
+
"""Generated repositories pass input mappings through and decode every column into a Row."""
|
|
292
|
+
|
|
293
|
+
def __init__(
|
|
294
|
+
self, port: DatabasePort, table: Table, row: Callable[[Mapping[str, object]], R]
|
|
295
|
+
) -> None:
|
|
296
|
+
self._port, self.table, self.row = port, table, row
|
|
297
|
+
self._name = '"public".' + quote_identifier(table.name)
|
|
298
|
+
self._select = ", ".join(
|
|
299
|
+
quote_identifier(c.name) for c in table.columns.values()
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
def _rows(self, rows: Sequence[Mapping[str, object]]) -> list[R]:
|
|
303
|
+
return [
|
|
304
|
+
self.row(
|
|
305
|
+
{
|
|
306
|
+
key: column.decode(row[column.name])
|
|
307
|
+
for key, column in self.table.columns.items()
|
|
308
|
+
}
|
|
309
|
+
)
|
|
310
|
+
for row in rows
|
|
311
|
+
]
|
|
312
|
+
|
|
313
|
+
def _record(self, value: Mapping[str, object], allowed: Sequence[str]) -> None:
|
|
314
|
+
if not isinstance(value, Mapping) or any(key not in allowed for key in value):
|
|
315
|
+
raise ValueError("Unknown input column or invalid input record.")
|
|
316
|
+
|
|
317
|
+
def _key(self, key: Mapping[str, object]) -> Filter:
|
|
318
|
+
self._record(key, self.table.primary_key)
|
|
319
|
+
if any(name not in key for name in self.table.primary_key):
|
|
320
|
+
raise ValueError("Missing primary key value.")
|
|
321
|
+
return and_(
|
|
322
|
+
*(
|
|
323
|
+
Filter("=", self.table.columns[name], (key[name],))
|
|
324
|
+
for name in self.table.primary_key
|
|
325
|
+
)
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
async def find_many(
|
|
329
|
+
self,
|
|
330
|
+
*,
|
|
331
|
+
where: Filter | None = None,
|
|
332
|
+
order_by: Sequence[Order] = (),
|
|
333
|
+
limit: int | None = None,
|
|
334
|
+
offset: int | None = None,
|
|
335
|
+
) -> list[R]:
|
|
336
|
+
params: list[object] = []
|
|
337
|
+
sql = f"select {self._select} from {self._name}"
|
|
338
|
+
if where is not None:
|
|
339
|
+
sql += " where " + _compile(where, self.table, params)
|
|
340
|
+
if order_by:
|
|
341
|
+
orders = []
|
|
342
|
+
for order in order_by:
|
|
343
|
+
column = self.table.column(order.column)
|
|
344
|
+
if order.direction not in ("asc", "desc"):
|
|
345
|
+
raise ValueError("Unsupported sort direction.")
|
|
346
|
+
orders.append(f"{quote_identifier(column.name)} {order.direction}")
|
|
347
|
+
sql += " order by " + ", ".join(orders)
|
|
348
|
+
for name, value in (("limit", limit), ("offset", offset)):
|
|
349
|
+
if value is not None:
|
|
350
|
+
if type(value) is not int or not 0 <= value <= 9007199254740991:
|
|
351
|
+
raise ValueError("Pagination requires non-negative safe integers.")
|
|
352
|
+
params.append(value)
|
|
353
|
+
sql += f" {name} ${len(params)}"
|
|
354
|
+
return self._rows(await self._port.query(sql, params))
|
|
355
|
+
|
|
356
|
+
async def find_by_id(self, key: Mapping[str, object]) -> R | None:
|
|
357
|
+
rows = await self.find_many(where=self._key(key), limit=1)
|
|
358
|
+
return rows[0] if rows else None
|
|
359
|
+
|
|
360
|
+
async def insert(self, values: Mapping[str, object]) -> R:
|
|
361
|
+
return await self._insert(values, upsert=False)
|
|
362
|
+
|
|
363
|
+
async def upsert(self, values: Mapping[str, object]) -> R:
|
|
364
|
+
return await self._insert(values, upsert=True)
|
|
365
|
+
|
|
366
|
+
async def _insert(self, values: Mapping[str, object], *, upsert: bool) -> R:
|
|
367
|
+
self._record(values, tuple(self.table.columns))
|
|
368
|
+
if any(name not in values for name in self.table.required_insert):
|
|
369
|
+
raise ValueError("Missing required insert column value.")
|
|
370
|
+
keys = [name for name in self.table.columns if name in values]
|
|
371
|
+
params = [self.table.columns[key].encode(values[key]) for key in keys]
|
|
372
|
+
sql = f"insert into {self._name}"
|
|
373
|
+
if upsert:
|
|
374
|
+
# Keep EXCLUDED separate from a table with the same name.
|
|
375
|
+
sql += ' as "target"'
|
|
376
|
+
if keys:
|
|
377
|
+
names = ", ".join(
|
|
378
|
+
quote_identifier(self.table.columns[key].name) for key in keys
|
|
379
|
+
)
|
|
380
|
+
sql += (
|
|
381
|
+
f" ({names}) values ("
|
|
382
|
+
+ ", ".join(f"${i + 1}" for i in range(len(keys)))
|
|
383
|
+
+ ")"
|
|
384
|
+
)
|
|
385
|
+
else:
|
|
386
|
+
sql += " default values"
|
|
387
|
+
if upsert:
|
|
388
|
+
if any(key not in values for key in self.table.primary_key):
|
|
389
|
+
raise ValueError("Upsert requires every primary key value.")
|
|
390
|
+
mutable = [key for key in keys if key not in self.table.primary_key]
|
|
391
|
+
if not mutable:
|
|
392
|
+
raise ValueError("Upsert requires mutable values.")
|
|
393
|
+
primary = ", ".join(
|
|
394
|
+
quote_identifier(self.table.columns[key].name)
|
|
395
|
+
for key in self.table.primary_key
|
|
396
|
+
)
|
|
397
|
+
assignments = []
|
|
398
|
+
for key in mutable:
|
|
399
|
+
name = quote_identifier(self.table.columns[key].name)
|
|
400
|
+
assignments.append(f"{name} = excluded.{name}")
|
|
401
|
+
sql += f" on conflict ({primary}) do update set {', '.join(assignments)}"
|
|
402
|
+
rows = self._rows(
|
|
403
|
+
await self._port.query(sql + " returning " + self._select, params)
|
|
404
|
+
)
|
|
405
|
+
if not rows:
|
|
406
|
+
raise ValueError("Insert result row is missing.")
|
|
407
|
+
return rows[0]
|
|
408
|
+
|
|
409
|
+
async def update_if(
|
|
410
|
+
self, key: Mapping[str, object], condition: Filter, patch: Mapping[str, object]
|
|
411
|
+
) -> R | None:
|
|
412
|
+
allowed = tuple(
|
|
413
|
+
key for key in self.table.columns if key not in self.table.primary_key
|
|
414
|
+
)
|
|
415
|
+
self._record(patch, allowed)
|
|
416
|
+
if not patch:
|
|
417
|
+
raise ValueError("No columns to update.")
|
|
418
|
+
params: list[object] = []
|
|
419
|
+
assignments = []
|
|
420
|
+
for name, column in self.table.columns.items():
|
|
421
|
+
if name in patch:
|
|
422
|
+
params.append(column.encode(patch[name]))
|
|
423
|
+
assignments.append(f"{quote_identifier(column.name)} = ${len(params)}")
|
|
424
|
+
where = _compile(and_(self._key(key), condition), self.table, params)
|
|
425
|
+
sql = f"update {self._name} set {', '.join(assignments)} where {where} returning {self._select}"
|
|
426
|
+
rows = self._rows(await self._port.query(sql, params))
|
|
427
|
+
return rows[0] if rows else None
|
|
428
|
+
|
|
429
|
+
async def update(self, key: Mapping[str, object], patch: Mapping[str, object]) -> R:
|
|
430
|
+
row = await self.update_if(key, self._key(key), patch)
|
|
431
|
+
if row is None:
|
|
432
|
+
raise OperationError("not_found", 404)
|
|
433
|
+
return row
|
|
434
|
+
|
|
435
|
+
async def increment(
|
|
436
|
+
self, key: Mapping[str, object], columns: Mapping[str, object]
|
|
437
|
+
) -> R:
|
|
438
|
+
row = await self._increment(key, self._key(key), columns, {})
|
|
439
|
+
if row is None:
|
|
440
|
+
raise OperationError("not_found", 404)
|
|
441
|
+
return row
|
|
442
|
+
|
|
443
|
+
async def increment_if(
|
|
444
|
+
self,
|
|
445
|
+
key: Mapping[str, object],
|
|
446
|
+
condition: Filter,
|
|
447
|
+
columns: Mapping[str, object],
|
|
448
|
+
patch: Mapping[str, object],
|
|
449
|
+
) -> R | None:
|
|
450
|
+
if not patch:
|
|
451
|
+
raise ValueError(
|
|
452
|
+
"Increment updates require both increment and set columns."
|
|
453
|
+
)
|
|
454
|
+
return await self._increment(key, condition, columns, patch)
|
|
455
|
+
|
|
456
|
+
async def _increment(
|
|
457
|
+
self,
|
|
458
|
+
key: Mapping[str, object],
|
|
459
|
+
condition: Filter,
|
|
460
|
+
columns: Mapping[str, object],
|
|
461
|
+
patch: Mapping[str, object],
|
|
462
|
+
) -> R | None:
|
|
463
|
+
allowed = tuple(
|
|
464
|
+
name for name in self.table.columns if name not in self.table.primary_key
|
|
465
|
+
)
|
|
466
|
+
self._record(columns, allowed)
|
|
467
|
+
self._record(patch, allowed)
|
|
468
|
+
if not columns:
|
|
469
|
+
raise ValueError("No columns to increment.")
|
|
470
|
+
if any(name in patch for name in columns):
|
|
471
|
+
raise ValueError("A column cannot be incremented and set together.")
|
|
472
|
+
params: list[object] = []
|
|
473
|
+
assignments = []
|
|
474
|
+
for name, column in self.table.columns.items():
|
|
475
|
+
quoted = quote_identifier(column.name)
|
|
476
|
+
if name in columns:
|
|
477
|
+
amount = columns[name]
|
|
478
|
+
if (
|
|
479
|
+
column.kind != "integer"
|
|
480
|
+
or type(amount) is not int
|
|
481
|
+
or amount == 0
|
|
482
|
+
or not -9007199254740991 <= amount <= 9007199254740991
|
|
483
|
+
):
|
|
484
|
+
raise ValueError(
|
|
485
|
+
"Increment amounts must be non-zero safe integers for integer columns."
|
|
486
|
+
)
|
|
487
|
+
params.append(amount)
|
|
488
|
+
assignments.append(f"{quoted} = {quoted} + ${len(params)}::bigint")
|
|
489
|
+
elif name in patch:
|
|
490
|
+
params.append(column.encode(patch[name]))
|
|
491
|
+
assignments.append(f"{quoted} = ${len(params)}")
|
|
492
|
+
where = _compile(and_(self._key(key), condition), self.table, params)
|
|
493
|
+
sql = f"update {self._name} set {', '.join(assignments)} where {where} returning {self._select}"
|
|
494
|
+
rows = self._rows(await self._port.query(sql, params))
|
|
495
|
+
return rows[0] if rows else None
|
|
496
|
+
|
|
497
|
+
async def delete(self, key: Mapping[str, object]) -> R | None:
|
|
498
|
+
params: list[object] = []
|
|
499
|
+
where = _compile(self._key(key), self.table, params)
|
|
500
|
+
rows = self._rows(
|
|
501
|
+
await self._port.query(
|
|
502
|
+
f"delete from {self._name} where {where} returning {self._select}",
|
|
503
|
+
params,
|
|
504
|
+
)
|
|
505
|
+
)
|
|
506
|
+
return rows[0] if rows else None
|