etchdb 0.3.0__tar.gz → 0.5.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 (50) hide show
  1. etchdb-0.5.0/.github/workflows/release.yml +78 -0
  2. {etchdb-0.3.0 → etchdb-0.5.0}/PKG-INFO +104 -4
  3. {etchdb-0.3.0 → etchdb-0.5.0}/README.md +103 -3
  4. {etchdb-0.3.0 → etchdb-0.5.0}/pyproject.toml +1 -1
  5. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/__init__.py +6 -1
  6. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/adapter.py +23 -1
  7. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/aiosqlite/adapter.py +23 -6
  8. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/asyncpg/adapter.py +57 -11
  9. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/db.py +88 -10
  10. etchdb-0.5.0/src/etchdb/expr.py +100 -0
  11. etchdb-0.5.0/src/etchdb/migrations.py +199 -0
  12. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/psycopg/adapter.py +35 -7
  13. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/row.py +16 -0
  14. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/sql/__init__.py +162 -46
  15. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_batch.py +36 -0
  16. etchdb-0.5.0/tests/integration/test_execute_rowcount.py +66 -0
  17. etchdb-0.5.0/tests/integration/test_expressions.py +77 -0
  18. etchdb-0.5.0/tests/integration/test_fields_not_in_db.py +31 -0
  19. etchdb-0.5.0/tests/integration/test_in_filter.py +60 -0
  20. etchdb-0.5.0/tests/integration/test_migrations.py +342 -0
  21. etchdb-0.5.0/tests/integration/test_pool_kwargs.py +43 -0
  22. {etchdb-0.3.0 → etchdb-0.5.0}/tests/unit/test_adapters.py +28 -0
  23. etchdb-0.5.0/tests/unit/test_db_dispatch.py +79 -0
  24. etchdb-0.5.0/tests/unit/test_migrations.py +126 -0
  25. {etchdb-0.3.0 → etchdb-0.5.0}/tests/unit/test_sql_emitter.py +307 -0
  26. etchdb-0.3.0/tests/unit/test_db_dispatch.py +0 -41
  27. {etchdb-0.3.0 → etchdb-0.5.0}/.gitignore +0 -0
  28. {etchdb-0.3.0 → etchdb-0.5.0}/.python-version +0 -0
  29. {etchdb-0.3.0 → etchdb-0.5.0}/LICENSE +0 -0
  30. {etchdb-0.3.0 → etchdb-0.5.0}/Makefile +0 -0
  31. {etchdb-0.3.0 → etchdb-0.5.0}/docker-compose.yml +0 -0
  32. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/aiosqlite/__init__.py +0 -0
  33. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/asyncpg/__init__.py +0 -0
  34. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/codecs.py +0 -0
  35. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/errors.py +0 -0
  36. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/psycopg/__init__.py +0 -0
  37. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/py.typed +0 -0
  38. {etchdb-0.3.0 → etchdb-0.5.0}/src/etchdb/query.py +0 -0
  39. {etchdb-0.3.0 → etchdb-0.5.0}/tests/__init__.py +0 -0
  40. {etchdb-0.3.0 → etchdb-0.5.0}/tests/_models.py +0 -0
  41. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/__init__.py +0 -0
  42. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/conftest.py +0 -0
  43. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_codecs.py +0 -0
  44. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_errors.py +0 -0
  45. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_facade.py +0 -0
  46. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_is_null.py +0 -0
  47. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_iter_rows.py +0 -0
  48. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_readme_example.py +0 -0
  49. {etchdb-0.3.0 → etchdb-0.5.0}/tests/integration/test_typed_crud.py +0 -0
  50. {etchdb-0.3.0 → etchdb-0.5.0}/tests/unit/__init__.py +0 -0
