etchdb 0.6.1__tar.gz → 0.8.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.8.0}/.github/workflows/ci.yml +7 -6
- {etchdb-0.6.1 → etchdb-0.8.0}/.github/workflows/release.yml +13 -2
- {etchdb-0.6.1 → etchdb-0.8.0}/Makefile +1 -1
- {etchdb-0.6.1 → etchdb-0.8.0}/PKG-INFO +223 -47
- etchdb-0.8.0/README.md +494 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/pyproject.toml +5 -2
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/__init__.py +25 -2
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/adapter.py +34 -7
- etchdb-0.8.0/src/etchdb/aiosqlite/adapter.py +280 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/asyncpg/__init__.py +2 -2
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/asyncpg/adapter.py +59 -38
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/codecs.py +16 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/db.py +79 -58
- etchdb-0.8.0/src/etchdb/expr.py +447 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/migrations.py +26 -13
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/psycopg/__init__.py +2 -2
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/psycopg/adapter.py +48 -18
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/row.py +11 -1
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/sql/__init__.py +129 -46
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/conftest.py +22 -2
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_batch.py +38 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_execute_rowcount.py +10 -0
- etchdb-0.8.0/tests/integration/test_filter_operators.py +265 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_migrations.py +34 -0
- etchdb-0.8.0/tests/integration/test_pool_kwargs.py +69 -0
- etchdb-0.8.0/tests/integration/test_sqlite_transactions.py +174 -0
- etchdb-0.8.0/tests/typing/crud_types.py +27 -0
- etchdb-0.8.0/tests/unit/test_adapters.py +108 -0
- etchdb-0.8.0/tests/unit/test_connection_hooks.py +89 -0
- etchdb-0.8.0/tests/unit/test_filter_operators.py +289 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/unit/test_migrations.py +40 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/unit/test_sql_emitter.py +66 -10
- etchdb-0.8.0/tests/unit/test_version.py +12 -0
- etchdb-0.6.1/README.md +0 -320
- etchdb-0.6.1/src/etchdb/aiosqlite/adapter.py +0 -196
- etchdb-0.6.1/src/etchdb/expr.py +0 -100
- 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.8.0}/.gitignore +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/.python-version +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/LICENSE +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/docker-compose.yml +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/__main__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/cli.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/errors.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/py.typed +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/src/etchdb/query.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/_models.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_cli.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_codecs.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_errors.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_expressions.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_facade.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_fields_not_in_db.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_in_filter.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_is_null.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_iter_rows.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_iter_rows_keyset.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_ping_and_aclose.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_readme_example.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_typed_crud.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/integration/test_update_where.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/unit/__init__.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.0}/tests/unit/test_cli.py +0 -0
- {etchdb-0.6.1 → etchdb-0.8.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.8.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
|
|
|
@@ -91,10 +157,17 @@ user = await db.get(User, id=alice.id) # one row or None
|
|
|
91
157
|
users = await db.query(User) # list of rows
|
|
92
158
|
no_email = await db.query(User, email=None) # IS NULL, not = NULL
|
|
93
159
|
recent = await db.query(User, id=[1, 5, 7]) # IN ($1, $2, $3)
|
|
160
|
+
|
|
161
|
+
# Filter operators for the common conditions beyond equality.
|
|
162
|
+
from etchdb import Contains, Ge, Not, Range
|
|
163
|
+
adults = await db.query(User, age=Ge(18), email=Not(None))
|
|
164
|
+
window = await db.query(Event, created_at=Range(ge=start, lt=end))
|
|
165
|
+
found = await db.query(User, name=Contains(term, ignore_case=True))
|
|
166
|
+
|
|
94
167
|
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
95
168
|
await db.delete(alice)
|
|
96
169
|
|
|
97
|
-
# Add `where=` to AND extra
|
|
170
|
+
# Add `where=` to AND extra filters onto the PK. Atomic, so
|
|
98
171
|
# the scope check runs in the same statement as the update.
|
|
99
172
|
await db.update(User(id=alice.id, name="Alice B"),
|
|
100
173
|
where={"email": "alice@example.com"})
|
|
@@ -111,14 +184,15 @@ from etchdb import Inc, Now
|
|
|
111
184
|
await db.update(Counter.patch(id=1, n=Inc())) # n = n + 1
|
|
112
185
|
await db.update(Article.patch(id=1, updated_at=Now())) # = CURRENT_TIMESTAMP
|
|
113
186
|
|
|
114
|
-
# Bulk insert / delete (chunked at the driver's parameter limit
|
|
187
|
+
# Bulk insert / delete (chunked at the driver's parameter limit; a
|
|
188
|
+
# batch that needs several statements runs them in one transaction).
|
|
115
189
|
await db.insert_many([User(name=n) for n in names], on_conflict="ignore")
|
|
116
190
|
await db.insert_many(rows, on_conflict="upsert") # ON CONFLICT (pk) DO UPDATE SET ...
|
|
117
191
|
await db.delete_many(User, [1, 2, 3])
|
|
118
192
|
|
|
119
193
|
# Bulk update: same patch applied to all rows matching a filter.
|
|
120
194
|
# Returns the affected-row count.
|
|
121
|
-
n = await db.update_where(User.patch(
|
|
195
|
+
n = await db.update_where(User.patch(email=None),
|
|
122
196
|
where={"id": [1, 2, 3]})
|
|
123
197
|
|
|
124
198
|
# Upsert via single insert: same rules, returns the DB's view.
|
|
@@ -130,11 +204,13 @@ alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
|
130
204
|
async for user in db.iter_rows(User, batch_size=500):
|
|
131
205
|
process(user)
|
|
132
206
|
|
|
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`
|
|
207
|
+
# For huge tables, iter_rows_keyset avoids the growing OFFSET by
|
|
208
|
+
# emitting a `(by, *pk_tail) > last_seen` cursor per page. PK tail
|
|
209
|
+
# breaks ties and lets the cursor paginate through NULL values.
|
|
210
|
+
# `by` defaults to __pk__[0], which walks the primary-key index.
|
|
211
|
+
# A non-PK `by` is ordered `NULLS FIRST` (deterministic across
|
|
212
|
+
# backends; SQLite 3.30+) and stays O(N) only with an index on
|
|
213
|
+
# `(by NULLS FIRST, *pk)`; without one each page sorts the table.
|
|
138
214
|
async for user in db.iter_rows_keyset(User, batch_size=500):
|
|
139
215
|
process(user)
|
|
140
216
|
|
|
@@ -152,13 +228,16 @@ val = await db.fetchval("SELECT count(*) FROM users") # always returns the coun
|
|
|
152
228
|
# fetchval returns None on no row.
|
|
153
229
|
await db.execute("UPDATE users SET active = false WHERE id = $1", uid)
|
|
154
230
|
|
|
155
|
-
# Transactions
|
|
231
|
+
# Transactions: use the `tx` handle inside the block. On Postgres a
|
|
232
|
+
# call on `db` there runs on another connection, outside the
|
|
233
|
+
# transaction. SQLite has one connection, so everything on a DB
|
|
234
|
+
# shares it; give concurrent tasks that need isolation their own DB.
|
|
156
235
|
async with db.transaction() as tx:
|
|
157
236
|
await tx.insert(User(name="Carol"))
|
|
158
237
|
await tx.execute("INSERT INTO audit_log (...) VALUES (...)")
|
|
159
238
|
|
|
160
239
|
# Healthcheck + lifecycle
|
|
161
|
-
ok = await db.ping() # SELECT 1 round-trip;
|
|
240
|
+
ok = await db.ping() # SELECT 1 round-trip; False on failure, never raises
|
|
162
241
|
async with db: # close on scope exit (DB must already be open)
|
|
163
242
|
...
|
|
164
243
|
|
|
@@ -171,7 +250,7 @@ status = await db.migration_status("migrations/") # MigrationStatus dataclass
|
|
|
171
250
|
|
|
172
251
|
# Inspect SQL before executing (etchdb's defining feature)
|
|
173
252
|
q = db.compose("get", User, id=1)
|
|
174
|
-
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
|
|
253
|
+
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1 LIMIT 1
|
|
175
254
|
print(q.params) # [1]
|
|
176
255
|
|
|
177
256
|
# Same inspector without a live DB - useful in tests:
|
|
@@ -181,12 +260,47 @@ q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
|
181
260
|
|
|
182
261
|
`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
262
|
|
|
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
|
|
263
|
+
`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 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 a per-column condition.
|
|
185
264
|
|
|
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.
|
|
265
|
+
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
266
|
|
|
188
267
|
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
268
|
|
|
269
|
+
## Filter operators
|
|
270
|
+
|
|
271
|
+
A filter value, in `query`, `iter_rows`, `iter_rows_keyset` and the `where=` of `update`, `update_where` and `delete`, is one of four things: a plain value (`=`), `None` (`IS NULL`), a list (`IN`), or one of the operators below.
|
|
272
|
+
|
|
273
|
+
| Operator | SQL |
|
|
274
|
+
|---|---|
|
|
275
|
+
| `Gt(x)`, `Ge(x)`, `Lt(x)`, `Le(x)` | `col > x`, `col >= x`, `col < x`, `col <= x` |
|
|
276
|
+
| `Range(ge=a, lt=b)` | `col >= a AND col < b`; any of `gt`, `ge`, `lt`, `le`, one per side |
|
|
277
|
+
| `Not(x)` | `col <> x`; `Not(None)` is `IS NOT NULL`; `Not([a, b])` is `NOT IN (a, b)` |
|
|
278
|
+
| `Like(p)`, `ILike(p)` | `col LIKE p`, case-insensitive for `ILike`; `%` and `_` are wildcards, `\` escapes |
|
|
279
|
+
| `StartsWith(s)`, `Contains(s)` | `s` matched literally, its wildcards escaped; `ignore_case=True` to fold case |
|
|
280
|
+
|
|
281
|
+
```python
|
|
282
|
+
from etchdb import Gt, Lt, Not, Now, Range, StartsWith
|
|
283
|
+
|
|
284
|
+
await db.query(Order, total=Gt(100), state=Not(["CANCELLED", "REFUNDED"]))
|
|
285
|
+
await db.query(Session, expires_at=Lt(Now())) # expires_at < CURRENT_TIMESTAMP
|
|
286
|
+
await db.query(Event, at=Range(ge=day, lt=day + timedelta(days=1)), order_by="at")
|
|
287
|
+
await db.update_where(Job.patch(state="STALE"), where={"heartbeat_at": Lt(cutoff)})
|
|
288
|
+
await db.query(File, path=StartsWith(user_input)) # % and _ in the input match themselves
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
Things to know:
|
|
292
|
+
|
|
293
|
+
- **One condition per column.** Filters are keyword arguments joined with `AND`; `Range` is the way to put two bounds on one column. `OR`, comparisons between two columns, functions and joins stay in raw SQL.
|
|
294
|
+
- **The primary key of `update` and `delete` is a value.** Those address one row, so an operator in the row's key raises; operators go in `where=`. `iter_rows_keyset` does not accept a filter on its `by` column, which the cursor already constrains.
|
|
295
|
+
- **`get` takes equality only.** An operator with `LIMIT 1` would return an arbitrary match, so `db.get` rejects it; use `db.query(..., order_by=..., limit=1)`.
|
|
296
|
+
- **`Not` follows SQL for NULL.** `Not("x")` and `Not([...])` leave out rows where the column is NULL, because `<>` and `NOT IN` are not true for NULL. `Not([])` raises, since an empty exclusion list is usually a caller bug; drop the filter for that case.
|
|
297
|
+
- **`Range` skips a bound that is `None`**, so one optional end of a window passes straight through. With every bound `None` there is nothing to filter on and `Range` raises; leave the filter out in that case. `Gt(None)` and the other comparisons raise, since a comparison with NULL never matches.
|
|
298
|
+
- **`Now()` works as the compared value** in `Gt`, `Ge`, `Lt`, `Le` and `Range`. On SQLite `CURRENT_TIMESTAMP` is the text `YYYY-MM-DD HH:MM:SS` in UTC, so the column has to hold the same format for the comparison to mean anything.
|
|
299
|
+
- **Case sensitivity.** `StartsWith` and `Contains` are case-sensitive on every backend (SQLite uses `GLOB` for this) unless `ignore_case=True`. A raw `Like` is case-sensitive on Postgres but not on SQLite, whose `LIKE` ignores case for ASCII letters. `ILike` and `ignore_case=True` fold ASCII only on SQLite and follow the database locale on Postgres. SQLite's `PRAGMA case_sensitive_like = ON` makes every `LIKE` case-sensitive, `ILike` and `ignore_case=True` included.
|
|
300
|
+
- **Text ordering follows the column's collation.** `Lt("b")` or `Range(ge="a", lt="c")` on a text column can return different rows on Postgres (the database's locale, where `B` usually sorts next to `b`) and SQLite (byte order, where every uppercase ASCII letter sorts before lowercase). Numbers and timestamps compare the same everywhere.
|
|
301
|
+
- **`Like` patterns are yours to escape.** The pattern is a bound parameter, so it cannot inject SQL, but a `%` from user input is still a wildcard. Use `StartsWith` or `Contains` for user text. A pattern that ends in a lone `\` raises `ValueError`.
|
|
302
|
+
- **Operators compare by type and arguments** (`Gt(5) == Gt(5)`) and print as the call that made them, so they work in test assertions and logs.
|
|
303
|
+
|
|
190
304
|
## Typed errors
|
|
191
305
|
|
|
192
306
|
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__`.
|
|
@@ -207,7 +321,7 @@ except IntegrityError as e:
|
|
|
207
321
|
# e.__cause__ is the original asyncpg / psycopg / sqlite3 exception
|
|
208
322
|
```
|
|
209
323
|
|
|
210
|
-
`except EtchdbError` catches every member of the family at once.
|
|
324
|
+
`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
325
|
|
|
212
326
|
## Install
|
|
213
327
|
|
|
@@ -230,14 +344,84 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
|
230
344
|
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
231
345
|
```
|
|
232
346
|
|
|
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.
|
|
347
|
+
`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.
|
|
348
|
+
|
|
349
|
+
### Connection setup
|
|
350
|
+
|
|
351
|
+
Pass an async `configure` callback to add connection setup without replacing
|
|
352
|
+
etchdb's codecs. Built-in codecs run first, then your callback runs once for
|
|
353
|
+
each new physical connection, including replacement connections. It receives
|
|
354
|
+
the native connection for the selected driver. For example, with asyncpg:
|
|
355
|
+
|
|
356
|
+
```python
|
|
357
|
+
async def configure(conn):
|
|
358
|
+
await conn.set_type_codec(
|
|
359
|
+
"memory_domain", encoder=str, decoder=str, schema="public", format="text",
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
db = await DB.from_url(
|
|
363
|
+
"postgresql+asyncpg://user@host/db",
|
|
364
|
+
min_size=2, max_size=10, configure=configure,
|
|
365
|
+
)
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
Use the asyncpg callback for codecs and types, not for session settings.
|
|
369
|
+
asyncpg runs `RESET ALL` when a connection returns to the pool, so a `SET`
|
|
370
|
+
made in `configure` lasts only until the first query finishes. Put session
|
|
371
|
+
settings in the URL instead (`postgresql+asyncpg://user@host/db?search_path=app`);
|
|
372
|
+
asyncpg sends unrecognised query parameters as server settings on every
|
|
373
|
+
connection.
|
|
374
|
+
|
|
375
|
+
With psycopg, session settings made in `configure` do persist. Leave the
|
|
376
|
+
connection idle after setup SQL, as required by psycopg_pool, by committing
|
|
377
|
+
setup statements explicitly:
|
|
378
|
+
|
|
379
|
+
```python
|
|
380
|
+
async def configure(conn):
|
|
381
|
+
await conn.execute("SET application_name = 'myapp'")
|
|
382
|
+
await conn.commit()
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
Setup exceptions propagate to the driver's pool, which retains its native
|
|
386
|
+
startup/reconnection behavior; etchdb does not retry application statements.
|
|
387
|
+
The two pools differ in when you hear about it. asyncpg connects inside
|
|
388
|
+
`from_url`, so a failing callback raises there. psycopg_pool connects in the
|
|
389
|
+
background: `from_url` returns, the failure goes to the `psycopg.pool` logger,
|
|
390
|
+
and the first query waits for the pool's timeout (30 seconds by default)
|
|
391
|
+
before raising. SQLite rejects `configure` rather than silently ignoring it.
|
|
392
|
+
|
|
393
|
+
Driver-specific options stay on the adapters. For connection validation at
|
|
394
|
+
checkout with psycopg:
|
|
395
|
+
|
|
396
|
+
```python
|
|
397
|
+
from etchdb.psycopg import PsycopgAdapter
|
|
398
|
+
from psycopg_pool import AsyncConnectionPool
|
|
399
|
+
|
|
400
|
+
db = DB(await PsycopgAdapter.from_url(
|
|
401
|
+
"postgresql://user@host/db",
|
|
402
|
+
check=AsyncConnectionPool.check_connection,
|
|
403
|
+
configure=configure,
|
|
404
|
+
))
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
`AsyncpgAdapter.from_url(..., command_timeout=60)` sets asyncpg's default
|
|
408
|
+
command timeout in seconds. A statement that exceeds it raises the built-in
|
|
409
|
+
`TimeoutError`, not an etchdb error. Both adapters accept `configure`, `min_size` and
|
|
410
|
+
`max_size`. Omitted options retain driver defaults.
|
|
411
|
+
|
|
412
|
+
### Externally owned pools
|
|
413
|
+
|
|
414
|
+
`from_pool` wraps your pool without changing its codecs, callbacks or ownership.
|
|
415
|
+
Use the public driver-specific `configure_codecs` helper when creating that
|
|
416
|
+
pool to opt into etchdb's JSONB behavior alongside your own setup:
|
|
234
417
|
|
|
235
418
|
```python
|
|
236
419
|
import asyncpg
|
|
237
420
|
from etchdb import DB
|
|
238
|
-
from etchdb.asyncpg import AsyncpgAdapter
|
|
421
|
+
from etchdb.asyncpg import AsyncpgAdapter, configure_codecs
|
|
239
422
|
|
|
240
423
|
async def init_conn(conn):
|
|
424
|
+
await configure_codecs(conn)
|
|
241
425
|
await conn.set_type_codec(
|
|
242
426
|
"memory_domain", # the ENUM type name
|
|
243
427
|
encoder=str, decoder=str,
|
|
@@ -247,30 +431,20 @@ async def init_conn(conn):
|
|
|
247
431
|
|
|
248
432
|
pool = await asyncpg.create_pool(url, init=init_conn, min_size=2, max_size=10)
|
|
249
433
|
db = DB(AsyncpgAdapter.from_pool(pool))
|
|
434
|
+
# The application closes this externally owned pool: await pool.close().
|
|
250
435
|
```
|
|
251
436
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
437
|
+
For psycopg, import `configure_codecs` from `etchdb.psycopg` and call it in
|
|
438
|
+
your pool's async `configure` callback before application setup. The old
|
|
439
|
+
private `_init_codecs` names remain compatibility aliases; new code should
|
|
440
|
+
use the public helper. Psycopg's helper adapts Python lists as JSONB, matching
|
|
441
|
+
etchdb's existing defaults, so a list bound to an array parameter
|
|
442
|
+
(`= ANY($1::int[])`) works on asyncpg and fails on psycopg. For a query that
|
|
443
|
+
runs on both, use an `IN` filter (`db.query(User, id=[1, 2, 3])`) or expand
|
|
444
|
+
the JSONB value: `id IN (SELECT jsonb_array_elements_text($1::jsonb)::int)`. SQL NULL remains `None`; codecs do not replace it with
|
|
445
|
+
an empty collection.
|
|
259
446
|
|
|
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
|
|
447
|
+
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
448
|
|
|
275
449
|
## Migrations
|
|
276
450
|
|
|
@@ -325,17 +499,19 @@ if not status.is_consistent:
|
|
|
325
499
|
|
|
326
500
|
### Transaction model
|
|
327
501
|
|
|
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
|
|
502
|
+
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
503
|
|
|
330
504
|
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
505
|
|
|
332
506
|
```sql
|
|
333
|
-
-- migrations/0004_concurrent_index.sql
|
|
334
507
|
-- etchdb:no-transaction
|
|
508
|
+
-- migrations/0004_concurrent_index.sql
|
|
335
509
|
CREATE INDEX CONCURRENTLY users_lower_email_idx ON users (lower(email));
|
|
336
510
|
```
|
|
337
511
|
|
|
338
|
-
|
|
512
|
+
The marker must be the first non-blank line; a comment above it turns it into an ordinary comment.
|
|
513
|
+
|
|
514
|
+
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
515
|
|
|
340
516
|
### Strict consistency
|
|
341
517
|
|
|
@@ -346,6 +522,8 @@ Tracking lives in a `_etchdb_migrations` table created lazily on first call, wit
|
|
|
346
522
|
|
|
347
523
|
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
524
|
|
|
525
|
+
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.
|
|
526
|
+
|
|
349
527
|
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
528
|
|
|
351
529
|
### Running migrations from the command line
|
|
@@ -369,9 +547,7 @@ Migration status (./migrations):
|
|
|
369
547
|
|
|
370
548
|
## Under consideration
|
|
371
549
|
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
`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.
|
|
550
|
+
`Inc` / `Now` composing with `on_conflict="upsert"` is a 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.
|
|
375
551
|
|
|
376
552
|
## Built with AI assistance
|
|
377
553
|
|