etchdb 0.3.0__tar.gz → 0.4.0__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.
- {etchdb-0.3.0 → etchdb-0.4.0}/PKG-INFO +22 -3
- {etchdb-0.3.0 → etchdb-0.4.0}/README.md +21 -2
- {etchdb-0.3.0 → etchdb-0.4.0}/pyproject.toml +1 -1
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/__init__.py +4 -1
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/adapter.py +11 -1
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/aiosqlite/adapter.py +6 -6
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/asyncpg/adapter.py +27 -4
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/db.py +48 -6
- etchdb-0.4.0/src/etchdb/expr.py +100 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/psycopg/adapter.py +8 -2
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/sql/__init__.py +147 -40
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_batch.py +36 -0
- etchdb-0.4.0/tests/integration/test_execute_rowcount.py +66 -0
- etchdb-0.4.0/tests/integration/test_expressions.py +77 -0
- etchdb-0.4.0/tests/integration/test_in_filter.py +60 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/unit/test_adapters.py +28 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/unit/test_sql_emitter.py +254 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/.gitignore +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/.python-version +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/LICENSE +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/Makefile +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/docker-compose.yml +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/asyncpg/__init__.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/codecs.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/errors.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/psycopg/__init__.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/py.typed +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/query.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/src/etchdb/row.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/__init__.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/_models.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/__init__.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/conftest.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_codecs.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_errors.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_facade.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_is_null.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_iter_rows.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_readme_example.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/integration/test_typed_crud.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/unit/__init__.py +0 -0
- {etchdb-0.3.0 → etchdb-0.4.0}/tests/unit/test_db_dispatch.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: etchdb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Minimal async DB layer for Python. Typed CRUD over Pydantic, raw SQL when you need it
|
|
5
5
|
Project-URL: Homepage, https://github.com/varjoranta/etchdb
|
|
6
6
|
Project-URL: Repository, https://github.com/varjoranta/etchdb
|
|
@@ -66,7 +66,7 @@ Minimal async DB layer for Python. Typed CRUD over Pydantic. Raw SQL when you ne
|
|
|
66
66
|
|
|
67
67
|
## Status
|
|
68
68
|
|
|
69
|
-
Alpha. v0.
|
|
69
|
+
Alpha. v0.4.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
70
70
|
|
|
71
71
|
## Example
|
|
72
72
|
|
|
@@ -90,6 +90,7 @@ alice = await db.insert(User(name="Alice")) # alice.id is now populate
|
|
|
90
90
|
user = await db.get(User, id=alice.id) # one row or None
|
|
91
91
|
users = await db.query(User) # list of rows
|
|
92
92
|
no_email = await db.query(User, email=None) # IS NULL, not = NULL
|
|
93
|
+
recent = await db.query(User, id=[1, 5, 7]) # IN ($1, $2, $3)
|
|
93
94
|
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
94
95
|
await db.delete(alice)
|
|
95
96
|
|
|
@@ -103,10 +104,22 @@ await db.update(User(id=alice.id, name="Alice B"),
|
|
|
103
104
|
# so models with required NOT NULL columns still flow through.
|
|
104
105
|
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
105
106
|
|
|
107
|
+
# Atomic column expressions in SET (use Row.patch so the sentinels
|
|
108
|
+
# slip past validation). Counter / Article are user-defined Row
|
|
109
|
+
# subclasses alongside User, with an int counter and a timestamp:
|
|
110
|
+
from etchdb import Inc, Now
|
|
111
|
+
await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
|
|
112
|
+
await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
|
|
113
|
+
|
|
106
114
|
# Bulk insert / delete (chunked at the driver's parameter limit).
|
|
107
115
|
await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
116
|
+
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
108
117
|
await db.delete_many(User, [1, 2, 3])
|
|
109
118
|
|
|
119
|
+
# Upsert via single insert: same rules, returns the DB's view.
|
|
120
|
+
alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
121
|
+
on_conflict="upsert")
|
|
122
|
+
|
|
110
123
|
# Stream every matching row (paginated, won't load the whole table at once)
|
|
111
124
|
# Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
|
|
112
125
|
# loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
|
|
@@ -237,9 +250,15 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
|
|
|
237
250
|
|
|
238
251
|
Out of scope so far. A small forward-only, file-based migration helper (no autogenerate, no rollback, no DAG) is planned for a later release. etchdb owns no schema state today, so any external tool slots in fine in the meantime: Alembic if you also use SQLAlchemy, dbmate or sqitch if you don't, or a few `db.execute` calls in your bootstrap path.
|
|
239
252
|
|
|
253
|
+
## Under consideration
|
|
254
|
+
|
|
255
|
+
Comparison sentinels for `where=` filters (`Gt`, `Gte`, `Lt`, `Lte`, accepting either a scalar or the existing `Now()` sentinel) are on the table for a later release. Scope would stay narrow: single-column inequality only; compound predicates, `LIKE`, and `BETWEEN` would still go through raw SQL. Holding the API for more real use cases before committing. Until then, raw SQL via `db.fetch_models(User, "SELECT * FROM users WHERE expires_at > NOW()")` is the canonical answer; that's what etchdb's first-class raw-SQL escape valve is for.
|
|
256
|
+
|
|
257
|
+
`Inc` / `Now` composing with `on_conflict="upsert"` is a related deferred shape: the create-or-increment pattern would let `db.insert(RateCounter(...), on_conflict="upsert")` carry an `Inc(by=N)` for the conflict SET, but the INSERT branch still needs a literal initial value, so the row would have to express two values per column. Today the sentinels are rejected by `db.insert` / `db.insert_many` outright; raw SQL with `INSERT ... ON CONFLICT (key) DO UPDATE SET count = table.count + 1` covers the case in one statement.
|
|
258
|
+
|
|
240
259
|
## Built with AI assistance
|
|
241
260
|
|
|
242
|
-
Built with Claude Code
|
|
261
|
+
Built with a mix of AI tools for writing and reviewing code: primarily Claude Code, with Codex and occasionally Gemini for second opinions, and not limited to these. spegl.ing pattern research is in active use alongside them. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
|
|
243
262
|
|
|
244
263
|
## License
|
|
245
264
|
|
|
@@ -4,7 +4,7 @@ Minimal async DB layer for Python. Typed CRUD over Pydantic. Raw SQL when you ne
|
|
|
4
4
|
|
|
5
5
|
## Status
|
|
6
6
|
|
|
7
|
-
Alpha. v0.
|
|
7
|
+
Alpha. v0.4.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
8
8
|
|
|
9
9
|
## Example
|
|
10
10
|
|
|
@@ -28,6 +28,7 @@ alice = await db.insert(User(name="Alice")) # alice.id is now populate
|
|
|
28
28
|
user = await db.get(User, id=alice.id) # one row or None
|
|
29
29
|
users = await db.query(User) # list of rows
|
|
30
30
|
no_email = await db.query(User, email=None) # IS NULL, not = NULL
|
|
31
|
+
recent = await db.query(User, id=[1, 5, 7]) # IN ($1, $2, $3)
|
|
31
32
|
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
32
33
|
await db.delete(alice)
|
|
33
34
|
|
|
@@ -41,10 +42,22 @@ await db.update(User(id=alice.id, name="Alice B"),
|
|
|
41
42
|
# so models with required NOT NULL columns still flow through.
|
|
42
43
|
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
43
44
|
|
|
45
|
+
# Atomic column expressions in SET (use Row.patch so the sentinels
|
|
46
|
+
# slip past validation). Counter / Article are user-defined Row
|
|
47
|
+
# subclasses alongside User, with an int counter and a timestamp:
|
|
48
|
+
from etchdb import Inc, Now
|
|
49
|
+
await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
|
|
50
|
+
await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
|
|
51
|
+
|
|
44
52
|
# Bulk insert / delete (chunked at the driver's parameter limit).
|
|
45
53
|
await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
54
|
+
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
46
55
|
await db.delete_many(User, [1, 2, 3])
|
|
47
56
|
|
|
57
|
+
# Upsert via single insert: same rules, returns the DB's view.
|
|
58
|
+
alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
59
|
+
on_conflict="upsert")
|
|
60
|
+
|
|
48
61
|
# Stream every matching row (paginated, won't load the whole table at once)
|
|
49
62
|
# Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
|
|
50
63
|
# loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
|
|
@@ -175,9 +188,15 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
|
|
|
175
188
|
|
|
176
189
|
Out of scope so far. A small forward-only, file-based migration helper (no autogenerate, no rollback, no DAG) is planned for a later release. etchdb owns no schema state today, so any external tool slots in fine in the meantime: Alembic if you also use SQLAlchemy, dbmate or sqitch if you don't, or a few `db.execute` calls in your bootstrap path.
|
|
177
190
|
|
|
191
|
+
## Under consideration
|
|
192
|
+
|
|
193
|
+
Comparison sentinels for `where=` filters (`Gt`, `Gte`, `Lt`, `Lte`, accepting either a scalar or the existing `Now()` sentinel) are on the table for a later release. Scope would stay narrow: single-column inequality only; compound predicates, `LIKE`, and `BETWEEN` would still go through raw SQL. Holding the API for more real use cases before committing. Until then, raw SQL via `db.fetch_models(User, "SELECT * FROM users WHERE expires_at > NOW()")` is the canonical answer; that's what etchdb's first-class raw-SQL escape valve is for.
|
|
194
|
+
|
|
195
|
+
`Inc` / `Now` composing with `on_conflict="upsert"` is a related deferred shape: the create-or-increment pattern would let `db.insert(RateCounter(...), on_conflict="upsert")` carry an `Inc(by=N)` for the conflict SET, but the INSERT branch still needs a literal initial value, so the row would have to express two values per column. Today the sentinels are rejected by `db.insert` / `db.insert_many` outright; raw SQL with `INSERT ... ON CONFLICT (key) DO UPDATE SET count = table.count + 1` covers the case in one statement.
|
|
196
|
+
|
|
178
197
|
## Built with AI assistance
|
|
179
198
|
|
|
180
|
-
Built with Claude Code
|
|
199
|
+
Built with a mix of AI tools for writing and reviewing code: primarily Claude Code, with Codex and occasionally Gemini for second opinions, and not limited to these. spegl.ing pattern research is in active use alongside them. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
|
|
181
200
|
|
|
182
201
|
## License
|
|
183
202
|
|
|
@@ -8,15 +8,18 @@ from etchdb.errors import (
|
|
|
8
8
|
UndefinedColumnError,
|
|
9
9
|
UndefinedTableError,
|
|
10
10
|
)
|
|
11
|
+
from etchdb.expr import Inc, Now
|
|
11
12
|
from etchdb.query import SqlQuery
|
|
12
13
|
from etchdb.row import Row
|
|
13
14
|
|
|
14
|
-
__version__ = "0.
|
|
15
|
+
__version__ = "0.4.0"
|
|
15
16
|
|
|
16
17
|
__all__ = [
|
|
17
18
|
"DB",
|
|
18
19
|
"EtchdbError",
|
|
20
|
+
"Inc",
|
|
19
21
|
"IntegrityError",
|
|
22
|
+
"Now",
|
|
20
23
|
"OperationalError",
|
|
21
24
|
"Row",
|
|
22
25
|
"SqlQuery",
|
|
@@ -24,7 +24,17 @@ class AdapterBase(ABC):
|
|
|
24
24
|
...
|
|
25
25
|
|
|
26
26
|
@abstractmethod
|
|
27
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
27
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
28
|
+
"""Execute a statement and return the affected-row count.
|
|
29
|
+
|
|
30
|
+
Returns the affected-row count for DML (INSERT / UPDATE /
|
|
31
|
+
DELETE), or `-1` for everything else (DDL, BEGIN, SELECT,
|
|
32
|
+
COPY, ...). The `-1` sentinel mirrors psycopg's and sqlite3's
|
|
33
|
+
native convention. SELECT through `execute` is explicitly not
|
|
34
|
+
a count contract; use `fetch` / `fetchrow` / `fetchval` for
|
|
35
|
+
SELECT and read the row count off the result.
|
|
36
|
+
"""
|
|
37
|
+
...
|
|
28
38
|
|
|
29
39
|
@abstractmethod
|
|
30
40
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]: ...
|
|
@@ -90,10 +90,10 @@ class AiosqliteAdapter(AdapterBase):
|
|
|
90
90
|
conn.row_factory = aiosqlite.Row
|
|
91
91
|
return cls(conn, owns_conn=True)
|
|
92
92
|
|
|
93
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
94
|
-
async with _wrap_errors():
|
|
95
|
-
await self._conn.execute(sql, params)
|
|
93
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
94
|
+
async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
|
|
96
95
|
await self._conn.commit()
|
|
96
|
+
return cursor.rowcount
|
|
97
97
|
|
|
98
98
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
99
99
|
async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
|
|
@@ -143,9 +143,9 @@ class _AiosqliteTxAdapter(AdapterBase):
|
|
|
143
143
|
def placeholder(i: int) -> str:
|
|
144
144
|
return "?"
|
|
145
145
|
|
|
146
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
147
|
-
async with _wrap_errors():
|
|
148
|
-
|
|
146
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
147
|
+
async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
|
|
148
|
+
return cursor.rowcount
|
|
149
149
|
|
|
150
150
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
151
151
|
async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
|
|
@@ -52,6 +52,29 @@ def _map_exception(exc: BaseException) -> errors.EtchdbError | None:
|
|
|
52
52
|
_wrap_errors = errors.wrap(_map_exception)
|
|
53
53
|
|
|
54
54
|
|
|
55
|
+
_DML_TAGS = ("INSERT", "UPDATE", "DELETE")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _rowcount_from_status(status: str) -> int:
|
|
59
|
+
"""Extract the affected-row count from an asyncpg command tag.
|
|
60
|
+
|
|
61
|
+
DML tags ('UPDATE 5', 'DELETE 3', 'INSERT 0 5') end in the
|
|
62
|
+
count and parse to a non-negative int. Anything else (DDL,
|
|
63
|
+
`BEGIN`, `SELECT`, `COPY`) returns -1, matching the psycopg /
|
|
64
|
+
sqlite3 'no rowcount available' sentinel. SELECT in particular
|
|
65
|
+
would otherwise parse to its row count, which `db.execute`
|
|
66
|
+
explicitly does not promise across drivers.
|
|
67
|
+
"""
|
|
68
|
+
verb, _, _ = status.partition(" ")
|
|
69
|
+
if verb not in _DML_TAGS:
|
|
70
|
+
return -1
|
|
71
|
+
tail = status.rsplit(" ", 1)[-1]
|
|
72
|
+
try:
|
|
73
|
+
return int(tail)
|
|
74
|
+
except ValueError:
|
|
75
|
+
return -1
|
|
76
|
+
|
|
77
|
+
|
|
55
78
|
class AsyncpgAdapter(AdapterBase):
|
|
56
79
|
"""AdapterBase implementation backed by an asyncpg pool.
|
|
57
80
|
|
|
@@ -90,9 +113,9 @@ class AsyncpgAdapter(AdapterBase):
|
|
|
90
113
|
pool = await asyncpg.create_pool(url, init=_init_codecs)
|
|
91
114
|
return cls(pool, owns_pool=True)
|
|
92
115
|
|
|
93
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
116
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
94
117
|
async with _wrap_errors(), self._pool.acquire() as conn:
|
|
95
|
-
return await conn.execute(sql, *params)
|
|
118
|
+
return _rowcount_from_status(await conn.execute(sql, *params))
|
|
96
119
|
|
|
97
120
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
98
121
|
async with _wrap_errors(), self._pool.acquire() as conn:
|
|
@@ -128,9 +151,9 @@ class _AsyncpgConnAdapter(AdapterBase):
|
|
|
128
151
|
def placeholder(i: int) -> str:
|
|
129
152
|
return f"${i + 1}"
|
|
130
153
|
|
|
131
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
154
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
132
155
|
async with _wrap_errors():
|
|
133
|
-
return await self._conn.execute(sql, *params)
|
|
156
|
+
return _rowcount_from_status(await self._conn.execute(sql, *params))
|
|
134
157
|
|
|
135
158
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
136
159
|
async with _wrap_errors():
|
|
@@ -11,7 +11,7 @@ an adapter, or via the URL-scheme dispatcher `DB.from_url`.
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
13
|
from contextlib import asynccontextmanager
|
|
14
|
-
from typing import TYPE_CHECKING, Any
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
15
|
from urllib.parse import urlparse
|
|
16
16
|
|
|
17
17
|
from etchdb import sql
|
|
@@ -29,6 +29,14 @@ if TYPE_CHECKING:
|
|
|
29
29
|
_PARAM_LIMIT = 32766
|
|
30
30
|
|
|
31
31
|
|
|
32
|
+
def _has_empty_collection_filter(filters: Mapping[str, Any] | None) -> bool:
|
|
33
|
+
"""An empty list / tuple filter would emit `IN ()` (invalid on
|
|
34
|
+
Postgres); short-circuit to "no rows" without round-tripping."""
|
|
35
|
+
if not filters:
|
|
36
|
+
return False
|
|
37
|
+
return any(isinstance(v, list | tuple) and not v for v in filters.values())
|
|
38
|
+
|
|
39
|
+
|
|
32
40
|
def _hydrate(model_or_row: type[Row] | Row, row: dict[str, Any] | None) -> Row | None:
|
|
33
41
|
"""Build a Row from a fetchrow result, or return None when there is no row.
|
|
34
42
|
|
|
@@ -84,7 +92,17 @@ class DB:
|
|
|
84
92
|
|
|
85
93
|
return cls(adapter)
|
|
86
94
|
|
|
87
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
95
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
96
|
+
"""Execute a statement and return the affected-row count.
|
|
97
|
+
|
|
98
|
+
Returns the rowcount for DML (INSERT / UPDATE / DELETE);
|
|
99
|
+
returns `-1` for everything else (DDL, BEGIN, SELECT, COPY,
|
|
100
|
+
...). Normalised across asyncpg, psycopg, and aiosqlite so
|
|
101
|
+
the same call site works on every backend. SELECT through
|
|
102
|
+
`execute` is explicitly not a count contract: use
|
|
103
|
+
`fetch` / `fetchrow` / `fetchval` and read the count off the
|
|
104
|
+
result.
|
|
105
|
+
"""
|
|
88
106
|
return await self._adapter.execute(sql, *params)
|
|
89
107
|
|
|
90
108
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
@@ -118,6 +136,8 @@ class DB:
|
|
|
118
136
|
return _hydrate(model, row)
|
|
119
137
|
|
|
120
138
|
async def get(self, model: type[Row], **filters: Any) -> Row | None:
|
|
139
|
+
if _has_empty_collection_filter(filters):
|
|
140
|
+
return None
|
|
121
141
|
q = sql.select_one(model, placeholder=self._adapter.placeholder, **filters)
|
|
122
142
|
return await self.fetch_model(model, q.sql, *q.params)
|
|
123
143
|
|
|
@@ -130,6 +150,8 @@ class DB:
|
|
|
130
150
|
order_by: str | list[str] | None = None,
|
|
131
151
|
**filters: Any,
|
|
132
152
|
) -> list[Row]:
|
|
153
|
+
if _has_empty_collection_filter(filters):
|
|
154
|
+
return []
|
|
133
155
|
q = sql.select_many(
|
|
134
156
|
model,
|
|
135
157
|
placeholder=self._adapter.placeholder,
|
|
@@ -156,6 +178,8 @@ class DB:
|
|
|
156
178
|
"""
|
|
157
179
|
if batch_size < 1:
|
|
158
180
|
raise ValueError(f"batch_size must be >= 1, got {batch_size}")
|
|
181
|
+
if _has_empty_collection_filter(filters):
|
|
182
|
+
return
|
|
159
183
|
if order_by is None:
|
|
160
184
|
order_by = list(model.__pk__)
|
|
161
185
|
offset = 0
|
|
@@ -175,8 +199,18 @@ class DB:
|
|
|
175
199
|
return
|
|
176
200
|
offset += batch_size
|
|
177
201
|
|
|
178
|
-
async def insert(self, row: Row) -> Row:
|
|
179
|
-
|
|
202
|
+
async def insert(self, row: Row, *, on_conflict: sql._OnConflict = None) -> Row:
|
|
203
|
+
"""Insert `row` and return the DB's view (RETURNING *).
|
|
204
|
+
|
|
205
|
+
`on_conflict="ignore"` appends `ON CONFLICT DO NOTHING`; if a
|
|
206
|
+
conflict happens, RETURNING is empty and the input `row` is
|
|
207
|
+
returned unchanged (so server-defaults are NOT populated).
|
|
208
|
+
`on_conflict="upsert"` appends `ON CONFLICT (<pk>) DO UPDATE
|
|
209
|
+
SET <non-pk> = excluded.<non-pk>`, so the returned row always
|
|
210
|
+
reflects the DB's view. Inc / Now sentinels do not compose
|
|
211
|
+
with upsert; for create-or-increment, drop to raw SQL.
|
|
212
|
+
"""
|
|
213
|
+
q = sql.insert(row, placeholder=self._adapter.placeholder, on_conflict=on_conflict)
|
|
180
214
|
result = await self._adapter.fetchrow(q.sql, *q.params)
|
|
181
215
|
return _hydrate(row, result) or row
|
|
182
216
|
|
|
@@ -191,7 +225,11 @@ class DB:
|
|
|
191
225
|
All rows must share `model_fields_set`. Long batches are
|
|
192
226
|
chunked at the driver's parameter limit so a single call can
|
|
193
227
|
cover thousands of rows. `on_conflict="ignore"` appends
|
|
194
|
-
`ON CONFLICT DO NOTHING
|
|
228
|
+
`ON CONFLICT DO NOTHING`; `on_conflict="upsert"` appends
|
|
229
|
+
`ON CONFLICT (<pk>) DO UPDATE SET <non-pk> = excluded.<non-pk>`.
|
|
230
|
+
Inc / Now sentinels do not compose with upsert; for
|
|
231
|
+
create-or-increment, drop to raw SQL. Empty `rows` is a
|
|
232
|
+
no-op."""
|
|
195
233
|
if not rows:
|
|
196
234
|
return
|
|
197
235
|
cols_per_row = sum(1 for f in type(rows[0]).model_fields if f in rows[0].model_fields_set)
|
|
@@ -226,18 +264,22 @@ class DB:
|
|
|
226
264
|
async def update(self, row: Row, *, where: Mapping[str, Any] | None = None) -> Row | None:
|
|
227
265
|
"""Update `row` by PK, AND'd with `where=`. Returns the updated
|
|
228
266
|
row, or None if PK + `where=` matched no row."""
|
|
267
|
+
if _has_empty_collection_filter(where):
|
|
268
|
+
return None
|
|
229
269
|
q = sql.update(row, placeholder=self._adapter.placeholder, returning="*", where=where)
|
|
230
270
|
result = await self._adapter.fetchrow(q.sql, *q.params)
|
|
231
271
|
return _hydrate(row, result)
|
|
232
272
|
|
|
233
273
|
async def delete(self, row: Row, *, where: Mapping[str, Any] | None = None) -> None:
|
|
234
274
|
"""Delete `row` by PK, AND'd with `where=`."""
|
|
275
|
+
if _has_empty_collection_filter(where):
|
|
276
|
+
return
|
|
235
277
|
q = sql.delete(row, placeholder=self._adapter.placeholder, where=where)
|
|
236
278
|
await self._adapter.execute(q.sql, *q.params)
|
|
237
279
|
|
|
238
280
|
def compose(
|
|
239
281
|
self,
|
|
240
|
-
op:
|
|
282
|
+
op: sql.Op,
|
|
241
283
|
*args: Any,
|
|
242
284
|
**kwargs: Any,
|
|
243
285
|
) -> SqlQuery:
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Column expression sentinels for UPDATE SET clauses.
|
|
2
|
+
|
|
3
|
+
Plain values bind as `column = $N`. Expression sentinels render as
|
|
4
|
+
raw SQL fragments instead, which is the right shape for atomic
|
|
5
|
+
increments and DB-side timestamps that need to evaluate inside the
|
|
6
|
+
single statement rather than at the Python call site.
|
|
7
|
+
|
|
8
|
+
Use these via `Row.patch(...)`: a sentinel does not satisfy the
|
|
9
|
+
field's declared type (`int`, `datetime`), so plain Pydantic
|
|
10
|
+
construction would raise. `patch` skips validation and lets the
|
|
11
|
+
sentinel flow through to the SET emitter.
|
|
12
|
+
|
|
13
|
+
from etchdb import Inc, Now, Row
|
|
14
|
+
|
|
15
|
+
# SET view_count = view_count + $1 WHERE id = $2
|
|
16
|
+
await db.update(User.patch(id=1, view_count=Inc()))
|
|
17
|
+
|
|
18
|
+
# SET updated_at = CURRENT_TIMESTAMP WHERE id = $1
|
|
19
|
+
await db.update(Article.patch(id=1, updated_at=Now()))
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from collections.abc import Callable
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _Expr:
|
|
29
|
+
"""Marker for column expressions in SET clauses.
|
|
30
|
+
|
|
31
|
+
Subclasses implement `render(column, placeholder, start)` returning
|
|
32
|
+
`(sql_fragment, params)` where `sql_fragment` is the right-hand
|
|
33
|
+
side of `column = ...` (no leading `column =`) and `params` is the
|
|
34
|
+
list of values bound to placeholders inside that fragment.
|
|
35
|
+
`start` is the surrounding parameter-list index where this
|
|
36
|
+
expression's first bound parameter sits.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
__slots__ = ()
|
|
40
|
+
|
|
41
|
+
def render(
|
|
42
|
+
self, column: str, placeholder: Callable[[int], str], start: int
|
|
43
|
+
) -> tuple[str, list[Any]]:
|
|
44
|
+
raise NotImplementedError
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Inc(_Expr):
|
|
48
|
+
"""Atomic increment: `column = column + by`.
|
|
49
|
+
|
|
50
|
+
`Inc()` adds 1; `Inc(by=5)` adds 5; `Inc(by=-1)` decrements.
|
|
51
|
+
Nothing forbids a non-int `by`, so the same shape works for any
|
|
52
|
+
column whose type supports `+` (interval columns, decimal
|
|
53
|
+
accumulators).
|
|
54
|
+
|
|
55
|
+
Two restrictions:
|
|
56
|
+
- Construct rows that hold an `Inc` via `Row.patch(...)`. A
|
|
57
|
+
sentinel does not pass Pydantic validation for the field's
|
|
58
|
+
declared type, so plain `Row(...)` would raise.
|
|
59
|
+
- `Inc` is accepted by `db.update` only. `db.insert` /
|
|
60
|
+
`db.insert_many` reject it (incrementing a row that does not
|
|
61
|
+
exist yet is undefined). The rejection covers `on_conflict=
|
|
62
|
+
"upsert"` too: the INSERT branch still needs a literal initial
|
|
63
|
+
value. For create-or-increment, drop to raw SQL.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
__slots__ = ("by",)
|
|
67
|
+
|
|
68
|
+
def __init__(self, by: Any = 1):
|
|
69
|
+
self.by = by
|
|
70
|
+
|
|
71
|
+
def render(
|
|
72
|
+
self, column: str, placeholder: Callable[[int], str], start: int
|
|
73
|
+
) -> tuple[str, list[Any]]:
|
|
74
|
+
return f"{column} + {placeholder(start)}", [self.by]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Now(_Expr):
|
|
78
|
+
"""DB-side current timestamp: `column = CURRENT_TIMESTAMP`.
|
|
79
|
+
|
|
80
|
+
`CURRENT_TIMESTAMP` is SQL-standard and works on both Postgres
|
|
81
|
+
(returns timestamptz) and SQLite (returns ISO-8601 text). Use a
|
|
82
|
+
column type that matches your driver's expectation.
|
|
83
|
+
|
|
84
|
+
Two restrictions:
|
|
85
|
+
- Construct rows that hold a `Now` via `Row.patch(...)`. A
|
|
86
|
+
sentinel does not pass Pydantic validation for the field's
|
|
87
|
+
declared type, so plain `Row(...)` would raise.
|
|
88
|
+
- `Now` is accepted by `db.update` only. `db.insert` /
|
|
89
|
+
`db.insert_many` reject it, including under `on_conflict=
|
|
90
|
+
"upsert"`; the INSERT branch still needs a literal initial
|
|
91
|
+
value. For a server-default insert timestamp, prefer a column
|
|
92
|
+
`DEFAULT CURRENT_TIMESTAMP` in the schema.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
__slots__ = ()
|
|
96
|
+
|
|
97
|
+
def render(
|
|
98
|
+
self, column: str, placeholder: Callable[[int], str], start: int
|
|
99
|
+
) -> tuple[str, list[Any]]:
|
|
100
|
+
return "CURRENT_TIMESTAMP", []
|
|
@@ -115,9 +115,12 @@ class PsycopgAdapter(AdapterBase):
|
|
|
115
115
|
# discourage SQL injection at the type level; etchdb passes runtime
|
|
116
116
|
# strings here (the SqlQuery / raw-SQL contract). The injection
|
|
117
117
|
# guard is the `*params` substitution, not the query type.
|
|
118
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
118
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
119
119
|
async with _wrap_errors(), self._cursor() as cur:
|
|
120
120
|
await cur.execute(cast(Any, sql), params)
|
|
121
|
+
if cur.description is not None:
|
|
122
|
+
return -1
|
|
123
|
+
return cur.rowcount
|
|
121
124
|
|
|
122
125
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
123
126
|
async with _wrap_errors(), self._cursor() as cur:
|
|
@@ -163,9 +166,12 @@ class _PsycopgConnAdapter(AdapterBase):
|
|
|
163
166
|
async with psycopg.AsyncRawCursor(self._conn, row_factory=row_factory) as cur:
|
|
164
167
|
yield cur
|
|
165
168
|
|
|
166
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
169
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
167
170
|
async with _wrap_errors(), self._cursor() as cur:
|
|
168
171
|
await cur.execute(cast(Any, sql), params)
|
|
172
|
+
if cur.description is not None:
|
|
173
|
+
return -1
|
|
174
|
+
return cur.rowcount
|
|
169
175
|
|
|
170
176
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
171
177
|
async with _wrap_errors(), self._cursor() as cur:
|