etchdb 0.4.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.
Files changed (57) hide show
  1. etchdb-0.6.0/.github/workflows/release.yml +83 -0
  2. {etchdb-0.4.0 → etchdb-0.6.0}/.gitignore +1 -0
  3. {etchdb-0.4.0 → etchdb-0.6.0}/PKG-INFO +119 -5
  4. {etchdb-0.4.0 → etchdb-0.6.0}/README.md +118 -4
  5. {etchdb-0.4.0 → etchdb-0.6.0}/pyproject.toml +4 -1
  6. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/__init__.py +3 -1
  7. etchdb-0.6.0/src/etchdb/__main__.py +5 -0
  8. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/adapter.py +12 -0
  9. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/aiosqlite/adapter.py +19 -2
  10. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/asyncpg/adapter.py +30 -7
  11. etchdb-0.6.0/src/etchdb/cli.py +112 -0
  12. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/db.py +140 -4
  13. etchdb-0.6.0/src/etchdb/migrations.py +199 -0
  14. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/psycopg/adapter.py +27 -5
  15. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/row.py +16 -0
  16. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/sql/__init__.py +112 -8
  17. etchdb-0.6.0/tests/integration/test_cli.py +103 -0
  18. etchdb-0.6.0/tests/integration/test_fields_not_in_db.py +31 -0
  19. etchdb-0.6.0/tests/integration/test_iter_rows_keyset.py +93 -0
  20. etchdb-0.6.0/tests/integration/test_migrations.py +342 -0
  21. etchdb-0.6.0/tests/integration/test_ping_and_aclose.py +42 -0
  22. etchdb-0.6.0/tests/integration/test_pool_kwargs.py +43 -0
  23. etchdb-0.6.0/tests/integration/test_update_where.py +79 -0
  24. etchdb-0.6.0/tests/unit/test_cli.py +77 -0
  25. etchdb-0.6.0/tests/unit/test_db_dispatch.py +79 -0
  26. etchdb-0.6.0/tests/unit/test_migrations.py +126 -0
  27. {etchdb-0.4.0 → etchdb-0.6.0}/tests/unit/test_sql_emitter.py +170 -0
  28. etchdb-0.4.0/tests/unit/test_db_dispatch.py +0 -41
  29. {etchdb-0.4.0 → etchdb-0.6.0}/.python-version +0 -0
  30. {etchdb-0.4.0 → etchdb-0.6.0}/LICENSE +0 -0
  31. {etchdb-0.4.0 → etchdb-0.6.0}/Makefile +0 -0
  32. {etchdb-0.4.0 → etchdb-0.6.0}/docker-compose.yml +0 -0
  33. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/aiosqlite/__init__.py +0 -0
  34. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/asyncpg/__init__.py +0 -0
  35. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/codecs.py +0 -0
  36. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/errors.py +0 -0
  37. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/expr.py +0 -0
  38. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/psycopg/__init__.py +0 -0
  39. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/py.typed +0 -0
  40. {etchdb-0.4.0 → etchdb-0.6.0}/src/etchdb/query.py +0 -0
  41. {etchdb-0.4.0 → etchdb-0.6.0}/tests/__init__.py +0 -0
  42. {etchdb-0.4.0 → etchdb-0.6.0}/tests/_models.py +0 -0
  43. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/__init__.py +0 -0
  44. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/conftest.py +0 -0
  45. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_batch.py +0 -0
  46. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_codecs.py +0 -0
  47. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_errors.py +0 -0
  48. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_execute_rowcount.py +0 -0
  49. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_expressions.py +0 -0
  50. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_facade.py +0 -0
  51. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_in_filter.py +0 -0
  52. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_is_null.py +0 -0
  53. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_iter_rows.py +0 -0
  54. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_readme_example.py +0 -0
  55. {etchdb-0.4.0 → etchdb-0.6.0}/tests/integration/test_typed_crud.py +0 -0
  56. {etchdb-0.4.0 → etchdb-0.6.0}/tests/unit/__init__.py +0 -0
  57. {etchdb-0.4.0 → etchdb-0.6.0}/tests/unit/test_adapters.py +0 -0
