etchdb 0.5.0__tar.gz → 0.6.1__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.
Files changed (57) hide show
  1. etchdb-0.6.1/.github/workflows/ci.yml +76 -0
  2. {etchdb-0.5.0 → etchdb-0.6.1}/.github/workflows/release.yml +5 -0
  3. {etchdb-0.5.0 → etchdb-0.6.1}/.gitignore +1 -0
  4. {etchdb-0.5.0 → etchdb-0.6.1}/PKG-INFO +40 -4
  5. {etchdb-0.5.0 → etchdb-0.6.1}/README.md +39 -3
  6. {etchdb-0.5.0 → etchdb-0.6.1}/pyproject.toml +4 -1
  7. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/__init__.py +1 -1
  8. etchdb-0.6.1/src/etchdb/__main__.py +5 -0
  9. etchdb-0.6.1/src/etchdb/cli.py +112 -0
  10. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/db.py +100 -0
  11. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/sql/__init__.py +161 -1
  12. etchdb-0.6.1/tests/integration/test_cli.py +103 -0
  13. etchdb-0.6.1/tests/integration/test_iter_rows_keyset.py +184 -0
  14. etchdb-0.6.1/tests/integration/test_ping_and_aclose.py +42 -0
  15. etchdb-0.6.1/tests/integration/test_update_where.py +79 -0
  16. etchdb-0.6.1/tests/unit/test_cli.py +77 -0
  17. {etchdb-0.5.0 → etchdb-0.6.1}/tests/unit/test_sql_emitter.py +187 -0
  18. {etchdb-0.5.0 → etchdb-0.6.1}/.python-version +0 -0
  19. {etchdb-0.5.0 → etchdb-0.6.1}/LICENSE +0 -0
  20. {etchdb-0.5.0 → etchdb-0.6.1}/Makefile +0 -0
  21. {etchdb-0.5.0 → etchdb-0.6.1}/docker-compose.yml +0 -0
  22. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/adapter.py +0 -0
  23. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/aiosqlite/__init__.py +0 -0
  24. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/aiosqlite/adapter.py +0 -0
  25. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/asyncpg/__init__.py +0 -0
  26. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/asyncpg/adapter.py +0 -0
  27. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/codecs.py +0 -0
  28. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/errors.py +0 -0
  29. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/expr.py +0 -0
  30. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/migrations.py +0 -0
  31. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/psycopg/__init__.py +0 -0
  32. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/psycopg/adapter.py +0 -0
  33. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/py.typed +0 -0
  34. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/query.py +0 -0
  35. {etchdb-0.5.0 → etchdb-0.6.1}/src/etchdb/row.py +0 -0
  36. {etchdb-0.5.0 → etchdb-0.6.1}/tests/__init__.py +0 -0
  37. {etchdb-0.5.0 → etchdb-0.6.1}/tests/_models.py +0 -0
  38. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/__init__.py +0 -0
  39. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/conftest.py +0 -0
  40. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_batch.py +0 -0
  41. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_codecs.py +0 -0
  42. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_errors.py +0 -0
  43. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_execute_rowcount.py +0 -0
  44. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_expressions.py +0 -0
  45. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_facade.py +0 -0
  46. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_fields_not_in_db.py +0 -0
  47. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_in_filter.py +0 -0
  48. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_is_null.py +0 -0
  49. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_iter_rows.py +0 -0
  50. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_migrations.py +0 -0
  51. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_pool_kwargs.py +0 -0
  52. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_readme_example.py +0 -0
  53. {etchdb-0.5.0 → etchdb-0.6.1}/tests/integration/test_typed_crud.py +0 -0
  54. {etchdb-0.5.0 → etchdb-0.6.1}/tests/unit/__init__.py +0 -0
  55. {etchdb-0.5.0 → etchdb-0.6.1}/tests/unit/test_adapters.py +0 -0
  56. {etchdb-0.5.0 → etchdb-0.6.1}/tests/unit/test_db_dispatch.py +0 -0
  57. {etchdb-0.5.0 → etchdb-0.6.1}/tests/unit/test_migrations.py +0 -0