@@ -0,0 +1,78 @@
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
+
50
+ - name: Install dependencies
51
+ run: uv sync --extra all --extra dev
52
+
53
+ - name: Run unit tests
54
+ # Unit tests only -- integration tests need a Postgres container
55
+ # and belong in a separate CI workflow on every push / PR.
56
+ # Treat this as a release safety net, not full CI.
57
+ run: uv run pytest tests/unit -q
58
+
59
+ - name: Build sdist + wheel
60
+ run: uv build
61
+
62
+ - name: Publish to PyPI
63
+ # Token-based publishing for now; switching to PyPI trusted
64
+ # publishing later just means dropping `UV_PUBLISH_TOKEN`,
65
+ # adding `permissions: id-token: write` to this job, and
66
+ # registering the publisher on PyPI.
67
+ env:
68
+ UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
69
+ run: uv publish
70
+
71
+ - name: Create GitHub Release
72
+ env:
73
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
74
+ run: |
75
+ gh release create "${GITHUB_REF_NAME}" \
76
+ --title "${GITHUB_REF_NAME}" \
77
+ --generate-notes \
78
+ dist/*.whl dist/*.tar.gz
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: etchdb
3
- Version: 0.3.0
3
+ Version: 0.5.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.3.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
69
+ Alpha. v0.5.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
70
70
 
71
71
  ## Example
72
72
 
@@ -90,6 +90,7 @@ alice = await db.insert(User(name="Alice")) # alice.id is now populate
90
90
  user = await db.get(User, id=alice.id) # one row or None
91
91
  users = await db.query(User) # list of rows
92
92
  no_email = await db.query(User, email=None) # IS NULL, not = NULL
93
+ recent = await db.query(User, id=[1, 5, 7]) # IN ($1, $2, $3)
93
94
  await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
94
95
  await db.delete(alice)
95
96
 
@@ -103,10 +104,22 @@ await db.update(User(id=alice.id, name="Alice B"),
103
104
  # so models with required NOT NULL columns still flow through.
104
105
  await db.update(User.patch(id=alice.id, name="Alice B"))
105
106
 
107
+ # Atomic column expressions in SET (use Row.patch so the sentinels
108
+ # slip past validation). Counter / Article are user-defined Row
109
+ # subclasses alongside User, with an int counter and a timestamp:
110
+ from etchdb import Inc, Now
111
+ await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
112
+ await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
113
+
106
114
  # Bulk insert / delete (chunked at the driver's parameter limit).
107
115
  await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
116
+ await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
108
117
  await db.delete_many(User, [1, 2, 3])
109
118
 
119
+ # Upsert via single insert: same rules, returns the DB's view.
120
+ alice = await db.insert(User(id=1, name="Alice", email="a@x"),
121
+ on_conflict="upsert")
122
+
110
123
  # Stream every matching row (paginated, won't load the whole table at once)
111
124
  # Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
112
125
  # loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
@@ -132,6 +145,13 @@ async with db.transaction() as tx:
132
145
  await tx.insert(User(name="Carol"))
133
146
  await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
134
147
 
148
+ # Migrations: apply every pending .sql file in a directory, in
149
+ # filename order. The runner creates a `_etchdb_migrations` tracking
150
+ # table on first call. See the Migrations section below for the
151
+ # transaction model, drift detection, and the no-transaction marker.
152
+ applied = await db.migrate("migrations/")
153
+ status = await db.migration_status("migrations/") # MigrationStatus dataclass
154
+
135
155
  # Inspect SQL before executing (etchdb's defining feature)
136
156
  q = db.compose("get", User, id=1)
137
157
  print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
@@ -148,6 +168,8 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
148
168
 
149
169
  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.
150
170
 
171
+ 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.
172
+
151
173
  ## Typed errors
152
174
 
153
175
  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__`.
@@ -235,11 +257,89 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
235
257
 
236
258
  ## Migrations
237
259
 
238
- 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.
260
+ 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.
261
+
262
+ ```
263
+ migrations/
264
+ 0001_create_users.sql
265
+ 0002_add_email_index.sql
266
+ 0003_add_articles.sql
267
+ ```
268
+
269
+ A migration is plain SQL. Multiple statements separated by `;` are fine on Postgres:
270
+
271
+ ```sql
272
+ -- migrations/0001_create_users.sql
273
+ CREATE TABLE users (
274
+ id SERIAL PRIMARY KEY,
275
+ name TEXT NOT NULL,
276
+ email TEXT UNIQUE,
277
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
278
+ );
279
+
280
+ CREATE INDEX users_email_idx ON users (email);
281
+ ```
282
+
283
+ Apply pending migrations from your application bootstrap (or a one-shot script):
284
+
285
+ ```python
286
+ from etchdb import DB
287
+
288
+ db = await DB.from_url("postgresql+asyncpg://user@host/db")
289
+ applied = await db.migrate("migrations/")
290
+ print(f"applied {applied} migrations")
291
+ ```
292
+
293
+ Inspect state without applying:
294
+
295
+ ```python
296
+ status = await db.migration_status("migrations/")
297
+ # MigrationStatus(
298
+ # pending=["0003_add_articles.sql"],
299
+ # applied=["0001_create_users.sql", "0002_add_email_index.sql"],
300
+ # drifted=[],
301
+ # missing=[],
302
+ # )
303
+ if not status.is_consistent:
304
+ raise SystemExit(f"migration state inconsistent: drifted={status.drifted}, missing={status.missing}")
305
+ ```
306
+
307
+ `MigrationStatus` is a small frozen dataclass exported from `etchdb`; `is_consistent` is `True` when both `drifted` and `missing` are empty.
308
+
309
+ ### Transaction model
310
+
311
+ 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).
312
+
313
+ For DDL that Postgres won't run inside a transaction (notably `CREATE INDEX CONCURRENTLY`), put `-- etchdb:no-transaction` on the first non-blank line:
314
+
315
+ ```sql
316
+ -- migrations/0004_concurrent_index.sql
317
+ -- etchdb:no-transaction
318
+ CREATE INDEX CONCURRENTLY users_lower_email_idx ON users (lower(email));
319
+ ```
320
+
321
+ 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.
322
+
323
+ ### Strict consistency
324
+
325
+ 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:
326
+
327
+ - **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.
328
+ - **Disappearance**: an applied filename is no longer in the directory. Renames count as both a disappearance and a new file.
329
+
330
+ 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.
331
+
332
+ 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
+
334
+ ## Under consideration
335
+
336
+ 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.
337
+
338
+ `Inc` / `Now` composing with `on_conflict="upsert"` is a related deferred shape: the create-or-increment pattern would let `db.insert(RateCounter(...), on_conflict="upsert")` carry an `Inc(by=N)` for the conflict SET, but the INSERT branch still needs a literal initial value, so the row would have to express two values per column. Today the sentinels are rejected by `db.insert` / `db.insert_many` outright; raw SQL with `INSERT ... ON CONFLICT (key) DO UPDATE SET count = table.count + 1` covers the case in one statement.
239
339
 
240
340
  ## Built with AI assistance
241
341
 
242
- Built with Claude Code as the primary development assistant. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
342
+ Built with a mix of AI tools for writing and reviewing code: primarily Claude Code, with Codex and occasionally Gemini for second opinions, and not limited to these. spegl.ing pattern research is in active use alongside them. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
243
343
 
244
344
  ## License
245
345
 
@@ -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.3.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
7
+ Alpha. v0.5.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
8
8
 
9
9
  ## Example
10
10
 
@@ -28,6 +28,7 @@ alice = await db.insert(User(name="Alice")) # alice.id is now populate
28
28
  user = await db.get(User, id=alice.id) # one row or None
29
29
  users = await db.query(User) # list of rows
30
30
  no_email = await db.query(User, email=None) # IS NULL, not = NULL
31
+ recent = await db.query(User, id=[1, 5, 7]) # IN ($1, $2, $3)
31
32
  await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
32
33
  await db.delete(alice)
33
34
 
@@ -41,10 +42,22 @@ await db.update(User(id=alice.id, name="Alice B"),
41
42
  # so models with required NOT NULL columns still flow through.
42
43
  await db.update(User.patch(id=alice.id, name="Alice B"))
43
44
 
45
+ # Atomic column expressions in SET (use Row.patch so the sentinels
46
+ # slip past validation). Counter / Article are user-defined Row
47
+ # subclasses alongside User, with an int counter and a timestamp:
48
+ from etchdb import Inc, Now
49
+ await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
50
+ await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
51
+
44
52
  # Bulk insert / delete (chunked at the driver's parameter limit).
45
53
  await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
54
+ await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
46
55
  await db.delete_many(User, [1, 2, 3])
47
56
 
57
+ # Upsert via single insert: same rules, returns the DB's view.
58
+ alice = await db.insert(User(id=1, name="Alice", email="a@x"),
59
+ on_conflict="upsert")
60
+
48
61
  # Stream every matching row (paginated, won't load the whole table at once)
49
62
  # Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
50
63
  # loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
@@ -70,6 +83,13 @@ async with db.transaction() as tx:
70
83
  await tx.insert(User(name="Carol"))
71
84
  await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
72
85
 
86
+ # Migrations: apply every pending .sql file in a directory, in
87
+ # filename order. The runner creates a `_etchdb_migrations` tracking
88
+ # table on first call. See the Migrations section below for the
89
+ # transaction model, drift detection, and the no-transaction marker.
90
+ applied = await db.migrate("migrations/")
91
+ status = await db.migration_status("migrations/") # MigrationStatus dataclass
92
+
73
93
  # Inspect SQL before executing (etchdb's defining feature)
74
94
  q = db.compose("get", User, id=1)
75
95
  print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
@@ -86,6 +106,8 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
86
106
 
87
107
  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.
88
108
 
109
+ 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.
110
+
89
111
  ## Typed errors
90
112
 
91
113
  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__`.
@@ -173,11 +195,89 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
173
195
 
174
196
  ## Migrations
175
197
 
176
- 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.
198
+ 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.
199
+
200
+ ```
201
+ migrations/
202
+ 0001_create_users.sql
203
+ 0002_add_email_index.sql
204
+ 0003_add_articles.sql
205
+ ```
206
+
207
+ A migration is plain SQL. Multiple statements separated by `;` are fine on Postgres:
208
+
209
+ ```sql
210
+ -- migrations/0001_create_users.sql
211
+ CREATE TABLE users (
212
+ id SERIAL PRIMARY KEY,
213
+ name TEXT NOT NULL,
214
+ email TEXT UNIQUE,
215
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
216
+ );
217
+
218
+ CREATE INDEX users_email_idx ON users (email);
219
+ ```
220
+
221
+ Apply pending migrations from your application bootstrap (or a one-shot script):
222
+
223
+ ```python
224
+ from etchdb import DB
225
+
226
+ db = await DB.from_url("postgresql+asyncpg://user@host/db")
227
+ applied = await db.migrate("migrations/")
228
+ print(f"applied {applied} migrations")
229
+ ```
230
+
231
+ Inspect state without applying:
232
+
233
+ ```python
234
+ status = await db.migration_status("migrations/")
235
+ # MigrationStatus(
236
+ # pending=["0003_add_articles.sql"],
237
+ # applied=["0001_create_users.sql", "0002_add_email_index.sql"],
238
+ # drifted=[],
239
+ # missing=[],
240
+ # )
241
+ if not status.is_consistent:
242
+ raise SystemExit(f"migration state inconsistent: drifted={status.drifted}, missing={status.missing}")
243
+ ```
244
+
245
+ `MigrationStatus` is a small frozen dataclass exported from `etchdb`; `is_consistent` is `True` when both `drifted` and `missing` are empty.
246
+
247
+ ### Transaction model
248
+
249
+ 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).
250
+
251
+ For DDL that Postgres won't run inside a transaction (notably `CREATE INDEX CONCURRENTLY`), put `-- etchdb:no-transaction` on the first non-blank line:
252
+
253
+ ```sql
254
+ -- migrations/0004_concurrent_index.sql
255
+ -- etchdb:no-transaction
256
+ CREATE INDEX CONCURRENTLY users_lower_email_idx ON users (lower(email));
257
+ ```
258
+
259
+ 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.
260
+
261
+ ### Strict consistency
262
+
263
+ 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:
264
+
265
+ - **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.
266
+ - **Disappearance**: an applied filename is no longer in the directory. Renames count as both a disappearance and a new file.
267
+
268
+ 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.
269
+
270
+ 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
+
272
+ ## Under consideration
273
+
274
+ 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.
275
+
276
+ `Inc` / `Now` composing with `on_conflict="upsert"` is a related deferred shape: the create-or-increment pattern would let `db.insert(RateCounter(...), on_conflict="upsert")` carry an `Inc(by=N)` for the conflict SET, but the INSERT branch still needs a literal initial value, so the row would have to express two values per column. Today the sentinels are rejected by `db.insert` / `db.insert_many` outright; raw SQL with `INSERT ... ON CONFLICT (key) DO UPDATE SET count = table.count + 1` covers the case in one statement.
177
277
 
178
278
  ## Built with AI assistance
179
279
 
180
- Built with Claude Code as the primary development assistant. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
280
+ Built with a mix of AI tools for writing and reviewing code: primarily Claude Code, with Codex and occasionally Gemini for second opinions, and not limited to these. spegl.ing pattern research is in active use alongside them. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
181
281
 
182
282
  ## License
183
283
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "etchdb"
3
- version = "0.3.0"
3
+ version = "0.5.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"
@@ -8,15 +8,20 @@ from etchdb.errors import (
8
8
  UndefinedColumnError,
9
9
  UndefinedTableError,
10
10
  )
11
+ from etchdb.expr import Inc, Now
12
+ from etchdb.migrations import MigrationStatus
11
13
  from etchdb.query import SqlQuery
12
14
  from etchdb.row import Row
13
15
 
14
- __version__ = "0.3.0"
16
+ __version__ = "0.5.0"
15
17
 
16
18
  __all__ = [
17
19
  "DB",
18
20
  "EtchdbError",
21
+ "Inc",
19
22
  "IntegrityError",
23
+ "MigrationStatus",
24
+ "Now",
20
25
  "OperationalError",
21
26
  "Row",
22
27
  "SqlQuery",
@@ -24,7 +24,29 @@ class AdapterBase(ABC):
24
24
  ...
25
25
 
26
26
  @abstractmethod
27
- async def execute(self, sql: str, *params: Any) -> Any: ...
27
+ async def execute(self, sql: str, *params: Any) -> int:
28
+ """Execute a statement and return the affected-row count.
29
+
30
+ Returns the affected-row count for DML (INSERT / UPDATE /
31
+ DELETE), or `-1` for everything else (DDL, BEGIN, SELECT,
32
+ COPY, ...). The `-1` sentinel mirrors psycopg's and sqlite3's
33
+ native convention. SELECT through `execute` is explicitly not
34
+ a count contract; use `fetch` / `fetchrow` / `fetchval` for
35
+ SELECT and read the row count off the result.
36
+ """
37
+ ...
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
+ ...
28
50
 
29
51
  @abstractmethod
30
52
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]: ...
@@ -80,19 +80,31 @@ 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)
90
93
  conn.row_factory = aiosqlite.Row
91
94
  return cls(conn, owns_conn=True)
92
95
 
93
- async def execute(self, sql: str, *params: Any) -> Any:
96
+ async def execute(self, sql: str, *params: Any) -> int:
97
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
98
+ await self._conn.commit()
99
+ return cursor.rowcount
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.
94
106
  async with _wrap_errors():
95
- await self._conn.execute(sql, params)
107
+ await self._conn.executescript(sql)
96
108
  await self._conn.commit()
97
109
 
98
110
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
@@ -143,9 +155,14 @@ class _AiosqliteTxAdapter(AdapterBase):
143
155
  def placeholder(i: int) -> str:
144
156
  return "?"
145
157
 
146
- async def execute(self, sql: str, *params: Any) -> Any:
158
+ async def execute(self, sql: str, *params: Any) -> int:
159
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
160
+ return cursor.rowcount
161
+
162
+ async def execute_script(self, sql: str) -> None:
163
+ # See AiosqliteAdapter.execute_script for the transaction caveat.
147
164
  async with _wrap_errors():
148
- await self._conn.execute(sql, params)
165
+ await self._conn.executescript(sql)
149
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:
@@ -52,6 +52,29 @@ def _map_exception(exc: BaseException) -> errors.EtchdbError | None:
52
52
  _wrap_errors = errors.wrap(_map_exception)
53
53
 
54
54
 
55
+ _DML_TAGS = ("INSERT", "UPDATE", "DELETE")
56
+
57
+
58
+ def _rowcount_from_status(status: str) -> int:
59
+ """Extract the affected-row count from an asyncpg command tag.
60
+
61
+ DML tags ('UPDATE 5', 'DELETE 3', 'INSERT 0 5') end in the
62
+ count and parse to a non-negative int. Anything else (DDL,
63
+ `BEGIN`, `SELECT`, `COPY`) returns -1, matching the psycopg /
64
+ sqlite3 'no rowcount available' sentinel. SELECT in particular
65
+ would otherwise parse to its row count, which `db.execute`
66
+ explicitly does not promise across drivers.
67
+ """
68
+ verb, _, _ = status.partition(" ")
69
+ if verb not in _DML_TAGS:
70
+ return -1
71
+ tail = status.rsplit(" ", 1)[-1]
72
+ try:
73
+ return int(tail)
74
+ except ValueError:
75
+ return -1
76
+
77
+
55
78
  class AsyncpgAdapter(AdapterBase):
56
79
  """AdapterBase implementation backed by an asyncpg pool.
57
80
 
@@ -59,9 +82,10 @@ class AsyncpgAdapter(AdapterBase):
59
82
  (etchdb will not close it), or `await from_url(url)` to let etchdb
60
83
  create and own the pool. The `owns_pool` flag tracks ownership.
61
84
 
62
- 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),
63
87
  create the pool yourself with `asyncpg.create_pool(...)` and pass
64
- it to `from_pool`. `from_url` is intentionally minimal.
88
+ it to `from_pool`.
65
89
  """
66
90
 
67
91
  def __init__(self, pool: asyncpg.Pool, *, owns_pool: bool = False):
@@ -78,21 +102,39 @@ class AsyncpgAdapter(AdapterBase):
78
102
  return cls(pool, owns_pool=False)
79
103
 
80
104
  @classmethod
81
- 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:
82
112
  """Create an asyncpg pool from `url` and wrap it.
83
113
 
84
114
  etchdb owns the pool; `close()` will close it. The pool is
85
115
  initialised with a JSONB codec that handles UUID, datetime,
86
- Enum, and Pydantic BaseModel transparently. Users wanting a
87
- pristine pool with no codec setup should construct the pool
88
- 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`.
89
122
  """
90
- 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)
91
129
  return cls(pool, owns_pool=True)
92
130
 
93
- async def execute(self, sql: str, *params: Any) -> Any:
131
+ async def execute(self, sql: str, *params: Any) -> int:
132
+ async with _wrap_errors(), self._pool.acquire() as conn:
133
+ return _rowcount_from_status(await conn.execute(sql, *params))
134
+
135
+ async def execute_script(self, sql: str) -> None:
94
136
  async with _wrap_errors(), self._pool.acquire() as conn:
95
- return await conn.execute(sql, *params)
137
+ await conn.execute(sql)
96
138
 
97
139
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
98
140
  async with _wrap_errors(), self._pool.acquire() as conn:
@@ -128,9 +170,13 @@ class _AsyncpgConnAdapter(AdapterBase):
128
170
  def placeholder(i: int) -> str:
129
171
  return f"${i + 1}"
130
172
 
131
- async def execute(self, sql: str, *params: Any) -> Any:
173
+ async def execute(self, sql: str, *params: Any) -> int:
174
+ async with _wrap_errors():
175
+ return _rowcount_from_status(await self._conn.execute(sql, *params))
176
+
177
+ async def execute_script(self, sql: str) -> None:
132
178
  async with _wrap_errors():
133
- return await self._conn.execute(sql, *params)
179
+ await self._conn.execute(sql)
134
180
 
135
181
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
136
182
  async with _wrap_errors():