@@ -0,0 +1,83 @@
1
+ name: Release
2
+
3
+ # Pushing a `vX.Y.Z` tag is the only ship action: this workflow runs unit
4
+ # tests, builds sdist + wheel, publishes to PyPI, and creates a GitHub
5
+ # Release (with the dist files attached) in one motion. Title and body
6
+ # are bare (just the tag name + auto-generated commit list); run
7
+ # `gh release edit vX.Y.Z` afterwards if you want a hand-curated title
8
+ # and body like the v0.2 / v0.3 / v0.4 ones.
9
+ #
10
+ # Failure recovery: if `uv publish` succeeds but `gh release create`
11
+ # fails (rare, e.g. transient GitHub API), don't re-push the tag --
12
+ # `uv publish` would reject the duplicate upload. Run `gh release
13
+ # create vX.Y.Z --generate-notes dist/*` manually to finish the job.
14
+
15
+ on:
16
+ push:
17
+ tags:
18
+ - 'v*'
19
+
20
+ # Creating a release writes to the repo's releases collection; the
21
+ # default-issued GITHUB_TOKEN needs that permission explicitly.
22
+ permissions:
23
+ contents: write
24
+
25
+ # Two pushes of the same tag (or a tag move + repush) shouldn't fight
26
+ # each other on PyPI uploads.
27
+ concurrency:
28
+ group: release-${{ github.ref }}
29
+ cancel-in-progress: false
30
+
31
+ jobs:
32
+ release:
33
+ runs-on: ubuntu-latest
34
+ steps:
35
+ - name: Checkout
36
+ uses: actions/checkout@v4
37
+ with:
38
+ # Full history so `gh release create --generate-notes` can
39
+ # diff against the previous tag for the auto-notes body.
40
+ fetch-depth: 0
41
+
42
+ - name: Install uv (with Python)
43
+ uses: astral-sh/setup-uv@v5
44
+ with:
45
+ # Tests run on 3.13 (current head). The wheel is `py3-none-any`
46
+ # so it installs on every supported version; per-push CI (when
47
+ # added) should cover the full 3.12 - 3.14 matrix.
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"
54
+
55
+ - name: Install dependencies
56
+ run: uv sync --extra all --extra dev
57
+
58
+ - name: Run unit tests
59
+ # Unit tests only -- integration tests need a Postgres container
60
+ # and belong in a separate CI workflow on every push / PR.
61
+ # Treat this as a release safety net, not full CI.
62
+ run: uv run pytest tests/unit -q
63
+
64
+ - name: Build sdist + wheel
65
+ run: uv build
66
+
67
+ - name: Publish to PyPI
68
+ # Token-based publishing for now; switching to PyPI trusted
69
+ # publishing later just means dropping `UV_PUBLISH_TOKEN`,
70
+ # adding `permissions: id-token: write` to this job, and
71
+ # registering the publisher on PyPI.
72
+ env:
73
+ UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
74
+ run: uv publish
75
+
76
+ - name: Create GitHub Release
77
+ env:
78
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
79
+ run: |
80
+ gh release create "${GITHUB_REF_NAME}" \
81
+ --title "${GITHUB_REF_NAME}" \
82
+ --generate-notes \
83
+ dist/*.whl dist/*.tar.gz
@@ -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.4.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.4.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,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
- # 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
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,18 @@ 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
+
162
+ # Migrations: apply every pending .sql file in a directory, in
163
+ # filename order. The runner creates a `_etchdb_migrations` tracking
164
+ # table on first call. See the Migrations section below for the
165
+ # transaction model, drift detection, and the no-transaction marker.
166
+ applied = await db.migrate("migrations/")
167
+ status = await db.migration_status("migrations/") # MigrationStatus dataclass
168
+
148
169
  # Inspect SQL before executing (etchdb's defining feature)
149
170
  q = db.compose("get", User, id=1)
150
171
  print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
@@ -161,6 +182,8 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
161
182
 
162
183
  Use `Row.patch(**fields)` to build a partial Row that satisfies neither validation nor missing-required-field checks. It's the right shape when you want partial updates against a model with NOT NULL columns.
163
184
 
185
+ Set `__fields_not_in_db__ = ("computed_label",)` on a Row class to carry computed or transient fields alongside DB-backed ones without etchdb sending them to or reading them from the database. The fields stay on the Pydantic model (validation, attribute access, type checking all work as normal); they're just dropped from INSERT, UPDATE, and SELECT column lists. Give such fields a default value -- read paths hydrate from the SELECT result, which never carries the column, so Pydantic uses the default.
186
+
164
187
  ## Typed errors
165
188
 
166
189
  Driver exceptions are mapped onto a small etchdb family so application code catches the same type regardless of the backend. The original driver exception is preserved as `__cause__`.
@@ -248,7 +271,98 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
248
271
 
249
272
  ## Migrations
250
273
 
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.
274
+ Forward-only, file-based, no autogenerate, no rollback. Drop `.sql` files into a directory; sort-order is apply-order. Any sortable filename prefix works — zero-padded numbers, `YYYYMMDDHHMM` timestamps, whatever you like.
275
+
276
+ ```
277
+ migrations/
278
+ 0001_create_users.sql
279
+ 0002_add_email_index.sql
280
+ 0003_add_articles.sql
281
+ ```
282
+
283
+ A migration is plain SQL. Multiple statements separated by `;` are fine on Postgres:
284
+
285
+ ```sql
286
+ -- migrations/0001_create_users.sql
287
+ CREATE TABLE users (
288
+ id SERIAL PRIMARY KEY,
289
+ name TEXT NOT NULL,
290
+ email TEXT UNIQUE,
291
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
292
+ );
293
+
294
+ CREATE INDEX users_email_idx ON users (email);
295
+ ```
296
+
297
+ Apply pending migrations from your application bootstrap (or a one-shot script):
298
+
299
+ ```python
300
+ from etchdb import DB
301
+
302
+ db = await DB.from_url("postgresql+asyncpg://user@host/db")
303
+ applied = await db.migrate("migrations/")
304
+ print(f"applied {applied} migrations")
305
+ ```
306
+
307
+ Inspect state without applying:
308
+
309
+ ```python
310
+ status = await db.migration_status("migrations/")
311
+ # MigrationStatus(
312
+ # pending=["0003_add_articles.sql"],
313
+ # applied=["0001_create_users.sql", "0002_add_email_index.sql"],
314
+ # drifted=[],
315
+ # missing=[],
316
+ # )
317
+ if not status.is_consistent:
318
+ raise SystemExit(f"migration state inconsistent: drifted={status.drifted}, missing={status.missing}")
319
+ ```
320
+
321
+ `MigrationStatus` is a small frozen dataclass exported from `etchdb`; `is_consistent` is `True` when both `drifted` and `missing` are empty.
322
+
323
+ ### Transaction model
324
+
325
+ Each migration runs in its own implicit transaction on Postgres. Don't write `BEGIN` / `COMMIT` / `ROLLBACK` in the file — the runner owns transaction control and rejects files that try to take it back (with PL/pgSQL `DO $$ ... $$` blocks and string literals stripped first, so legitimate uses don't trip the check).
326
+
327
+ For DDL that Postgres won't run inside a transaction (notably `CREATE INDEX CONCURRENTLY`), put `-- etchdb:no-transaction` on the first non-blank line:
328
+
329
+ ```sql
330
+ -- migrations/0004_concurrent_index.sql
331
+ -- etchdb:no-transaction
332
+ CREATE INDEX CONCURRENTLY users_lower_email_idx ON users (lower(email));
333
+ ```
334
+
335
+ On SQLite multi-statement migrations run via `sqlite3.executescript`, which auto-commits any pending transaction (a sqlite3 stdlib behavior, unavoidable); treat each SQLite migration file as one logical unit. Postgres is the canonical target.
336
+
337
+ ### Strict consistency
338
+
339
+ Tracking lives in a `_etchdb_migrations` table created lazily on first call, with `(filename, checksum, applied_at)`. The checksum is sha256 of the file content. The runner refuses to operate when state is inconsistent:
340
+
341
+ - **Drift**: an applied file's content has changed since it was applied. Editing a migration after it's been applied is silent state corruption; the runner refuses until you resolve it.
342
+ - **Disappearance**: an applied filename is no longer in the directory. Renames count as both a disappearance and a new file.
343
+
344
+ In both cases the error names the recovery (`DELETE FROM _etchdb_migrations WHERE filename = '...'` then re-run, or restore the missing file). Silent continuation with unknown state is exactly what a forward-only tool exists to prevent.
345
+
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.
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).
252
366
 
253
367
  ## Under consideration
254
368
 
@@ -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.4.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,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
- # 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
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,18 @@ 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
+
100
+ # Migrations: apply every pending .sql file in a directory, in
101
+ # filename order. The runner creates a `_etchdb_migrations` tracking
102
+ # table on first call. See the Migrations section below for the
103
+ # transaction model, drift detection, and the no-transaction marker.
104
+ applied = await db.migrate("migrations/")
105
+ status = await db.migration_status("migrations/") # MigrationStatus dataclass
106
+
86
107
  # Inspect SQL before executing (etchdb's defining feature)
87
108
  q = db.compose("get", User, id=1)
88
109
  print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
@@ -99,6 +120,8 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
99
120
 
100
121
  Use `Row.patch(**fields)` to build a partial Row that satisfies neither validation nor missing-required-field checks. It's the right shape when you want partial updates against a model with NOT NULL columns.
101
122
 
123
+ Set `__fields_not_in_db__ = ("computed_label",)` on a Row class to carry computed or transient fields alongside DB-backed ones without etchdb sending them to or reading them from the database. The fields stay on the Pydantic model (validation, attribute access, type checking all work as normal); they're just dropped from INSERT, UPDATE, and SELECT column lists. Give such fields a default value -- read paths hydrate from the SELECT result, which never carries the column, so Pydantic uses the default.
124
+
102
125
  ## Typed errors
103
126
 
104
127
  Driver exceptions are mapped onto a small etchdb family so application code catches the same type regardless of the backend. The original driver exception is preserved as `__cause__`.
@@ -186,7 +209,98 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
186
209
 
187
210
  ## Migrations
188
211
 
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.
212
+ Forward-only, file-based, no autogenerate, no rollback. Drop `.sql` files into a directory; sort-order is apply-order. Any sortable filename prefix works — zero-padded numbers, `YYYYMMDDHHMM` timestamps, whatever you like.
213
+
214
+ ```
215
+ migrations/
216
+ 0001_create_users.sql
217
+ 0002_add_email_index.sql
218
+ 0003_add_articles.sql
219
+ ```
220
+
221
+ A migration is plain SQL. Multiple statements separated by `;` are fine on Postgres:
222
+
223
+ ```sql
224
+ -- migrations/0001_create_users.sql
225
+ CREATE TABLE users (
226
+ id SERIAL PRIMARY KEY,
227
+ name TEXT NOT NULL,
228
+ email TEXT UNIQUE,
229
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
230
+ );
231
+
232
+ CREATE INDEX users_email_idx ON users (email);
233
+ ```
234
+
235
+ Apply pending migrations from your application bootstrap (or a one-shot script):
236
+
237
+ ```python
238
+ from etchdb import DB
239
+
240
+ db = await DB.from_url("postgresql+asyncpg://user@host/db")
241
+ applied = await db.migrate("migrations/")
242
+ print(f"applied {applied} migrations")
243
+ ```
244
+
245
+ Inspect state without applying:
246
+
247
+ ```python
248
+ status = await db.migration_status("migrations/")
249
+ # MigrationStatus(
250
+ # pending=["0003_add_articles.sql"],
251
+ # applied=["0001_create_users.sql", "0002_add_email_index.sql"],
252
+ # drifted=[],
253
+ # missing=[],
254
+ # )
255
+ if not status.is_consistent:
256
+ raise SystemExit(f"migration state inconsistent: drifted={status.drifted}, missing={status.missing}")
257
+ ```
258
+
259
+ `MigrationStatus` is a small frozen dataclass exported from `etchdb`; `is_consistent` is `True` when both `drifted` and `missing` are empty.
260
+
261
+ ### Transaction model
262
+
263
+ Each migration runs in its own implicit transaction on Postgres. Don't write `BEGIN` / `COMMIT` / `ROLLBACK` in the file — the runner owns transaction control and rejects files that try to take it back (with PL/pgSQL `DO $$ ... $$` blocks and string literals stripped first, so legitimate uses don't trip the check).
264
+
265
+ For DDL that Postgres won't run inside a transaction (notably `CREATE INDEX CONCURRENTLY`), put `-- etchdb:no-transaction` on the first non-blank line:
266
+
267
+ ```sql
268
+ -- migrations/0004_concurrent_index.sql
269
+ -- etchdb:no-transaction
270
+ CREATE INDEX CONCURRENTLY users_lower_email_idx ON users (lower(email));
271
+ ```
272
+
273
+ On SQLite multi-statement migrations run via `sqlite3.executescript`, which auto-commits any pending transaction (a sqlite3 stdlib behavior, unavoidable); treat each SQLite migration file as one logical unit. Postgres is the canonical target.
274
+
275
+ ### Strict consistency
276
+
277
+ Tracking lives in a `_etchdb_migrations` table created lazily on first call, with `(filename, checksum, applied_at)`. The checksum is sha256 of the file content. The runner refuses to operate when state is inconsistent:
278
+
279
+ - **Drift**: an applied file's content has changed since it was applied. Editing a migration after it's been applied is silent state corruption; the runner refuses until you resolve it.
280
+ - **Disappearance**: an applied filename is no longer in the directory. Renames count as both a disappearance and a new file.
281
+
282
+ In both cases the error names the recovery (`DELETE FROM _etchdb_migrations WHERE filename = '...'` then re-run, or restore the missing file). Silent continuation with unknown state is exactly what a forward-only tool exists to prevent.
283
+
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.
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).
190
304
 
191
305
  ## Under consideration
192
306
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "etchdb"
3
- version = "0.4.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"
@@ -9,16 +9,18 @@ from etchdb.errors import (
9
9
  UndefinedTableError,
10
10
  )
11
11
  from etchdb.expr import Inc, Now
12
+ from etchdb.migrations import MigrationStatus
12
13
  from etchdb.query import SqlQuery
13
14
  from etchdb.row import Row
14
15
 
15
- __version__ = "0.4.0"
16
+ __version__ = "0.6.0"
16
17
 
17
18
  __all__ = [
18
19
  "DB",
19
20
  "EtchdbError",
20
21
  "Inc",
21
22
  "IntegrityError",
23
+ "MigrationStatus",
22
24
  "Now",
23
25
  "OperationalError",
24
26
  "Row",
@@ -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())
@@ -36,6 +36,18 @@ class AdapterBase(ABC):
36
36
  """
37
37
  ...
38
38
 
39
+ @abstractmethod
40
+ async def execute_script(self, sql: str) -> None:
41
+ """Execute one or more SQL statements with no parameters.
42
+
43
+ Used by the migration runner for files that may contain
44
+ multiple statements separated by `;`. asyncpg / psycopg accept
45
+ multi-statement SQL through the regular execute path;
46
+ aiosqlite wraps `sqlite3.executescript`, which auto-commits
47
+ any pending transaction (a sqlite3 stdlib behavior).
48
+ """
49
+ ...
50
+
39
51
  @abstractmethod
40
52
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]: ...
41
53
 
@@ -80,10 +80,13 @@ class AiosqliteAdapter(AdapterBase):
80
80
  return cls(conn, owns_conn=False)
81
81
 
82
82
  @classmethod
83
- async def from_url(cls, url: str) -> AiosqliteAdapter:
83
+ async def from_url(cls, url: str, **_pool_kwargs: object) -> AiosqliteAdapter:
84
84
  """Open an aiosqlite connection from `url` and wrap it.
85
85
 
86
- etchdb owns the connection; `close()` will close it.
86
+ etchdb owns the connection; `close()` will close it. Pool
87
+ kwargs (`min_size`, `max_size`) are accepted for cross-driver
88
+ consistency with the Postgres adapters but ignored here --
89
+ aiosqlite wraps a single sqlite3 connection, not a pool.
87
90
  """
88
91
  path = _path_from_url(url)
89
92
  conn = await aiosqlite.connect(path)
@@ -95,6 +98,15 @@ class AiosqliteAdapter(AdapterBase):
95
98
  await self._conn.commit()
96
99
  return cursor.rowcount
97
100
 
101
+ async def execute_script(self, sql: str) -> None:
102
+ # sqlite3.Connection.executescript auto-commits any pending
103
+ # transaction before running, so a multi-statement migration
104
+ # cannot be wrapped in an outer transaction. Documented in
105
+ # AdapterBase.execute_script and in the migration helper.
106
+ async with _wrap_errors():
107
+ await self._conn.executescript(sql)
108
+ await self._conn.commit()
109
+
98
110
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
99
111
  async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
100
112
  rows = await cursor.fetchall()
@@ -147,6 +159,11 @@ class _AiosqliteTxAdapter(AdapterBase):
147
159
  async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
148
160
  return cursor.rowcount
149
161
 
162
+ async def execute_script(self, sql: str) -> None:
163
+ # See AiosqliteAdapter.execute_script for the transaction caveat.
164
+ async with _wrap_errors():
165
+ await self._conn.executescript(sql)
166
+
150
167
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
151
168
  async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
152
169
  rows = await cursor.fetchall()
@@ -82,9 +82,10 @@ class AsyncpgAdapter(AdapterBase):
82
82
  (etchdb will not close it), or `await from_url(url)` to let etchdb
83
83
  create and own the pool. The `owns_pool` flag tracks ownership.
84
84
 
85
- For custom pool settings (init=, min_size=, max_size=, codecs),
85
+ `from_url` accepts `min_size` / `max_size`. For pool concerns
86
+ beyond size (custom `init=`, `statement_cache_size`, ENUM codecs),
86
87
  create the pool yourself with `asyncpg.create_pool(...)` and pass
87
- it to `from_pool`. `from_url` is intentionally minimal.
88
+ it to `from_pool`.
88
89
  """
89
90
 
90
91
  def __init__(self, pool: asyncpg.Pool, *, owns_pool: bool = False):
@@ -101,22 +102,40 @@ class AsyncpgAdapter(AdapterBase):
101
102
  return cls(pool, owns_pool=False)
102
103
 
103
104
  @classmethod
104
- async def from_url(cls, url: str) -> AsyncpgAdapter:
105
+ async def from_url(
106
+ cls,
107
+ url: str,
108
+ *,
109
+ min_size: int | None = None,
110
+ max_size: int | None = None,
111
+ ) -> AsyncpgAdapter:
105
112
  """Create an asyncpg pool from `url` and wrap it.
106
113
 
107
114
  etchdb owns the pool; `close()` will close it. The pool is
108
115
  initialised with a JSONB codec that handles UUID, datetime,
109
- Enum, and Pydantic BaseModel transparently. Users wanting a
110
- pristine pool with no codec setup should construct the pool
111
- themselves and use `from_pool`.
116
+ Enum, and Pydantic BaseModel transparently.
117
+
118
+ `min_size` / `max_size` are forwarded to `asyncpg.create_pool`
119
+ if set. For pool concerns beyond size (asyncpg's
120
+ `statement_cache_size`, custom ENUM codecs, etc.), construct
121
+ the pool yourself and use `from_pool`.
112
122
  """
113
- pool = await asyncpg.create_pool(url, init=_init_codecs)
123
+ pool_kwargs: dict[str, Any] = {"init": _init_codecs}
124
+ if min_size is not None:
125
+ pool_kwargs["min_size"] = min_size
126
+ if max_size is not None:
127
+ pool_kwargs["max_size"] = max_size
128
+ pool = await asyncpg.create_pool(url, **pool_kwargs)
114
129
  return cls(pool, owns_pool=True)
115
130
 
116
131
  async def execute(self, sql: str, *params: Any) -> int:
117
132
  async with _wrap_errors(), self._pool.acquire() as conn:
118
133
  return _rowcount_from_status(await conn.execute(sql, *params))
119
134
 
135
+ async def execute_script(self, sql: str) -> None:
136
+ async with _wrap_errors(), self._pool.acquire() as conn:
137
+ await conn.execute(sql)
138
+
120
139
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
121
140
  async with _wrap_errors(), self._pool.acquire() as conn:
122
141
  records = await conn.fetch(sql, *params)
@@ -155,6 +174,10 @@ class _AsyncpgConnAdapter(AdapterBase):
155
174
  async with _wrap_errors():
156
175
  return _rowcount_from_status(await self._conn.execute(sql, *params))
157
176
 
177
+ async def execute_script(self, sql: str) -> None:
178
+ async with _wrap_errors():
179
+ await self._conn.execute(sql)
180
+
158
181
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
159
182
  async with _wrap_errors():
160
183
  records = await self._conn.fetch(sql, *params)