etchdb 0.6.1__tar.gz → 0.7.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.6.1 → etchdb-0.7.0}/.github/workflows/ci.yml +7 -6
- {etchdb-0.6.1 → etchdb-0.7.0}/.github/workflows/release.yml +13 -2
- {etchdb-0.6.1 → etchdb-0.7.0}/Makefile +1 -1
- {etchdb-0.6.1 → etchdb-0.7.0}/PKG-INFO +179 -43
- {etchdb-0.6.1 → etchdb-0.7.0}/README.md +175 -41
- {etchdb-0.6.1 → etchdb-0.7.0}/pyproject.toml +5 -2
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/__init__.py +1 -1
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/adapter.py +34 -7
- etchdb-0.7.0/src/etchdb/aiosqlite/adapter.py +280 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/asyncpg/__init__.py +2 -2
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/asyncpg/adapter.py +59 -38
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/codecs.py +16 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/db.py +79 -58
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/expr.py +4 -2
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/migrations.py +26 -13
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/psycopg/__init__.py +2 -2
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/psycopg/adapter.py +48 -18
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/row.py +11 -1
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/sql/__init__.py +64 -28
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/conftest.py +22 -2
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_batch.py +38 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_execute_rowcount.py +10 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_migrations.py +34 -0
- etchdb-0.7.0/tests/integration/test_pool_kwargs.py +69 -0
- etchdb-0.7.0/tests/integration/test_sqlite_transactions.py +174 -0
- etchdb-0.7.0/tests/typing/crud_types.py +27 -0
- etchdb-0.7.0/tests/unit/test_adapters.py +108 -0
- etchdb-0.7.0/tests/unit/test_connection_hooks.py +89 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/unit/test_migrations.py +40 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/unit/test_sql_emitter.py +66 -10
- etchdb-0.7.0/tests/unit/test_version.py +12 -0
- etchdb-0.6.1/src/etchdb/aiosqlite/adapter.py +0 -196
- etchdb-0.6.1/tests/integration/test_pool_kwargs.py +0 -43
- etchdb-0.6.1/tests/unit/test_adapters.py +0 -65
- {etchdb-0.6.1 → etchdb-0.7.0}/.gitignore +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/.python-version +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/LICENSE +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/docker-compose.yml +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/__main__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/cli.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/errors.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/py.typed +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/src/etchdb/query.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/_models.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_cli.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_codecs.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_errors.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_expressions.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_facade.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_fields_not_in_db.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_in_filter.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_is_null.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_iter_rows.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_iter_rows_keyset.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_ping_and_aclose.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_readme_example.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_typed_crud.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/integration/test_update_where.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/unit/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/unit/test_cli.py +0 -0
- {etchdb-0.6.1 → etchdb-0.7.0}/tests/unit/test_db_dispatch.py +0 -0
|
@@ -20,13 +20,14 @@ jobs:
|
|
|
20
20
|
lint:
|
|
21
21
|
runs-on: ubuntu-latest
|
|
22
22
|
steps:
|
|
23
|
-
- uses: actions/checkout@
|
|
24
|
-
- uses: astral-sh/setup-uv@
|
|
23
|
+
- uses: actions/checkout@v6
|
|
24
|
+
- uses: astral-sh/setup-uv@v7
|
|
25
25
|
with:
|
|
26
26
|
python-version: "3.14"
|
|
27
27
|
cache-dependency-glob: "pyproject.toml"
|
|
28
28
|
- run: uv sync --extra dev
|
|
29
29
|
- run: uv run ruff check src/etchdb tests
|
|
30
|
+
- run: uv run ruff format --check src/etchdb tests
|
|
30
31
|
|
|
31
32
|
unit:
|
|
32
33
|
runs-on: ubuntu-latest
|
|
@@ -35,8 +36,8 @@ jobs:
|
|
|
35
36
|
matrix:
|
|
36
37
|
python-version: ["3.12", "3.13", "3.14"]
|
|
37
38
|
steps:
|
|
38
|
-
- uses: actions/checkout@
|
|
39
|
-
- uses: astral-sh/setup-uv@
|
|
39
|
+
- uses: actions/checkout@v6
|
|
40
|
+
- uses: astral-sh/setup-uv@v7
|
|
40
41
|
with:
|
|
41
42
|
python-version: ${{ matrix.python-version }}
|
|
42
43
|
cache-dependency-glob: "pyproject.toml"
|
|
@@ -67,8 +68,8 @@ jobs:
|
|
|
67
68
|
--health-timeout 5s
|
|
68
69
|
--health-retries 5
|
|
69
70
|
steps:
|
|
70
|
-
- uses: actions/checkout@
|
|
71
|
-
- uses: astral-sh/setup-uv@
|
|
71
|
+
- uses: actions/checkout@v6
|
|
72
|
+
- uses: astral-sh/setup-uv@v7
|
|
72
73
|
with:
|
|
73
74
|
python-version: ${{ matrix.python-version }}
|
|
74
75
|
cache-dependency-glob: "pyproject.toml"
|
|
@@ -33,14 +33,14 @@ jobs:
|
|
|
33
33
|
runs-on: ubuntu-latest
|
|
34
34
|
steps:
|
|
35
35
|
- name: Checkout
|
|
36
|
-
uses: actions/checkout@
|
|
36
|
+
uses: actions/checkout@v6
|
|
37
37
|
with:
|
|
38
38
|
# Full history so `gh release create --generate-notes` can
|
|
39
39
|
# diff against the previous tag for the auto-notes body.
|
|
40
40
|
fetch-depth: 0
|
|
41
41
|
|
|
42
42
|
- name: Install uv (with Python)
|
|
43
|
-
uses: astral-sh/setup-uv@
|
|
43
|
+
uses: astral-sh/setup-uv@v7
|
|
44
44
|
with:
|
|
45
45
|
# Tests run on 3.13 (current head). The wheel is `py3-none-any`
|
|
46
46
|
# so it installs on every supported version; per-push CI (when
|
|
@@ -52,6 +52,17 @@ jobs:
|
|
|
52
52
|
# pyproject.toml so the cache key tracks dependency changes.
|
|
53
53
|
cache-dependency-glob: "pyproject.toml"
|
|
54
54
|
|
|
55
|
+
- name: Check the tag matches the package version
|
|
56
|
+
# A tag pushed before the version bump would build the previous
|
|
57
|
+
# version's files, which PyPI rejects as a duplicate upload.
|
|
58
|
+
# Fail here, before anything is built or published.
|
|
59
|
+
run: |
|
|
60
|
+
version="$(uv version --short)"
|
|
61
|
+
if [ "v${version}" != "${GITHUB_REF_NAME}" ]; then
|
|
62
|
+
echo "::error::tag ${GITHUB_REF_NAME} does not match package version ${version}"
|
|
63
|
+
exit 1
|
|
64
|
+
fi
|
|
65
|
+
|
|
55
66
|
- name: Install dependencies
|
|
56
67
|
run: uv sync --extra all --extra dev
|
|
57
68
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: etchdb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.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,6 +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-pool>=3.2; extra == 'all'
|
|
48
49
|
Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'all'
|
|
49
50
|
Provides-Extra: asyncpg
|
|
50
51
|
Requires-Dist: asyncpg>=0.30.0; extra == 'asyncpg'
|
|
@@ -55,6 +56,7 @@ Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
|
55
56
|
Requires-Dist: ruff>=0.5.0; extra == 'dev'
|
|
56
57
|
Requires-Dist: ty; extra == 'dev'
|
|
57
58
|
Provides-Extra: psycopg
|
|
59
|
+
Requires-Dist: psycopg-pool>=3.2; extra == 'psycopg'
|
|
58
60
|
Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'psycopg'
|
|
59
61
|
Provides-Extra: sqlite
|
|
60
62
|
Requires-Dist: aiosqlite>=0.19.0; extra == 'sqlite'
|
|
@@ -62,11 +64,75 @@ Description-Content-Type: text/markdown
|
|
|
62
64
|
|
|
63
65
|
# etchdb
|
|
64
66
|
|
|
65
|
-
|
|
67
|
+
Typed Pydantic rows for the boring database work. Raw SQL for everything else.
|
|
68
|
+
|
|
69
|
+
etchdb is a small async database layer for Python applications that want:
|
|
70
|
+
|
|
71
|
+
- typed CRUD without ORM magic
|
|
72
|
+
- raw SQL as the escape hatch, not a second-class API
|
|
73
|
+
- inspectable generated SQL before execution
|
|
74
|
+
- asyncpg, psycopg3, and SQLite behind one small facade
|
|
75
|
+
|
|
76
|
+
It is for people who like SQL but are tired of rewriting the same Pydantic bridge in every project.
|
|
66
77
|
|
|
67
78
|
## Status
|
|
68
79
|
|
|
69
|
-
Alpha.
|
|
80
|
+
Alpha. On PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
81
|
+
|
|
82
|
+
## First look
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from etchdb import DB, Row
|
|
86
|
+
|
|
87
|
+
class User(Row):
|
|
88
|
+
__table__ = "users"
|
|
89
|
+
id: int | None = None
|
|
90
|
+
name: str
|
|
91
|
+
email: str | None = None
|
|
92
|
+
|
|
93
|
+
db = await DB.from_url("postgresql+asyncpg://user@host/db")
|
|
94
|
+
|
|
95
|
+
alice = await db.insert(User(name="Alice")) # id populated from RETURNING *
|
|
96
|
+
user = await db.get(User, id=alice.id) # User | None
|
|
97
|
+
users = await db.query(User, email=None) # IS NULL, not = NULL
|
|
98
|
+
|
|
99
|
+
users = await db.fetch_models(User, """
|
|
100
|
+
SELECT u.*
|
|
101
|
+
FROM users u
|
|
102
|
+
JOIN orders o ON o.user_id = u.id
|
|
103
|
+
WHERE o.created_at > $1
|
|
104
|
+
""", since)
|
|
105
|
+
|
|
106
|
+
q = db.compose("get", User, id=alice.id)
|
|
107
|
+
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1 LIMIT 1
|
|
108
|
+
print(q.params) # [1]
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Why etchdb?
|
|
112
|
+
|
|
113
|
+
Most Python ORMs become awkward exactly when the database gets interesting: pgvector, PostGIS, CTEs, window functions, custom SQL functions, partial indexes, or hand-tuned joins.
|
|
114
|
+
|
|
115
|
+
Raw asyncpg is excellent, but then every service grows the same glue: map rows into models, build simple CRUD safely, handle transactions, and keep generated SQL visible for debugging.
|
|
116
|
+
|
|
117
|
+
etchdb sits between those worlds: simple typed operations for simple cases, raw SQL for real queries, and no framework takeover.
|
|
118
|
+
|
|
119
|
+
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 assistants can generate and review it because the library has a small surface area and the database behavior stays visible.
|
|
120
|
+
|
|
121
|
+
## What etchdb is
|
|
122
|
+
|
|
123
|
+
- a typed CRUD layer over Pydantic models
|
|
124
|
+
- a raw SQL passthrough with typed result helpers
|
|
125
|
+
- a small driver facade for asyncpg, psycopg3, and aiosqlite
|
|
126
|
+
- a way to inspect generated SQL before executing it
|
|
127
|
+
- a forward-only SQL migration helper
|
|
128
|
+
|
|
129
|
+
## What etchdb is not
|
|
130
|
+
|
|
131
|
+
- not a full ORM
|
|
132
|
+
- not a relationship or lazy-loading framework
|
|
133
|
+
- not a query builder for complex joins
|
|
134
|
+
- not a schema autogenerator
|
|
135
|
+
- not a replacement for knowing SQL
|
|
70
136
|
|
|
71
137
|
## Example
|
|
72
138
|
|
|
@@ -111,14 +177,15 @@ from etchdb import Inc, Now
|
|
|
111
177
|
await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
|
|
112
178
|
await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
|
|
113
179
|
|
|
114
|
-
# Bulk insert / delete (chunked at the driver's parameter limit
|
|
180
|
+
# Bulk insert / delete (chunked at the driver's parameter limit; a
|
|
181
|
+
# batch that needs several statements runs them in one transaction).
|
|
115
182
|
await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
116
183
|
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
117
184
|
await db.delete_many(User, [1, 2, 3])
|
|
118
185
|
|
|
119
186
|
# Bulk update: same patch applied to all rows matching a filter.
|
|
120
187
|
# Returns the affected-row count.
|
|
121
|
-
n = await db.update_where(User.patch(
|
|
188
|
+
n = await db.update_where(User.patch(email=None),
|
|
122
189
|
where={"id": [1, 2, 3]})
|
|
123
190
|
|
|
124
191
|
# Upsert via single insert: same rules, returns the DB's view.
|
|
@@ -130,11 +197,13 @@ alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
|
130
197
|
async for user in db.iter_rows(User, batch_size=500):
|
|
131
198
|
process(user)
|
|
132
199
|
|
|
133
|
-
# For huge tables, iter_rows_keyset
|
|
134
|
-
# `(by, *pk_tail) > last_seen` cursor per page. PK tail
|
|
135
|
-
# ties and lets the cursor paginate through NULL values.
|
|
136
|
-
#
|
|
137
|
-
# `by`
|
|
200
|
+
# For huge tables, iter_rows_keyset avoids the growing OFFSET by
|
|
201
|
+
# emitting a `(by, *pk_tail) > last_seen` cursor per page. PK tail
|
|
202
|
+
# breaks ties and lets the cursor paginate through NULL values.
|
|
203
|
+
# `by` defaults to __pk__[0], which walks the primary-key index.
|
|
204
|
+
# A non-PK `by` is ordered `NULLS FIRST` (deterministic across
|
|
205
|
+
# backends; SQLite 3.30+) and stays O(N) only with an index on
|
|
206
|
+
# `(by NULLS FIRST, *pk)`; without one each page sorts the table.
|
|
138
207
|
async for user in db.iter_rows_keyset(User, batch_size=500):
|
|
139
208
|
process(user)
|
|
140
209
|
|
|
@@ -152,13 +221,16 @@ val = await db.fetchval("SELECT count(*) FROM users") # always returns the coun
|
|
|
152
221
|
# fetchval returns None on no row.
|
|
153
222
|
await db.execute("UPDATE users SET active = false WHERE id = $1", uid)
|
|
154
223
|
|
|
155
|
-
# Transactions
|
|
224
|
+
# Transactions: use the `tx` handle inside the block. On Postgres a
|
|
225
|
+
# call on `db` there runs on another connection, outside the
|
|
226
|
+
# transaction. SQLite has one connection, so everything on a DB
|
|
227
|
+
# shares it; give concurrent tasks that need isolation their own DB.
|
|
156
228
|
async with db.transaction() as tx:
|
|
157
229
|
await tx.insert(User(name="Carol"))
|
|
158
230
|
await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
|
|
159
231
|
|
|
160
232
|
# Healthcheck + lifecycle
|
|
161
|
-
ok = await db.ping() # SELECT 1 round-trip;
|
|
233
|
+
ok = await db.ping() # SELECT 1 round-trip; False on failure, never raises
|
|
162
234
|
async with db: # close on scope exit (DB must already be open)
|
|
163
235
|
...
|
|
164
236
|
|
|
@@ -171,7 +243,7 @@ status = await db.migration_status("migrations/") # MigrationStatus dataclass
|
|
|
171
243
|
|
|
172
244
|
# Inspect SQL before executing (etchdb's defining feature)
|
|
173
245
|
q = db.compose("get", User, id=1)
|
|
174
|
-
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
|
|
246
|
+
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1 LIMIT 1
|
|
175
247
|
print(q.params) # [1]
|
|
176
248
|
|
|
177
249
|
# Same inspector without a live DB - useful in tests:
|
|
@@ -181,9 +253,9 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
|
181
253
|
|
|
182
254
|
`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.
|
|
183
255
|
|
|
184
|
-
`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.
|
|
256
|
+
`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. Filter values are always bound as parameters. Filter names go into the statement as column names, so they must be plain identifiers (letters, digits, underscore) and anything else raises `ValueError`; keep them in your code rather than taking them from request input. Raw SQL is still the right tool when you need anything richer than equality.
|
|
185
257
|
|
|
186
|
-
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.
|
|
258
|
+
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. A name that is not a field of the model raises `ValueError`.
|
|
187
259
|
|
|
188
260
|
Set `__fields_not_in_db__ = ("computed_label",)` on a Row class to carry computed or transient fields alongside DB-backed ones without etchdb sending them to or reading them from the database. The fields stay on the Pydantic model (validation, attribute access, type checking all work as normal); they're just dropped from INSERT, UPDATE, and SELECT column lists. Give such fields a default value -- read paths hydrate from the SELECT result, which never carries the column, so Pydantic uses the default.
|
|
189
261
|
|
|
@@ -207,7 +279,7 @@ except IntegrityError as e:
|
|
|
207
279
|
# e.__cause__ is the original asyncpg / psycopg / sqlite3 exception
|
|
208
280
|
```
|
|
209
281
|
|
|
210
|
-
`except EtchdbError` catches every member of the family at once.
|
|
282
|
+
`except EtchdbError` catches every member of the family at once. The family covers the categories listed above; other driver errors (a syntax error, a data-type error, asyncpg's command timeout) propagate as the driver's own exception.
|
|
211
283
|
|
|
212
284
|
## Install
|
|
213
285
|
|
|
@@ -230,14 +302,84 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
|
230
302
|
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
231
303
|
```
|
|
232
304
|
|
|
233
|
-
`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.
|
|
305
|
+
`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. Pass the `dict` or `list` itself: a string you serialised beforehand is stored as a JSON string value on asyncpg, not as the object it spells.
|
|
306
|
+
|
|
307
|
+
### Connection setup
|
|
308
|
+
|
|
309
|
+
Pass an async `configure` callback to add connection setup without replacing
|
|
310
|
+
etchdb's codecs. Built-in codecs run first, then your callback runs once for
|
|
311
|
+
each new physical connection, including replacement connections. It receives
|
|
312
|
+
the native connection for the selected driver. For example, with asyncpg:
|
|
313
|
+
|
|
314
|
+
```python
|
|
315
|
+
async def configure(conn):
|
|
316
|
+
await conn.set_type_codec(
|
|
317
|
+
"memory_domain", encoder=str, decoder=str, schema="public", format="text",
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
db = await DB.from_url(
|
|
321
|
+
"postgresql+asyncpg://user@host/db",
|
|
322
|
+
min_size=2, max_size=10, configure=configure,
|
|
323
|
+
)
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
Use the asyncpg callback for codecs and types, not for session settings.
|
|
327
|
+
asyncpg runs `RESET ALL` when a connection returns to the pool, so a `SET`
|
|
328
|
+
made in `configure` lasts only until the first query finishes. Put session
|
|
329
|
+
settings in the URL instead (`postgresql+asyncpg://user@host/db?search_path=app`);
|
|
330
|
+
asyncpg sends unrecognised query parameters as server settings on every
|
|
331
|
+
connection.
|
|
332
|
+
|
|
333
|
+
With psycopg, session settings made in `configure` do persist. Leave the
|
|
334
|
+
connection idle after setup SQL, as required by psycopg_pool, by committing
|
|
335
|
+
setup statements explicitly:
|
|
336
|
+
|
|
337
|
+
```python
|
|
338
|
+
async def configure(conn):
|
|
339
|
+
await conn.execute("SET application_name = 'myapp'")
|
|
340
|
+
await conn.commit()
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Setup exceptions propagate to the driver's pool, which retains its native
|
|
344
|
+
startup/reconnection behavior; etchdb does not retry application statements.
|
|
345
|
+
The two pools differ in when you hear about it. asyncpg connects inside
|
|
346
|
+
`from_url`, so a failing callback raises there. psycopg_pool connects in the
|
|
347
|
+
background: `from_url` returns, the failure goes to the `psycopg.pool` logger,
|
|
348
|
+
and the first query waits for the pool's timeout (30 seconds by default)
|
|
349
|
+
before raising. SQLite rejects `configure` rather than silently ignoring it.
|
|
350
|
+
|
|
351
|
+
Driver-specific options stay on the adapters. For connection validation at
|
|
352
|
+
checkout with psycopg:
|
|
353
|
+
|
|
354
|
+
```python
|
|
355
|
+
from etchdb.psycopg import PsycopgAdapter
|
|
356
|
+
from psycopg_pool import AsyncConnectionPool
|
|
357
|
+
|
|
358
|
+
db = DB(await PsycopgAdapter.from_url(
|
|
359
|
+
"postgresql://user@host/db",
|
|
360
|
+
check=AsyncConnectionPool.check_connection,
|
|
361
|
+
configure=configure,
|
|
362
|
+
))
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
`AsyncpgAdapter.from_url(..., command_timeout=60)` sets asyncpg's default
|
|
366
|
+
command timeout in seconds. A statement that exceeds it raises the built-in
|
|
367
|
+
`TimeoutError`, not an etchdb error. Both adapters accept `configure`, `min_size` and
|
|
368
|
+
`max_size`. Omitted options retain driver defaults.
|
|
369
|
+
|
|
370
|
+
### Externally owned pools
|
|
371
|
+
|
|
372
|
+
`from_pool` wraps your pool without changing its codecs, callbacks or ownership.
|
|
373
|
+
Use the public driver-specific `configure_codecs` helper when creating that
|
|
374
|
+
pool to opt into etchdb's JSONB behavior alongside your own setup:
|
|
234
375
|
|
|
235
376
|
```python
|
|
236
377
|
import asyncpg
|
|
237
378
|
from etchdb import DB
|
|
238
|
-
from etchdb.asyncpg import AsyncpgAdapter
|
|
379
|
+
from etchdb.asyncpg import AsyncpgAdapter, configure_codecs
|
|
239
380
|
|
|
240
381
|
async def init_conn(conn):
|
|
382
|
+
await configure_codecs(conn)
|
|
241
383
|
await conn.set_type_codec(
|
|
242
384
|
"memory_domain", # the ENUM type name
|
|
243
385
|
encoder=str, decoder=str,
|
|
@@ -247,30 +389,20 @@ async def init_conn(conn):
|
|
|
247
389
|
|
|
248
390
|
pool = await asyncpg.create_pool(url, init=init_conn, min_size=2, max_size=10)
|
|
249
391
|
db = DB(AsyncpgAdapter.from_pool(pool))
|
|
392
|
+
# The application closes this externally owned pool: await pool.close().
|
|
250
393
|
```
|
|
251
394
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
395
|
+
For psycopg, import `configure_codecs` from `etchdb.psycopg` and call it in
|
|
396
|
+
your pool's async `configure` callback before application setup. The old
|
|
397
|
+
private `_init_codecs` names remain compatibility aliases; new code should
|
|
398
|
+
use the public helper. Psycopg's helper adapts Python lists as JSONB, matching
|
|
399
|
+
etchdb's existing defaults, so a list bound to an array parameter
|
|
400
|
+
(`= ANY($1::int[])`) works on asyncpg and fails on psycopg. For a query that
|
|
401
|
+
runs on both, use an `IN` filter (`db.query(User, id=[1, 2, 3])`) or expand
|
|
402
|
+
the JSONB value: `id IN (SELECT jsonb_array_elements_text($1::jsonb)::int)`. SQL NULL remains `None`; codecs do not replace it with
|
|
403
|
+
an empty collection.
|
|
259
404
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
- Driver-agnostic (asyncpg or psycopg3, swap freely)
|
|
263
|
-
- Multi-dialect (Postgres primary, SQLite secondary, MySQL maybe)
|
|
264
|
-
- Async native, no sync wrappers
|
|
265
|
-
- Typed CRUD via Pydantic; raw SQL as first-class escape valve
|
|
266
|
-
- Inspectable SQL: every typed op exposes its `(sql, params)` without executing
|
|
267
|
-
|
|
268
|
-
## Non-goals
|
|
269
|
-
|
|
270
|
-
- Query builder beyond simple CRUD (use raw SQL for joins)
|
|
271
|
-
- Implicit relationships, lazy loading, eager loading
|
|
272
|
-
- Sync support
|
|
273
|
-
- A second canonical way to do anything
|
|
405
|
+
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.
|
|
274
406
|
|
|
275
407
|
## Migrations
|
|
276
408
|
|
|
@@ -325,17 +457,19 @@ if not status.is_consistent:
|
|
|
325
457
|
|
|
326
458
|
### Transaction model
|
|
327
459
|
|
|
328
|
-
Each migration runs in its own implicit transaction on Postgres. Don't write `BEGIN` / `COMMIT` / `ROLLBACK` in the file — the runner owns transaction control and rejects files that try to take it back
|
|
460
|
+
Each migration runs in its own implicit transaction on Postgres. Don't write `BEGIN` / `COMMIT` / `ROLLBACK` in the file — the runner owns transaction control and rejects files that try to take it back, including the Postgres spellings `END` and `ABORT`. The check looks only at the start of each statement and skips comments, string literals, dollar-quoted bodies (`DO $$ ... $$`) and SQLite trigger bodies (`CREATE TRIGGER ... BEGIN ... END`), so legitimate uses don't trip it.
|
|
329
461
|
|
|
330
462
|
For DDL that Postgres won't run inside a transaction (notably `CREATE INDEX CONCURRENTLY`), put `-- etchdb:no-transaction` on the first non-blank line:
|
|
331
463
|
|
|
332
464
|
```sql
|
|
333
|
-
-- migrations/0004_concurrent_index.sql
|
|
334
465
|
-- etchdb:no-transaction
|
|
466
|
+
-- migrations/0004_concurrent_index.sql
|
|
335
467
|
CREATE INDEX CONCURRENTLY users_lower_email_idx ON users (lower(email));
|
|
336
468
|
```
|
|
337
469
|
|
|
338
|
-
|
|
470
|
+
The marker must be the first non-blank line; a comment above it turns it into an ordinary comment.
|
|
471
|
+
|
|
472
|
+
On SQLite a migration runs through `sqlite3.executescript` inside the same kind of transaction: a file that fails part-way is rolled back together with its tracking row, so fixing the file and re-running applies it cleanly. That holds for connections etchdb opens (`DB.from_url`, the CLI). A connection you open yourself and wrap with `AiosqliteAdapter.from_connection` is in sqlite3's legacy transaction mode unless you pass `autocommit=True` to `aiosqlite.connect`, and in that mode `executescript` commits before it runs, so a failed file can leave its earlier statements applied.
|
|
339
473
|
|
|
340
474
|
### Strict consistency
|
|
341
475
|
|
|
@@ -346,6 +480,8 @@ Tracking lives in a `_etchdb_migrations` table created lazily on first call, wit
|
|
|
346
480
|
|
|
347
481
|
In both cases the error names the recovery (`DELETE FROM _etchdb_migrations WHERE filename = '...'` then re-run, or restore the missing file). Silent continuation with unknown state is exactly what a forward-only tool exists to prevent.
|
|
348
482
|
|
|
483
|
+
Run `migrate` from one process at a time (a deploy step or a one-shot job, not every replica at boot): the runner takes no lock, so two processes that start together both try to apply the same pending file.
|
|
484
|
+
|
|
349
485
|
Other migration tools (Alembic, dbmate, sqitch) still slot in fine if you want autogenerate, branching, or rollback — etchdb's helper covers the simple forward-only case without dragging those in.
|
|
350
486
|
|
|
351
487
|
### Running migrations from the command line
|