etchdb 0.5.0__tar.gz → 0.6.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.5.0 → etchdb-0.6.0}/.github/workflows/release.yml +5 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/.gitignore +1 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/PKG-INFO +37 -4
- {etchdb-0.5.0 → etchdb-0.6.0}/README.md +36 -3
- {etchdb-0.5.0 → etchdb-0.6.0}/pyproject.toml +4 -1
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/__init__.py +1 -1
- etchdb-0.6.0/src/etchdb/__main__.py +5 -0
- etchdb-0.6.0/src/etchdb/cli.py +112 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/db.py +100 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/sql/__init__.py +96 -1
- etchdb-0.6.0/tests/integration/test_cli.py +103 -0
- etchdb-0.6.0/tests/integration/test_iter_rows_keyset.py +93 -0
- etchdb-0.6.0/tests/integration/test_ping_and_aclose.py +42 -0
- etchdb-0.6.0/tests/integration/test_update_where.py +79 -0
- etchdb-0.6.0/tests/unit/test_cli.py +77 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/unit/test_sql_emitter.py +117 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/.python-version +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/LICENSE +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/Makefile +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/docker-compose.yml +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/adapter.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/aiosqlite/adapter.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/asyncpg/__init__.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/asyncpg/adapter.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/codecs.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/errors.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/expr.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/migrations.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/psycopg/__init__.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/psycopg/adapter.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/py.typed +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/query.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/src/etchdb/row.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/__init__.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/_models.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/__init__.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/conftest.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_batch.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_codecs.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_errors.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_execute_rowcount.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_expressions.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_facade.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_fields_not_in_db.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_in_filter.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_is_null.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_iter_rows.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_migrations.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_pool_kwargs.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_readme_example.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/integration/test_typed_crud.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/unit/__init__.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/unit/test_adapters.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/unit/test_db_dispatch.py +0 -0
- {etchdb-0.5.0 → etchdb-0.6.0}/tests/unit/test_migrations.py +0 -0
|
@@ -46,6 +46,11 @@ jobs:
|
|
|
46
46
|
# so it installs on every supported version; per-push CI (when
|
|
47
47
|
# added) should cover the full 3.12 - 3.14 matrix.
|
|
48
48
|
python-version: "3.13"
|
|
49
|
+
# The project does not commit `uv.lock` (library-style: consumers
|
|
50
|
+
# decide their lockfile). Without an explicit dependency glob the
|
|
51
|
+
# setup-uv cache silently never invalidates; pin it to
|
|
52
|
+
# pyproject.toml so the cache key tracks dependency changes.
|
|
53
|
+
cache-dependency-glob: "pyproject.toml"
|
|
49
54
|
|
|
50
55
|
- name: Install dependencies
|
|
51
56
|
run: uv sync --extra all --extra dev
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: etchdb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.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.6.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
70
70
|
|
|
71
71
|
## Example
|
|
72
72
|
|
|
@@ -116,16 +116,25 @@ await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
|
116
116
|
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
117
117
|
await db.delete_many(User, [1, 2, 3])
|
|
118
118
|
|
|
119
|
+
# Bulk update: same patch applied to all rows matching a filter.
|
|
120
|
+
# Returns the affected-row count.
|
|
121
|
+
n = await db.update_where(User.patch(status="archived"),
|
|
122
|
+
where={"id": [1, 2, 3]})
|
|
123
|
+
|
|
119
124
|
# Upsert via single insert: same rules, returns the DB's view.
|
|
120
125
|
alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
121
126
|
on_conflict="upsert")
|
|
122
127
|
|
|
123
128
|
# Stream every matching row (paginated, won't load the whole table at once)
|
|
124
|
-
#
|
|
125
|
-
# loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
|
|
129
|
+
# iter_rows uses offset pagination, so cost scales O(N**2) on huge tables.
|
|
126
130
|
async for user in db.iter_rows(User, batch_size=500):
|
|
127
131
|
process(user)
|
|
128
132
|
|
|
133
|
+
# For huge tables, iter_rows_keyset stays O(N) by emitting
|
|
134
|
+
# `WHERE <by> > <last_seen>` per page. `by` defaults to __pk__[0].
|
|
135
|
+
async for user in db.iter_rows_keyset(User, batch_size=500):
|
|
136
|
+
process(user)
|
|
137
|
+
|
|
129
138
|
# Typed-result raw SQL (covers most joins)
|
|
130
139
|
users = await db.fetch_models(User, """
|
|
131
140
|
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
@@ -145,6 +154,11 @@ async with db.transaction() as tx:
|
|
|
145
154
|
await tx.insert(User(name="Carol"))
|
|
146
155
|
await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
|
|
147
156
|
|
|
157
|
+
# Healthcheck + lifecycle
|
|
158
|
+
ok = await db.ping() # SELECT 1 round-trip; raises on failure
|
|
159
|
+
async with db: # close on scope exit (DB must already be open)
|
|
160
|
+
...
|
|
161
|
+
|
|
148
162
|
# Migrations: apply every pending .sql file in a directory, in
|
|
149
163
|
# filename order. The runner creates a `_etchdb_migrations` tracking
|
|
150
164
|
# table on first call. See the Migrations section below for the
|
|
@@ -331,6 +345,25 @@ In both cases the error names the recovery (`DELETE FROM _etchdb_migrations WHER
|
|
|
331
345
|
|
|
332
346
|
Other migration tools (Alembic, dbmate, sqitch) still slot in fine if you want autogenerate, branching, or rollback — etchdb's helper covers the simple forward-only case without dragging those in.
|
|
333
347
|
|
|
348
|
+
### Running migrations from the command line
|
|
349
|
+
|
|
350
|
+
Installing `etchdb` registers an `etchdb` console script for use in CI, deploy scripts, and Docker entrypoints — no Python bootstrap needed:
|
|
351
|
+
|
|
352
|
+
```bash
|
|
353
|
+
$ etchdb migrate ./migrations --url "$DATABASE_URL"
|
|
354
|
+
applied 2 migrations
|
|
355
|
+
|
|
356
|
+
$ etchdb status ./migrations --url "$DATABASE_URL"
|
|
357
|
+
Migration status (./migrations):
|
|
358
|
+
applied (2):
|
|
359
|
+
0001_create_users.sql
|
|
360
|
+
0002_add_email_index.sql
|
|
361
|
+
pending (1):
|
|
362
|
+
0003_add_articles.sql
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
`--url` falls back to the `DATABASE_URL` environment variable. Exit codes: `0` on success, `1` on inconsistent state (drift or disappearance) -- so `etchdb status` is the natural gate before `etchdb migrate` in a deploy pipeline -- and `2` on usage errors (missing directory, no URL).
|
|
366
|
+
|
|
334
367
|
## Under consideration
|
|
335
368
|
|
|
336
369
|
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.
|
|
@@ -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.6.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
8
8
|
|
|
9
9
|
## Example
|
|
10
10
|
|
|
@@ -54,16 +54,25 @@ await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
|
54
54
|
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
55
55
|
await db.delete_many(User, [1, 2, 3])
|
|
56
56
|
|
|
57
|
+
# Bulk update: same patch applied to all rows matching a filter.
|
|
58
|
+
# Returns the affected-row count.
|
|
59
|
+
n = await db.update_where(User.patch(status="archived"),
|
|
60
|
+
where={"id": [1, 2, 3]})
|
|
61
|
+
|
|
57
62
|
# Upsert via single insert: same rules, returns the DB's view.
|
|
58
63
|
alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
59
64
|
on_conflict="upsert")
|
|
60
65
|
|
|
61
66
|
# Stream every matching row (paginated, won't load the whole table at once)
|
|
62
|
-
#
|
|
63
|
-
# loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
|
|
67
|
+
# iter_rows uses offset pagination, so cost scales O(N**2) on huge tables.
|
|
64
68
|
async for user in db.iter_rows(User, batch_size=500):
|
|
65
69
|
process(user)
|
|
66
70
|
|
|
71
|
+
# For huge tables, iter_rows_keyset stays O(N) by emitting
|
|
72
|
+
# `WHERE <by> > <last_seen>` per page. `by` defaults to __pk__[0].
|
|
73
|
+
async for user in db.iter_rows_keyset(User, batch_size=500):
|
|
74
|
+
process(user)
|
|
75
|
+
|
|
67
76
|
# Typed-result raw SQL (covers most joins)
|
|
68
77
|
users = await db.fetch_models(User, """
|
|
69
78
|
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
@@ -83,6 +92,11 @@ async with db.transaction() as tx:
|
|
|
83
92
|
await tx.insert(User(name="Carol"))
|
|
84
93
|
await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
|
|
85
94
|
|
|
95
|
+
# Healthcheck + lifecycle
|
|
96
|
+
ok = await db.ping() # SELECT 1 round-trip; raises on failure
|
|
97
|
+
async with db: # close on scope exit (DB must already be open)
|
|
98
|
+
...
|
|
99
|
+
|
|
86
100
|
# Migrations: apply every pending .sql file in a directory, in
|
|
87
101
|
# filename order. The runner creates a `_etchdb_migrations` tracking
|
|
88
102
|
# table on first call. See the Migrations section below for the
|
|
@@ -269,6 +283,25 @@ In both cases the error names the recovery (`DELETE FROM _etchdb_migrations WHER
|
|
|
269
283
|
|
|
270
284
|
Other migration tools (Alembic, dbmate, sqitch) still slot in fine if you want autogenerate, branching, or rollback — etchdb's helper covers the simple forward-only case without dragging those in.
|
|
271
285
|
|
|
286
|
+
### Running migrations from the command line
|
|
287
|
+
|
|
288
|
+
Installing `etchdb` registers an `etchdb` console script for use in CI, deploy scripts, and Docker entrypoints — no Python bootstrap needed:
|
|
289
|
+
|
|
290
|
+
```bash
|
|
291
|
+
$ etchdb migrate ./migrations --url "$DATABASE_URL"
|
|
292
|
+
applied 2 migrations
|
|
293
|
+
|
|
294
|
+
$ etchdb status ./migrations --url "$DATABASE_URL"
|
|
295
|
+
Migration status (./migrations):
|
|
296
|
+
applied (2):
|
|
297
|
+
0001_create_users.sql
|
|
298
|
+
0002_add_email_index.sql
|
|
299
|
+
pending (1):
|
|
300
|
+
0003_add_articles.sql
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
`--url` falls back to the `DATABASE_URL` environment variable. Exit codes: `0` on success, `1` on inconsistent state (drift or disappearance) -- so `etchdb status` is the natural gate before `etchdb migrate` in a deploy pipeline -- and `2` on usage errors (missing directory, no URL).
|
|
304
|
+
|
|
272
305
|
## Under consideration
|
|
273
306
|
|
|
274
307
|
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.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "etchdb"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.6.0"
|
|
4
4
|
description = "Minimal async DB layer for Python. Typed CRUD over Pydantic, raw SQL when you need it"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12"
|
|
@@ -57,6 +57,9 @@ Homepage = "https://github.com/varjoranta/etchdb"
|
|
|
57
57
|
Repository = "https://github.com/varjoranta/etchdb"
|
|
58
58
|
Issues = "https://github.com/varjoranta/etchdb/issues"
|
|
59
59
|
|
|
60
|
+
[project.scripts]
|
|
61
|
+
etchdb = "etchdb.cli:main"
|
|
62
|
+
|
|
60
63
|
[build-system]
|
|
61
64
|
requires = ["hatchling"]
|
|
62
65
|
build-backend = "hatchling.build"
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""etchdb command-line entry point.
|
|
2
|
+
|
|
3
|
+
Two subcommands:
|
|
4
|
+
|
|
5
|
+
etchdb migrate ./migrations --url $DATABASE_URL
|
|
6
|
+
etchdb status ./migrations --url $DATABASE_URL
|
|
7
|
+
|
|
8
|
+
`--url` falls back to the `DATABASE_URL` env var if not given. Exit
|
|
9
|
+
codes: 0 on success, 1 on inconsistent migration state (drift or
|
|
10
|
+
disappearance), 2 on usage error (missing args, missing directory,
|
|
11
|
+
no database URL).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import asyncio
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import TYPE_CHECKING
|
|
22
|
+
|
|
23
|
+
from etchdb import DB
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from etchdb.migrations import MigrationStatus
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _format_status(status: MigrationStatus, directory: Path) -> str:
|
|
30
|
+
lines: list[str] = [f"Migration status ({directory}):"]
|
|
31
|
+
if not status.is_consistent:
|
|
32
|
+
lines.append(" ! INCONSISTENT -- fix before applying")
|
|
33
|
+
for label, names in (
|
|
34
|
+
("drifted", status.drifted),
|
|
35
|
+
("missing", status.missing),
|
|
36
|
+
("applied", status.applied),
|
|
37
|
+
("pending", status.pending),
|
|
38
|
+
):
|
|
39
|
+
if names:
|
|
40
|
+
lines.append(f" {label} ({len(names)}):")
|
|
41
|
+
lines.extend(f" {fn}" for fn in names)
|
|
42
|
+
if not any((status.applied, status.pending, status.drifted, status.missing)):
|
|
43
|
+
lines.append(" (no migrations found)")
|
|
44
|
+
return "\n".join(lines)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def _run_migrate(url: str, directory: Path) -> int:
|
|
48
|
+
db = await DB.from_url(url)
|
|
49
|
+
try:
|
|
50
|
+
applied = await db.migrate(directory)
|
|
51
|
+
print(f"applied {applied} migration{'s' if applied != 1 else ''}")
|
|
52
|
+
return 0
|
|
53
|
+
finally:
|
|
54
|
+
await db.close()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def _run_status(url: str, directory: Path) -> int:
|
|
58
|
+
db = await DB.from_url(url)
|
|
59
|
+
try:
|
|
60
|
+
status = await db.migration_status(directory)
|
|
61
|
+
print(_format_status(status, directory))
|
|
62
|
+
return 0 if status.is_consistent else 1
|
|
63
|
+
finally:
|
|
64
|
+
await db.close()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
68
|
+
parser = argparse.ArgumentParser(prog="etchdb", description="etchdb command-line tools")
|
|
69
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
70
|
+
for cmd_name, help_text in (
|
|
71
|
+
("migrate", "apply pending migrations"),
|
|
72
|
+
("status", "show migration state without applying"),
|
|
73
|
+
):
|
|
74
|
+
p = sub.add_parser(cmd_name, help=help_text)
|
|
75
|
+
p.add_argument(
|
|
76
|
+
"directory",
|
|
77
|
+
type=Path,
|
|
78
|
+
help="migrations directory (e.g. ./migrations)",
|
|
79
|
+
)
|
|
80
|
+
p.add_argument(
|
|
81
|
+
"--url",
|
|
82
|
+
help="database URL (falls back to DATABASE_URL env var)",
|
|
83
|
+
)
|
|
84
|
+
return parser
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def main(argv: list[str] | None = None) -> int:
|
|
88
|
+
args = _build_parser().parse_args(argv)
|
|
89
|
+
|
|
90
|
+
url = args.url or os.environ.get("DATABASE_URL")
|
|
91
|
+
if not url:
|
|
92
|
+
print(
|
|
93
|
+
"error: database URL required (pass --url or set DATABASE_URL)",
|
|
94
|
+
file=sys.stderr,
|
|
95
|
+
)
|
|
96
|
+
return 2
|
|
97
|
+
|
|
98
|
+
runner = {"migrate": _run_migrate, "status": _run_status}[args.cmd]
|
|
99
|
+
try:
|
|
100
|
+
return asyncio.run(runner(url, args.directory))
|
|
101
|
+
except RuntimeError as e:
|
|
102
|
+
# Migration inconsistency (drift / disappearance) from db.migrate.
|
|
103
|
+
print(f"error: {e}", file=sys.stderr)
|
|
104
|
+
return 1
|
|
105
|
+
except ValueError as e:
|
|
106
|
+
# Missing directory, malformed migration file, etc.
|
|
107
|
+
print(f"error: {e}", file=sys.stderr)
|
|
108
|
+
return 2
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
sys.exit(main())
|
|
@@ -59,6 +59,17 @@ class DB:
|
|
|
59
59
|
def __init__(self, adapter: AdapterBase):
|
|
60
60
|
self._adapter = adapter
|
|
61
61
|
|
|
62
|
+
async def __aenter__(self) -> DB:
|
|
63
|
+
"""Enable `async with db:` on an already-open DB; closes on exit.
|
|
64
|
+
|
|
65
|
+
`async with DB.from_url(...) as db:` does not work -- `from_url`
|
|
66
|
+
is a coroutine. Open first, then enter the block.
|
|
67
|
+
"""
|
|
68
|
+
return self
|
|
69
|
+
|
|
70
|
+
async def __aexit__(self, *_exc_info: object) -> None:
|
|
71
|
+
await self.close()
|
|
72
|
+
|
|
62
73
|
@classmethod
|
|
63
74
|
async def from_url(
|
|
64
75
|
cls,
|
|
@@ -128,6 +139,20 @@ class DB:
|
|
|
128
139
|
async def fetchval(self, sql: str, *params: Any) -> Any:
|
|
129
140
|
return await self._adapter.fetchval(sql, *params)
|
|
130
141
|
|
|
142
|
+
async def ping(self) -> bool:
|
|
143
|
+
"""Round-trip a `SELECT 1` to verify the connection is alive.
|
|
144
|
+
|
|
145
|
+
Returns `True` on success, `False` on any failure (closed pool,
|
|
146
|
+
network error, etc.). Useful for liveness probes and health
|
|
147
|
+
endpoints. If you want the underlying exception (e.g. for
|
|
148
|
+
diagnostics), call `fetchval('SELECT 1')` directly.
|
|
149
|
+
"""
|
|
150
|
+
try:
|
|
151
|
+
await self._adapter.fetchval("SELECT 1")
|
|
152
|
+
except Exception: # noqa: BLE001 healthcheck: any failure -> False
|
|
153
|
+
return False
|
|
154
|
+
return True
|
|
155
|
+
|
|
131
156
|
@asynccontextmanager
|
|
132
157
|
async def transaction(self) -> AsyncIterator[DB]:
|
|
133
158
|
"""Open a transaction. Commits on clean exit, rolls back on exception.
|
|
@@ -213,6 +238,61 @@ class DB:
|
|
|
213
238
|
return
|
|
214
239
|
offset += batch_size
|
|
215
240
|
|
|
241
|
+
async def iter_rows_keyset(
|
|
242
|
+
self,
|
|
243
|
+
model: type[Row],
|
|
244
|
+
*,
|
|
245
|
+
by: str | None = None,
|
|
246
|
+
batch_size: int = 500,
|
|
247
|
+
**filters: Any,
|
|
248
|
+
) -> AsyncIterator[Row]:
|
|
249
|
+
"""Stream every matching row via keyset pagination.
|
|
250
|
+
|
|
251
|
+
Unlike `iter_rows`, the per-page cost stays constant -- each
|
|
252
|
+
page reads `batch_size` rows via `WHERE <by> > <last_seen>`
|
|
253
|
+
rather than `OFFSET N`, so total cost is O(N) instead of
|
|
254
|
+
O(N^2). The trade-off is the constraint on `by`:
|
|
255
|
+
|
|
256
|
+
- It must be a single column (composite-PK keyset uses
|
|
257
|
+
`(a, b) > (last_a, last_b)` and isn't supported here).
|
|
258
|
+
- It must be monotonic-ordered and unique enough that no two
|
|
259
|
+
rows tie. Primary keys usually qualify; created_at columns
|
|
260
|
+
can if the resolution is high enough.
|
|
261
|
+
|
|
262
|
+
Defaults to `model.__pk__[0]`. Filters are AND'd with the
|
|
263
|
+
cursor. Ordering is ascending; descending is not supported.
|
|
264
|
+
"""
|
|
265
|
+
if batch_size < 1:
|
|
266
|
+
raise ValueError(f"batch_size must be >= 1, got {batch_size}")
|
|
267
|
+
if _has_empty_collection_filter(filters):
|
|
268
|
+
return
|
|
269
|
+
if by is None:
|
|
270
|
+
if len(model.__pk__) > 1:
|
|
271
|
+
raise ValueError(
|
|
272
|
+
f"{model.__name__} has composite PK {model.__pk__}; "
|
|
273
|
+
f"pass `by=<column>` explicitly."
|
|
274
|
+
)
|
|
275
|
+
by = model.__pk__[0]
|
|
276
|
+
|
|
277
|
+
last_seen: Any = None
|
|
278
|
+
while True:
|
|
279
|
+
q = sql.select_keyset(
|
|
280
|
+
model,
|
|
281
|
+
placeholder=self._adapter.placeholder,
|
|
282
|
+
by=by,
|
|
283
|
+
batch_size=batch_size,
|
|
284
|
+
last_seen=last_seen,
|
|
285
|
+
**filters,
|
|
286
|
+
)
|
|
287
|
+
rows = await self._adapter.fetch(q.sql, *q.params)
|
|
288
|
+
if not rows:
|
|
289
|
+
return
|
|
290
|
+
for row in rows:
|
|
291
|
+
yield model(**row)
|
|
292
|
+
if len(rows) < batch_size:
|
|
293
|
+
return
|
|
294
|
+
last_seen = rows[-1][by]
|
|
295
|
+
|
|
216
296
|
async def insert(self, row: Row, *, on_conflict: sql._OnConflict = None) -> Row:
|
|
217
297
|
"""Insert `row` and return the DB's view (RETURNING *).
|
|
218
298
|
|
|
@@ -284,6 +364,26 @@ class DB:
|
|
|
284
364
|
result = await self._adapter.fetchrow(q.sql, *q.params)
|
|
285
365
|
return _hydrate(row, result)
|
|
286
366
|
|
|
367
|
+
async def update_where(self, row: Row, *, where: Mapping[str, Any]) -> int:
|
|
368
|
+
"""Bulk-update rows scoped entirely by `where=`. Returns the
|
|
369
|
+
affected-row count.
|
|
370
|
+
|
|
371
|
+
The row's PK is not part of the WHERE clause; it supplies only
|
|
372
|
+
the SET fields. Common shape:
|
|
373
|
+
|
|
374
|
+
n = await db.update_where(
|
|
375
|
+
User.patch(status="archived"),
|
|
376
|
+
where={"id": [1, 2, 3]},
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
`where=` must be non-empty; for "update every row" use
|
|
380
|
+
`db.execute` with raw SQL. For single-row updates by PK, use
|
|
381
|
+
`db.update`."""
|
|
382
|
+
if _has_empty_collection_filter(where):
|
|
383
|
+
return 0
|
|
384
|
+
q = sql.update_where(row, placeholder=self._adapter.placeholder, where=where)
|
|
385
|
+
return await self._adapter.execute(q.sql, *q.params)
|
|
386
|
+
|
|
287
387
|
async def delete(self, row: Row, *, where: Mapping[str, Any] | None = None) -> None:
|
|
288
388
|
"""Delete `row` by PK, AND'd with `where=`."""
|
|
289
389
|
if _has_empty_collection_filter(where):
|
|
@@ -140,6 +140,46 @@ def select_many(
|
|
|
140
140
|
return SqlQuery(sql=sql, params=params)
|
|
141
141
|
|
|
142
142
|
|
|
143
|
+
def select_keyset(
|
|
144
|
+
row_class: type[Row],
|
|
145
|
+
*,
|
|
146
|
+
placeholder: Callable[[int], str],
|
|
147
|
+
by: str,
|
|
148
|
+
batch_size: int,
|
|
149
|
+
last_seen: Any = None,
|
|
150
|
+
**filters: Any,
|
|
151
|
+
) -> SqlQuery:
|
|
152
|
+
"""Build a single page of a keyset-paginated SELECT.
|
|
153
|
+
|
|
154
|
+
Emits `SELECT cols FROM table [WHERE <filters> [AND by > last_seen]]
|
|
155
|
+
ORDER BY by LIMIT batch_size`. The first page passes
|
|
156
|
+
`last_seen=None`, which drops the cursor predicate; subsequent
|
|
157
|
+
pages bind the previous page's max value for `by`.
|
|
158
|
+
"""
|
|
159
|
+
if by not in _db_fields(row_class):
|
|
160
|
+
raise ValueError(f"keyset column {by!r} is not a DB column on {row_class.__name__}.")
|
|
161
|
+
if by in filters:
|
|
162
|
+
raise ValueError(f"keyset column {by!r} cannot also appear in filters.")
|
|
163
|
+
|
|
164
|
+
table = _table_name(row_class)
|
|
165
|
+
columns = ", ".join(_db_fields(row_class))
|
|
166
|
+
where_sql, params = _where_clauses(filters, placeholder=placeholder)
|
|
167
|
+
where_parts = [where_sql] if where_sql else []
|
|
168
|
+
|
|
169
|
+
if last_seen is not None:
|
|
170
|
+
where_parts.append(f"{by} > {placeholder(len(params))}")
|
|
171
|
+
params.append(last_seen)
|
|
172
|
+
|
|
173
|
+
sql = f"SELECT {columns} FROM {table}"
|
|
174
|
+
if where_parts:
|
|
175
|
+
sql += f" WHERE {' AND '.join(where_parts)}"
|
|
176
|
+
sql += f" ORDER BY {by}"
|
|
177
|
+
params.append(batch_size)
|
|
178
|
+
sql += f" LIMIT {placeholder(len(params) - 1)}"
|
|
179
|
+
|
|
180
|
+
return SqlQuery(sql=sql, params=params)
|
|
181
|
+
|
|
182
|
+
|
|
143
183
|
def update(
|
|
144
184
|
row: Row,
|
|
145
185
|
*,
|
|
@@ -182,6 +222,49 @@ def update(
|
|
|
182
222
|
return SqlQuery(sql=sql, params=set_values + where_values)
|
|
183
223
|
|
|
184
224
|
|
|
225
|
+
def update_where(
|
|
226
|
+
row: Row,
|
|
227
|
+
*,
|
|
228
|
+
placeholder: Callable[[int], str],
|
|
229
|
+
where: Mapping[str, Any],
|
|
230
|
+
) -> SqlQuery:
|
|
231
|
+
"""Build a bulk UPDATE scoped entirely by `where=`.
|
|
232
|
+
|
|
233
|
+
Unlike `update`, the row's PK is not part of the WHERE clause; the
|
|
234
|
+
row is used only to supply the SET fields (everything in
|
|
235
|
+
`model_fields_set` except PK columns). `where=` must be non-empty
|
|
236
|
+
-- a missing WHERE would update every row, which is almost always
|
|
237
|
+
a bug; for that, use `db.execute` with raw SQL.
|
|
238
|
+
|
|
239
|
+
Returns the affected-row count from the underlying execute, not a
|
|
240
|
+
Row. The common shape is `update_where(User.patch(status="x"),
|
|
241
|
+
where={"id": [...]})` for "apply this patch to all matching rows".
|
|
242
|
+
"""
|
|
243
|
+
if not where:
|
|
244
|
+
raise ValueError(
|
|
245
|
+
"update_where requires a non-empty `where=` mapping. "
|
|
246
|
+
"Bulk-updating every row in a table without a filter is "
|
|
247
|
+
"almost always a bug; use db.execute with raw SQL if you "
|
|
248
|
+
"really mean it."
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
table = _table_name(row)
|
|
252
|
+
pk_set = set(row.__pk__)
|
|
253
|
+
set_fields = [f for f in _db_fields(type(row)) if f in row.model_fields_set and f not in pk_set]
|
|
254
|
+
if not set_fields:
|
|
255
|
+
raise ValueError(
|
|
256
|
+
f"{type(row).__name__} has no non-PK fields to update; "
|
|
257
|
+
f"update_where needs at least one set field as the patch."
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
set_items = {f: getattr(row, f) for f in set_fields}
|
|
261
|
+
set_sql, set_values = _set_clauses(set_items, placeholder=placeholder)
|
|
262
|
+
where_sql, where_values = _where_clauses(where, placeholder=placeholder, start=len(set_values))
|
|
263
|
+
|
|
264
|
+
sql = f"UPDATE {table} SET {set_sql} WHERE {where_sql}"
|
|
265
|
+
return SqlQuery(sql=sql, params=set_values + where_values)
|
|
266
|
+
|
|
267
|
+
|
|
185
268
|
def delete(
|
|
186
269
|
row: Row,
|
|
187
270
|
*,
|
|
@@ -311,14 +394,26 @@ def delete_many(
|
|
|
311
394
|
_OPS = {
|
|
312
395
|
"get": select_one,
|
|
313
396
|
"query": select_many,
|
|
397
|
+
"select_keyset": select_keyset,
|
|
314
398
|
"insert": insert,
|
|
315
399
|
"update": update,
|
|
400
|
+
"update_where": update_where,
|
|
316
401
|
"delete": delete,
|
|
317
402
|
"insert_many": insert_many,
|
|
318
403
|
"delete_many": delete_many,
|
|
319
404
|
}
|
|
320
405
|
|
|
321
|
-
Op = Literal[
|
|
406
|
+
Op = Literal[
|
|
407
|
+
"get",
|
|
408
|
+
"query",
|
|
409
|
+
"select_keyset",
|
|
410
|
+
"insert",
|
|
411
|
+
"update",
|
|
412
|
+
"update_where",
|
|
413
|
+
"delete",
|
|
414
|
+
"insert_many",
|
|
415
|
+
"delete_many",
|
|
416
|
+
]
|
|
322
417
|
|
|
323
418
|
|
|
324
419
|
def compose(
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Integration tests for the CLI: call `main(argv=...)` against a
|
|
2
|
+
real SQLite database and verify exit codes + output. We use SQLite
|
|
3
|
+
because it's always available; the CLI uses the same DB.from_url
|
|
4
|
+
path as the rest of etchdb so PG-only verification would only
|
|
5
|
+
exercise the URL dispatch we already test elsewhere."""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from etchdb.cli import main
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture
|
|
15
|
+
def db_url(tmp_path: Path) -> str:
|
|
16
|
+
"""Each test gets its own SQLite file URL so state doesn't leak."""
|
|
17
|
+
return f"sqlite+aiosqlite:///{tmp_path}/test.db"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _write_migration(directory: Path, name: str, sql: str) -> None:
|
|
21
|
+
directory.mkdir(exist_ok=True)
|
|
22
|
+
(directory / name).write_text(sql)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_cli_migrate_applies_pending(tmp_path, db_url, capsys):
|
|
26
|
+
mig_dir = tmp_path / "migrations"
|
|
27
|
+
_write_migration(mig_dir, "0001_init.sql", "CREATE TABLE m_cli (id INTEGER PRIMARY KEY)")
|
|
28
|
+
|
|
29
|
+
rc = main(["migrate", str(mig_dir), "--url", db_url])
|
|
30
|
+
|
|
31
|
+
assert rc == 0
|
|
32
|
+
assert "applied 1 migration" in capsys.readouterr().out
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_cli_migrate_via_env_var(tmp_path, monkeypatch, db_url, capsys):
|
|
36
|
+
"""DATABASE_URL is the fallback when --url is not given."""
|
|
37
|
+
mig_dir = tmp_path / "migrations"
|
|
38
|
+
_write_migration(mig_dir, "0001_init.sql", "CREATE TABLE m_env (id INTEGER PRIMARY KEY)")
|
|
39
|
+
monkeypatch.setenv("DATABASE_URL", db_url)
|
|
40
|
+
|
|
41
|
+
rc = main(["migrate", str(mig_dir)])
|
|
42
|
+
|
|
43
|
+
assert rc == 0
|
|
44
|
+
assert "applied 1 migration" in capsys.readouterr().out
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_cli_status_consistent_returns_zero(tmp_path, db_url, capsys):
|
|
48
|
+
mig_dir = tmp_path / "migrations"
|
|
49
|
+
_write_migration(mig_dir, "0001_init.sql", "CREATE TABLE m_cli_s (id INTEGER PRIMARY KEY)")
|
|
50
|
+
|
|
51
|
+
main(["migrate", str(mig_dir), "--url", db_url])
|
|
52
|
+
capsys.readouterr() # discard
|
|
53
|
+
rc = main(["status", str(mig_dir), "--url", db_url])
|
|
54
|
+
|
|
55
|
+
out = capsys.readouterr().out
|
|
56
|
+
assert rc == 0
|
|
57
|
+
assert "INCONSISTENT" not in out
|
|
58
|
+
assert "applied (1)" in out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_cli_status_inconsistent_returns_one(tmp_path, db_url, capsys):
|
|
62
|
+
"""Drift makes status exit 1 -- CI / deploy scripts can use this
|
|
63
|
+
as the gate before running migrate."""
|
|
64
|
+
mig_dir = tmp_path / "migrations"
|
|
65
|
+
_write_migration(mig_dir, "0001_init.sql", "CREATE TABLE m_cli_d (id INTEGER PRIMARY KEY)")
|
|
66
|
+
main(["migrate", str(mig_dir), "--url", db_url])
|
|
67
|
+
capsys.readouterr()
|
|
68
|
+
|
|
69
|
+
# Drift the file content after applying.
|
|
70
|
+
_write_migration(
|
|
71
|
+
mig_dir,
|
|
72
|
+
"0001_init.sql",
|
|
73
|
+
"CREATE TABLE m_cli_d (id INTEGER PRIMARY KEY, name TEXT)",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
rc = main(["status", str(mig_dir), "--url", db_url])
|
|
77
|
+
|
|
78
|
+
out = capsys.readouterr().out
|
|
79
|
+
assert rc == 1
|
|
80
|
+
assert "INCONSISTENT" in out
|
|
81
|
+
assert "drifted" in out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_cli_migrate_inconsistent_returns_one(tmp_path, db_url, capsys):
|
|
85
|
+
mig_dir = tmp_path / "migrations"
|
|
86
|
+
_write_migration(mig_dir, "0001_init.sql", "CREATE TABLE m_cli_m (id INTEGER PRIMARY KEY)")
|
|
87
|
+
main(["migrate", str(mig_dir), "--url", db_url])
|
|
88
|
+
capsys.readouterr()
|
|
89
|
+
(mig_dir / "0001_init.sql").unlink()
|
|
90
|
+
|
|
91
|
+
rc = main(["migrate", str(mig_dir), "--url", db_url])
|
|
92
|
+
|
|
93
|
+
assert rc == 1
|
|
94
|
+
assert "inconsistent" in capsys.readouterr().err.lower()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_cli_missing_directory_returns_two(tmp_path, db_url, capsys):
|
|
98
|
+
"""Pointing at a directory that doesn't exist is a usage error
|
|
99
|
+
(exit 2), not a runtime error."""
|
|
100
|
+
rc = main(["migrate", str(tmp_path / "no-such-dir"), "--url", db_url])
|
|
101
|
+
|
|
102
|
+
assert rc == 2
|
|
103
|
+
assert "not found" in capsys.readouterr().err.lower()
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Integration tests for db.iter_rows_keyset across all three backends.
|
|
2
|
+
|
|
3
|
+
The keyset iterator emits `WHERE <by> > <last_seen>` per page, so total
|
|
4
|
+
cost stays O(N) rather than O(N^2) like `iter_rows`. Tests pin: full
|
|
5
|
+
ordered yield, batch boundaries, filter propagation, default `by`
|
|
6
|
+
column, explicit `by` override, and the input validation."""
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from etchdb import DB
|
|
11
|
+
from tests._models import User
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def test_iter_rows_keyset_yields_all_rows_ordered(db: DB):
|
|
15
|
+
for i in range(1, 8):
|
|
16
|
+
await db.insert(User(id=i, name=f"u{i}"))
|
|
17
|
+
|
|
18
|
+
rows = [u async for u in db.iter_rows_keyset(User, batch_size=3)]
|
|
19
|
+
|
|
20
|
+
assert [u.id for u in rows] == [1, 2, 3, 4, 5, 6, 7]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def test_iter_rows_keyset_uses_pk_by_default(db: DB):
|
|
24
|
+
"""`by=None` defaults to `model.__pk__[0]`; pagination still
|
|
25
|
+
works when the user doesn't specify the column."""
|
|
26
|
+
for i in range(1, 4):
|
|
27
|
+
await db.insert(User(id=i, name=f"u{i}"))
|
|
28
|
+
|
|
29
|
+
rows = [u async for u in db.iter_rows_keyset(User)]
|
|
30
|
+
|
|
31
|
+
assert [u.id for u in rows] == [1, 2, 3]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def test_iter_rows_keyset_filter_propagates(db: DB):
|
|
35
|
+
"""Extra filter kwargs are AND'd with the keyset cursor on every
|
|
36
|
+
page. Only rows that match the filter are yielded."""
|
|
37
|
+
await db.insert(User(id=1, name="alice"))
|
|
38
|
+
await db.insert(User(id=2, name="bob"))
|
|
39
|
+
await db.insert(User(id=3, name="alice"))
|
|
40
|
+
await db.insert(User(id=4, name="bob"))
|
|
41
|
+
|
|
42
|
+
rows = [u async for u in db.iter_rows_keyset(User, batch_size=2, name="alice")]
|
|
43
|
+
|
|
44
|
+
assert [u.id for u in rows] == [1, 3]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def test_iter_rows_keyset_empty_table_yields_nothing(db: DB):
|
|
48
|
+
rows = [u async for u in db.iter_rows_keyset(User)]
|
|
49
|
+
assert rows == []
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def test_iter_rows_keyset_rejects_non_positive_batch_size(db: DB):
|
|
53
|
+
with pytest.raises(ValueError, match="batch_size"):
|
|
54
|
+
async for _ in db.iter_rows_keyset(User, batch_size=0):
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def test_iter_rows_keyset_rejects_by_in_filters(db: DB):
|
|
59
|
+
"""If the user already constrains the keyset column via a filter,
|
|
60
|
+
the cursor's `>` predicate plus their `=` predicate would be
|
|
61
|
+
over-determined. Reject up front."""
|
|
62
|
+
with pytest.raises(ValueError, match="cannot also appear in filters"):
|
|
63
|
+
async for _ in db.iter_rows_keyset(User, by="id", id=5):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def test_iter_rows_keyset_empty_list_filter_short_circuits(db: DB):
|
|
68
|
+
"""Empty-list filter follows the same short-circuit convention as
|
|
69
|
+
iter_rows / query / get; nothing is yielded, no round trip."""
|
|
70
|
+
await db.insert(User(id=1, name="alice"))
|
|
71
|
+
rows = [u async for u in db.iter_rows_keyset(User, id=[])]
|
|
72
|
+
assert rows == []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def test_iter_rows_keyset_composite_pk_requires_explicit_by(db: DB):
|
|
76
|
+
"""Defaulting `by` to `__pk__[0]` on a composite PK can silently
|
|
77
|
+
duplicate or skip rows when the leading column ties. Refuse and
|
|
78
|
+
point the user at the explicit `by=` form."""
|
|
79
|
+
from tests._models import UserRole
|
|
80
|
+
|
|
81
|
+
with pytest.raises(ValueError, match="composite PK"):
|
|
82
|
+
async for _ in db.iter_rows_keyset(UserRole):
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def test_iter_rows_keyset_rejects_non_db_column(db: DB):
|
|
87
|
+
"""If the user passes `by=<col>` for a field that isn't a DB
|
|
88
|
+
column (e.g. excluded via __fields_not_in_db__), the row dict
|
|
89
|
+
won't carry it and the cursor advance would KeyError mid-loop.
|
|
90
|
+
Catch the misuse before the first query."""
|
|
91
|
+
with pytest.raises(ValueError, match="not a DB column"):
|
|
92
|
+
async for _ in db.iter_rows_keyset(User, by="nonexistent_col"):
|
|
93
|
+
pass
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Integration tests for db.ping() and the `async with db:` context
|
|
2
|
+
manager. Both are small but exercise the cross-driver path."""
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from etchdb import DB
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def test_ping_returns_true_on_healthy_db(db: DB):
|
|
10
|
+
assert await db.ping() is True
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def test_ping_returns_false_on_closed_db():
|
|
14
|
+
"""A closed pool / connection makes ping return False rather than
|
|
15
|
+
raising. Callers can do `if await db.ping(): ...` in healthchecks
|
|
16
|
+
without wrapping in try/except."""
|
|
17
|
+
db = await DB.from_url("sqlite+aiosqlite:///:memory:")
|
|
18
|
+
await db.close()
|
|
19
|
+
assert await db.ping() is False
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
async def test_async_with_closes_on_exit():
|
|
23
|
+
"""`async with db:` calls close() on exit; subsequent ping is False."""
|
|
24
|
+
db = await DB.from_url("sqlite+aiosqlite:///:memory:")
|
|
25
|
+
async with db:
|
|
26
|
+
assert await db.ping() is True
|
|
27
|
+
assert await db.ping() is False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
async def test_async_with_closes_on_exception():
|
|
31
|
+
"""Exit-on-exception still closes the DB; the follow-up ping
|
|
32
|
+
reflects that with False."""
|
|
33
|
+
db = await DB.from_url("sqlite+aiosqlite:///:memory:")
|
|
34
|
+
|
|
35
|
+
class _SentinelError(Exception):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
with pytest.raises(_SentinelError):
|
|
39
|
+
async with db:
|
|
40
|
+
raise _SentinelError
|
|
41
|
+
|
|
42
|
+
assert await db.ping() is False
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Integration tests for db.update_where: bulk update scoped by where=.
|
|
2
|
+
|
|
3
|
+
Pin the behaviour across all three backends: the patch (set fields)
|
|
4
|
+
applies, the WHERE scopes correctly, the return value is the
|
|
5
|
+
affected-row count, and the empty-list short-circuit works."""
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from etchdb import DB
|
|
10
|
+
from tests._models import User
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def test_update_where_bulk_patch_applies_to_matching_rows(db: DB):
|
|
14
|
+
"""One patch is applied to every row that matches the IN filter;
|
|
15
|
+
rows outside the filter stay unchanged."""
|
|
16
|
+
for i in range(1, 5):
|
|
17
|
+
await db.insert(User(id=i, name=f"u{i}"))
|
|
18
|
+
|
|
19
|
+
n = await db.update_where(
|
|
20
|
+
User.patch(name="archived"),
|
|
21
|
+
where={"id": [1, 3]},
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
assert n == 2
|
|
25
|
+
rows = await db.query(User, order_by="id")
|
|
26
|
+
assert [u.name for u in rows] == ["archived", "u2", "archived", "u4"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def test_update_where_no_match_returns_zero(db: DB):
|
|
30
|
+
await db.insert(User(id=1, name="alice"))
|
|
31
|
+
|
|
32
|
+
n = await db.update_where(
|
|
33
|
+
User.patch(name="x"),
|
|
34
|
+
where={"id": [999]},
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
assert n == 0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def test_update_where_empty_list_short_circuits(db: DB):
|
|
41
|
+
"""Empty-list filter follows the same short-circuit convention as
|
|
42
|
+
query / get / update: returns 0 without round-tripping. No SQL is
|
|
43
|
+
emitted, so the emitter's non-empty-where check isn't reached."""
|
|
44
|
+
await db.insert(User(id=1, name="alice"))
|
|
45
|
+
|
|
46
|
+
n = await db.update_where(
|
|
47
|
+
User.patch(name="x"),
|
|
48
|
+
where={"id": []},
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
assert n == 0
|
|
52
|
+
fetched = await db.get(User, id=1)
|
|
53
|
+
assert fetched is not None and fetched.name == "alice"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def test_update_where_is_null_filter(db: DB):
|
|
57
|
+
"""None in `where=` emits IS NULL via _where_clauses; rows with
|
|
58
|
+
NULL in the targeted column match, rows with a value don't."""
|
|
59
|
+
await db.insert(User(id=1, name="a", email=None))
|
|
60
|
+
await db.insert(User(id=2, name="b", email="b@x"))
|
|
61
|
+
await db.insert(User(id=3, name="c", email=None))
|
|
62
|
+
|
|
63
|
+
n = await db.update_where(
|
|
64
|
+
User.patch(name="cleaned"),
|
|
65
|
+
where={"email": None},
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
assert n == 2
|
|
69
|
+
rows = await db.query(User, order_by="id")
|
|
70
|
+
assert [u.name for u in rows] == ["cleaned", "b", "cleaned"]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def test_update_where_empty_dict_raises(db: DB):
|
|
74
|
+
"""Distinct from the empty-list short-circuit: an empty dict
|
|
75
|
+
means 'no filter at all', which would update every row -- almost
|
|
76
|
+
always a bug -- so the emitter raises."""
|
|
77
|
+
await db.insert(User(id=1, name="alice"))
|
|
78
|
+
with pytest.raises(ValueError, match="non-empty"):
|
|
79
|
+
await db.update_where(User.patch(name="x"), where={})
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Unit tests for the CLI entry point.
|
|
2
|
+
|
|
3
|
+
DB-touching paths are covered in tests/integration/test_cli.py.
|
|
4
|
+
These tests cover argument parsing, status formatting, and the
|
|
5
|
+
env-var / exit-code surface that doesn't need a live database."""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from etchdb.cli import _build_parser, _format_status, main
|
|
12
|
+
from etchdb.migrations import MigrationStatus
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_parser_requires_subcommand():
|
|
16
|
+
"""`etchdb` with no args should error rather than do something
|
|
17
|
+
surprising."""
|
|
18
|
+
parser = _build_parser()
|
|
19
|
+
with pytest.raises(SystemExit):
|
|
20
|
+
parser.parse_args([])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_parser_accepts_migrate_with_directory():
|
|
24
|
+
parser = _build_parser()
|
|
25
|
+
args = parser.parse_args(["migrate", "./migrations"])
|
|
26
|
+
assert args.cmd == "migrate"
|
|
27
|
+
assert args.directory == Path("./migrations")
|
|
28
|
+
assert args.url is None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_parser_accepts_status_with_url():
|
|
32
|
+
parser = _build_parser()
|
|
33
|
+
args = parser.parse_args(["status", "./migrations", "--url", "sqlite:///:memory:"])
|
|
34
|
+
assert args.cmd == "status"
|
|
35
|
+
assert args.url == "sqlite:///:memory:"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_main_returns_2_when_no_url(monkeypatch, capsys):
|
|
39
|
+
"""Missing both --url and DATABASE_URL is a usage error (exit 2),
|
|
40
|
+
not a runtime error (exit 1)."""
|
|
41
|
+
monkeypatch.delenv("DATABASE_URL", raising=False)
|
|
42
|
+
rc = main(["migrate", "./does-not-matter"])
|
|
43
|
+
assert rc == 2
|
|
44
|
+
assert "database URL required" in capsys.readouterr().err
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_format_status_consistent_with_pending_and_applied(tmp_path):
|
|
48
|
+
s = MigrationStatus(
|
|
49
|
+
pending=["0003_x.sql"],
|
|
50
|
+
applied=["0001_a.sql", "0002_b.sql"],
|
|
51
|
+
)
|
|
52
|
+
out = _format_status(s, tmp_path)
|
|
53
|
+
assert "INCONSISTENT" not in out
|
|
54
|
+
assert "applied (2)" in out
|
|
55
|
+
assert "0001_a.sql" in out
|
|
56
|
+
assert "pending (1)" in out
|
|
57
|
+
assert "0003_x.sql" in out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_format_status_inconsistent_shows_drift_and_missing(tmp_path):
|
|
61
|
+
s = MigrationStatus(
|
|
62
|
+
applied=["0001_a.sql"],
|
|
63
|
+
drifted=["0002_b.sql"],
|
|
64
|
+
missing=["0003_c.sql"],
|
|
65
|
+
)
|
|
66
|
+
out = _format_status(s, tmp_path)
|
|
67
|
+
assert "INCONSISTENT" in out
|
|
68
|
+
assert "drifted (1)" in out
|
|
69
|
+
assert "0002_b.sql" in out
|
|
70
|
+
assert "missing (1)" in out
|
|
71
|
+
assert "0003_c.sql" in out
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_format_status_empty_directory(tmp_path):
|
|
75
|
+
s = MigrationStatus()
|
|
76
|
+
out = _format_status(s, tmp_path)
|
|
77
|
+
assert "(no migrations found)" in out
|
|
@@ -745,6 +745,123 @@ def test_insert_many_with_now_raises():
|
|
|
745
745
|
sql.insert_many([Article.patch(id=1, updated_at=Now())], placeholder=pg)
|
|
746
746
|
|
|
747
747
|
|
|
748
|
+
# --- select_keyset: single page of cursor-paginated SELECT ------------
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def test_select_keyset_first_page_omits_cursor_pg():
|
|
752
|
+
"""First page (last_seen=None) drops the `by > ...` predicate and
|
|
753
|
+
relies on ORDER BY + LIMIT alone."""
|
|
754
|
+
q = sql.select_keyset(User, placeholder=pg, by="id", batch_size=3)
|
|
755
|
+
assert q.sql == "SELECT id, name, email FROM users ORDER BY id LIMIT $1"
|
|
756
|
+
assert q.params == [3]
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def test_select_keyset_subsequent_page_emits_cursor_pg():
|
|
760
|
+
"""Once last_seen is set, the page's WHERE binds the previous max."""
|
|
761
|
+
q = sql.select_keyset(User, placeholder=pg, by="id", batch_size=3, last_seen=10)
|
|
762
|
+
assert q.sql == "SELECT id, name, email FROM users WHERE id > $1 ORDER BY id LIMIT $2"
|
|
763
|
+
assert q.params == [10, 3]
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def test_select_keyset_with_filter_pg():
|
|
767
|
+
"""Filter predicates land before the cursor in the WHERE chain;
|
|
768
|
+
placeholder numbering threads through filter binds first."""
|
|
769
|
+
q = sql.select_keyset(User, placeholder=pg, by="id", batch_size=2, last_seen=5, name="alice")
|
|
770
|
+
assert q.sql == (
|
|
771
|
+
"SELECT id, name, email FROM users WHERE name = $1 AND id > $2 ORDER BY id LIMIT $3"
|
|
772
|
+
)
|
|
773
|
+
assert q.params == ["alice", 5, 2]
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def test_select_keyset_sqlite():
|
|
777
|
+
q = sql.select_keyset(User, placeholder=lite, by="id", batch_size=2, last_seen=5)
|
|
778
|
+
assert q.sql == "SELECT id, name, email FROM users WHERE id > ? ORDER BY id LIMIT ?"
|
|
779
|
+
assert q.params == [5, 2]
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def test_select_keyset_rejects_non_db_column():
|
|
783
|
+
with pytest.raises(ValueError, match="not a DB column"):
|
|
784
|
+
sql.select_keyset(User, placeholder=pg, by="nope", batch_size=1)
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def test_select_keyset_rejects_by_in_filters():
|
|
788
|
+
with pytest.raises(ValueError, match="cannot also appear in filters"):
|
|
789
|
+
sql.select_keyset(User, placeholder=pg, by="id", batch_size=1, id=5)
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
# --- update_where: bulk update scoped by where= -------------------------
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def test_update_where_simple_pg():
|
|
796
|
+
"""Patch is built from a partial Row (no PK); WHERE comes entirely
|
|
797
|
+
from the `where=` mapping."""
|
|
798
|
+
q = sql.update_where(
|
|
799
|
+
User.patch(name="archived"),
|
|
800
|
+
placeholder=pg,
|
|
801
|
+
where={"id": 1},
|
|
802
|
+
)
|
|
803
|
+
assert q.sql == "UPDATE users SET name = $1 WHERE id = $2"
|
|
804
|
+
assert q.params == ["archived", 1]
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def test_update_where_in_clause_pg():
|
|
808
|
+
"""List values in `where=` produce IN clauses (the v0.4 IN feature
|
|
809
|
+
composes naturally with update_where)."""
|
|
810
|
+
q = sql.update_where(
|
|
811
|
+
User.patch(name="archived"),
|
|
812
|
+
placeholder=pg,
|
|
813
|
+
where={"id": [1, 2, 3]},
|
|
814
|
+
)
|
|
815
|
+
assert q.sql == "UPDATE users SET name = $1 WHERE id IN ($2, $3, $4)"
|
|
816
|
+
assert q.params == ["archived", 1, 2, 3]
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def test_update_where_is_null_filter_pg():
|
|
820
|
+
"""None in `where=` emits IS NULL just like in `update(where=...)`."""
|
|
821
|
+
q = sql.update_where(
|
|
822
|
+
User.patch(name="cleaned"),
|
|
823
|
+
placeholder=pg,
|
|
824
|
+
where={"email": None},
|
|
825
|
+
)
|
|
826
|
+
assert q.sql == "UPDATE users SET name = $1 WHERE email IS NULL"
|
|
827
|
+
assert q.params == ["cleaned"]
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def test_update_where_sqlite():
|
|
831
|
+
q = sql.update_where(
|
|
832
|
+
User.patch(name="archived"),
|
|
833
|
+
placeholder=lite,
|
|
834
|
+
where={"id": [1, 2]},
|
|
835
|
+
)
|
|
836
|
+
assert q.sql == "UPDATE users SET name = ? WHERE id IN (?, ?)"
|
|
837
|
+
assert q.params == ["archived", 1, 2]
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
def test_update_where_ignores_pk_field_in_patch():
|
|
841
|
+
"""If the caller accidentally sets a PK column on the patch row,
|
|
842
|
+
update_where drops it from SET silently. Updating PK values in a
|
|
843
|
+
bulk update is almost always a bug and never the intent."""
|
|
844
|
+
q = sql.update_where(
|
|
845
|
+
User.patch(id=99, name="x"), # id is in __pk__; gets dropped
|
|
846
|
+
placeholder=pg,
|
|
847
|
+
where={"email": "old@x"},
|
|
848
|
+
)
|
|
849
|
+
assert q.sql == "UPDATE users SET name = $1 WHERE email = $2"
|
|
850
|
+
assert q.params == ["x", "old@x"]
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def test_update_where_empty_where_raises():
|
|
854
|
+
"""Bulk-updating without a filter would update every row; refuse."""
|
|
855
|
+
with pytest.raises(ValueError, match="non-empty"):
|
|
856
|
+
sql.update_where(User.patch(name="x"), placeholder=pg, where={})
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def test_update_where_no_set_fields_raises():
|
|
860
|
+
"""A patch with only PK columns (or nothing) has nothing to set."""
|
|
861
|
+
with pytest.raises(ValueError, match="no non-PK fields"):
|
|
862
|
+
sql.update_where(User.patch(id=1), placeholder=pg, where={"status": "old"})
|
|
863
|
+
|
|
864
|
+
|
|
748
865
|
# --- delete ----------------------------------------------------------
|
|
749
866
|
|
|
750
867
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|