@@ -0,0 +1,76 @@
1
+ name: CI
2
+
3
+ # Runs on every push to main and every pull request. Three jobs:
4
+ # - lint: ruff on src + tests (single Python)
5
+ # - unit: pytest tests/unit across the full supported Python matrix
6
+ # - integration: pytest tests/integration across the matrix, with a
7
+ # Postgres 16 service container. SQLite always runs; the two
8
+ # Postgres adapters point at the service via ETCHDB_TEST_POSTGRES_DSN.
9
+
10
+ on:
11
+ push:
12
+ branches: [main]
13
+ pull_request:
14
+
15
+ concurrency:
16
+ group: ci-${{ github.ref }}
17
+ cancel-in-progress: true
18
+
19
+ jobs:
20
+ lint:
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+ - uses: astral-sh/setup-uv@v5
25
+ with:
26
+ python-version: "3.14"
27
+ cache-dependency-glob: "pyproject.toml"
28
+ - run: uv sync --extra dev
29
+ - run: uv run ruff check src/etchdb tests
30
+
31
+ unit:
32
+ runs-on: ubuntu-latest
33
+ strategy:
34
+ fail-fast: false
35
+ matrix:
36
+ python-version: ["3.12", "3.13", "3.14"]
37
+ steps:
38
+ - uses: actions/checkout@v4
39
+ - uses: astral-sh/setup-uv@v5
40
+ with:
41
+ python-version: ${{ matrix.python-version }}
42
+ cache-dependency-glob: "pyproject.toml"
43
+ - run: uv sync --extra all --extra dev
44
+ - run: uv run pytest tests/unit -q
45
+
46
+ integration:
47
+ runs-on: ubuntu-latest
48
+ strategy:
49
+ fail-fast: false
50
+ matrix:
51
+ python-version: ["3.12", "3.13", "3.14"]
52
+ services:
53
+ postgres:
54
+ image: postgres:16
55
+ env:
56
+ POSTGRES_USER: etchdb
57
+ POSTGRES_PASSWORD: etchdb-test-password
58
+ POSTGRES_DB: etchdb_test
59
+ ports:
60
+ # conftest probes localhost:5532 (matches local `make db-up`);
61
+ # expose the service on the same port so no env override is
62
+ # needed and the Postgres skip-guard sees the service.
63
+ - 5532:5432
64
+ options: >-
65
+ --health-cmd pg_isready
66
+ --health-interval 10s
67
+ --health-timeout 5s
68
+ --health-retries 5
69
+ steps:
70
+ - uses: actions/checkout@v4
71
+ - uses: astral-sh/setup-uv@v5
72
+ with:
73
+ python-version: ${{ matrix.python-version }}
74
+ cache-dependency-glob: "pyproject.toml"
75
+ - run: uv sync --extra all --extra dev
76
+ - run: uv run pytest tests/integration -q
@@ -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
@@ -67,3 +67,4 @@ uv.lock
67
67
  scratch/
68
68
  TODO.local.md
69
69
  .local/
70
+ .claude/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: etchdb
3
- Version: 0.5.0
3
+ Version: 0.6.1
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.5.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
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,28 @@ 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
- # Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
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 a
134
+ # `(by, *pk_tail) > last_seen` cursor per page. PK tail breaks
135
+ # ties and lets the cursor paginate through NULL values. Order
136
+ # is `ORDER BY by NULLS FIRST` -- deterministic across backends.
137
+ # `by` defaults to __pk__[0]. SQLite 3.30+ required.
138
+ async for user in db.iter_rows_keyset(User, batch_size=500):
139
+ process(user)
140
+
129
141
  # Typed-result raw SQL (covers most joins)
