etchdb 0.2.0__tar.gz → 0.3.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 (40) hide show
  1. {etchdb-0.2.0 → etchdb-0.3.0}/PKG-INFO +41 -8
  2. {etchdb-0.2.0 → etchdb-0.3.0}/README.md +40 -7
  3. {etchdb-0.2.0 → etchdb-0.3.0}/pyproject.toml +1 -1
  4. etchdb-0.3.0/src/etchdb/__init__.py +26 -0
  5. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/aiosqlite/adapter.py +42 -11
  6. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/asyncpg/adapter.py +61 -12
  7. etchdb-0.3.0/src/etchdb/codecs.py +27 -0
  8. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/db.py +84 -1
  9. etchdb-0.3.0/src/etchdb/errors.py +67 -0
  10. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/psycopg/adapter.py +60 -12
  11. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/sql/__init__.py +175 -34
  12. etchdb-0.3.0/tests/integration/test_batch.py +109 -0
  13. etchdb-0.3.0/tests/integration/test_codecs.py +97 -0
  14. etchdb-0.3.0/tests/integration/test_errors.py +51 -0
  15. etchdb-0.3.0/tests/integration/test_is_null.py +87 -0
  16. etchdb-0.3.0/tests/integration/test_iter_rows.py +63 -0
  17. {etchdb-0.2.0 → etchdb-0.3.0}/tests/unit/test_sql_emitter.py +223 -0
  18. etchdb-0.2.0/src/etchdb/__init__.py +0 -9
  19. {etchdb-0.2.0 → etchdb-0.3.0}/.gitignore +0 -0
  20. {etchdb-0.2.0 → etchdb-0.3.0}/.python-version +0 -0
  21. {etchdb-0.2.0 → etchdb-0.3.0}/LICENSE +0 -0
  22. {etchdb-0.2.0 → etchdb-0.3.0}/Makefile +0 -0
  23. {etchdb-0.2.0 → etchdb-0.3.0}/docker-compose.yml +0 -0
  24. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/adapter.py +0 -0
  25. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/aiosqlite/__init__.py +0 -0
  26. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/asyncpg/__init__.py +0 -0
  27. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/psycopg/__init__.py +0 -0
  28. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/py.typed +0 -0
  29. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/query.py +0 -0
  30. {etchdb-0.2.0 → etchdb-0.3.0}/src/etchdb/row.py +0 -0
  31. {etchdb-0.2.0 → etchdb-0.3.0}/tests/__init__.py +0 -0
  32. {etchdb-0.2.0 → etchdb-0.3.0}/tests/_models.py +0 -0
  33. {etchdb-0.2.0 → etchdb-0.3.0}/tests/integration/__init__.py +0 -0
  34. {etchdb-0.2.0 → etchdb-0.3.0}/tests/integration/conftest.py +0 -0
  35. {etchdb-0.2.0 → etchdb-0.3.0}/tests/integration/test_facade.py +0 -0
  36. {etchdb-0.2.0 → etchdb-0.3.0}/tests/integration/test_readme_example.py +0 -0
  37. {etchdb-0.2.0 → etchdb-0.3.0}/tests/integration/test_typed_crud.py +0 -0
  38. {etchdb-0.2.0 → etchdb-0.3.0}/tests/unit/__init__.py +0 -0
  39. {etchdb-0.2.0 → etchdb-0.3.0}/tests/unit/test_adapters.py +0 -0
  40. {etchdb-0.2.0 → etchdb-0.3.0}/tests/unit/test_db_dispatch.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: etchdb
3
- Version: 0.2.0
3
+ Version: 0.3.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.2.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
69
+ Alpha. v0.3.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
70
70
 
71
71
  ## Example
72
72
 
@@ -80,12 +80,16 @@ class User(Row):
80
80
  email: str | None = None
81
81
 
82
82
  # Connect (driver inferred from URL scheme)
83
+ # postgresql+asyncpg://... asyncpg + Postgres
84
+ # postgresql+psycopg://... psycopg3 + Postgres
85
+ # sqlite+aiosqlite:///... aiosqlite + SQLite
83
86
  db = await DB.from_url("postgresql+asyncpg://user@host/db")
84
87
 
85
88
  # Typed CRUD
86
89
  alice = await db.insert(User(name="Alice")) # alice.id is now populated by the DB
