etchdb 0.1.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.
- {etchdb-0.1.0 → etchdb-0.3.0}/PKG-INFO +85 -7
- etchdb-0.3.0/README.md +184 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/pyproject.toml +3 -3
- etchdb-0.3.0/src/etchdb/__init__.py +26 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/aiosqlite/adapter.py +42 -11
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/asyncpg/adapter.py +61 -12
- etchdb-0.3.0/src/etchdb/codecs.py +27 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/db.py +102 -31
- etchdb-0.3.0/src/etchdb/errors.py +67 -0
- etchdb-0.3.0/src/etchdb/psycopg/__init__.py +20 -0
- etchdb-0.3.0/src/etchdb/psycopg/adapter.py +192 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/row.py +9 -1
- etchdb-0.3.0/src/etchdb/sql/__init__.py +412 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/integration/conftest.py +28 -13
- etchdb-0.3.0/tests/integration/test_batch.py +109 -0
- etchdb-0.3.0/tests/integration/test_codecs.py +97 -0
- etchdb-0.3.0/tests/integration/test_errors.py +51 -0
- etchdb-0.3.0/tests/integration/test_is_null.py +87 -0
- etchdb-0.3.0/tests/integration/test_iter_rows.py +63 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/integration/test_readme_example.py +26 -2
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/integration/test_typed_crud.py +38 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/unit/test_adapters.py +10 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/unit/test_db_dispatch.py +15 -3
- etchdb-0.3.0/tests/unit/test_sql_emitter.py +738 -0
- etchdb-0.1.0/README.md +0 -106
- etchdb-0.1.0/src/etchdb/__init__.py +0 -9
- etchdb-0.1.0/src/etchdb/sql/__init__.py +0 -209
- etchdb-0.1.0/tests/unit/test_sql_emitter.py +0 -382
- {etchdb-0.1.0 → etchdb-0.3.0}/.gitignore +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/.python-version +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/LICENSE +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/Makefile +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/docker-compose.yml +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/adapter.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/asyncpg/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/py.typed +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/src/etchdb/query.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/_models.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/integration/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/integration/test_facade.py +0 -0
- {etchdb-0.1.0 → etchdb-0.3.0}/tests/unit/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: etchdb
|
|
3
|
-
Version: 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
|
|
@@ -45,7 +45,7 @@ Requires-Dist: pydantic>=2.0.0
|
|
|
45
45
|
Provides-Extra: all
|
|
46
46
|
Requires-Dist: aiosqlite>=0.19.0; extra == 'all'
|
|
47
47
|
Requires-Dist: asyncpg>=0.30.0; extra == 'all'
|
|
48
|
-
Requires-Dist: psycopg[binary]>=3.2; extra == 'all'
|
|
48
|
+
Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'all'
|
|
49
49
|
Provides-Extra: asyncpg
|
|
50
50
|
Requires-Dist: asyncpg>=0.30.0; extra == 'asyncpg'
|
|
51
51
|
Provides-Extra: dev
|
|
@@ -55,7 +55,7 @@ Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
|
55
55
|
Requires-Dist: ruff>=0.5.0; extra == 'dev'
|
|
56
56
|
Requires-Dist: ty; extra == 'dev'
|
|
57
57
|
Provides-Extra: psycopg
|
|
58
|
-
Requires-Dist: psycopg[binary]>=3.2; extra == 'psycopg'
|
|
58
|
+
Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'psycopg'
|
|
59
59
|
Provides-Extra: sqlite
|
|
60
60
|
Requires-Dist: aiosqlite>=0.19.0; extra == 'sqlite'
|
|
61
61
|
Description-Content-Type: text/markdown
|
|
@@ -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.
|
|
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,24 +80,51 @@ 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
|
|
|
96
|
+
# Add `where=` to AND extra equality filters onto the PK. Atomic, so
|
|
97
|
+
# the scope check runs in the same statement as the update.
|
|
98
|
+
await db.update(User(id=alice.id, name="Alice B"),
|
|
99
|
+
where={"email": "alice@example.com"})
|
|
100
|
+
|
|
101
|
+
# Partial update without making your model lie about the schema:
|
|
102
|
+
# patch() builds a Row with only the given fields set; no validation,
|
|
103
|
+
# so models with required NOT NULL columns still flow through.
|
|
104
|
+
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
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
|
+
|
|
92
116
|
# Typed-result raw SQL (covers most joins)
|
|
93
117
|
users = await db.fetch_models(User, """
|
|
94
118
|
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
95
119
|
WHERE o.created_at > $1
|
|
96
120
|
""", since)
|
|
121
|
+
top = await db.fetch_model(User, "SELECT * FROM users ORDER BY id LIMIT 1") # Row | None
|
|
97
122
|
|
|
98
123
|
# Untyped raw SQL (mirrors asyncpg)
|
|
99
124
|
rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
|
|
100
|
-
val = await db.fetchval("SELECT count(*) FROM users")
|
|
125
|
+
val = await db.fetchval("SELECT count(*) FROM users") # always returns the count;
|
|
126
|
+
# for non-aggregate selects,
|
|
127
|
+
# fetchval returns None on no row.
|
|
101
128
|
await db.execute("UPDATE users SET active = false WHERE id = $1", uid)
|
|
102
129
|
|
|
103
130
|
# Transactions
|
|
@@ -109,9 +136,39 @@ async with db.transaction() as tx:
|
|
|
109
136
|
q = db.compose("get", User, id=1)
|
|
110
137
|
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
|
|
111
138
|
print(q.params) # [1]
|
|
139
|
+
|
|
140
|
+
# Same inspector without a live DB - useful in tests:
|
|
141
|
+
from etchdb import sql
|
|
142
|
+
q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`insert` only emits the columns you actually set, so an unset `id` lets the database allocate one (SERIAL or INTEGER PRIMARY KEY); the returned Row reflects the DB's view (`RETURNING *`), so server-defaults like `id` and `created_at` are populated in place. `update` does the same: a column you didn't touch keeps its current value rather than being clobbered. An explicit `None` counts as set in both cases.
|
|
146
|
+
|
|
147
|
+
`update` and `delete` use the value of every column in `__pk__` (default: `("id",)`) as the WHERE clause; override the class attribute for a composite or differently-named primary key. Add extra equality filters with `where={...}` for guarded updates: multi-tenant scoping like `where={"user_id": current_user}` is the canonical use case. Raw SQL is still the right tool when you need anything richer than equality.
|
|
148
|
+
|
|
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.
|
|
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
|
|
112
169
|
```
|
|
113
170
|
|
|
114
|
-
`
|
|
171
|
+
`except EtchdbError` catches every member of the family at once.
|
|
115
172
|
|
|
116
173
|
## Install
|
|
117
174
|
|
|
@@ -134,6 +191,27 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
|
134
191
|
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
135
192
|
```
|
|
136
193
|
|
|
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`:
|
|
195
|
+
|
|
196
|
+
```python
|
|
197
|
+
import asyncpg
|
|
198
|
+
from etchdb import DB
|
|
199
|
+
from etchdb.asyncpg import AsyncpgAdapter
|
|
200
|
+
|
|
201
|
+
async def init_conn(conn):
|
|
202
|
+
await conn.set_type_codec(
|
|
203
|
+
"memory_domain", # the ENUM type name
|
|
204
|
+
encoder=str, decoder=str,
|
|
205
|
+
schema="public",
|
|
206
|
+
format="text",
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
pool = await asyncpg.create_pool(url, init=init_conn, min_size=2, max_size=10)
|
|
210
|
+
db = DB(AsyncpgAdapter.from_pool(pool))
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Both Postgres adapters take libpq-native `$1, $2, ...` placeholders in raw SQL. The psycopg adapter uses `AsyncRawCursor` so the `$N` form works there too; psycopg's default `%s` form is not used and will produce a Postgres syntax error.
|
|
214
|
+
|
|
137
215
|
## Why
|
|
138
216
|
|
|
139
217
|
Most Python ORMs are heavy, opinionated, and leak at the seams when you reach for pgvector or PostGIS. Raw asyncpg works, but every project ends up writing the same Pydantic-bridge code. etchdb closes that gap without becoming a framework.
|
|
@@ -157,7 +235,7 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
|
|
|
157
235
|
|
|
158
236
|
## Migrations
|
|
159
237
|
|
|
160
|
-
Out of scope
|
|
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.
|
|
161
239
|
|
|
162
240
|
## Built with AI assistance
|
|
163
241
|
|
etchdb-0.3.0/README.md
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# etchdb
|
|
2
|
+
|
|
3
|
+
Minimal async DB layer for Python. Typed CRUD over Pydantic. Raw SQL when you need it.
|
|
4
|
+
|
|
5
|
+
## Status
|
|
6
|
+
|
|
7
|
+
Alpha. v0.3.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
8
|
+
|
|
9
|
+
## Example
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from etchdb import DB, Row
|
|
13
|
+
|
|
14
|
+
class User(Row):
|
|
15
|
+
__table__ = "users"
|
|
16
|
+
id: int | None = None # leave unset and the DB allocates it (SERIAL / INTEGER PK)
|
|
17
|
+
name: str
|
|
18
|
+
email: str | None = None
|
|
19
|
+
|
|
20
|
+
# Connect (driver inferred from URL scheme)
|
|
21
|
+
# postgresql+asyncpg://... asyncpg + Postgres
|
|
22
|
+
# postgresql+psycopg://... psycopg3 + Postgres
|
|
23
|
+
# sqlite+aiosqlite:///... aiosqlite + SQLite
|
|
24
|
+
db = await DB.from_url("postgresql+asyncpg://user@host/db")
|
|
25
|
+
|
|
26
|
+
# Typed CRUD
|
|
27
|
+
alice = await db.insert(User(name="Alice")) # alice.id is now populated by the DB
|
|
28
|
+
user = await db.get(User, id=alice.id) # one row or None
|
|
29
|
+
users = await db.query(User) # list of rows
|
|
30
|
+
no_email = await db.query(User, email=None) # IS NULL, not = NULL
|
|
31
|
+
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
32
|
+
await db.delete(alice)
|
|
33
|
+
|
|
34
|
+
# Add `where=` to AND extra equality filters onto the PK. Atomic, so
|
|
35
|
+
# the scope check runs in the same statement as the update.
|
|
36
|
+
await db.update(User(id=alice.id, name="Alice B"),
|
|
37
|
+
where={"email": "alice@example.com"})
|
|
38
|
+
|
|
39
|
+
# Partial update without making your model lie about the schema:
|
|
40
|
+
# patch() builds a Row with only the given fields set; no validation,
|
|
41
|
+
# so models with required NOT NULL columns still flow through.
|
|
42
|
+
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
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
|
+
|
|
54
|
+
# Typed-result raw SQL (covers most joins)
|
|
55
|
+
users = await db.fetch_models(User, """
|
|
56
|
+
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
57
|
+
WHERE o.created_at > $1
|
|
58
|
+
""", since)
|
|
59
|
+
top = await db.fetch_model(User, "SELECT * FROM users ORDER BY id LIMIT 1") # Row | None
|
|
60
|
+
|
|
61
|
+
# Untyped raw SQL (mirrors asyncpg)
|
|
62
|
+
rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
|
|
63
|
+
val = await db.fetchval("SELECT count(*) FROM users") # always returns the count;
|
|
64
|
+
# for non-aggregate selects,
|
|
65
|
+
# fetchval returns None on no row.
|
|
66
|
+
await db.execute("UPDATE users SET active = false WHERE id = $1", uid)
|
|
67
|
+
|
|
68
|
+
# Transactions
|
|
69
|
+
async with db.transaction() as tx:
|
|
70
|
+
await tx.insert(User(name="Carol"))
|
|
71
|
+
await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
|
|
72
|
+
|
|
73
|
+
# Inspect SQL before executing (etchdb's defining feature)
|
|
74
|
+
q = db.compose("get", User, id=1)
|
|
75
|
+
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
|
|
76
|
+
print(q.params) # [1]
|
|
77
|
+
|
|
78
|
+
# Same inspector without a live DB - useful in tests:
|
|
79
|
+
from etchdb import sql
|
|
80
|
+
q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`insert` only emits the columns you actually set, so an unset `id` lets the database allocate one (SERIAL or INTEGER PRIMARY KEY); the returned Row reflects the DB's view (`RETURNING *`), so server-defaults like `id` and `created_at` are populated in place. `update` does the same: a column you didn't touch keeps its current value rather than being clobbered. An explicit `None` counts as set in both cases.
|
|
84
|
+
|
|
85
|
+
`update` and `delete` use the value of every column in `__pk__` (default: `("id",)`) as the WHERE clause; override the class attribute for a composite or differently-named primary key. Add extra equality filters with `where={...}` for guarded updates: multi-tenant scoping like `where={"user_id": current_user}` is the canonical use case. Raw SQL is still the right tool when you need anything richer than equality.
|
|
86
|
+
|
|
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.
|
|
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
|
+
|
|
111
|
+
## Install
|
|
112
|
+
|
|
113
|
+
Drivers are optional extras. Install only what you use:
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
pip install etchdb[asyncpg] # asyncpg + Postgres
|
|
117
|
+
pip install etchdb[psycopg] # psycopg3 + Postgres
|
|
118
|
+
pip install etchdb[sqlite] # aiosqlite + SQLite
|
|
119
|
+
pip install etchdb[all] # everything
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The top-level `etchdb` namespace depends only on Pydantic. Driver subpackages import their driver eagerly with a clear error if it is not installed.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from etchdb import DB, Row # always safe
|
|
126
|
+
from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
127
|
+
|
|
128
|
+
# Bring your own pool
|
|
129
|
+
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
130
|
+
```
|
|
131
|
+
|
|
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`:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
import asyncpg
|
|
136
|
+
from etchdb import DB
|
|
137
|
+
from etchdb.asyncpg import AsyncpgAdapter
|
|
138
|
+
|
|
139
|
+
async def init_conn(conn):
|
|
140
|
+
await conn.set_type_codec(
|
|
141
|
+
"memory_domain", # the ENUM type name
|
|
142
|
+
encoder=str, decoder=str,
|
|
143
|
+
schema="public",
|
|
144
|
+
format="text",
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
pool = await asyncpg.create_pool(url, init=init_conn, min_size=2, max_size=10)
|
|
148
|
+
db = DB(AsyncpgAdapter.from_pool(pool))
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Both Postgres adapters take libpq-native `$1, $2, ...` placeholders in raw SQL. The psycopg adapter uses `AsyncRawCursor` so the `$N` form works there too; psycopg's default `%s` form is not used and will produce a Postgres syntax error.
|
|
152
|
+
|
|
153
|
+
## Why
|
|
154
|
+
|
|
155
|
+
Most Python ORMs are heavy, opinionated, and leak at the seams when you reach for pgvector or PostGIS. Raw asyncpg works, but every project ends up writing the same Pydantic-bridge code. etchdb closes that gap without becoming a framework.
|
|
156
|
+
|
|
157
|
+
The design also targets AI-assisted development: predictable verbs, no metaclass magic, no implicit context vars, no lazy loading, every typed operation produces inspectable SQL. Code an LLM can write correctly on the first attempt.
|
|
158
|
+
|
|
159
|
+
## Goals
|
|
160
|
+
|
|
161
|
+
- Driver-agnostic (asyncpg or psycopg3, swap freely)
|
|
162
|
+
- Multi-dialect (Postgres primary, SQLite secondary, MySQL maybe)
|
|
163
|
+
- Async native, no sync wrappers
|
|
164
|
+
- Typed CRUD via Pydantic; raw SQL as first-class escape valve
|
|
165
|
+
- Inspectable SQL: every typed op exposes its `(sql, params)` without executing
|
|
166
|
+
|
|
167
|
+
## Non-goals
|
|
168
|
+
|
|
169
|
+
- Query builder beyond simple CRUD (use raw SQL for joins)
|
|
170
|
+
- Implicit relationships, lazy loading, eager loading
|
|
171
|
+
- Sync support
|
|
172
|
+
- A second canonical way to do anything
|
|
173
|
+
|
|
174
|
+
## Migrations
|
|
175
|
+
|
|
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.
|
|
177
|
+
|
|
178
|
+
## Built with AI assistance
|
|
179
|
+
|
|
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.
|
|
181
|
+
|
|
182
|
+
## License
|
|
183
|
+
|
|
184
|
+
MIT.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "etchdb"
|
|
3
|
-
version = "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"
|
|
@@ -37,11 +37,11 @@ dependencies = [
|
|
|
37
37
|
|
|
38
38
|
[project.optional-dependencies]
|
|
39
39
|
asyncpg = ["asyncpg>=0.30.0"]
|
|
40
|
-
psycopg = ["psycopg[binary]>=3.2"]
|
|
40
|
+
psycopg = ["psycopg[binary,pool]>=3.2"]
|
|
41
41
|
sqlite = ["aiosqlite>=0.19.0"]
|
|
42
42
|
all = [
|
|
43
43
|
"asyncpg>=0.30.0",
|
|
44
|
-
"psycopg[binary]>=3.2",
|
|
44
|
+
"psycopg[binary,pool]>=3.2",
|
|
45
45
|
"aiosqlite>=0.19.0",
|
|
46
46
|
]
|
|
47
47
|
dev = [
|
|
@@ -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
|
-
|
|
71
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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()
|