130
142
  users = await db.fetch_models(User, """
131
143
  SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
@@ -145,6 +157,11 @@ async with db.transaction() as tx:
145
157
  await tx.insert(User(name="Carol"))
146
158
  await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
147
159
 
160
+ # Healthcheck + lifecycle
161
+ ok = await db.ping() # SELECT 1 round-trip; raises on failure
162
+ async with db: # close on scope exit (DB must already be open)
163
+ ...
164
+
148
165
  # Migrations: apply every pending .sql file in a directory, in
149
166
  # filename order. The runner creates a `_etchdb_migrations` tracking
150
167
  # table on first call. See the Migrations section below for the
@@ -331,6 +348,25 @@ In both cases the error names the recovery (`DELETE FROM _etchdb_migrations WHER
331
348
 
332
349
  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
350
 
351
+ ### Running migrations from the command line
352
+
353
+ Installing `etchdb` registers an `etchdb` console script for use in CI, deploy scripts, and Docker entrypoints — no Python bootstrap needed:
354
+
355
+ ```bash
356
+ $ etchdb migrate ./migrations --url "$DATABASE_URL"
357
+ applied 2 migrations
358
+
359
+ $ etchdb status ./migrations --url "$DATABASE_URL"
360
+ Migration status (./migrations):
361
+ applied (2):
362
+ 0001_create_users.sql
363
+ 0002_add_email_index.sql
364
+ pending (1):
365
+ 0003_add_articles.sql
366
+ ```
367
+
368
+ `--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).
369
+
334
370
  ## Under consideration
335
371
 
336
372
  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.5.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
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,28 @@ 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
- # Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
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 a
72
+ # `(by, *pk_tail) > last_seen` cursor per page. PK tail breaks
73
+ # ties and lets the cursor paginate through NULL values. Order
74
+ # is `ORDER BY by NULLS FIRST` -- deterministic across backends.
75
+ # `by` defaults to __pk__[0]. SQLite 3.30+ required.
76
+ async for user in db.iter_rows_keyset(User, batch_size=500):
77
+ process(user)
78
+
67
79
  # Typed-result raw SQL (covers most joins)
68
80
  users = await db.fetch_models(User, """
69
81
  SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
@@ -83,6 +95,11 @@ async with db.transaction() as tx:
83
95
  await tx.insert(User(name="Carol"))
84
96
  await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
85
97
 
98
+ # Healthcheck + lifecycle
99
+ ok = await db.ping() # SELECT 1 round-trip; raises on failure
100
+ async with db: # close on scope exit (DB must already be open)
101
+ ...
102
+
86
103
  # Migrations: apply every pending .sql file in a directory, in
87
104
  # filename order. The runner creates a `_etchdb_migrations` tracking
88
105
  # table on first call. See the Migrations section below for the
@@ -269,6 +286,25 @@ In both cases the error names the recovery (`DELETE FROM _etchdb_migrations WHER
269
286
 
270
287
  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
288
 
289
+ ### Running migrations from the command line
290
+
291
+ Installing `etchdb` registers an `etchdb` console script for use in CI, deploy scripts, and Docker entrypoints — no Python bootstrap needed:
292
+
293
+ ```bash
294
+ $ etchdb migrate ./migrations --url "$DATABASE_URL"
295
+ applied 2 migrations
296
+
297
+ $ etchdb status ./migrations --url "$DATABASE_URL"
298
+ Migration status (./migrations):
299
+ applied (2):
300
+ 0001_create_users.sql
301
+ 0002_add_email_index.sql
302
+ pending (1):
303
+ 0003_add_articles.sql
304
+ ```
305
+
306
+ `--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).
307
+
272
308
  ## Under consideration
273
309
 
274
310
  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.5.0"
3
+ version = "0.6.1"
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"
@@ -13,7 +13,7 @@ from etchdb.migrations import MigrationStatus
13
13
  from etchdb.query import SqlQuery
14
14
  from etchdb.row import Row
15
15
 
16
- __version__ = "0.5.0"
16
+ __version__ = "0.6.1"
17
17
 
18
18
  __all__ = [
19
19
  "DB",
@@ -0,0 +1,5 @@
1
+ """Allow `python -m etchdb` as an alias for the installed `etchdb` script."""
2
+
3
+ from etchdb.cli import main
4
+
5
+ raise SystemExit(main())
@@ -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`, per-page cost stays constant: each page
252
+ reads `batch_size` rows via `WHERE (by, *pk_tail) > (...)`
253
+ rather than `OFFSET N`, so total cost is O(N) instead of
254
+ O(N^2). `by` must be a single DB-orderable column. PK columns
255
+ break ties on `by` and let the cursor paginate through NULL
256
+ values; the cursor is `[by] + [p for p in __pk__ if p != by]`.
257
+
258
+ `by` defaults to `model.__pk__[0]` (composite PK requires
259
+ explicit `by=`). Filters are AND'd with the cursor. Ordering
260
+ is ascending with `NULLS FIRST` -- NULL rows iterate first
261
+ on every backend. Descending is not supported. SQLite 3.30+
262
+ is required (for the `NULLS FIRST` keyword).
263
+ """
264
+ if batch_size < 1:
265
+ raise ValueError(f"batch_size must be >= 1, got {batch_size}")
266
+ if _has_empty_collection_filter(filters):
267
+ return
268
+ if by is None:
269
+ if len(model.__pk__) > 1:
270
+ raise ValueError(
271
+ f"{model.__name__} has composite PK {model.__pk__}; "
272
+ f"pass `by=<column>` explicitly."
273
+ )
274
+ by = model.__pk__[0]
275
+
276
+ order_cols = [by] + [p for p in model.__pk__ if p != by]
277
+ last_seen: list[Any] | None = 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][c] for c in order_cols]
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):