87
90
  user = await db.get(User, id=alice.id) # one row or None
88
91
  users = await db.query(User) # list of rows
92
+ no_email = await db.query(User, email=None) # IS NULL, not = NULL
89
93
  await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
90
94
  await db.delete(alice)
91
95
 
@@ -99,11 +103,22 @@ await db.update(User(id=alice.id, name="Alice B"),
99
103
  # so models with required NOT NULL columns still flow through.
100
104
  await db.update(User.patch(id=alice.id, name="Alice B"))
101
105
 
106
+ # Bulk insert / delete (chunked at the driver's parameter limit).
107
+ await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
108
+ await db.delete_many(User, [1, 2, 3])
109
+
110
+ # Stream every matching row (paginated, won't load the whole table at once)
111
+ # Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
112
+ # loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
113
+ async for user in db.iter_rows(User, batch_size=500):
114
+ process(user)
115
+
102
116
  # Typed-result raw SQL (covers most joins)
103
117
  users = await db.fetch_models(User, """
104
118
  SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
105
119
  WHERE o.created_at > $1
106
120
  """, since)
121
+ top = await db.fetch_model(User, "SELECT * FROM users ORDER BY id LIMIT 1") # Row | None
107
122
 
108
123
  # Untyped raw SQL (mirrors asyncpg)
109
124
  rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
@@ -133,6 +148,28 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
133
148
 
134
149
  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.
135
150
 
151
+ ## Typed errors
152
+
153
+ 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__`.
154
+
155
+ ```python
156
+ from etchdb import (
157
+ EtchdbError, # base for everything etchdb raises
158
+ IntegrityError, # unique / FK / NOT NULL / check violation
159
+ UndefinedTableError, # table referenced by a query does not exist
160
+ UndefinedColumnError, # column referenced by a query does not exist
161
+ OperationalError, # connection-level / driver-level failure
162
+ )
163
+
164
+ try:
165
+ await db.insert(User(id=1, name="Alice"))
166
+ except IntegrityError as e:
167
+ log.warning("duplicate or constraint violation: %s", e)
168
+ # e.__cause__ is the original asyncpg / psycopg / sqlite3 exception
169
+ ```
170
+
171
+ `except EtchdbError` catches every member of the family at once.
172
+
136
173
  ## Install
137
174
 
138
175
  Drivers are optional extras. Install only what you use:
@@ -154,11 +191,7 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
154
191
  db = DB(AsyncpgAdapter.from_pool(my_pool))
155
192
  ```
156
193
 
157
- `from_url` keeps the construction surface tiny. For pool-init concerns
158
- (pgvector tuning, JSONB / ENUM codec registration, custom `min_size` /
159
- `max_size`), construct the pool yourself and pass it via `from_pool`.
160
- Example, registering a Postgres ENUM as a Python `str` via asyncpg's
161
- `set_type_codec`:
194
+ `from_url` registers a JSONB codec on every connection so `dict` and `list` parameters round-trip with `UUID`, `datetime`, `Enum`, and Pydantic `BaseModel` values handled transparently. JSONB columns come back as Python objects directly: no `json.loads` at the call site, no manual `json.dumps` to insert. For pool-init concerns beyond that (pgvector tuning, custom ENUM codec, custom `min_size` / `max_size`), construct the pool yourself and pass it via `from_pool`. Example, registering a Postgres ENUM as a Python `str` via asyncpg's `set_type_codec`:
162
195
 
163
196
  ```python
164
197
  import asyncpg
@@ -202,7 +235,7 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
202
235
 
203
236
  ## Migrations
204
237
 
205
- Out of scope for v0.1. 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.
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.
206
239
 
207
240
  ## Built with AI assistance
208
241
 
@@ -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.2.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
7
+ Alpha. v0.3.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
8
8
 
9
9
  ## Example
10
10
 
@@ -18,12 +18,16 @@ class User(Row):
18
18
  email: str | None = None
19
19
 
20
20
  # Connect (driver inferred from URL scheme)
21
+ # postgresql+asyncpg://... asyncpg + Postgres
22
+ # postgresql+psycopg://... psycopg3 + Postgres
23
+ # sqlite+aiosqlite:///... aiosqlite + SQLite
21
24
  db = await DB.from_url("postgresql+asyncpg://user@host/db")
22
25
 
23
26
  # Typed CRUD
24
27
  alice = await db.insert(User(name="Alice")) # alice.id is now populated by the DB
25
28
  user = await db.get(User, id=alice.id) # one row or None
26
29
  users = await db.query(User) # list of rows
30
+ no_email = await db.query(User, email=None) # IS NULL, not = NULL
27
31
  await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
28
32
  await db.delete(alice)
29
33
 
@@ -37,11 +41,22 @@ await db.update(User(id=alice.id, name="Alice B"),
37
41
  # so models with required NOT NULL columns still flow through.
38
42
  await db.update(User.patch(id=alice.id, name="Alice B"))
39
43
 
44
+ # Bulk insert / delete (chunked at the driver's parameter limit).
45
+ await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
46
+ await db.delete_many(User, [1, 2, 3])
47
+
48
+ # Stream every matching row (paginated, won't load the whole table at once)
49
+ # Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
50
+ # loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
51
+ async for user in db.iter_rows(User, batch_size=500):
52
+ process(user)
53
+
40
54
  # Typed-result raw SQL (covers most joins)
41
55
  users = await db.fetch_models(User, """
42
56
  SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
43
57
  WHERE o.created_at > $1
44
58
  """, since)
59
+ top = await db.fetch_model(User, "SELECT * FROM users ORDER BY id LIMIT 1") # Row | None
45
60
 
46
61
  # Untyped raw SQL (mirrors asyncpg)
47
62
  rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
@@ -71,6 +86,28 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
71
86
 
72
87
  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.
73
88
 
89
+ ## Typed errors
90
+
91
+ 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__`.
92
+
93
+ ```python
94
+ from etchdb import (
95
+ EtchdbError, # base for everything etchdb raises
96
+ IntegrityError, # unique / FK / NOT NULL / check violation
97
+ UndefinedTableError, # table referenced by a query does not exist
98
+ UndefinedColumnError, # column referenced by a query does not exist
99
+ OperationalError, # connection-level / driver-level failure
100
+ )
101
+
102
+ try:
103
+ await db.insert(User(id=1, name="Alice"))
104
+ except IntegrityError as e:
105
+ log.warning("duplicate or constraint violation: %s", e)
106
+ # e.__cause__ is the original asyncpg / psycopg / sqlite3 exception
107
+ ```
108
+
109
+ `except EtchdbError` catches every member of the family at once.
110
+
74
111
  ## Install
75
112
 
76
113
  Drivers are optional extras. Install only what you use:
@@ -92,11 +129,7 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
92
129
  db = DB(AsyncpgAdapter.from_pool(my_pool))
93
130
  ```
94
131
 
95
- `from_url` keeps the construction surface tiny. For pool-init concerns
96
- (pgvector tuning, JSONB / ENUM codec registration, custom `min_size` /
97
- `max_size`), construct the pool yourself and pass it via `from_pool`.
98
- Example, registering a Postgres ENUM as a Python `str` via asyncpg's
99
- `set_type_codec`:
132
+ `from_url` registers a JSONB codec on every connection so `dict` and `list` parameters round-trip with `UUID`, `datetime`, `Enum`, and Pydantic `BaseModel` values handled transparently. JSONB columns come back as Python objects directly: no `json.loads` at the call site, no manual `json.dumps` to insert. For pool-init concerns beyond that (pgvector tuning, custom ENUM codec, custom `min_size` / `max_size`), construct the pool yourself and pass it via `from_pool`. Example, registering a Postgres ENUM as a Python `str` via asyncpg's `set_type_codec`:
100
133
 
101
134
  ```python
102
135
  import asyncpg
@@ -140,7 +173,7 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
140
173
 
141
174
  ## Migrations
142
175
 
143
- Out of scope for v0.1. 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.
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.
144
177
 
145
178
  ## Built with AI assistance
146
179
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "etchdb"
3
- version = "0.2.0"
3
+ version = "0.3.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"
@@ -0,0 +1,26 @@
1
+ """etchdb: minimal async DB layer for Python."""
2
+
3
+ from etchdb.db import DB
4
+ from etchdb.errors import (
5
+ EtchdbError,
6
+ IntegrityError,
7
+ OperationalError,
8
+ UndefinedColumnError,
9
+ UndefinedTableError,
10
+ )
11
+ from etchdb.query import SqlQuery
12
+ from etchdb.row import Row
13
+
14
+ __version__ = "0.3.0"
15
+
16
+ __all__ = [
17
+ "DB",
18
+ "EtchdbError",
19
+ "IntegrityError",
20
+ "OperationalError",
21
+ "Row",
22
+ "SqlQuery",
23
+ "UndefinedColumnError",
24
+ "UndefinedTableError",
25
+ "__version__",
26
+ ]
@@ -8,6 +8,7 @@ aiosqlite's internal queue, which is the correct sqlite3 model.
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
+ import sqlite3
11
12
  from collections.abc import AsyncIterator
12
13
  from contextlib import asynccontextmanager
13
14
  from typing import Any
@@ -15,9 +16,32 @@ from urllib.parse import urlparse
15
16
 
16
17
  import aiosqlite
17
18
 
19
+ from etchdb import errors
18
20
  from etchdb.adapter import AdapterBase
19
21
 
20
22
 
23
+ def _map_exception(exc: BaseException) -> errors.EtchdbError | None:
24
+ """Translate a sqlite3 exception (raised through aiosqlite) to its
25
+ etchdb equivalent, or None if the exception should propagate as-is.
26
+ """
27
+ if isinstance(exc, sqlite3.IntegrityError):
28
+ return errors.IntegrityError(str(exc))
29
+ if isinstance(exc, sqlite3.OperationalError):
30
+ # sqlite3.OperationalError covers schema lookup failures and
31
+ # connection-level failures alike; sqlite3 has no richer
32
+ # subclass, so disambiguate by message text.
33
+ msg = str(exc).lower()
34
+ if "no such table" in msg:
35
+ return errors.UndefinedTableError(str(exc))
36
+ if "no such column" in msg:
37
+ return errors.UndefinedColumnError(str(exc))
38
+ return errors.OperationalError(str(exc))
39
+ return None
40
+
41
+
42
+ _wrap_errors = errors.wrap(_map_exception)
43
+
44
+
21
45
  def _path_from_url(url: str) -> str:
22
46
  """Extract the SQLite database path from a URL.
23
47
 
@@ -67,21 +91,22 @@ class AiosqliteAdapter(AdapterBase):
67
91
  return cls(conn, owns_conn=True)
68
92
 
69
93
  async def execute(self, sql: str, *params: Any) -> Any:
70
- await self._conn.execute(sql, params)
71
- await self._conn.commit()
94
+ async with _wrap_errors():
95
+ await self._conn.execute(sql, params)
96
+ await self._conn.commit()
72
97
 
73
98
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
74
- async with self._conn.execute(sql, params) as cursor:
99
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
75
100
  rows = await cursor.fetchall()
76
101
  return [dict(r) for r in rows]
77
102
 
78
103
  async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
79
- async with self._conn.execute(sql, params) as cursor:
104
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
80
105
  row = await cursor.fetchone()
81
106
  return dict(row) if row is not None else None
82
107
 
83
108
  async def fetchval(self, sql: str, *params: Any) -> Any:
84
- async with self._conn.execute(sql, params) as cursor:
109
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
85
110
  row = await cursor.fetchone()
86
111
  return row[0] if row is not None else None
87
112
 
@@ -89,11 +114,16 @@ class AiosqliteAdapter(AdapterBase):
89
114
  async def transaction(self) -> AsyncIterator[AdapterBase]:
90
115
  # sqlite3's default isolation_level auto-injects BEGIN before DML,
91
116
  # so we don't emit one explicitly; we just commit on clean exit
92
- # and rollback on any exception.
117
+ # and rollback on any exception. Rollback must run before the
118
+ # mapped exception escapes, so we can't reuse `_wrap_errors`.
93
119
  try:
94
120
  yield _AiosqliteTxAdapter(self._conn)
95
- except BaseException:
121
+ except BaseException as e:
96
122
  await self._conn.rollback()
123
+ if isinstance(e, Exception):
124
+ mapped = _map_exception(e)
125
+ if mapped is not None:
126
+ raise mapped from e
97
127
  raise
98
128
  else:
99
129
  await self._conn.commit()
@@ -114,20 +144,21 @@ class _AiosqliteTxAdapter(AdapterBase):
114
144
  return "?"
115
145
 
116
146
  async def execute(self, sql: str, *params: Any) -> Any:
117
- await self._conn.execute(sql, params)
147
+ async with _wrap_errors():
148
+ await self._conn.execute(sql, params)
118
149
 
119
150
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
120
- async with self._conn.execute(sql, params) as cursor:
151
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
121
152
  rows = await cursor.fetchall()
122
153
  return [dict(r) for r in rows]
123
154
 
124
155
  async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
125
- async with self._conn.execute(sql, params) as cursor:
156
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
126
157
  row = await cursor.fetchone()
127
158
  return dict(row) if row is not None else None
128
159
 
129
160
  async def fetchval(self, sql: str, *params: Any) -> Any:
130
- async with self._conn.execute(sql, params) as cursor:
161
+ async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
131
162
  row = await cursor.fetchone()
132
163
  return row[0] if row is not None else None
133
164
 
@@ -2,13 +2,54 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import json
5
6
  from collections.abc import AsyncIterator
6
7
  from contextlib import asynccontextmanager
7
8
  from typing import Any
8
9
 
9
10
  import asyncpg
10
11
 
12
+ from etchdb import errors
11
13
  from etchdb.adapter import AdapterBase
14
+ from etchdb.codecs import json_dumps
15
+
16
+
17
+ async def _init_codecs(conn: asyncpg.Connection) -> None:
18
+ """Pool `init=` callback: register a JSONB codec on every new
19
+ connection so `dict | list` round-trips with UUID, datetime, Enum,
20
+ and Pydantic BaseModel encoded transparently. asyncpg returns JSONB
21
+ as `str` without this; with it, JSONB columns come back as Python
22
+ objects directly."""
23
+ await conn.set_type_codec(
24
+ "jsonb",
25
+ encoder=json_dumps,
26
+ decoder=json.loads,
27
+ schema="pg_catalog",
28
+ format="text",
29
+ )
30
+
31
+
32
+ def _map_exception(exc: BaseException) -> errors.EtchdbError | None:
33
+ """Translate an asyncpg exception to its etchdb equivalent, or
34
+ None if the exception should propagate unchanged."""
35
+ if isinstance(exc, asyncpg.exceptions.IntegrityConstraintViolationError):
36
+ return errors.IntegrityError(str(exc))
37
+ if isinstance(exc, asyncpg.exceptions.UndefinedTableError):
38
+ return errors.UndefinedTableError(str(exc))
39
+ if isinstance(exc, asyncpg.exceptions.UndefinedColumnError):
40
+ return errors.UndefinedColumnError(str(exc))
41
+ if isinstance(
42
+ exc,
43
+ asyncpg.exceptions.InvalidPasswordError
44
+ | asyncpg.exceptions.PostgresConnectionError
45
+ | asyncpg.exceptions.ConnectionDoesNotExistError
46
+ | ConnectionError,
47
+ ):
48
+ return errors.OperationalError(str(exc))
49
+ return None
50
+
51
+
52
+ _wrap_errors = errors.wrap(_map_exception)
12
53
 
13
54
 
14
55
  class AsyncpgAdapter(AdapterBase):
@@ -40,32 +81,36 @@ class AsyncpgAdapter(AdapterBase):
40
81
  async def from_url(cls, url: str) -> AsyncpgAdapter:
41
82
  """Create an asyncpg pool from `url` and wrap it.
42
83
 
43
- etchdb owns the pool; `close()` will close it.
84
+ etchdb owns the pool; `close()` will close it. The pool is
85
+ 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`.
44
89
  """
45
- pool = await asyncpg.create_pool(url)
90
+ pool = await asyncpg.create_pool(url, init=_init_codecs)
46
91
  return cls(pool, owns_pool=True)
47
92
 
48
93
  async def execute(self, sql: str, *params: Any) -> Any:
49
- async with self._pool.acquire() as conn:
94
+ async with _wrap_errors(), self._pool.acquire() as conn:
50
95
  return await conn.execute(sql, *params)
51
96
 
52
97
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
53
- async with self._pool.acquire() as conn:
98
+ async with _wrap_errors(), self._pool.acquire() as conn:
54
99
  records = await conn.fetch(sql, *params)
55
100
  return [dict(r) for r in records]
56
101
 
57
102
  async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
58
- async with self._pool.acquire() as conn:
103
+ async with _wrap_errors(), self._pool.acquire() as conn:
59
104
  record = await conn.fetchrow(sql, *params)
60
105
  return dict(record) if record is not None else None
61
106
 
62
107
  async def fetchval(self, sql: str, *params: Any) -> Any:
63
- async with self._pool.acquire() as conn:
108
+ async with _wrap_errors(), self._pool.acquire() as conn:
64
109
  return await conn.fetchval(sql, *params)
65
110
 
66
111
  @asynccontextmanager
67
112
  async def transaction(self) -> AsyncIterator[AdapterBase]:
68
- async with self._pool.acquire() as conn, conn.transaction():
113
+ async with _wrap_errors(), self._pool.acquire() as conn, conn.transaction():
69
114
  yield _AsyncpgConnAdapter(conn)
70
115
 
71
116
  async def close(self) -> None:
@@ -84,22 +129,26 @@ class _AsyncpgConnAdapter(AdapterBase):
84
129
  return f"${i + 1}"
85
130
 
86
131
  async def execute(self, sql: str, *params: Any) -> Any:
87
- return await self._conn.execute(sql, *params)
132
+ async with _wrap_errors():
133
+ return await self._conn.execute(sql, *params)
88
134
 
89
135
  async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
90
- records = await self._conn.fetch(sql, *params)
136
+ async with _wrap_errors():
137
+ records = await self._conn.fetch(sql, *params)
91
138
  return [dict(r) for r in records]
92
139
 
93
140
  async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
94
- record = await self._conn.fetchrow(sql, *params)
141
+ async with _wrap_errors():
142
+ record = await self._conn.fetchrow(sql, *params)
95
143
  return dict(record) if record is not None else None
96
144
 
97
145
  async def fetchval(self, sql: str, *params: Any) -> Any:
98
- return await self._conn.fetchval(sql, *params)
146
+ async with _wrap_errors():
147
+ return await self._conn.fetchval(sql, *params)
99
148
 
100
149
  @asynccontextmanager
101
150
  async def transaction(self) -> AsyncIterator[AdapterBase]:
102
- async with self._conn.transaction():
151
+ async with _wrap_errors(), self._conn.transaction():
103
152
  yield self
104
153
 
105
154
  async def close(self) -> None:
@@ -0,0 +1,27 @@
1
+ """JSONB serialisation helpers used by the Postgres adapters' `from_url`.
2
+
3
+ The default `json.dumps` raises on `UUID`, `datetime`, `date`, `Enum`,
4
+ and Pydantic v2 `BaseModel`. `json_dumps` here delegates to
5
+ `pydantic_core.to_json`, which handles those plus `bytes`, `Decimal`,
6
+ IP addresses, and more in C-implemented code.
7
+
8
+ Wired into `AsyncpgAdapter.from_url` via asyncpg's `init=` callback,
9
+ and into `PsycopgAdapter.from_url` via the pool's `configure=` callback.
10
+ The `from_pool` paths intentionally don't run this; users with their
11
+ own pool own their codec setup. They can import `json_dumps` here and
12
+ register it the same way if they want the same default behaviour.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Any
18
+
19
+ from pydantic_core import to_json
20
+
21
+
22
+ def json_dumps(obj: Any) -> str:
23
+ """Serialize `obj` for a JSONB column. Handles UUID, datetime, Enum,
24
+ Pydantic `BaseModel`, `bytes`, `Decimal`, IP addresses, and other
25
+ types `pydantic_core` knows about. Raises
26
+ `pydantic_core.PydanticSerializationError` for unknown types."""
27
+ return to_json(obj).decode()
@@ -17,13 +17,18 @@ from urllib.parse import urlparse
17
17
  from etchdb import sql
18
18
 
19
19
  if TYPE_CHECKING:
20
- from collections.abc import AsyncIterator, Mapping
20
+ from collections.abc import AsyncIterator, Mapping, Sequence
21
21
 
22
22
  from etchdb.adapter import AdapterBase
23
23
  from etchdb.query import SqlQuery
24
24
  from etchdb.row import Row
25
25
 
26
26
 
27
+ # Postgres caps query parameters at 32767; SQLite is at least 32766 since
28
+ # 3.32. Pick the lower bound so a chunk fits in any backend.
29
+ _PARAM_LIMIT = 32766
30
+
31
+
27
32
  def _hydrate(model_or_row: type[Row] | Row, row: dict[str, Any] | None) -> Row | None:
28
33
  """Build a Row from a fetchrow result, or return None when there is no row.
29
34
 
@@ -135,11 +140,89 @@ class DB:
135
140
  )
136
141
  return await self.fetch_models(model, q.sql, *q.params)
137
142
 
143
+ async def iter_rows(
144
+ self,
145
+ model: type[Row],
146
+ *,
147
+ batch_size: int = 500,
148
+ order_by: str | list[str] | None = None,
149
+ **filters: Any,
150
+ ) -> AsyncIterator[Row]:
151
+ """Stream every matching row, paged by `batch_size`. Default
152
+ `order_by` is `__pk__` so pagination stays stable across pages.
153
+
154
+ Uses offset pagination, which is O(N^2) over huge tables. For
155
+ full scans of large tables, prefer a raw keyset loop instead.
156
+ """
157
+ if batch_size < 1:
158
+ raise ValueError(f"batch_size must be >= 1, got {batch_size}")
159
+ if order_by is None:
160
+ order_by = list(model.__pk__)
161
+ offset = 0
162
+ while True:
163
+ page = await self.query(
164
+ model,
165
+ limit=batch_size,
166
+ offset=offset,
167
+ order_by=order_by,
168
+ **filters,
169
+ )
170
+ for row in page:
171
+ yield row
172
+ # Short page means we're past the end; skip the empty
173
+ # round-trip the next iteration would do.
174
+ if len(page) < batch_size:
175
+ return
176
+ offset += batch_size
177
+
138
178
  async def insert(self, row: Row) -> Row:
139
179
  q = sql.insert(row, placeholder=self._adapter.placeholder)
140
180
  result = await self._adapter.fetchrow(q.sql, *q.params)
141
181
  return _hydrate(row, result) or row
142
182
 
183
+ async def insert_many(
184
+ self,
185
+ rows: Sequence[Row],
186
+ *,
187
+ on_conflict: sql._OnConflict = None,
188
+ ) -> None:
189
+ """Insert many rows in one or more multi-VALUES statements.
190
+
191
+ All rows must share `model_fields_set`. Long batches are
192
+ chunked at the driver's parameter limit so a single call can
193
+ cover thousands of rows. `on_conflict="ignore"` appends
194
+ `ON CONFLICT DO NOTHING`. Empty `rows` is a no-op."""
195
+ if not rows:
196
+ return
197
+ cols_per_row = sum(1 for f in type(rows[0]).model_fields if f in rows[0].model_fields_set)
198
+ if cols_per_row == 0:
199
+ raise ValueError("insert_many requires at least one field set on the first row")
200
+ chunk_size = _PARAM_LIMIT // cols_per_row
201
+ for i in range(0, len(rows), chunk_size):
202
+ chunk = rows[i : i + chunk_size]
203
+ q = sql.insert_many(
204
+ chunk, placeholder=self._adapter.placeholder, on_conflict=on_conflict
205
+ )
206
+ await self._adapter.execute(q.sql, *q.params)
207
+
208
+ async def delete_many(
209
+ self,
210
+ model: type[Row],
211
+ pk_values: Sequence[Any],
212
+ ) -> None:
213
+ """Delete many rows by primary key.
214
+
215
+ For single-column PK, pass scalar values; for composite PK,
216
+ pass a list of mappings. Long batches are chunked at the
217
+ driver's parameter limit. Empty `pk_values` is a no-op."""
218
+ if not pk_values:
219
+ return
220
+ chunk_size = _PARAM_LIMIT // len(model.__pk__)
221
+ for i in range(0, len(pk_values), chunk_size):
222
+ chunk = pk_values[i : i + chunk_size]
223
+ q = sql.delete_many(model, chunk, placeholder=self._adapter.placeholder)
224
+ await self._adapter.execute(q.sql, *q.params)
225
+
143
226
  async def update(self, row: Row, *, where: Mapping[str, Any] | None = None) -> Row | None:
144
227
  """Update `row` by PK, AND'd with `where=`. Returns the updated
145
228
  row, or None if PK + `where=` matched no row."""