etchdb 0.4.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.4.0 → etchdb-0.5.0}/PKG-INFO +84 -3
  3. {etchdb-0.4.0 → etchdb-0.5.0}/README.md +83 -2
  4. {etchdb-0.4.0 → etchdb-0.5.0}/pyproject.toml +1 -1
  5. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/__init__.py +3 -1
  6. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/adapter.py +12 -0
  7. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/aiosqlite/adapter.py +19 -2
  8. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/asyncpg/adapter.py +30 -7
  9. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/db.py +40 -4
  10. etchdb-0.5.0/src/etchdb/migrations.py +199 -0
  11. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/psycopg/adapter.py +27 -5
  12. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/row.py +16 -0
  13. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/sql/__init__.py +16 -7
  14. etchdb-0.5.0/tests/integration/test_fields_not_in_db.py +31 -0
  15. etchdb-0.5.0/tests/integration/test_migrations.py +342 -0
  16. etchdb-0.5.0/tests/integration/test_pool_kwargs.py +43 -0
  17. etchdb-0.5.0/tests/unit/test_db_dispatch.py +79 -0
  18. etchdb-0.5.0/tests/unit/test_migrations.py +126 -0
  19. {etchdb-0.4.0 → etchdb-0.5.0}/tests/unit/test_sql_emitter.py +53 -0
  20. etchdb-0.4.0/tests/unit/test_db_dispatch.py +0 -41
  21. {etchdb-0.4.0 → etchdb-0.5.0}/.gitignore +0 -0
  22. {etchdb-0.4.0 → etchdb-0.5.0}/.python-version +0 -0
  23. {etchdb-0.4.0 → etchdb-0.5.0}/LICENSE +0 -0
  24. {etchdb-0.4.0 → etchdb-0.5.0}/Makefile +0 -0
  25. {etchdb-0.4.0 → etchdb-0.5.0}/docker-compose.yml +0 -0
  26. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/aiosqlite/__init__.py +0 -0
  27. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/asyncpg/__init__.py +0 -0
  28. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/codecs.py +0 -0
  29. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/errors.py +0 -0
  30. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/expr.py +0 -0
  31. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/psycopg/__init__.py +0 -0
  32. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/py.typed +0 -0
  33. {etchdb-0.4.0 → etchdb-0.5.0}/src/etchdb/query.py +0 -0
  34. {etchdb-0.4.0 → etchdb-0.5.0}/tests/__init__.py +0 -0
  35. {etchdb-0.4.0 → etchdb-0.5.0}/tests/_models.py +0 -0
  36. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/__init__.py +0 -0
  37. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/conftest.py +0 -0
  38. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_batch.py +0 -0
  39. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_codecs.py +0 -0
  40. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_errors.py +0 -0
  41. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_execute_rowcount.py +0 -0
  42. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_expressions.py +0 -0
  43. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_facade.py +0 -0
  44. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_in_filter.py +0 -0
  45. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_is_null.py +0 -0
  46. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_iter_rows.py +0 -0
  47. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_readme_example.py +0 -0
  48. {etchdb-0.4.0 → etchdb-0.5.0}/tests/integration/test_typed_crud.py +0 -0
  49. {etchdb-0.4.0 → etchdb-0.5.0}/tests/unit/__init__.py +0 -0
  50. {etchdb-0.4.0 → etchdb-0.5.0}/tests/unit/test_adapters.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.4.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.4.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
 
@@ -145,6 +145,13 @@ async with db.transaction() as tx:
145
145
  await tx.insert(User(name="Carol"))
146
146
  await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
147
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
+
148
155
  # Inspect SQL before executing (etchdb's defining feature)
149
156
  q = db.compose("get", User, id=1)
150
157
  print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
@@ -161,6 +168,8 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
161
168
 
162
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.
163
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
+
164
173
  ## Typed errors
165
174
 
166
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__`.
@@ -248,7 +257,79 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
248
257
 
249
258
  ## Migrations
250
259
 
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.
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.
252
333
 
253
334
  ## Under consideration
254
335
 
@@ -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.5.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
8
8
 
9
9
  ## Example
10
10
 
@@ -83,6 +83,13 @@ async with db.transaction() as tx:
83
83
  await tx.insert(User(name="Carol"))
84
84
  await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
85
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
+
86
93
  # Inspect SQL before executing (etchdb's defining feature)
87
94
  q = db.compose("get", User, id=1)
88
95
  print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
@@ -99,6 +106,8 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
99
106
 
100
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.
101
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
+
102
111
  ## Typed errors
103
112
 
104
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__`.
@@ -186,7 +195,79 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
186
195
 
