etchdb 0.2.0__tar.gz → 0.4.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.2.0 → etchdb-0.4.0}/PKG-INFO +61 -9
- {etchdb-0.2.0 → etchdb-0.4.0}/README.md +60 -8
- {etchdb-0.2.0 → etchdb-0.4.0}/pyproject.toml +1 -1
- etchdb-0.4.0/src/etchdb/__init__.py +29 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/adapter.py +11 -1
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/aiosqlite/adapter.py +44 -13
- etchdb-0.4.0/src/etchdb/asyncpg/adapter.py +178 -0
- etchdb-0.4.0/src/etchdb/codecs.py +27 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/db.py +131 -6
- etchdb-0.4.0/src/etchdb/errors.py +67 -0
- etchdb-0.4.0/src/etchdb/expr.py +100 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/psycopg/adapter.py +68 -14
- etchdb-0.4.0/src/etchdb/sql/__init__.py +519 -0
- etchdb-0.4.0/tests/integration/test_batch.py +145 -0
- etchdb-0.4.0/tests/integration/test_codecs.py +97 -0
- etchdb-0.4.0/tests/integration/test_errors.py +51 -0
- etchdb-0.4.0/tests/integration/test_execute_rowcount.py +66 -0
- etchdb-0.4.0/tests/integration/test_expressions.py +77 -0
- etchdb-0.4.0/tests/integration/test_in_filter.py +60 -0
- etchdb-0.4.0/tests/integration/test_is_null.py +87 -0
- etchdb-0.4.0/tests/integration/test_iter_rows.py +63 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/unit/test_adapters.py +28 -0
- etchdb-0.4.0/tests/unit/test_sql_emitter.py +992 -0
- etchdb-0.2.0/src/etchdb/__init__.py +0 -9
- etchdb-0.2.0/src/etchdb/asyncpg/adapter.py +0 -106
- etchdb-0.2.0/src/etchdb/sql/__init__.py +0 -271
- etchdb-0.2.0/tests/unit/test_sql_emitter.py +0 -515
- {etchdb-0.2.0 → etchdb-0.4.0}/.gitignore +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/.python-version +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/LICENSE +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/Makefile +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/docker-compose.yml +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/asyncpg/__init__.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/psycopg/__init__.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/py.typed +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/query.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/src/etchdb/row.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/__init__.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/_models.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/integration/__init__.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/integration/conftest.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/integration/test_facade.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/integration/test_readme_example.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/integration/test_typed_crud.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.0}/tests/unit/__init__.py +0 -0
- {etchdb-0.2.0 → etchdb-0.4.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.
|
|
3
|
+
Version: 0.4.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.
|
|
69
|
+
Alpha. v0.4.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
70
70
|
|
|
71
71
|
## Example
|
|
72
72
|
|
|
@@ -80,12 +80,17 @@ 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
|
|
93
|
+
recent = await db.query(User, id=[1, 5, 7]) # IN ($1, $2, $3)
|
|
89
94
|
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
90
95
|
await db.delete(alice)
|
|
91
96
|
|
|
@@ -99,11 +104,34 @@ await db.update(User(id=alice.id, name="Alice B"),
|
|
|
99
104
|
# so models with required NOT NULL columns still flow through.
|
|
100
105
|
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
101
106
|
|
|
107
|
+
# Atomic column expressions in SET (use Row.patch so the sentinels
|
|
108
|
+
# slip past validation). Counter / Article are user-defined Row
|
|
109
|
+
# subclasses alongside User, with an int counter and a timestamp:
|
|
110
|
+
from etchdb import Inc, Now
|
|
111
|
+
await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
|
|
112
|
+
await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
|
|
113
|
+
|
|
114
|
+
# Bulk insert / delete (chunked at the driver's parameter limit).
|
|
115
|
+
await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
116
|
+
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
117
|
+
await db.delete_many(User, [1, 2, 3])
|
|
118
|
+
|
|
119
|
+
# Upsert via single insert: same rules, returns the DB's view.
|
|
120
|
+
alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
121
|
+
on_conflict="upsert")
|
|
122
|
+
|
|
123
|
+
# Stream every matching row (paginated, won't load the whole table at once)
|
|
124
|
+
# Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
|
|
125
|
+
# loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
|
|
126
|
+
async for user in db.iter_rows(User, batch_size=500):
|
|
127
|
+
process(user)
|
|
128
|
+
|
|
102
129
|
# Typed-result raw SQL (covers most joins)
|
|
103
130
|
users = await db.fetch_models(User, """
|
|
104
131
|
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
105
132
|
WHERE o.created_at > $1
|
|
106
133
|
""", since)
|
|
134
|
+
top = await db.fetch_model(User, "SELECT * FROM users ORDER BY id LIMIT 1") # Row | None
|
|
107
135
|
|
|
108
136
|
# Untyped raw SQL (mirrors asyncpg)
|
|
109
137
|
rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
|
|
@@ -133,6 +161,28 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
|
133
161
|
|
|
134
162
|
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
163
|
|
|
164
|
+
## Typed errors
|
|
165
|
+
|
|
166
|
+
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__`.
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
from etchdb import (
|
|
170
|
+
EtchdbError, # base for everything etchdb raises
|
|
171
|
+
IntegrityError, # unique / FK / NOT NULL / check violation
|
|
172
|
+
UndefinedTableError, # table referenced by a query does not exist
|
|
173
|
+
UndefinedColumnError, # column referenced by a query does not exist
|
|
174
|
+
OperationalError, # connection-level / driver-level failure
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
try:
|
|
178
|
+
await db.insert(User(id=1, name="Alice"))
|
|
179
|
+
except IntegrityError as e:
|
|
180
|
+
log.warning("duplicate or constraint violation: %s", e)
|
|
181
|
+
# e.__cause__ is the original asyncpg / psycopg / sqlite3 exception
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`except EtchdbError` catches every member of the family at once.
|
|
185
|
+
|
|
136
186
|
## Install
|
|
137
187
|
|
|
138
188
|
Drivers are optional extras. Install only what you use:
|
|
@@ -154,11 +204,7 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
|
154
204
|
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
155
205
|
```
|
|
156
206
|
|
|
157
|
-
`from_url`
|
|
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`:
|
|
207
|
+
`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
208
|
|
|
163
209
|
```python
|
|
164
210
|
import asyncpg
|
|
@@ -202,11 +248,17 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
|
|
|
202
248
|
|
|
203
249
|
## Migrations
|
|
204
250
|
|
|
205
|
-
Out of scope
|
|
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.
|
|
252
|
+
|
|
253
|
+
## Under consideration
|
|
254
|
+
|
|
255
|
+
Comparison sentinels for `where=` filters (`Gt`, `Gte`, `Lt`, `Lte`, accepting either a scalar or the existing `Now()` sentinel) are on the table for a later release. Scope would stay narrow: single-column inequality only; compound predicates, `LIKE`, and `BETWEEN` would still go through raw SQL. Holding the API for more real use cases before committing. Until then, raw SQL via `db.fetch_models(User, "SELECT * FROM users WHERE expires_at > NOW()")` is the canonical answer; that's what etchdb's first-class raw-SQL escape valve is for.
|
|
256
|
+
|
|
257
|
+
`Inc` / `Now` composing with `on_conflict="upsert"` is a related deferred shape: the create-or-increment pattern would let `db.insert(RateCounter(...), on_conflict="upsert")` carry an `Inc(by=N)` for the conflict SET, but the INSERT branch still needs a literal initial value, so the row would have to express two values per column. Today the sentinels are rejected by `db.insert` / `db.insert_many` outright; raw SQL with `INSERT ... ON CONFLICT (key) DO UPDATE SET count = table.count + 1` covers the case in one statement.
|
|
206
258
|
|
|
207
259
|
## Built with AI assistance
|
|
208
260
|
|
|
209
|
-
Built with Claude Code
|
|
261
|
+
Built with a mix of AI tools for writing and reviewing code: primarily Claude Code, with Codex and occasionally Gemini for second opinions, and not limited to these. spegl.ing pattern research is in active use alongside them. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
|
|
210
262
|
|
|
211
263
|
## License
|
|
212
264
|
|
|
@@ -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.
|
|
7
|
+
Alpha. v0.4.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
8
8
|
|
|
9
9
|
## Example
|
|
10
10
|
|
|
@@ -18,12 +18,17 @@ 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
|
|
31
|
+
recent = await db.query(User, id=[1, 5, 7]) # IN ($1, $2, $3)
|
|
27
32
|
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
28
33
|
await db.delete(alice)
|
|
29
34
|
|
|
@@ -37,11 +42,34 @@ await db.update(User(id=alice.id, name="Alice B"),
|
|
|
37
42
|
# so models with required NOT NULL columns still flow through.
|
|
38
43
|
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
39
44
|
|
|
45
|
+
# Atomic column expressions in SET (use Row.patch so the sentinels
|
|
46
|
+
# slip past validation). Counter / Article are user-defined Row
|
|
47
|
+
# subclasses alongside User, with an int counter and a timestamp:
|
|
48
|
+
from etchdb import Inc, Now
|
|
49
|
+
await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
|
|
50
|
+
await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
|
|
51
|
+
|
|
52
|
+
# Bulk insert / delete (chunked at the driver's parameter limit).
|
|
53
|
+
await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
54
|
+
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
55
|
+
await db.delete_many(User, [1, 2, 3])
|
|
56
|
+
|
|
57
|
+
# Upsert via single insert: same rules, returns the DB's view.
|
|
58
|
+
alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
59
|
+
on_conflict="upsert")
|
|
60
|
+
|
|
61
|
+
# Stream every matching row (paginated, won't load the whole table at once)
|
|
62
|
+
# Uses offset pagination, so cost scales O(N**2) on huge tables; for those,
|
|
63
|
+
# loop with a raw keyset query (WHERE id > last_id ORDER BY id LIMIT n).
|
|
64
|
+
async for user in db.iter_rows(User, batch_size=500):
|
|
65
|
+
process(user)
|
|
66
|
+
|
|
40
67
|
# Typed-result raw SQL (covers most joins)
|
|
41
68
|
users = await db.fetch_models(User, """
|
|
42
69
|
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
43
70
|
WHERE o.created_at > $1
|
|
44
71
|
""", since)
|
|
72
|
+
top = await db.fetch_model(User, "SELECT * FROM users ORDER BY id LIMIT 1") # Row | None
|
|
45
73
|
|
|
46
74
|
# Untyped raw SQL (mirrors asyncpg)
|
|
47
75
|
rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
|
|
@@ -71,6 +99,28 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
|
71
99
|
|
|
72
100
|
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
101
|
|
|
102
|
+
## Typed errors
|
|
103
|
+
|
|
104
|
+
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__`.
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from etchdb import (
|
|
108
|
+
EtchdbError, # base for everything etchdb raises
|
|
109
|
+
IntegrityError, # unique / FK / NOT NULL / check violation
|
|
110
|
+
UndefinedTableError, # table referenced by a query does not exist
|
|
111
|
+
UndefinedColumnError, # column referenced by a query does not exist
|
|
112
|
+
OperationalError, # connection-level / driver-level failure
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
try:
|
|
116
|
+
await db.insert(User(id=1, name="Alice"))
|
|
117
|
+
except IntegrityError as e:
|
|
118
|
+
log.warning("duplicate or constraint violation: %s", e)
|
|
119
|
+
# e.__cause__ is the original asyncpg / psycopg / sqlite3 exception
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`except EtchdbError` catches every member of the family at once.
|
|
123
|
+
|
|
74
124
|
## Install
|
|
75
125
|
|
|
76
126
|
Drivers are optional extras. Install only what you use:
|
|
@@ -92,11 +142,7 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
|
92
142
|
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
93
143
|
```
|
|
94
144
|
|
|
95
|
-
`from_url`
|
|
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`:
|
|
145
|
+
`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
146
|
|
|
101
147
|
```python
|
|
102
148
|
import asyncpg
|
|
@@ -140,11 +186,17 @@ The design also targets AI-assisted development: predictable verbs, no metaclass
|
|
|
140
186
|
|
|
141
187
|
## Migrations
|
|
142
188
|
|
|
143
|
-
Out of scope
|
|
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.
|
|
190
|
+
|
|
191
|
+
## Under consideration
|
|
192
|
+
|
|
193
|
+
Comparison sentinels for `where=` filters (`Gt`, `Gte`, `Lt`, `Lte`, accepting either a scalar or the existing `Now()` sentinel) are on the table for a later release. Scope would stay narrow: single-column inequality only; compound predicates, `LIKE`, and `BETWEEN` would still go through raw SQL. Holding the API for more real use cases before committing. Until then, raw SQL via `db.fetch_models(User, "SELECT * FROM users WHERE expires_at > NOW()")` is the canonical answer; that's what etchdb's first-class raw-SQL escape valve is for.
|
|
194
|
+
|
|
195
|
+
`Inc` / `Now` composing with `on_conflict="upsert"` is a related deferred shape: the create-or-increment pattern would let `db.insert(RateCounter(...), on_conflict="upsert")` carry an `Inc(by=N)` for the conflict SET, but the INSERT branch still needs a literal initial value, so the row would have to express two values per column. Today the sentinels are rejected by `db.insert` / `db.insert_many` outright; raw SQL with `INSERT ... ON CONFLICT (key) DO UPDATE SET count = table.count + 1` covers the case in one statement.
|
|
144
196
|
|
|
145
197
|
## Built with AI assistance
|
|
146
198
|
|
|
147
|
-
Built with Claude Code
|
|
199
|
+
Built with a mix of AI tools for writing and reviewing code: primarily Claude Code, with Codex and occasionally Gemini for second opinions, and not limited to these. spegl.ing pattern research is in active use alongside them. Design, code, and commits are reviewed and shipped by Hannu Varjoranta. Building in public, openly using AI tooling, is part of the project's premise.
|
|
148
200
|
|
|
149
201
|
## License
|
|
150
202
|
|
|
@@ -0,0 +1,29 @@
|
|
|
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.expr import Inc, Now
|
|
12
|
+
from etchdb.query import SqlQuery
|
|
13
|
+
from etchdb.row import Row
|
|
14
|
+
|
|
15
|
+
__version__ = "0.4.0"
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"DB",
|
|
19
|
+
"EtchdbError",
|
|
20
|
+
"Inc",
|
|
21
|
+
"IntegrityError",
|
|
22
|
+
"Now",
|
|
23
|
+
"OperationalError",
|
|
24
|
+
"Row",
|
|
25
|
+
"SqlQuery",
|
|
26
|
+
"UndefinedColumnError",
|
|
27
|
+
"UndefinedTableError",
|
|
28
|
+
"__version__",
|
|
29
|
+
]
|
|
@@ -24,7 +24,17 @@ class AdapterBase(ABC):
|
|
|
24
24
|
...
|
|
25
25
|
|
|
26
26
|
@abstractmethod
|
|
27
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
27
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
28
|
+
"""Execute a statement and return the affected-row count.
|
|
29
|
+
|
|
30
|
+
Returns the affected-row count for DML (INSERT / UPDATE /
|
|
31
|
+
DELETE), or `-1` for everything else (DDL, BEGIN, SELECT,
|
|
32
|
+
COPY, ...). The `-1` sentinel mirrors psycopg's and sqlite3's
|
|
33
|
+
native convention. SELECT through `execute` is explicitly not
|
|
34
|
+
a count contract; use `fetch` / `fetchrow` / `fetchval` for
|
|
35
|
+
SELECT and read the row count off the result.
|
|
36
|
+
"""
|
|
37
|
+
...
|
|
28
38
|
|
|
29
39
|
@abstractmethod
|
|
30
40
|
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]: ...
|
|
@@ -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
|
|
|
@@ -66,22 +90,23 @@ class AiosqliteAdapter(AdapterBase):
|
|
|
66
90
|
conn.row_factory = aiosqlite.Row
|
|
67
91
|
return cls(conn, owns_conn=True)
|
|
68
92
|
|
|
69
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
70
|
-
|
|
71
|
-
|
|
93
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
94
|
+
async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
|
|
95
|
+
await self._conn.commit()
|
|
96
|
+
return cursor.rowcount
|
|
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()
|
|
@@ -113,21 +143,22 @@ class _AiosqliteTxAdapter(AdapterBase):
|
|
|
113
143
|
def placeholder(i: int) -> str:
|
|
114
144
|
return "?"
|
|
115
145
|
|
|
116
|
-
async def execute(self, sql: str, *params: Any) ->
|
|
117
|
-
|
|
146
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
147
|
+
async with _wrap_errors(), self._conn.execute(sql, params) as cursor:
|
|
148
|
+
return cursor.rowcount
|
|
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
|
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""asyncpg adapter implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import AsyncIterator
|
|
7
|
+
from contextlib import asynccontextmanager
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import asyncpg
|
|
11
|
+
|
|
12
|
+
from etchdb import errors
|
|
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)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
_DML_TAGS = ("INSERT", "UPDATE", "DELETE")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _rowcount_from_status(status: str) -> int:
|
|
59
|
+
"""Extract the affected-row count from an asyncpg command tag.
|
|
60
|
+
|
|
61
|
+
DML tags ('UPDATE 5', 'DELETE 3', 'INSERT 0 5') end in the
|
|
62
|
+
count and parse to a non-negative int. Anything else (DDL,
|
|
63
|
+
`BEGIN`, `SELECT`, `COPY`) returns -1, matching the psycopg /
|
|
64
|
+
sqlite3 'no rowcount available' sentinel. SELECT in particular
|
|
65
|
+
would otherwise parse to its row count, which `db.execute`
|
|
66
|
+
explicitly does not promise across drivers.
|
|
67
|
+
"""
|
|
68
|
+
verb, _, _ = status.partition(" ")
|
|
69
|
+
if verb not in _DML_TAGS:
|
|
70
|
+
return -1
|
|
71
|
+
tail = status.rsplit(" ", 1)[-1]
|
|
72
|
+
try:
|
|
73
|
+
return int(tail)
|
|
74
|
+
except ValueError:
|
|
75
|
+
return -1
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class AsyncpgAdapter(AdapterBase):
|
|
79
|
+
"""AdapterBase implementation backed by an asyncpg pool.
|
|
80
|
+
|
|
81
|
+
Construct via `from_pool(pool)` to wrap an externally-managed pool
|
|
82
|
+
(etchdb will not close it), or `await from_url(url)` to let etchdb
|
|
83
|
+
create and own the pool. The `owns_pool` flag tracks ownership.
|
|
84
|
+
|
|
85
|
+
For custom pool settings (init=, min_size=, max_size=, codecs),
|
|
86
|
+
create the pool yourself with `asyncpg.create_pool(...)` and pass
|
|
87
|
+
it to `from_pool`. `from_url` is intentionally minimal.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, pool: asyncpg.Pool, *, owns_pool: bool = False):
|
|
91
|
+
self._pool = pool
|
|
92
|
+
self._owns_pool = owns_pool
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def placeholder(i: int) -> str:
|
|
96
|
+
return f"${i + 1}"
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_pool(cls, pool: asyncpg.Pool) -> AsyncpgAdapter:
|
|
100
|
+
"""Wrap an externally-managed asyncpg pool. The caller closes it."""
|
|
101
|
+
return cls(pool, owns_pool=False)
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
async def from_url(cls, url: str) -> AsyncpgAdapter:
|
|
105
|
+
"""Create an asyncpg pool from `url` and wrap it.
|
|
106
|
+
|
|
107
|
+
etchdb owns the pool; `close()` will close it. The pool is
|
|
108
|
+
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`.
|
|
112
|
+
"""
|
|
113
|
+
pool = await asyncpg.create_pool(url, init=_init_codecs)
|
|
114
|
+
return cls(pool, owns_pool=True)
|
|
115
|
+
|
|
116
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
117
|
+
async with _wrap_errors(), self._pool.acquire() as conn:
|
|
118
|
+
return _rowcount_from_status(await conn.execute(sql, *params))
|
|
119
|
+
|
|
120
|
+
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
121
|
+
async with _wrap_errors(), self._pool.acquire() as conn:
|
|
122
|
+
records = await conn.fetch(sql, *params)
|
|
123
|
+
return [dict(r) for r in records]
|
|
124
|
+
|
|
125
|
+
async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
|
|
126
|
+
async with _wrap_errors(), self._pool.acquire() as conn:
|
|
127
|
+
record = await conn.fetchrow(sql, *params)
|
|
128
|
+
return dict(record) if record is not None else None
|
|
129
|
+
|
|
130
|
+
async def fetchval(self, sql: str, *params: Any) -> Any:
|
|
131
|
+
async with _wrap_errors(), self._pool.acquire() as conn:
|
|
132
|
+
return await conn.fetchval(sql, *params)
|
|
133
|
+
|
|
134
|
+
@asynccontextmanager
|
|
135
|
+
async def transaction(self) -> AsyncIterator[AdapterBase]:
|
|
136
|
+
async with _wrap_errors(), self._pool.acquire() as conn, conn.transaction():
|
|
137
|
+
yield _AsyncpgConnAdapter(conn)
|
|
138
|
+
|
|
139
|
+
async def close(self) -> None:
|
|
140
|
+
if self._owns_pool:
|
|
141
|
+
await self._pool.close()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class _AsyncpgConnAdapter(AdapterBase):
|
|
145
|
+
"""Single-connection adapter, used inside a transaction."""
|
|
146
|
+
|
|
147
|
+
def __init__(self, conn: asyncpg.Connection):
|
|
148
|
+
self._conn = conn
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def placeholder(i: int) -> str:
|
|
152
|
+
return f"${i + 1}"
|
|
153
|
+
|
|
154
|
+
async def execute(self, sql: str, *params: Any) -> int:
|
|
155
|
+
async with _wrap_errors():
|
|
156
|
+
return _rowcount_from_status(await self._conn.execute(sql, *params))
|
|
157
|
+
|
|
158
|
+
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
159
|
+
async with _wrap_errors():
|
|
160
|
+
records = await self._conn.fetch(sql, *params)
|
|
161
|
+
return [dict(r) for r in records]
|
|
162
|
+
|
|
163
|
+
async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
|
|
164
|
+
async with _wrap_errors():
|
|
165
|
+
record = await self._conn.fetchrow(sql, *params)
|
|
166
|
+
return dict(record) if record is not None else None
|
|
167
|
+
|
|
168
|
+
async def fetchval(self, sql: str, *params: Any) -> Any:
|
|
169
|
+
async with _wrap_errors():
|
|
170
|
+
return await self._conn.fetchval(sql, *params)
|
|
171
|
+
|
|
172
|
+
@asynccontextmanager
|
|
173
|
+
async def transaction(self) -> AsyncIterator[AdapterBase]:
|
|
174
|
+
async with _wrap_errors(), self._conn.transaction():
|
|
175
|
+
yield self
|
|
176
|
+
|
|
177
|
+
async def close(self) -> None:
|
|
178
|
+
return 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()
|