etchdb 0.1.0__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {etchdb-0.1.0 → etchdb-0.2.0}/PKG-INFO +51 -6
- {etchdb-0.1.0 → etchdb-0.2.0}/README.md +48 -3
- {etchdb-0.1.0 → etchdb-0.2.0}/pyproject.toml +3 -3
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/__init__.py +1 -1
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/db.py +19 -31
- etchdb-0.2.0/src/etchdb/psycopg/__init__.py +20 -0
- etchdb-0.2.0/src/etchdb/psycopg/adapter.py +144 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/row.py +9 -1
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/sql/__init__.py +89 -27
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/integration/conftest.py +28 -13
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/integration/test_readme_example.py +26 -2
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/integration/test_typed_crud.py +38 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/unit/test_adapters.py +10 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/unit/test_db_dispatch.py +15 -3
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/unit/test_sql_emitter.py +133 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/.gitignore +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/.python-version +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/LICENSE +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/Makefile +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/docker-compose.yml +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/adapter.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/aiosqlite/adapter.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/asyncpg/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/asyncpg/adapter.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/py.typed +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/src/etchdb/query.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/_models.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/integration/__init__.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/integration/test_facade.py +0 -0
- {etchdb-0.1.0 → etchdb-0.2.0}/tests/unit/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: etchdb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Minimal async DB layer for Python. Typed CRUD over Pydantic, raw SQL when you need it
|
|
5
5
|
Project-URL: Homepage, https://github.com/varjoranta/etchdb
|
|
6
6
|
Project-URL: Repository, https://github.com/varjoranta/etchdb
|
|
@@ -45,7 +45,7 @@ Requires-Dist: pydantic>=2.0.0
|
|
|
45
45
|
Provides-Extra: all
|
|
46
46
|
Requires-Dist: aiosqlite>=0.19.0; extra == 'all'
|
|
47
47
|
Requires-Dist: asyncpg>=0.30.0; extra == 'all'
|
|
48
|
-
Requires-Dist: psycopg[binary]>=3.2; extra == 'all'
|
|
48
|
+
Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'all'
|
|
49
49
|
Provides-Extra: asyncpg
|
|
50
50
|
Requires-Dist: asyncpg>=0.30.0; extra == 'asyncpg'
|
|
51
51
|
Provides-Extra: dev
|
|
@@ -55,7 +55,7 @@ Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
|
55
55
|
Requires-Dist: ruff>=0.5.0; extra == 'dev'
|
|
56
56
|
Requires-Dist: ty; extra == 'dev'
|
|
57
57
|
Provides-Extra: psycopg
|
|
58
|
-
Requires-Dist: psycopg[binary]>=3.2; extra == 'psycopg'
|
|
58
|
+
Requires-Dist: psycopg[binary,pool]>=3.2; extra == 'psycopg'
|
|
59
59
|
Provides-Extra: sqlite
|
|
60
60
|
Requires-Dist: aiosqlite>=0.19.0; extra == 'sqlite'
|
|
61
61
|
Description-Content-Type: text/markdown
|
|
@@ -66,7 +66,7 @@ Minimal async DB layer for Python. Typed CRUD over Pydantic. Raw SQL when you ne
|
|
|
66
66
|
|
|
67
67
|
## Status
|
|
68
68
|
|
|
69
|
-
Alpha. v0.
|
|
69
|
+
Alpha. v0.2.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
70
70
|
|
|
71
71
|
## Example
|
|
72
72
|
|
|
@@ -89,6 +89,16 @@ users = await db.query(User) # list of rows
|
|
|
89
89
|
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
90
90
|
await db.delete(alice)
|
|
91
91
|
|
|
92
|
+
# Add `where=` to AND extra equality filters onto the PK. Atomic, so
|
|
93
|
+
# the scope check runs in the same statement as the update.
|
|
94
|
+
await db.update(User(id=alice.id, name="Alice B"),
|
|
95
|
+
where={"email": "alice@example.com"})
|
|
96
|
+
|
|
97
|
+
# Partial update without making your model lie about the schema:
|
|
98
|
+
# patch() builds a Row with only the given fields set; no validation,
|
|
99
|
+
# so models with required NOT NULL columns still flow through.
|
|
100
|
+
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
101
|
+
|
|
92
102
|
# Typed-result raw SQL (covers most joins)
|
|
93
103
|
users = await db.fetch_models(User, """
|
|
94
104
|
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
@@ -97,7 +107,9 @@ users = await db.fetch_models(User, """
|
|
|
97
107
|
|
|
98
108
|
# Untyped raw SQL (mirrors asyncpg)
|
|
99
109
|
rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
|
|
100
|
-
val = await db.fetchval("SELECT count(*) FROM users")
|
|
110
|
+
val = await db.fetchval("SELECT count(*) FROM users") # always returns the count;
|
|
111
|
+
# for non-aggregate selects,
|
|
112
|
+
# fetchval returns None on no row.
|
|
101
113
|
await db.execute("UPDATE users SET active = false WHERE id = $1", uid)
|
|
102
114
|
|
|
103
115
|
# Transactions
|
|
@@ -109,9 +121,17 @@ async with db.transaction() as tx:
|
|
|
109
121
|
q = db.compose("get", User, id=1)
|
|
110
122
|
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
|
|
111
123
|
print(q.params) # [1]
|
|
124
|
+
|
|
125
|
+
# Same inspector without a live DB - useful in tests:
|
|
126
|
+
from etchdb import sql
|
|
127
|
+
q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
112
128
|
```
|
|
113
129
|
|
|
114
|
-
`insert` only emits the columns you actually set, so an unset `id` lets the database allocate one (SERIAL or INTEGER PRIMARY KEY). `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.
|
|
130
|
+
`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.
|
|
131
|
+
|
|
132
|
+
`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.
|
|
133
|
+
|
|
134
|
+
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.
|
|
115
135
|
|
|
116
136
|
## Install
|
|
117
137
|
|
|
@@ -134,6 +154,31 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
|
134
154
|
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
135
155
|
```
|
|
136
156
|
|
|
157
|
+
`from_url` keeps the construction surface tiny. For pool-init concerns
|
|
158
|
+
(pgvector tuning, JSONB / ENUM codec registration, custom `min_size` /
|
|
159
|
+
`max_size`), construct the pool yourself and pass it via `from_pool`.
|
|
160
|
+
Example, registering a Postgres ENUM as a Python `str` via asyncpg's
|
|
161
|
+
`set_type_codec`:
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
import asyncpg
|
|
165
|
+
from etchdb import DB
|
|
166
|
+
from etchdb.asyncpg import AsyncpgAdapter
|
|
167
|
+
|
|
168
|
+
async def init_conn(conn):
|
|
169
|
+
await conn.set_type_codec(
|
|
170
|
+
"memory_domain", # the ENUM type name
|
|
171
|
+
encoder=str, decoder=str,
|
|
172
|
+
schema="public",
|
|
173
|
+
format="text",
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
pool = await asyncpg.create_pool(url, init=init_conn, min_size=2, max_size=10)
|
|
177
|
+
db = DB(AsyncpgAdapter.from_pool(pool))
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
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.
|
|
181
|
+
|
|
137
182
|
## Why
|
|
138
183
|
|
|
139
184
|
Most Python ORMs are heavy, opinionated, and leak at the seams when you reach for pgvector or PostGIS. Raw asyncpg works, but every project ends up writing the same Pydantic-bridge code. etchdb closes that gap without becoming a framework.
|
|
@@ -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.2.0 on PyPI. Built in public from day one; expect tightening between alpha releases.
|
|
8
8
|
|
|
9
9
|
## Example
|
|
10
10
|
|
|
@@ -27,6 +27,16 @@ users = await db.query(User) # list of rows
|
|
|
27
27
|
await db.update(User(id=alice.id, name="Alice B")) # partial: email is preserved
|
|
28
28
|
await db.delete(alice)
|
|
29
29
|
|
|
30
|
+
# Add `where=` to AND extra equality filters onto the PK. Atomic, so
|
|
31
|
+
# the scope check runs in the same statement as the update.
|
|
32
|
+
await db.update(User(id=alice.id, name="Alice B"),
|
|
33
|
+
where={"email": "alice@example.com"})
|
|
34
|
+
|
|
35
|
+
# Partial update without making your model lie about the schema:
|
|
36
|
+
# patch() builds a Row with only the given fields set; no validation,
|
|
37
|
+
# so models with required NOT NULL columns still flow through.
|
|
38
|
+
await db.update(User.patch(id=alice.id, name="Alice B"))
|
|
39
|
+
|
|
30
40
|
# Typed-result raw SQL (covers most joins)
|
|
31
41
|
users = await db.fetch_models(User, """
|
|
32
42
|
SELECT u.* FROM users u JOIN orders o ON o.user_id = u.id
|
|
@@ -35,7 +45,9 @@ users = await db.fetch_models(User, """
|
|
|
35
45
|
|
|
36
46
|
# Untyped raw SQL (mirrors asyncpg)
|
|
37
47
|
rows = await db.fetch("SELECT count(*) FROM events WHERE site_id = $1", site_id)
|
|
38
|
-
val = await db.fetchval("SELECT count(*) FROM users")
|
|
48
|
+
val = await db.fetchval("SELECT count(*) FROM users") # always returns the count;
|
|
49
|
+
# for non-aggregate selects,
|
|
50
|
+
# fetchval returns None on no row.
|
|
39
51
|
await db.execute("UPDATE users SET active = false WHERE id = $1", uid)
|
|
40
52
|
|
|
41
53
|
# Transactions
|
|
@@ -47,9 +59,17 @@ async with db.transaction() as tx:
|
|
|
47
59
|
q = db.compose("get", User, id=1)
|
|
48
60
|
print(q.sql) # SELECT id, name, email FROM users WHERE id = $1
|
|
49
61
|
print(q.params) # [1]
|
|
62
|
+
|
|
63
|
+
# Same inspector without a live DB - useful in tests:
|
|
64
|
+
from etchdb import sql
|
|
65
|
+
q = sql.compose("get", User, id=1, placeholder=lambda i: f"${i + 1}")
|
|
50
66
|
```
|
|
51
67
|
|
|
52
|
-
`insert` only emits the columns you actually set, so an unset `id` lets the database allocate one (SERIAL or INTEGER PRIMARY KEY). `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.
|
|
68
|
+
`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.
|
|
69
|
+
|
|
70
|
+
`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.
|
|
71
|
+
|
|
72
|
+
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.
|
|
53
73
|
|
|
54
74
|
## Install
|
|
55
75
|
|
|
@@ -72,6 +92,31 @@ from etchdb.asyncpg import AsyncpgAdapter # requires asyncpg
|
|
|
72
92
|
db = DB(AsyncpgAdapter.from_pool(my_pool))
|
|
73
93
|
```
|
|
74
94
|
|
|
95
|
+
`from_url` keeps the construction surface tiny. For pool-init concerns
|
|
96
|
+
(pgvector tuning, JSONB / ENUM codec registration, custom `min_size` /
|
|
97
|
+
`max_size`), construct the pool yourself and pass it via `from_pool`.
|
|
98
|
+
Example, registering a Postgres ENUM as a Python `str` via asyncpg's
|
|
99
|
+
`set_type_codec`:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import asyncpg
|
|
103
|
+
from etchdb import DB
|
|
104
|
+
from etchdb.asyncpg import AsyncpgAdapter
|
|
105
|
+
|
|
106
|
+
async def init_conn(conn):
|
|
107
|
+
await conn.set_type_codec(
|
|
108
|
+
"memory_domain", # the ENUM type name
|
|
109
|
+
encoder=str, decoder=str,
|
|
110
|
+
schema="public",
|
|
111
|
+
format="text",
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
pool = await asyncpg.create_pool(url, init=init_conn, min_size=2, max_size=10)
|
|
115
|
+
db = DB(AsyncpgAdapter.from_pool(pool))
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
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.
|
|
119
|
+
|
|
75
120
|
## Why
|
|
76
121
|
|
|
77
122
|
Most Python ORMs are heavy, opinionated, and leak at the seams when you reach for pgvector or PostGIS. Raw asyncpg works, but every project ends up writing the same Pydantic-bridge code. etchdb closes that gap without becoming a framework.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "etchdb"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.2.0"
|
|
4
4
|
description = "Minimal async DB layer for Python. Typed CRUD over Pydantic, raw SQL when you need it"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12"
|
|
@@ -37,11 +37,11 @@ dependencies = [
|
|
|
37
37
|
|
|
38
38
|
[project.optional-dependencies]
|
|
39
39
|
asyncpg = ["asyncpg>=0.30.0"]
|
|
40
|
-
psycopg = ["psycopg[binary]>=3.2"]
|
|
40
|
+
psycopg = ["psycopg[binary,pool]>=3.2"]
|
|
41
41
|
sqlite = ["aiosqlite>=0.19.0"]
|
|
42
42
|
all = [
|
|
43
43
|
"asyncpg>=0.30.0",
|
|
44
|
-
"psycopg[binary]>=3.2",
|
|
44
|
+
"psycopg[binary,pool]>=3.2",
|
|
45
45
|
"aiosqlite>=0.19.0",
|
|
46
46
|
]
|
|
47
47
|
dev = [
|
|
@@ -17,7 +17,7 @@ from urllib.parse import urlparse
|
|
|
17
17
|
from etchdb import sql
|
|
18
18
|
|
|
19
19
|
if TYPE_CHECKING:
|
|
20
|
-
from collections.abc import AsyncIterator
|
|
20
|
+
from collections.abc import AsyncIterator, Mapping
|
|
21
21
|
|
|
22
22
|
from etchdb.adapter import AdapterBase
|
|
23
23
|
from etchdb.query import SqlQuery
|
|
@@ -38,15 +38,6 @@ def _hydrate(model_or_row: type[Row] | Row, row: dict[str, Any] | None) -> Row |
|
|
|
38
38
|
return cls(**row)
|
|
39
39
|
|
|
40
40
|
|
|
41
|
-
_COMPOSE_OPS = {
|
|
42
|
-
"get": sql.select_one,
|
|
43
|
-
"query": sql.select_many,
|
|
44
|
-
"insert": sql.insert,
|
|
45
|
-
"update": sql.update,
|
|
46
|
-
"delete": sql.delete,
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
|
|
50
41
|
class DB:
|
|
51
42
|
"""User-facing DB facade."""
|
|
52
43
|
|
|
@@ -59,8 +50,8 @@ class DB:
|
|
|
59
50
|
|
|
60
51
|
Supported schemes:
|
|
61
52
|
postgresql://, postgres://, postgresql+asyncpg:// -> asyncpg
|
|
53
|
+
postgresql+psycopg:// -> psycopg
|
|
62
54
|
sqlite:///, sqlite+aiosqlite:/// -> aiosqlite
|
|
63
|
-
postgresql+psycopg:// -> NotImplementedError
|
|
64
55
|
|
|
65
56
|
Driver subpackages are imported lazily so users only need the
|
|
66
57
|
driver they actually use installed.
|
|
@@ -74,12 +65,15 @@ class DB:
|
|
|
74
65
|
if scheme == "postgresql+asyncpg":
|
|
75
66
|
url = "postgresql://" + url.split("://", 1)[1]
|
|
76
67
|
adapter: AdapterBase = await AsyncpgAdapter.from_url(url)
|
|
68
|
+
elif scheme == "postgresql+psycopg":
|
|
69
|
+
from etchdb.psycopg import PsycopgAdapter
|
|
70
|
+
|
|
71
|
+
url = "postgresql://" + url.split("://", 1)[1]
|
|
72
|
+
adapter = await PsycopgAdapter.from_url(url)
|
|
77
73
|
elif scheme in {"sqlite", "sqlite+aiosqlite"}:
|
|
78
74
|
from etchdb.aiosqlite import AiosqliteAdapter
|
|
79
75
|
|
|
80
76
|
adapter = await AiosqliteAdapter.from_url(url)
|
|
81
|
-
elif scheme == "postgresql+psycopg":
|
|
82
|
-
raise NotImplementedError("psycopg adapter not yet shipped")
|
|
83
77
|
else:
|
|
84
78
|
raise ValueError(f"Unsupported URL scheme: {scheme!r}")
|
|
85
79
|
|
|
@@ -146,15 +140,16 @@ class DB:
|
|
|
146
140
|
result = await self._adapter.fetchrow(q.sql, *q.params)
|
|
147
141
|
return _hydrate(row, result) or row
|
|
148
142
|
|
|
149
|
-
async def update(self, row: Row) -> Row | None:
|
|
150
|
-
"""Update `row`
|
|
151
|
-
or None if no row
|
|
152
|
-
q = sql.update(row, placeholder=self._adapter.placeholder, returning="*")
|
|
143
|
+
async def update(self, row: Row, *, where: Mapping[str, Any] | None = None) -> Row | None:
|
|
144
|
+
"""Update `row` by PK, AND'd with `where=`. Returns the updated
|
|
145
|
+
row, or None if PK + `where=` matched no row."""
|
|
146
|
+
q = sql.update(row, placeholder=self._adapter.placeholder, returning="*", where=where)
|
|
153
147
|
result = await self._adapter.fetchrow(q.sql, *q.params)
|
|
154
148
|
return _hydrate(row, result)
|
|
155
149
|
|
|
156
|
-
async def delete(self, row: Row) -> None:
|
|
157
|
-
|
|
150
|
+
async def delete(self, row: Row, *, where: Mapping[str, Any] | None = None) -> None:
|
|
151
|
+
"""Delete `row` by PK, AND'd with `where=`."""
|
|
152
|
+
q = sql.delete(row, placeholder=self._adapter.placeholder, where=where)
|
|
158
153
|
await self._adapter.execute(q.sql, *q.params)
|
|
159
154
|
|
|
160
155
|
def compose(
|
|
@@ -163,17 +158,10 @@ class DB:
|
|
|
163
158
|
*args: Any,
|
|
164
159
|
**kwargs: Any,
|
|
165
160
|
) -> SqlQuery:
|
|
166
|
-
"""Return the SqlQuery a typed op would produce, without executing
|
|
167
|
-
|
|
168
|
-
Lets callers inspect or test SQL before it touches the DB. The
|
|
169
|
-
placeholder style follows the underlying adapter ($N for asyncpg,
|
|
170
|
-
? for aiosqlite).
|
|
161
|
+
"""Return the SqlQuery a typed op would produce, without executing.
|
|
171
162
|
|
|
172
|
-
|
|
173
|
-
|
|
163
|
+
Thin wrapper over `etchdb.sql.compose` that fills in `placeholder`
|
|
164
|
+
from the live adapter. Use `sql.compose(...)` directly when you
|
|
165
|
+
don't have a DB instance.
|
|
174
166
|
"""
|
|
175
|
-
|
|
176
|
-
fn = _COMPOSE_OPS[op]
|
|
177
|
-
except KeyError as e:
|
|
178
|
-
raise ValueError(f"Unknown op {op!r}. Expected one of: {sorted(_COMPOSE_OPS)}") from e
|
|
179
|
-
return fn(*args, placeholder=self._adapter.placeholder, **kwargs)
|
|
167
|
+
return sql.compose(op, *args, placeholder=self._adapter.placeholder, **kwargs)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""psycopg adapter for etchdb.
|
|
2
|
+
|
|
3
|
+
Importing this subpackage requires both the psycopg driver and its
|
|
4
|
+
pool package: install with `pip install etchdb[psycopg]`. The
|
|
5
|
+
top-level `etchdb` namespace does NOT depend on either; only this
|
|
6
|
+
subpackage does.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import psycopg as _psycopg # noqa: F401
|
|
11
|
+
import psycopg_pool as _psycopg_pool # noqa: F401
|
|
12
|
+
except ImportError as e:
|
|
13
|
+
raise ImportError(
|
|
14
|
+
"etchdb.psycopg requires the psycopg and psycopg-pool packages. "
|
|
15
|
+
"Install with: pip install etchdb[psycopg]"
|
|
16
|
+
) from e
|
|
17
|
+
|
|
18
|
+
from etchdb.psycopg.adapter import PsycopgAdapter
|
|
19
|
+
|
|
20
|
+
__all__ = ["PsycopgAdapter"]
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""psycopg adapter implementation.
|
|
2
|
+
|
|
3
|
+
Uses `psycopg.AsyncRawCursor` so raw SQL keeps libpq-native `$1, $2, ...`
|
|
4
|
+
placeholders: the same form the asyncpg adapter accepts. Callers can
|
|
5
|
+
swap between the two Postgres adapters without rewriting their queries.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import AsyncIterator
|
|
11
|
+
from contextlib import asynccontextmanager
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
import psycopg
|
|
15
|
+
from psycopg.rows import AsyncRowFactory, dict_row, tuple_row
|
|
16
|
+
from psycopg_pool import AsyncConnectionPool
|
|
17
|
+
|
|
18
|
+
from etchdb.adapter import AdapterBase
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PsycopgAdapter(AdapterBase):
|
|
22
|
+
"""AdapterBase implementation backed by a psycopg AsyncConnectionPool.
|
|
23
|
+
|
|
24
|
+
Construct via `from_pool(pool)` to wrap an externally-managed pool
|
|
25
|
+
(etchdb will not close it), or `await from_url(url)` to let etchdb
|
|
26
|
+
create and own the pool. The `owns_pool` flag tracks ownership.
|
|
27
|
+
|
|
28
|
+
Raw-SQL methods use `$1, $2, ...` placeholders (libpq native, same
|
|
29
|
+
as asyncpg). psycopg's default `%s` form is not used here, so SQL
|
|
30
|
+
written for the asyncpg adapter runs against this one unchanged.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, pool: AsyncConnectionPool, *, owns_pool: bool = False):
|
|
34
|
+
self._pool = pool
|
|
35
|
+
self._owns_pool = owns_pool
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def placeholder(i: int) -> str:
|
|
39
|
+
return f"${i + 1}"
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def from_pool(cls, pool: AsyncConnectionPool) -> PsycopgAdapter:
|
|
43
|
+
"""Wrap an externally-managed psycopg AsyncConnectionPool."""
|
|
44
|
+
return cls(pool, owns_pool=False)
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
async def from_url(cls, url: str) -> PsycopgAdapter:
|
|
48
|
+
"""Open a psycopg AsyncConnectionPool against `url` and wrap it.
|
|
49
|
+
|
|
50
|
+
etchdb owns the pool; `close()` will close it.
|
|
51
|
+
"""
|
|
52
|
+
pool = AsyncConnectionPool(url, open=False)
|
|
53
|
+
await pool.open()
|
|
54
|
+
return cls(pool, owns_pool=True)
|
|
55
|
+
|
|
56
|
+
@asynccontextmanager
|
|
57
|
+
async def _cursor(
|
|
58
|
+
self, *, row_factory: AsyncRowFactory[Any] = dict_row
|
|
59
|
+
) -> AsyncIterator[psycopg.AsyncRawCursor[Any]]:
|
|
60
|
+
async with (
|
|
61
|
+
self._pool.connection() as conn,
|
|
62
|
+
psycopg.AsyncRawCursor(conn, row_factory=row_factory) as cur,
|
|
63
|
+
):
|
|
64
|
+
yield cur
|
|
65
|
+
|
|
66
|
+
# psycopg types `cur.execute`'s query arg as LiteralString to
|
|
67
|
+
# discourage SQL injection at the type level; etchdb passes runtime
|
|
68
|
+
# strings here (the SqlQuery / raw-SQL contract). The injection
|
|
69
|
+
# guard is the `*params` substitution, not the query type.
|
|
70
|
+
async def execute(self, sql: str, *params: Any) -> Any:
|
|
71
|
+
async with self._cursor() as cur:
|
|
72
|
+
await cur.execute(cast(Any, sql), params)
|
|
73
|
+
|
|
74
|
+
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
75
|
+
async with self._cursor() as cur:
|
|
76
|
+
await cur.execute(cast(Any, sql), params)
|
|
77
|
+
return await cur.fetchall()
|
|
78
|
+
|
|
79
|
+
async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
|
|
80
|
+
async with self._cursor() as cur:
|
|
81
|
+
await cur.execute(cast(Any, sql), params)
|
|
82
|
+
return await cur.fetchone()
|
|
83
|
+
|
|
84
|
+
async def fetchval(self, sql: str, *params: Any) -> Any:
|
|
85
|
+
# tuple_row skips the dict allocation we'd just throw away.
|
|
86
|
+
async with self._cursor(row_factory=tuple_row) as cur:
|
|
87
|
+
await cur.execute(cast(Any, sql), params)
|
|
88
|
+
row = await cur.fetchone()
|
|
89
|
+
return row[0] if row is not None else None
|
|
90
|
+
|
|
91
|
+
@asynccontextmanager
|
|
92
|
+
async def transaction(self) -> AsyncIterator[AdapterBase]:
|
|
93
|
+
async with self._pool.connection() as conn, conn.transaction():
|
|
94
|
+
yield _PsycopgConnAdapter(conn)
|
|
95
|
+
|
|
96
|
+
async def close(self) -> None:
|
|
97
|
+
if self._owns_pool:
|
|
98
|
+
await self._pool.close()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _PsycopgConnAdapter(AdapterBase):
|
|
102
|
+
"""Single-connection adapter, used inside a transaction."""
|
|
103
|
+
|
|
104
|
+
def __init__(self, conn: psycopg.AsyncConnection):
|
|
105
|
+
self._conn = conn
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def placeholder(i: int) -> str:
|
|
109
|
+
return f"${i + 1}"
|
|
110
|
+
|
|
111
|
+
@asynccontextmanager
|
|
112
|
+
async def _cursor(
|
|
113
|
+
self, *, row_factory: AsyncRowFactory[Any] = dict_row
|
|
114
|
+
) -> AsyncIterator[psycopg.AsyncRawCursor[Any]]:
|
|
115
|
+
async with psycopg.AsyncRawCursor(self._conn, row_factory=row_factory) as cur:
|
|
116
|
+
yield cur
|
|
117
|
+
|
|
118
|
+
async def execute(self, sql: str, *params: Any) -> Any:
|
|
119
|
+
async with self._cursor() as cur:
|
|
120
|
+
await cur.execute(cast(Any, sql), params)
|
|
121
|
+
|
|
122
|
+
async def fetch(self, sql: str, *params: Any) -> list[dict[str, Any]]:
|
|
123
|
+
async with self._cursor() as cur:
|
|
124
|
+
await cur.execute(cast(Any, sql), params)
|
|
125
|
+
return await cur.fetchall()
|
|
126
|
+
|
|
127
|
+
async def fetchrow(self, sql: str, *params: Any) -> dict[str, Any] | None:
|
|
128
|
+
async with self._cursor() as cur:
|
|
129
|
+
await cur.execute(cast(Any, sql), params)
|
|
130
|
+
return await cur.fetchone()
|
|
131
|
+
|
|
132
|
+
async def fetchval(self, sql: str, *params: Any) -> Any:
|
|
133
|
+
async with self._cursor(row_factory=tuple_row) as cur:
|
|
134
|
+
await cur.execute(cast(Any, sql), params)
|
|
135
|
+
row = await cur.fetchone()
|
|
136
|
+
return row[0] if row is not None else None
|
|
137
|
+
|
|
138
|
+
@asynccontextmanager
|
|
139
|
+
async def transaction(self) -> AsyncIterator[AdapterBase]:
|
|
140
|
+
async with self._conn.transaction():
|
|
141
|
+
yield self
|
|
142
|
+
|
|
143
|
+
async def close(self) -> None:
|
|
144
|
+
return None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Base class for typed table rows."""
|
|
2
2
|
|
|
3
|
-
from typing import ClassVar
|
|
3
|
+
from typing import Any, ClassVar, Self
|
|
4
4
|
|
|
5
5
|
from pydantic import BaseModel
|
|
6
6
|
|
|
@@ -27,3 +27,11 @@ class Row(BaseModel):
|
|
|
27
27
|
|
|
28
28
|
__table__: ClassVar[str]
|
|
29
29
|
__pk__: ClassVar[tuple[str, ...]] = ("id",)
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def patch(cls, **fields: Any) -> Self:
|
|
33
|
+
"""Build a partial Row for `db.update` / `db.delete`, skipping
|
|
34
|
+
Pydantic validation so partials with missing required fields
|
|
35
|
+
work. NOT a general-purpose constructor: use `Cls(...)` for
|
|
36
|
+
fully-formed rows that should be validated."""
|
|
37
|
+
return cls.model_construct(**fields)
|
|
@@ -6,8 +6,8 @@ own `placeholder` callable so the same emitter works for both Postgres
|
|
|
6
6
|
($1, $2, ...) and SQLite (?, ?, ...).
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
-
from collections.abc import Callable
|
|
10
|
-
from typing import Any
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from typing import Any, Literal
|
|
11
11
|
|
|
12
12
|
from etchdb.query import SqlQuery
|
|
13
13
|
from etchdb.row import Row
|
|
@@ -111,68 +111,130 @@ def update(
|
|
|
111
111
|
*,
|
|
112
112
|
placeholder: Callable[[int], str],
|
|
113
113
|
returning: str | list[str] | None = None,
|
|
114
|
+
where: Mapping[str, Any] | None = None,
|
|
114
115
|
) -> SqlQuery:
|
|
115
116
|
"""Build an UPDATE for `row` keyed by its primary key.
|
|
116
117
|
|
|
117
118
|
Only fields in `model_fields_set` go into the SET clause, giving
|
|
118
119
|
partial-update semantics: columns the caller didn't touch are
|
|
119
|
-
preserved. WHERE uses every field in `__pk__
|
|
120
|
-
|
|
121
|
-
|
|
120
|
+
preserved. WHERE uses every field in `__pk__`, AND'd with any
|
|
121
|
+
extra equality filters from `where=`. The common multi-tenant
|
|
122
|
+
pattern is `update(row, where={"user_id": current_user_id})` so
|
|
123
|
+
the update is atomic with the ownership check.
|
|
124
|
+
|
|
125
|
+
Raises ValueError if any PK field is unset, if no non-PK field is
|
|
126
|
+
set, or if `where=` keys overlap with `__pk__`. Pass `returning="*"`
|
|
127
|
+
to add RETURNING.
|
|
122
128
|
"""
|
|
123
129
|
table = _table_name(row)
|
|
124
|
-
_ensure_pk_set(row, "update")
|
|
125
130
|
pk_set = set(row.__pk__)
|
|
131
|
+
where_fields, where_values = _pk_where(row, "update", where)
|
|
132
|
+
|
|
126
133
|
set_fields = [
|
|
127
134
|
f for f in type(row).model_fields if f in row.model_fields_set and f not in pk_set
|
|
128
135
|
]
|
|
129
|
-
|
|
130
136
|
if not set_fields:
|
|
131
137
|
raise ValueError(f"{type(row).__name__} has no non-PK fields to update")
|
|
132
138
|
|
|
133
139
|
set_sql = _eq_clauses(set_fields, placeholder=placeholder, sep=", ")
|
|
134
|
-
|
|
140
|
+
where_sql = _eq_clauses(where_fields, placeholder=placeholder, start=len(set_fields))
|
|
135
141
|
|
|
136
142
|
set_values = [getattr(row, f) for f in set_fields]
|
|
137
|
-
pk_values = [getattr(row, f) for f in row.__pk__]
|
|
138
143
|
|
|
139
|
-
sql = f"UPDATE {table} SET {set_sql} WHERE {
|
|
144
|
+
sql = f"UPDATE {table} SET {set_sql} WHERE {where_sql}"
|
|
140
145
|
if returning is not None:
|
|
141
146
|
sql += f" RETURNING {_format_columns(returning)}"
|
|
142
147
|
|
|
143
|
-
return SqlQuery(sql=sql, params=set_values +
|
|
148
|
+
return SqlQuery(sql=sql, params=set_values + where_values)
|
|
144
149
|
|
|
145
150
|
|
|
146
|
-
def delete(
|
|
147
|
-
|
|
151
|
+
def delete(
|
|
152
|
+
row: Row,
|
|
153
|
+
*,
|
|
154
|
+
placeholder: Callable[[int], str],
|
|
155
|
+
where: Mapping[str, Any] | None = None,
|
|
156
|
+
) -> SqlQuery:
|
|
157
|
+
"""Build a DELETE for `row` keyed by its primary key, optionally
|
|
158
|
+
AND'd with extra equality filters from `where=`.
|
|
148
159
|
|
|
149
|
-
Raises ValueError if any PK field is unset (no row to identify)
|
|
160
|
+
Raises ValueError if any PK field is unset (no row to identify),
|
|
161
|
+
or if `where=` keys overlap with `__pk__`.
|
|
150
162
|
"""
|
|
151
163
|
table = _table_name(row)
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
164
|
+
where_fields, where_values = _pk_where(row, "delete", where)
|
|
165
|
+
|
|
166
|
+
where_sql = _eq_clauses(where_fields, placeholder=placeholder)
|
|
167
|
+
sql = f"DELETE FROM {table} WHERE {where_sql}"
|
|
168
|
+
return SqlQuery(sql=sql, params=where_values)
|
|
169
|
+
|
|
155
170
|
|
|
156
|
-
|
|
157
|
-
|
|
171
|
+
_OPS = {
|
|
172
|
+
"get": select_one,
|
|
173
|
+
"query": select_many,
|
|
174
|
+
"insert": insert,
|
|
175
|
+
"update": update,
|
|
176
|
+
"delete": delete,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def compose(
|
|
181
|
+
op: Literal["get", "query", "insert", "update", "delete"],
|
|
182
|
+
*args: Any,
|
|
183
|
+
placeholder: Callable[[int], str],
|
|
184
|
+
**kwargs: Any,
|
|
185
|
+
) -> SqlQuery:
|
|
186
|
+
"""Build the SqlQuery for a typed op without a live adapter.
|
|
187
|
+
|
|
188
|
+
Useful in tests, scripts, and any code that wants to inspect SQL
|
|
189
|
+
without opening a connection. The DB facade's `compose` method is
|
|
190
|
+
a thin wrapper that fills in `placeholder` from the live adapter
|
|
191
|
+
so callers don't have to.
|
|
192
|
+
|
|
193
|
+
from etchdb import sql
|
|
194
|
+
|
|
195
|
+
pg = lambda i: f"${i + 1}"
|
|
196
|
+
q = sql.compose("get", User, id=1, placeholder=pg)
|
|
197
|
+
assert q.sql == "SELECT id, name FROM users WHERE id = $1 LIMIT 1"
|
|
198
|
+
"""
|
|
199
|
+
try:
|
|
200
|
+
fn = _OPS[op]
|
|
201
|
+
except KeyError as e:
|
|
202
|
+
raise ValueError(f"Unknown op {op!r}. Expected one of: {sorted(_OPS)}") from e
|
|
203
|
+
return fn(*args, placeholder=placeholder, **kwargs)
|
|
158
204
|
|
|
159
205
|
|
|
160
206
|
# --- helpers ----------------------------------------------------------
|
|
161
207
|
|
|
162
208
|
|
|
163
|
-
def
|
|
164
|
-
"""
|
|
209
|
+
def _pk_where(row: Row, op: str, where: Mapping[str, Any] | None) -> tuple[list[str], list[Any]]:
|
|
210
|
+
"""Validate and build the WHERE field+value lists for `update`/`delete`.
|
|
165
211
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
212
|
+
Asserts every PK field is set on `row` (else `WHERE id = NULL`
|
|
213
|
+
silently matches nothing) and that `where=` does not re-specify a
|
|
214
|
+
PK field (else `id = $1 AND id = $2` would either confuse the
|
|
215
|
+
reader or match nothing). Returns ordered (field_names, values),
|
|
216
|
+
PK first, `where=` second.
|
|
169
217
|
"""
|
|
170
|
-
|
|
171
|
-
if
|
|
218
|
+
unset_pk = [f for f in row.__pk__ if f not in row.model_fields_set]
|
|
219
|
+
if unset_pk:
|
|
172
220
|
raise ValueError(
|
|
173
|
-
f"Cannot {op}: primary key field(s) {
|
|
221
|
+
f"Cannot {op}: primary key field(s) {unset_pk} not set on this "
|
|
174
222
|
f"{type(row).__name__}. Set them so the row can be identified."
|
|
175
223
|
)
|
|
224
|
+
if where:
|
|
225
|
+
overlap = set(row.__pk__) & where.keys()
|
|
226
|
+
if overlap:
|
|
227
|
+
raise ValueError(
|
|
228
|
+
f"where= keys overlap with __pk__: {sorted(overlap)}. "
|
|
229
|
+
f"PK fields are already in WHERE; remove them from where=."
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
fields = list(row.__pk__)
|
|
233
|
+
values: list[Any] = [getattr(row, f) for f in row.__pk__]
|
|
234
|
+
if where:
|
|
235
|
+
fields.extend(where)
|
|
236
|
+
values.extend(where.values())
|
|
237
|
+
return fields, values
|
|
176
238
|
|
|
177
239
|
|
|
178
240
|
def _table_name(row_or_class: Row | type[Row]) -> str:
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
"""Fixtures for integration tests across SQLite (always) and Postgres (Docker).
|
|
2
2
|
|
|
3
3
|
The `sqlite_db` fixture runs against an in-memory aiosqlite database and
|
|
4
|
-
is always available. The `
|
|
5
|
-
running on localhost:5532. The
|
|
6
|
-
|
|
7
|
-
when Postgres is
|
|
4
|
+
is always available. The `postgres_asyncpg_db` and `postgres_psycopg_db`
|
|
5
|
+
fixtures skip when Docker isn't running on localhost:5532. The
|
|
6
|
+
parametrized `db` fixture runs each test against every backend in turn;
|
|
7
|
+
per-param skipping means SQLite tests still run when Postgres is
|
|
8
|
+
unavailable.
|
|
8
9
|
"""
|
|
9
10
|
|
|
10
11
|
import os
|
|
@@ -15,10 +16,12 @@ import pytest_asyncio
|
|
|
15
16
|
|
|
16
17
|
from etchdb import DB
|
|
17
18
|
|
|
18
|
-
|
|
19
|
-
"
|
|
20
|
-
"
|
|
19
|
+
POSTGRES_DSN = os.environ.get(
|
|
20
|
+
"ETCHDB_TEST_POSTGRES_DSN",
|
|
21
|
+
"etchdb:etchdb-test-password@localhost:5532/etchdb_test",
|
|
21
22
|
)
|
|
23
|
+
POSTGRES_ASYNCPG_URL = f"postgresql+asyncpg://{POSTGRES_DSN}"
|
|
24
|
+
POSTGRES_PSYCOPG_URL = f"postgresql+psycopg://{POSTGRES_DSN}"
|
|
22
25
|
|
|
23
26
|
|
|
24
27
|
def _postgres_available() -> bool:
|
|
@@ -53,24 +56,36 @@ async def sqlite_db():
|
|
|
53
56
|
await db.close()
|
|
54
57
|
|
|
55
58
|
|
|
56
|
-
|
|
57
|
-
async def postgres_db():
|
|
59
|
+
async def _open_postgres(url: str) -> DB:
|
|
58
60
|
if not _postgres_available():
|
|
59
61
|
pytest.skip("Postgres not available on localhost:5532. Run `make db-up`.")
|
|
60
|
-
db = await DB.from_url(
|
|
62
|
+
db = await DB.from_url(url)
|
|
61
63
|
await db.execute("DROP TABLE IF EXISTS users CASCADE")
|
|
62
64
|
await db.execute("DROP TABLE IF EXISTS user_roles CASCADE")
|
|
63
65
|
for stmt in POSTGRES_SCHEMA:
|
|
64
66
|
await db.execute(stmt)
|
|
67
|
+
return db
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest_asyncio.fixture
|
|
71
|
+
async def postgres_asyncpg_db():
|
|
72
|
+
db = await _open_postgres(POSTGRES_ASYNCPG_URL)
|
|
73
|
+
yield db
|
|
74
|
+
await db.close()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@pytest_asyncio.fixture
|
|
78
|
+
async def postgres_psycopg_db():
|
|
79
|
+
db = await _open_postgres(POSTGRES_PSYCOPG_URL)
|
|
65
80
|
yield db
|
|
66
81
|
await db.close()
|
|
67
82
|
|
|
68
83
|
|
|
69
|
-
@pytest.fixture(params=["sqlite_db", "
|
|
84
|
+
@pytest.fixture(params=["sqlite_db", "postgres_asyncpg_db", "postgres_psycopg_db"])
|
|
70
85
|
def db(request):
|
|
71
86
|
"""Parametrized fixture that yields each backend in turn.
|
|
72
87
|
|
|
73
|
-
Lazy resolution via `getfixturevalue` means the
|
|
74
|
-
|
|
88
|
+
Lazy resolution via `getfixturevalue` means the postgres skips
|
|
89
|
+
trigger per-param, not for the whole test.
|
|
75
90
|
"""
|
|
76
91
|
return request.getfixturevalue(request.param)
|
|
@@ -5,7 +5,7 @@ substitution since the README uses a Postgres URL for narrative).
|
|
|
5
5
|
This test guards against the README drifting from the API.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
from etchdb import DB, Row
|
|
8
|
+
from etchdb import DB, Row, sql
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class User(Row):
|
|
@@ -39,6 +39,26 @@ async def test_readme_example_round_trip():
|
|
|
39
39
|
assert updated.name == "Alice B"
|
|
40
40
|
assert updated.email == "a@example.com"
|
|
41
41
|
|
|
42
|
+
# Multi-tenant-style scoping: where= AND's onto the PK.
|
|
43
|
+
scoped = await db.update(
|
|
44
|
+
User(id=alice.id, name="Alice C"),
|
|
45
|
+
where={"email": "a@example.com"},
|
|
46
|
+
)
|
|
47
|
+
assert scoped is not None and scoped.name == "Alice C"
|
|
48
|
+
|
|
49
|
+
# Same scope-mismatch returns None and leaves the row alone.
|
|
50
|
+
miss = await db.update(
|
|
51
|
+
User(id=alice.id, name="Hacked"),
|
|
52
|
+
where={"email": "wrong@example.com"},
|
|
53
|
+
)
|
|
54
|
+
assert miss is None
|
|
55
|
+
still = await db.get(User, id=alice.id)
|
|
56
|
+
assert still is not None and still.name == "Alice C"
|
|
57
|
+
|
|
58
|
+
# Row.patch builds a partial Row without validating required fields.
|
|
59
|
+
patched = await db.update(User.patch(id=alice.id, email="b@example.com"))
|
|
60
|
+
assert patched is not None and patched.email == "b@example.com"
|
|
61
|
+
|
|
42
62
|
await db.delete(alice)
|
|
43
63
|
assert await db.get(User, id=alice.id) is None
|
|
44
64
|
|
|
@@ -57,9 +77,13 @@ async def test_readme_example_round_trip():
|
|
|
57
77
|
await tx.insert(User(name="Carol"))
|
|
58
78
|
assert (await db.fetchval("SELECT count(*) FROM users")) == 2
|
|
59
79
|
|
|
60
|
-
# Inspect SQL before executing
|
|
80
|
+
# Inspect SQL before executing (DB-bound)
|
|
61
81
|
q = db.compose("get", User, id=1)
|
|
62
82
|
assert "SELECT" in q.sql
|
|
63
83
|
assert q.params == [1]
|
|
84
|
+
|
|
85
|
+
# Same inspector adapter-free, useful in unit tests.
|
|
86
|
+
q2 = sql.compose("get", User, id=1, placeholder=lambda i: f"?{i + 1}")
|
|
87
|
+
assert q2.params == [1]
|
|
64
88
|
finally:
|
|
65
89
|
await db.close()
|
|
@@ -111,6 +111,30 @@ async def test_update_partial_preserves_unset_fields(db: DB):
|
|
|
111
111
|
assert updated.email == "original@x"
|
|
112
112
|
|
|
113
113
|
|
|
114
|
+
async def test_update_with_where_atomic_scoping(db: DB):
|
|
115
|
+
"""update with where= must scope atomically: a non-matching extra
|
|
116
|
+
filter leaves the row unchanged and returns None, no fetch-then-
|
|
117
|
+
update race window."""
|
|
118
|
+
await db.insert(User(id=1, name="Alice", email="original@x"))
|
|
119
|
+
|
|
120
|
+
# Wrong scope: row stays put.
|
|
121
|
+
result = await db.update(
|
|
122
|
+
User(id=1, name="Hacked"),
|
|
123
|
+
where={"email": "wrong@x"},
|
|
124
|
+
)
|
|
125
|
+
assert result is None
|
|
126
|
+
found = await db.get(User, id=1)
|
|
127
|
+
assert found is not None and found.name == "Alice"
|
|
128
|
+
|
|
129
|
+
# Correct scope: SET applied.
|
|
130
|
+
result = await db.update(
|
|
131
|
+
User(id=1, name="Alice B"),
|
|
132
|
+
where={"email": "original@x"},
|
|
133
|
+
)
|
|
134
|
+
assert result is not None
|
|
135
|
+
assert result.name == "Alice B"
|
|
136
|
+
|
|
137
|
+
|
|
114
138
|
async def test_update_composite_pk(db: DB):
|
|
115
139
|
await db.insert(UserRole(user_id=1, role_id=2, note="initial"))
|
|
116
140
|
await db.update(UserRole(user_id=1, role_id=2, note="changed"))
|
|
@@ -134,6 +158,20 @@ async def test_delete_composite_pk(db: DB):
|
|
|
134
158
|
assert await db.get(UserRole, user_id=1, role_id=2) is None
|
|
135
159
|
|
|
136
160
|
|
|
161
|
+
async def test_delete_with_where_scoped(db: DB):
|
|
162
|
+
"""delete with where= scopes the deletion atomically: a wrong scope
|
|
163
|
+
is a no-op, the right scope removes the row."""
|
|
164
|
+
await db.insert(User(id=1, name="Alice", email="original@x"))
|
|
165
|
+
|
|
166
|
+
# Wrong scope: row stays.
|
|
167
|
+
await db.delete(User(id=1, name="Alice"), where={"email": "wrong@x"})
|
|
168
|
+
assert await db.get(User, id=1) is not None
|
|
169
|
+
|
|
170
|
+
# Correct scope: row gone.
|
|
171
|
+
await db.delete(User(id=1, name="Alice"), where={"email": "original@x"})
|
|
172
|
+
assert await db.get(User, id=1) is None
|
|
173
|
+
|
|
174
|
+
|
|
137
175
|
# --- compose -------------------------------------------------------
|
|
138
176
|
|
|
139
177
|
|
|
@@ -8,6 +8,7 @@ fail loudly when their backing driver is unavailable.
|
|
|
8
8
|
from etchdb.adapter import AdapterBase
|
|
9
9
|
from etchdb.aiosqlite import AiosqliteAdapter
|
|
10
10
|
from etchdb.asyncpg import AsyncpgAdapter
|
|
11
|
+
from etchdb.psycopg import PsycopgAdapter
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
def test_asyncpg_placeholder_is_dollar_n():
|
|
@@ -16,6 +17,14 @@ def test_asyncpg_placeholder_is_dollar_n():
|
|
|
16
17
|
assert AsyncpgAdapter.placeholder(7) == "$8"
|
|
17
18
|
|
|
18
19
|
|
|
20
|
+
def test_psycopg_placeholder_matches_asyncpg():
|
|
21
|
+
"""psycopg uses AsyncRawCursor, so $N placeholders match asyncpg
|
|
22
|
+
exactly. Raw SQL written for one adapter runs against the other."""
|
|
23
|
+
assert PsycopgAdapter.placeholder(0) == "$1"
|
|
24
|
+
assert PsycopgAdapter.placeholder(1) == "$2"
|
|
25
|
+
assert PsycopgAdapter.placeholder(7) == "$8"
|
|
26
|
+
|
|
27
|
+
|
|
19
28
|
def test_aiosqlite_placeholder_is_question_mark():
|
|
20
29
|
assert AiosqliteAdapter.placeholder(0) == "?"
|
|
21
30
|
assert AiosqliteAdapter.placeholder(1) == "?"
|
|
@@ -25,3 +34,4 @@ def test_aiosqlite_placeholder_is_question_mark():
|
|
|
25
34
|
def test_adapters_inherit_adapter_base():
|
|
26
35
|
assert issubclass(AsyncpgAdapter, AdapterBase)
|
|
27
36
|
assert issubclass(AiosqliteAdapter, AdapterBase)
|
|
37
|
+
assert issubclass(PsycopgAdapter, AdapterBase)
|
|
@@ -14,9 +14,21 @@ async def test_from_url_unsupported_scheme_raises():
|
|
|
14
14
|
await DB.from_url("mysql://x@y/z")
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
async def
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
async def test_from_url_psycopg_dispatches_to_adapter(monkeypatch):
|
|
18
|
+
"""Confirm the psycopg URL routes to PsycopgAdapter.from_url with the
|
|
19
|
+
+psycopg prefix stripped, without opening a real connection."""
|
|
20
|
+
from etchdb.psycopg import PsycopgAdapter
|
|
21
|
+
|
|
22
|
+
captured: dict[str, str] = {}
|
|
23
|
+
|
|
24
|
+
async def fake_from_url(cls, url: str) -> PsycopgAdapter:
|
|
25
|
+
captured["url"] = url
|
|
26
|
+
return cls.__new__(cls)
|
|
27
|
+
|
|
28
|
+
monkeypatch.setattr(PsycopgAdapter, "from_url", classmethod(fake_from_url))
|
|
29
|
+
|
|
30
|
+
await DB.from_url("postgresql+psycopg://user:pw@host:5432/dbname")
|
|
31
|
+
assert captured["url"] == "postgresql://user:pw@host:5432/dbname"
|
|
20
32
|
|
|
21
33
|
|
|
22
34
|
@pytest.mark.parametrize("url", ["sqlite:///:memory:", "sqlite+aiosqlite:///:memory:"])
|
|
@@ -308,6 +308,55 @@ def test_update_attribute_assignment_tracks_in_fields_set():
|
|
|
308
308
|
assert q.params == ["Alice", "new@example.com", 1]
|
|
309
309
|
|
|
310
310
|
|
|
311
|
+
def test_update_with_extra_where_pg():
|
|
312
|
+
"""`where=` AND's extra equality filters onto the PK-only WHERE."""
|
|
313
|
+
user = User(id=1, name="Alice")
|
|
314
|
+
q = sql.update(user, placeholder=pg, where={"tenant_id": 5})
|
|
315
|
+
|
|
316
|
+
assert q.sql == "UPDATE users SET name = $1 WHERE id = $2 AND tenant_id = $3"
|
|
317
|
+
assert q.params == ["Alice", 1, 5]
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def test_update_with_extra_where_sqlite():
|
|
321
|
+
user = User(id=1, name="Alice")
|
|
322
|
+
q = sql.update(user, placeholder=lite, where={"tenant_id": 5})
|
|
323
|
+
|
|
324
|
+
assert q.sql == "UPDATE users SET name = ? WHERE id = ? AND tenant_id = ?"
|
|
325
|
+
assert q.params == ["Alice", 1, 5]
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def test_update_with_returning_and_extra_where():
|
|
329
|
+
user = User(id=1, name="Alice")
|
|
330
|
+
q = sql.update(user, placeholder=pg, returning="*", where={"tenant_id": 5})
|
|
331
|
+
|
|
332
|
+
assert q.sql == ("UPDATE users SET name = $1 WHERE id = $2 AND tenant_id = $3 RETURNING *")
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def test_update_where_overlapping_pk_raises():
|
|
336
|
+
"""Re-specifying a PK field in where= would produce a confusing
|
|
337
|
+
`id = $a AND id = $b` clause; reject it."""
|
|
338
|
+
user = User(id=1, name="Alice")
|
|
339
|
+
with pytest.raises(ValueError, match=r"overlap with __pk__"):
|
|
340
|
+
sql.update(user, placeholder=pg, where={"id": 99})
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def test_update_with_empty_where_is_same_as_no_where():
|
|
344
|
+
"""An empty mapping adds no extra filters, identical to where=None."""
|
|
345
|
+
user = User(id=1, name="Alice")
|
|
346
|
+
q_none = sql.update(user, placeholder=pg)
|
|
347
|
+
q_empty = sql.update(user, placeholder=pg, where={})
|
|
348
|
+
assert q_empty.sql == q_none.sql
|
|
349
|
+
assert q_empty.params == q_none.params
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def test_delete_with_empty_where_is_same_as_no_where():
|
|
353
|
+
user = User(id=1, name="Alice")
|
|
354
|
+
q_none = sql.delete(user, placeholder=pg)
|
|
355
|
+
q_empty = sql.delete(user, placeholder=pg, where={})
|
|
356
|
+
assert q_empty.sql == q_none.sql
|
|
357
|
+
assert q_empty.params == q_none.params
|
|
358
|
+
|
|
359
|
+
|
|
311
360
|
def test_update_unset_pk_raises():
|
|
312
361
|
"""Without an explicit id, WHERE would silently match nothing; raise
|
|
313
362
|
instead so the caller notices."""
|
|
@@ -316,6 +365,33 @@ def test_update_unset_pk_raises():
|
|
|
316
365
|
sql.update(user, placeholder=pg)
|
|
317
366
|
|
|
318
367
|
|
|
368
|
+
def test_update_via_row_patch_emits_only_set_fields():
|
|
369
|
+
"""Row.patch lets a model with required fields produce a partial
|
|
370
|
+
update without Optional-everywhere lying about the schema."""
|
|
371
|
+
q = sql.update(User.patch(id=1, name="Alice B"), placeholder=pg)
|
|
372
|
+
|
|
373
|
+
assert q.sql == "UPDATE users SET name = $1 WHERE id = $2"
|
|
374
|
+
assert q.params == ["Alice B", 1]
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def test_row_patch_skips_validation():
|
|
378
|
+
"""patch() uses model_construct, so required fields don't need
|
|
379
|
+
placeholder values when only updating a subset."""
|
|
380
|
+
|
|
381
|
+
class StrictNote(Row):
|
|
382
|
+
__table__ = "notes"
|
|
383
|
+
id: int
|
|
384
|
+
body: str # NOT NULL in DB
|
|
385
|
+
status: str # NOT NULL in DB
|
|
386
|
+
|
|
387
|
+
# Plain construction would raise ValidationError for missing body.
|
|
388
|
+
note = StrictNote.patch(id=1, status="archived")
|
|
389
|
+
assert note.model_fields_set == {"id", "status"}
|
|
390
|
+
q = sql.update(note, placeholder=pg)
|
|
391
|
+
assert q.sql == "UPDATE notes SET status = $1 WHERE id = $2"
|
|
392
|
+
assert q.params == ["archived", 1]
|
|
393
|
+
|
|
394
|
+
|
|
319
395
|
def test_update_partial_composite_pk_raises():
|
|
320
396
|
"""Even one missing PK component is enough to identify nothing."""
|
|
321
397
|
role = UserRole.model_construct(user_id=1, note="x") # role_id not set
|
|
@@ -362,6 +438,30 @@ def test_delete_unset_pk_raises():
|
|
|
362
438
|
sql.delete(user, placeholder=pg)
|
|
363
439
|
|
|
364
440
|
|
|
441
|
+
def test_delete_with_extra_where_pg():
|
|
442
|
+
# delete only consults the PK + where=, but the Row's other fields
|
|
443
|
+
# need to satisfy Pydantic validation at construction time.
|
|
444
|
+
user = User(id=1, name="Alice")
|
|
445
|
+
q = sql.delete(user, placeholder=pg, where={"tenant_id": 5})
|
|
446
|
+
|
|
447
|
+
assert q.sql == "DELETE FROM users WHERE id = $1 AND tenant_id = $2"
|
|
448
|
+
assert q.params == [1, 5]
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def test_delete_with_extra_where_sqlite():
|
|
452
|
+
user = User(id=1, name="Alice")
|
|
453
|
+
q = sql.delete(user, placeholder=lite, where={"tenant_id": 5})
|
|
454
|
+
|
|
455
|
+
assert q.sql == "DELETE FROM users WHERE id = ? AND tenant_id = ?"
|
|
456
|
+
assert q.params == [1, 5]
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def test_delete_where_overlapping_pk_raises():
|
|
460
|
+
user = User(id=1, name="Alice")
|
|
461
|
+
with pytest.raises(ValueError, match=r"overlap with __pk__"):
|
|
462
|
+
sql.delete(user, placeholder=pg, where={"id": 99})
|
|
463
|
+
|
|
464
|
+
|
|
365
465
|
# --- error cases -----------------------------------------------------
|
|
366
466
|
|
|
367
467
|
|
|
@@ -380,3 +480,36 @@ def test_select_without_table_raises():
|
|
|
380
480
|
|
|
381
481
|
with pytest.raises(ValueError, match="__table__"):
|
|
382
482
|
sql.select_one(NoTable, placeholder=pg, id=1)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# --- compose ---------------------------------------------------------
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def test_sql_compose_get_without_adapter():
|
|
489
|
+
"""sql.compose works in plain Python: no DB, no adapter, just a
|
|
490
|
+
placeholder callable."""
|
|
491
|
+
q = sql.compose("get", User, placeholder=pg, id=1)
|
|
492
|
+
|
|
493
|
+
assert q.sql == "SELECT id, name, email FROM users WHERE id = $1 LIMIT 1"
|
|
494
|
+
assert q.params == [1]
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def test_sql_compose_for_each_op():
|
|
498
|
+
user = User(id=1, name="Alice", email="a@x")
|
|
499
|
+
|
|
500
|
+
q_insert = sql.compose("insert", user, placeholder=pg)
|
|
501
|
+
assert q_insert.sql.startswith("INSERT INTO users")
|
|
502
|
+
|
|
503
|
+
q_update = sql.compose("update", user, placeholder=pg)
|
|
504
|
+
assert q_update.sql.startswith("UPDATE users")
|
|
505
|
+
|
|
506
|
+
q_delete = sql.compose("delete", user, placeholder=pg)
|
|
507
|
+
assert q_delete.sql.startswith("DELETE FROM users")
|
|
508
|
+
|
|
509
|
+
q_query = sql.compose("query", User, placeholder=pg, limit=5)
|
|
510
|
+
assert "LIMIT" in q_query.sql
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def test_sql_compose_unknown_op_raises():
|
|
514
|
+
with pytest.raises(ValueError, match="Unknown op"):
|
|
515
|
+
sql.compose("frobnicate", User, placeholder=pg) # type: ignore[arg-type]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|