187
196
  ## Migrations
188
197
 
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.
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.
190
271
 
191
272
  ## Under consideration
192
273
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "etchdb"
3
- version = "0.4.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"
@@ -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.5.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",
@@ -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)
@@ -18,8 +18,10 @@ from etchdb import sql
18
18
 
19
19
  if TYPE_CHECKING:
20
20
  from collections.abc import AsyncIterator, Mapping, Sequence
21
+ from pathlib import Path
21
22
 
22
23
  from etchdb.adapter import AdapterBase
24
+ from etchdb.migrations import MigrationStatus
23
25
  from etchdb.query import SqlQuery
24
26
  from etchdb.row import Row
25
27
 
@@ -58,7 +60,13 @@ class DB:
58
60
  self._adapter = adapter
59
61
 
60
62
  @classmethod
61
- async def from_url(cls, url: str) -> DB:
63
+ async def from_url(
64
+ cls,
65
+ url: str,
66
+ *,
67
+ min_size: int | None = None,
68
+ max_size: int | None = None,
69
+ ) -> DB:
62
70
  """Open a DB from a URL, dispatching on the URL scheme.
63
71
 
64
72
  Supported schemes:
@@ -68,8 +76,14 @@ class DB:
68
76
 
69
77
  Driver subpackages are imported lazily so users only need the
70
78
  driver they actually use installed.
79
+
80
+ `min_size` / `max_size` forward to the underlying Postgres pool
81
+ and are ignored on aiosqlite (no pool concept). For knobs
82
+ beyond size, construct the pool yourself and use the adapter's
83
+ `from_pool` directly.
71
84
  """
72
85
  scheme = urlparse(url).scheme.lower()
86
+ pool_kwargs = {"min_size": min_size, "max_size": max_size}
73
87
 
74
88
  if scheme in {"postgresql", "postgres", "postgresql+asyncpg"}:
75
89
  from etchdb.asyncpg import AsyncpgAdapter
@@ -77,16 +91,16 @@ class DB:
77
91
  # asyncpg only accepts the bare postgresql:// scheme.
78
92
  if scheme == "postgresql+asyncpg":
79
93
  url = "postgresql://" + url.split("://", 1)[1]
80
- adapter: AdapterBase = await AsyncpgAdapter.from_url(url)
94
+ adapter: AdapterBase = await AsyncpgAdapter.from_url(url, **pool_kwargs)
81
95
  elif scheme == "postgresql+psycopg":
82
96
  from etchdb.psycopg import PsycopgAdapter
83
97
 
84
98
  url = "postgresql://" + url.split("://", 1)[1]
85
- adapter = await PsycopgAdapter.from_url(url)
99
+ adapter = await PsycopgAdapter.from_url(url, **pool_kwargs)
86
100
  elif scheme in {"sqlite", "sqlite+aiosqlite"}:
87
101
  from etchdb.aiosqlite import AiosqliteAdapter
88
102
 
89
- adapter = await AiosqliteAdapter.from_url(url)
103
+ adapter = await AiosqliteAdapter.from_url(url, **pool_kwargs)
90
104
  else:
91
105
  raise ValueError(f"Unsupported URL scheme: {scheme!r}")
92
106
 
@@ -290,3 +304,25 @@ class DB:
290
304
  don't have a DB instance.
291
305
  """
292
306
  return sql.compose(op, *args, placeholder=self._adapter.placeholder, **kwargs)
307
+
308
+ async def migrate(self, directory: str | Path) -> int:
309
+ """Apply every pending `.sql` file in `directory`. Returns the
310
+ count applied. See `etchdb.migrations` for the conventions
311
+ (filename ordering, transaction wrapping, drift / disappearance
312
+ rejection).
313
+ """
314
+ from etchdb.migrations import migrate as _migrate
315
+
316
+ return await _migrate(self, directory)
317
+
318
+ async def migration_status(self, directory: str | Path) -> MigrationStatus:
319
+ """Compare the migrations directory against the tracking table.
320
+
321
+ Creates the tracking table on first call (idempotent). Returns
322
+ a `MigrationStatus` listing pending / applied / drifted /
323
+ missing filenames; check `is_consistent` before relying on
324
+ the state.
325
+ """
326
+ from etchdb.migrations import status as _status
327
+
328
+ return await _status(self, directory)