etchdb 0.6.0__tar.gz → 0.6.1__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/.github/workflows/ci.yml +76 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/PKG-INFO +6 -3
- {etchdb-0.6.0 → etchdb-0.6.1}/README.md +5 -2
- {etchdb-0.6.0 → etchdb-0.6.1}/pyproject.toml +1 -1
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/__init__.py +1 -1
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/db.py +14 -14
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/sql/__init__.py +76 -11
- etchdb-0.6.1/tests/integration/test_iter_rows_keyset.py +184 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/unit/test_sql_emitter.py +87 -17
- etchdb-0.6.0/tests/integration/test_iter_rows_keyset.py +0 -93
- {etchdb-0.6.0 → etchdb-0.6.1}/.github/workflows/release.yml +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/.gitignore +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/.python-version +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/LICENSE +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/Makefile +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/docker-compose.yml +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/__main__.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/adapter.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/aiosqlite/__init__.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/aiosqlite/adapter.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/asyncpg/__init__.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/asyncpg/adapter.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/cli.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/codecs.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/errors.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/expr.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/migrations.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/psycopg/__init__.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/psycopg/adapter.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/py.typed +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/query.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/src/etchdb/row.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/__init__.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/_models.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/__init__.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/conftest.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_batch.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_cli.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_codecs.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_errors.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_execute_rowcount.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_expressions.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_facade.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_fields_not_in_db.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_in_filter.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_is_null.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_iter_rows.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_migrations.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_ping_and_aclose.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_pool_kwargs.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_readme_example.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_typed_crud.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/integration/test_update_where.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/unit/__init__.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/unit/test_adapters.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/unit/test_cli.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/unit/test_db_dispatch.py +0 -0
- {etchdb-0.6.0 → etchdb-0.6.1}/tests/unit/test_migrations.py +0 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
# Runs on every push to main and every pull request. Three jobs:
|
|
4
|
+
# - lint: ruff on src + tests (single Python)
|
|
5
|
+
# - unit: pytest tests/unit across the full supported Python matrix
|
|
6
|
+
# - integration: pytest tests/integration across the matrix, with a
|
|
7
|
+
# Postgres 16 service container. SQLite always runs; the two
|
|
8
|
+
# Postgres adapters point at the service via ETCHDB_TEST_POSTGRES_DSN.
|
|
9
|
+
|
|
10
|
+
on:
|
|
11
|
+
push:
|
|
12
|
+
branches: [main]
|
|
13
|
+
pull_request:
|
|
14
|
+
|
|
15
|
+
concurrency:
|
|
16
|
+
group: ci-${{ github.ref }}
|
|
17
|
+
cancel-in-progress: true
|
|
18
|
+
|
|
19
|
+
jobs:
|
|
20
|
+
lint:
|
|
21
|
+
runs-on: ubuntu-latest
|
|
22
|
+
steps:
|
|
23
|
+
- uses: actions/checkout@v4
|
|
24
|
+
- uses: astral-sh/setup-uv@v5
|
|
25
|
+
with:
|
|
26
|
+
python-version: "3.14"
|
|
27
|
+
cache-dependency-glob: "pyproject.toml"
|
|
28
|
+
- run: uv sync --extra dev
|
|
29
|
+
- run: uv run ruff check src/etchdb tests
|
|
30
|
+
|
|
31
|
+
unit:
|
|
32
|
+
runs-on: ubuntu-latest
|
|
33
|
+
strategy:
|
|
34
|
+
fail-fast: false
|
|
35
|
+
matrix:
|
|
36
|
+
python-version: ["3.12", "3.13", "3.14"]
|
|
37
|
+
steps:
|
|
38
|
+
- uses: actions/checkout@v4
|
|
39
|
+
- uses: astral-sh/setup-uv@v5
|
|
40
|
+
with:
|
|
41
|
+
python-version: ${{ matrix.python-version }}
|
|
42
|
+
cache-dependency-glob: "pyproject.toml"
|
|
43
|
+
- run: uv sync --extra all --extra dev
|
|
44
|
+
- run: uv run pytest tests/unit -q
|
|
45
|
+
|
|
46
|
+
integration:
|
|
47
|
+
runs-on: ubuntu-latest
|
|
48
|
+
strategy:
|
|
49
|
+
fail-fast: false
|
|
50
|
+
matrix:
|
|
51
|
+
python-version: ["3.12", "3.13", "3.14"]
|
|
52
|
+
services:
|
|
53
|
+
postgres:
|
|
54
|
+
image: postgres:16
|
|
55
|
+
env:
|
|
56
|
+
POSTGRES_USER: etchdb
|
|
57
|
+
POSTGRES_PASSWORD: etchdb-test-password
|
|
58
|
+
POSTGRES_DB: etchdb_test
|
|
59
|
+
ports:
|
|
60
|
+
# conftest probes localhost:5532 (matches local `make db-up`);
|
|
61
|
+
# expose the service on the same port so no env override is
|
|
62
|
+
# needed and the Postgres skip-guard sees the service.
|
|
63
|
+
- 5532:5432
|
|
64
|
+
options: >-
|
|
65
|
+
--health-cmd pg_isready
|
|
66
|
+
--health-interval 10s
|
|
67
|
+
--health-timeout 5s
|
|
68
|
+
--health-retries 5
|
|
69
|
+
steps:
|
|
70
|
+
- uses: actions/checkout@v4
|
|
71
|
+
- uses: astral-sh/setup-uv@v5
|
|
72
|
+
with:
|
|
73
|
+
python-version: ${{ matrix.python-version }}
|
|
74
|
+
cache-dependency-glob: "pyproject.toml"
|
|
75
|
+
- run: uv sync --extra all --extra dev
|
|
76
|
+
- run: uv run pytest tests/integration -q
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: etchdb
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.1
|
|
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
|
|
@@ -130,8 +130,11 @@ alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
|
130
130
|
async for user in db.iter_rows(User, batch_size=500):
|
|
131
131
|
process(user)
|
|
132
132
|
|
|
133
|
-
# For huge tables, iter_rows_keyset stays O(N) by emitting
|
|
134
|
-
# `
|
|
133
|
+
# For huge tables, iter_rows_keyset stays O(N) by emitting a
|
|
134
|
+
# `(by, *pk_tail) > last_seen` cursor per page. PK tail breaks
|
|
135
|
+
# ties and lets the cursor paginate through NULL values. Order
|
|
136
|
+
# is `ORDER BY by NULLS FIRST` -- deterministic across backends.
|
|
137
|
+
# `by` defaults to __pk__[0]. SQLite 3.30+ required.
|
|
135
138
|
async for user in db.iter_rows_keyset(User, batch_size=500):
|
|
136
139
|
process(user)
|
|
137
140
|
|
|
@@ -68,8 +68,11 @@ alice = await db.insert(User(id=1, name="Alice", email="a@x"),
|
|
|
68
68
|
async for user in db.iter_rows(User, batch_size=500):
|
|
69
69
|
process(user)
|
|
70
70
|
|
|
71
|
-
# For huge tables, iter_rows_keyset stays O(N) by emitting
|
|
72
|
-
# `
|
|
71
|
+
# For huge tables, iter_rows_keyset stays O(N) by emitting a
|
|
72
|
+
# `(by, *pk_tail) > last_seen` cursor per page. PK tail breaks
|
|
73
|
+
# ties and lets the cursor paginate through NULL values. Order
|
|
74
|
+
# is `ORDER BY by NULLS FIRST` -- deterministic across backends.
|
|
75
|
+
# `by` defaults to __pk__[0]. SQLite 3.30+ required.
|
|
73
76
|
async for user in db.iter_rows_keyset(User, batch_size=500):
|
|
74
77
|
process(user)
|
|
75
78
|
|
|
@@ -248,19 +248,18 @@ class DB:
|
|
|
248
248
|
) -> AsyncIterator[Row]:
|
|
249
249
|
"""Stream every matching row via keyset pagination.
|
|
250
250
|
|
|
251
|
-
Unlike `iter_rows`,
|
|
252
|
-
|
|
251
|
+
Unlike `iter_rows`, per-page cost stays constant: each page
|
|
252
|
+
reads `batch_size` rows via `WHERE (by, *pk_tail) > (...)`
|
|
253
253
|
rather than `OFFSET N`, so total cost is O(N) instead of
|
|
254
|
-
O(N^2).
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
cursor. Ordering is ascending; descending is not supported.
|
|
254
|
+
O(N^2). `by` must be a single DB-orderable column. PK columns
|
|
255
|
+
break ties on `by` and let the cursor paginate through NULL
|
|
256
|
+
values; the cursor is `[by] + [p for p in __pk__ if p != by]`.
|
|
257
|
+
|
|
258
|
+
`by` defaults to `model.__pk__[0]` (composite PK requires
|
|
259
|
+
explicit `by=`). Filters are AND'd with the cursor. Ordering
|
|
260
|
+
is ascending with `NULLS FIRST` -- NULL rows iterate first
|
|
261
|
+
on every backend. Descending is not supported. SQLite 3.30+
|
|
262
|
+
is required (for the `NULLS FIRST` keyword).
|
|
264
263
|
"""
|
|
265
264
|
if batch_size < 1:
|
|
266
265
|
raise ValueError(f"batch_size must be >= 1, got {batch_size}")
|
|
@@ -274,7 +273,8 @@ class DB:
|
|
|
274
273
|
)
|
|
275
274
|
by = model.__pk__[0]
|
|
276
275
|
|
|
277
|
-
|
|
276
|
+
order_cols = [by] + [p for p in model.__pk__ if p != by]
|
|
277
|
+
last_seen: list[Any] | None = None
|
|
278
278
|
while True:
|
|
279
279
|
q = sql.select_keyset(
|
|
280
280
|
model,
|
|
@@ -291,7 +291,7 @@ class DB:
|
|
|
291
291
|
yield model(**row)
|
|
292
292
|
if len(rows) < batch_size:
|
|
293
293
|
return
|
|
294
|
-
last_seen = rows[-1][
|
|
294
|
+
last_seen = [rows[-1][c] for c in order_cols]
|
|
295
295
|
|
|
296
296
|
async def insert(self, row: Row, *, on_conflict: sql._OnConflict = None) -> Row:
|
|
297
297
|
"""Insert `row` and return the DB's view (RETURNING *).
|
|
@@ -146,40 +146,105 @@ def select_keyset(
|
|
|
146
146
|
placeholder: Callable[[int], str],
|
|
147
147
|
by: str,
|
|
148
148
|
batch_size: int,
|
|
149
|
-
last_seen: Any = None,
|
|
149
|
+
last_seen: Sequence[Any] | None = None,
|
|
150
150
|
**filters: Any,
|
|
151
151
|
) -> SqlQuery:
|
|
152
152
|
"""Build a single page of a keyset-paginated SELECT.
|
|
153
153
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
`
|
|
157
|
-
|
|
154
|
+
Cursor columns are `[by] + [p for p in __pk__ if p != by]`, so the
|
|
155
|
+
cursor is unique (PK tail breaks ties). `last_seen` is a sequence
|
|
156
|
+
aligned with those columns; `None` drops the cursor predicate
|
|
157
|
+
(first page). `ORDER BY ... NULLS FIRST` is explicit so NULL rows
|
|
158
|
+
iterate first on every backend (Postgres default would be NULLS
|
|
159
|
+
LAST otherwise; SQLite already defaults NULLS FIRST). SQLite 3.30+
|
|
160
|
+
is required.
|
|
161
|
+
|
|
162
|
+
Three WHERE shapes, branched on `last_seen` state:
|
|
163
|
+
first page -- no cursor predicate
|
|
164
|
+
NULL region -- (by IS NULL AND <pk_cursor>) OR by IS NOT NULL
|
|
165
|
+
past NULL -- (by, *pk_tail) > (last_by, *last_pk_tail)
|
|
166
|
+
|
|
167
|
+
Single-column cursor (1 PK col and by == that col) degenerates to
|
|
168
|
+
the scalar form `by > $k` so we never emit one-element row-value
|
|
169
|
+
syntax. The OR-group is fully parenthesized inside the AND chain
|
|
170
|
+
so filters and the cursor compose correctly.
|
|
158
171
|
"""
|
|
159
|
-
if by not in _db_fields(row_class):
|
|
160
|
-
raise ValueError(f"keyset column {by!r} is not a DB column on {row_class.__name__}.")
|
|
161
172
|
if by in filters:
|
|
162
173
|
raise ValueError(f"keyset column {by!r} cannot also appear in filters.")
|
|
163
174
|
|
|
175
|
+
db_fields = _db_fields(row_class)
|
|
176
|
+
order_cols = [by] + [p for p in row_class.__pk__ if p != by]
|
|
177
|
+
for col in order_cols:
|
|
178
|
+
if col not in db_fields:
|
|
179
|
+
raise ValueError(
|
|
180
|
+
f"keyset column {col!r} is not a DB column on {row_class.__name__}."
|
|
181
|
+
)
|
|
182
|
+
|
|
164
183
|
table = _table_name(row_class)
|
|
165
|
-
columns = ", ".join(
|
|
184
|
+
columns = ", ".join(db_fields)
|
|
166
185
|
where_sql, params = _where_clauses(filters, placeholder=placeholder)
|
|
167
186
|
where_parts = [where_sql] if where_sql else []
|
|
168
187
|
|
|
169
188
|
if last_seen is not None:
|
|
170
|
-
|
|
171
|
-
|
|
189
|
+
if len(last_seen) != len(order_cols):
|
|
190
|
+
raise ValueError(
|
|
191
|
+
f"last_seen has {len(last_seen)} values but cursor has "
|
|
192
|
+
f"{len(order_cols)} columns ({order_cols})."
|
|
193
|
+
)
|
|
194
|
+
cursor_sql, cursor_values = _keyset_cursor_sql(
|
|
195
|
+
order_cols, last_seen, placeholder, start=len(params)
|
|
196
|
+
)
|
|
197
|
+
where_parts.append(cursor_sql)
|
|
198
|
+
params.extend(cursor_values)
|
|
172
199
|
|
|
173
200
|
sql = f"SELECT {columns} FROM {table}"
|
|
174
201
|
if where_parts:
|
|
175
202
|
sql += f" WHERE {' AND '.join(where_parts)}"
|
|
176
|
-
|
|
203
|
+
order_by = ", ".join([f"{order_cols[0]} NULLS FIRST", *order_cols[1:]])
|
|
204
|
+
sql += f" ORDER BY {order_by}"
|
|
177
205
|
params.append(batch_size)
|
|
178
206
|
sql += f" LIMIT {placeholder(len(params) - 1)}"
|
|
179
207
|
|
|
180
208
|
return SqlQuery(sql=sql, params=params)
|
|
181
209
|
|
|
182
210
|
|
|
211
|
+
def _keyset_cursor_sql(
|
|
212
|
+
order_cols: list[str],
|
|
213
|
+
last_seen: Sequence[Any],
|
|
214
|
+
placeholder: Callable[[int], str],
|
|
215
|
+
*,
|
|
216
|
+
start: int,
|
|
217
|
+
) -> tuple[str, list[Any]]:
|
|
218
|
+
"""Emit the WHERE cursor predicate. Returns `(sql, bound_values)`.
|
|
219
|
+
|
|
220
|
+
`start` is the offset for placeholder numbering -- `start + i` is
|
|
221
|
+
the param index for value `i`, so the caller controls placement in
|
|
222
|
+
its own params list.
|
|
223
|
+
"""
|
|
224
|
+
by = order_cols[0]
|
|
225
|
+
|
|
226
|
+
def _gt(cols: list[str], values: Sequence[Any], offset: int) -> str:
|
|
227
|
+
lhs = ", ".join(cols)
|
|
228
|
+
rhs = ", ".join(placeholder(offset + i) for i in range(len(values)))
|
|
229
|
+
if len(cols) == 1:
|
|
230
|
+
return f"{lhs} > {rhs}"
|
|
231
|
+
return f"({lhs}) > ({rhs})"
|
|
232
|
+
|
|
233
|
+
if last_seen[0] is None:
|
|
234
|
+
pk_tail = order_cols[1:]
|
|
235
|
+
if not pk_tail:
|
|
236
|
+
raise ValueError(
|
|
237
|
+
f"keyset cursor has NULL in {by!r} but no PK tie-breaker "
|
|
238
|
+
f"is available (single-PK case where by IS pk)."
|
|
239
|
+
)
|
|
240
|
+
values = list(last_seen[1:])
|
|
241
|
+
pk_cursor = _gt(pk_tail, values, start)
|
|
242
|
+
return f"(({by} IS NULL AND {pk_cursor}) OR {by} IS NOT NULL)", values
|
|
243
|
+
|
|
244
|
+
values = list(last_seen)
|
|
245
|
+
return _gt(order_cols, values, start), values
|
|
246
|
+
|
|
247
|
+
|
|
183
248
|
def update(
|
|
184
249
|
row: Row,
|
|
185
250
|
*,
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Integration tests for db.iter_rows_keyset across all three backends.
|
|
2
|
+
|
|
3
|
+
The keyset iterator emits `WHERE <by> > <last_seen>` per page, so total
|
|
4
|
+
cost stays O(N) rather than O(N^2) like `iter_rows`. Tests pin: full
|
|
5
|
+
ordered yield, batch boundaries, filter propagation, default `by`
|
|
6
|
+
column, explicit `by` override, and the input validation."""
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from etchdb import DB
|
|
11
|
+
from tests._models import User
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def test_iter_rows_keyset_yields_all_rows_ordered(db: DB):
|
|
15
|
+
for i in range(1, 8):
|
|
16
|
+
await db.insert(User(id=i, name=f"u{i}"))
|
|
17
|
+
|
|
18
|
+
rows = [u async for u in db.iter_rows_keyset(User, batch_size=3)]
|
|
19
|
+
|
|
20
|
+
assert [u.id for u in rows] == [1, 2, 3, 4, 5, 6, 7]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def test_iter_rows_keyset_uses_pk_by_default(db: DB):
|
|
24
|
+
"""`by=None` defaults to `model.__pk__[0]`; pagination still
|
|
25
|
+
works when the user doesn't specify the column."""
|
|
26
|
+
for i in range(1, 4):
|
|
27
|
+
await db.insert(User(id=i, name=f"u{i}"))
|
|
28
|
+
|
|
29
|
+
rows = [u async for u in db.iter_rows_keyset(User)]
|
|
30
|
+
|
|
31
|
+
assert [u.id for u in rows] == [1, 2, 3]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def test_iter_rows_keyset_filter_propagates(db: DB):
|
|
35
|
+
"""Extra filter kwargs are AND'd with the keyset cursor on every
|
|
36
|
+
page. Only rows that match the filter are yielded."""
|
|
37
|
+
await db.insert(User(id=1, name="alice"))
|
|
38
|
+
await db.insert(User(id=2, name="bob"))
|
|
39
|
+
await db.insert(User(id=3, name="alice"))
|
|
40
|
+
await db.insert(User(id=4, name="bob"))
|
|
41
|
+
|
|
42
|
+
rows = [u async for u in db.iter_rows_keyset(User, batch_size=2, name="alice")]
|
|
43
|
+
|
|
44
|
+
assert [u.id for u in rows] == [1, 3]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def test_iter_rows_keyset_empty_table_yields_nothing(db: DB):
|
|
48
|
+
rows = [u async for u in db.iter_rows_keyset(User)]
|
|
49
|
+
assert rows == []
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def test_iter_rows_keyset_rejects_non_positive_batch_size(db: DB):
|
|
53
|
+
with pytest.raises(ValueError, match="batch_size"):
|
|
54
|
+
async for _ in db.iter_rows_keyset(User, batch_size=0):
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def test_iter_rows_keyset_rejects_by_in_filters(db: DB):
|
|
59
|
+
"""If the user already constrains the keyset column via a filter,
|
|
60
|
+
the cursor's `>` predicate plus their `=` predicate would be
|
|
61
|
+
over-determined. Reject up front."""
|
|
62
|
+
with pytest.raises(ValueError, match="cannot also appear in filters"):
|
|
63
|
+
async for _ in db.iter_rows_keyset(User, by="id", id=5):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def test_iter_rows_keyset_empty_list_filter_short_circuits(db: DB):
|
|
68
|
+
"""Empty-list filter follows the same short-circuit convention as
|
|
69
|
+
iter_rows / query / get; nothing is yielded, no round trip."""
|
|
70
|
+
await db.insert(User(id=1, name="alice"))
|
|
71
|
+
rows = [u async for u in db.iter_rows_keyset(User, id=[])]
|
|
72
|
+
assert rows == []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def test_iter_rows_keyset_composite_pk_requires_explicit_by(db: DB):
|
|
76
|
+
"""Defaulting `by` to `__pk__[0]` on a composite PK can silently
|
|
77
|
+
duplicate or skip rows when the leading column ties. Refuse and
|
|
78
|
+
point the user at the explicit `by=` form."""
|
|
79
|
+
from tests._models import UserRole
|
|
80
|
+
|
|
81
|
+
with pytest.raises(ValueError, match="composite PK"):
|
|
82
|
+
async for _ in db.iter_rows_keyset(UserRole):
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def test_iter_rows_keyset_rejects_non_db_column(db: DB):
|
|
87
|
+
"""If the user passes `by=<col>` for a field that isn't a DB
|
|
88
|
+
column (e.g. excluded via __fields_not_in_db__), the row dict
|
|
89
|
+
won't carry it and the cursor advance would KeyError mid-loop.
|
|
90
|
+
Catch the misuse before the first query."""
|
|
91
|
+
with pytest.raises(ValueError, match="not a DB column"):
|
|
92
|
+
async for _ in db.iter_rows_keyset(User, by="nonexistent_col"):
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def test_iter_rows_keyset_paginates_through_all_nulls(db: DB):
|
|
97
|
+
"""Every row has `email=NULL`. Cursor advances via the PK tail
|
|
98
|
+
(id) inside the NULL region and terminates correctly."""
|
|
99
|
+
for i in range(1, 5):
|
|
100
|
+
await db.insert(User(id=i, name=f"u{i}", email=None))
|
|
101
|
+
|
|
102
|
+
rows = [u async for u in db.iter_rows_keyset(User, by="email", batch_size=2)]
|
|
103
|
+
|
|
104
|
+
assert [u.id for u in rows] == [1, 2, 3, 4]
|
|
105
|
+
assert all(u.email is None for u in rows)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def test_iter_rows_keyset_paginates_through_mixed_nulls(db: DB):
|
|
109
|
+
"""Mixed NULL + non-NULL with NULL at a full-page boundary --
|
|
110
|
+
the failure mode from issue #1. With explicit NULLS FIRST and a
|
|
111
|
+
compound cursor, NULL rows come first and we paginate through
|
|
112
|
+
cleanly."""
|
|
113
|
+
await db.insert(User(id=1, name="u1", email=None))
|
|
114
|
+
await db.insert(User(id=2, name="u2", email=None))
|
|
115
|
+
await db.insert(User(id=3, name="u3", email="a@x"))
|
|
116
|
+
await db.insert(User(id=4, name="u4", email="b@x"))
|
|
117
|
+
|
|
118
|
+
rows = [u async for u in db.iter_rows_keyset(User, by="email", batch_size=2)]
|
|
119
|
+
|
|
120
|
+
assert [u.id for u in rows] == [1, 2, 3, 4]
|
|
121
|
+
assert [u.email for u in rows] == [None, None, "a@x", "b@x"]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def test_iter_rows_keyset_paginates_through_tied_values(db: DB):
|
|
125
|
+
"""Same `email` on every row. The PK tail breaks ties so all
|
|
126
|
+
rows yield in id order; with the pre-fix `WHERE by > last_seen`
|
|
127
|
+
cursor, only the first page would be yielded."""
|
|
128
|
+
for i in range(1, 5):
|
|
129
|
+
await db.insert(User(id=i, name=f"u{i}", email="same@x"))
|
|
130
|
+
|
|
131
|
+
rows = [u async for u in db.iter_rows_keyset(User, by="email", batch_size=2)]
|
|
132
|
+
|
|
133
|
+
assert [u.id for u in rows] == [1, 2, 3, 4]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
async def test_iter_rows_keyset_paginates_through_nulls_and_ties(db: DB):
|
|
137
|
+
"""Combination case: some NULLs, two distinct non-NULL values
|
|
138
|
+
each repeated. Order must be NULLs first then non-NULL groups,
|
|
139
|
+
tie-broken by id within each group."""
|
|
140
|
+
await db.insert(User(id=1, name="u1", email=None))
|
|
141
|
+
await db.insert(User(id=2, name="u2", email=None))
|
|
142
|
+
await db.insert(User(id=3, name="u3", email="a@x"))
|
|
143
|
+
await db.insert(User(id=4, name="u4", email="a@x"))
|
|
144
|
+
await db.insert(User(id=5, name="u5", email="b@x"))
|
|
145
|
+
await db.insert(User(id=6, name="u6", email="b@x"))
|
|
146
|
+
|
|
147
|
+
rows = [u async for u in db.iter_rows_keyset(User, by="email", batch_size=2)]
|
|
148
|
+
|
|
149
|
+
assert [u.id for u in rows] == [1, 2, 3, 4, 5, 6]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
async def test_iter_rows_keyset_composite_pk_tie_break(db: DB):
|
|
153
|
+
"""Non-PK `by` on a composite-PK model. Ties in `by` resolve via
|
|
154
|
+
both PK columns chained, so the cursor advances correctly when
|
|
155
|
+
a non-PK column duplicates across PK combinations."""
|
|
156
|
+
from tests._models import UserRole
|
|
157
|
+
|
|
158
|
+
await db.insert(UserRole(user_id=1, role_id=10, note="x"))
|
|
159
|
+
await db.insert(UserRole(user_id=1, role_id=20, note="x"))
|
|
160
|
+
await db.insert(UserRole(user_id=2, role_id=10, note="x"))
|
|
161
|
+
await db.insert(UserRole(user_id=2, role_id=20, note="y"))
|
|
162
|
+
|
|
163
|
+
rows = [u async for u in db.iter_rows_keyset(UserRole, by="note", batch_size=2)]
|
|
164
|
+
|
|
165
|
+
assert [(r.user_id, r.role_id, r.note) for r in rows] == [
|
|
166
|
+
(1, 10, "x"),
|
|
167
|
+
(1, 20, "x"),
|
|
168
|
+
(2, 10, "x"),
|
|
169
|
+
(2, 20, "y"),
|
|
170
|
+
]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def test_iter_rows_keyset_filter_with_nulls_and_ties(db: DB):
|
|
174
|
+
"""Filter AND'd with the cursor predicate -- exercises the
|
|
175
|
+
parenthesization of the OR-group inside the WHERE chain."""
|
|
176
|
+
await db.insert(User(id=1, name="alice", email=None))
|
|
177
|
+
await db.insert(User(id=2, name="bob", email=None))
|
|
178
|
+
await db.insert(User(id=3, name="alice", email="a@x"))
|
|
179
|
+
await db.insert(User(id=4, name="alice", email="a@x"))
|
|
180
|
+
await db.insert(User(id=5, name="bob", email="a@x"))
|
|
181
|
+
|
|
182
|
+
rows = [u async for u in db.iter_rows_keyset(User, by="email", batch_size=2, name="alice")]
|
|
183
|
+
|
|
184
|
+
assert [u.id for u in rows] == [1, 3, 4]
|
|
@@ -748,35 +748,98 @@ def test_insert_many_with_now_raises():
|
|
|
748
748
|
# --- select_keyset: single page of cursor-paginated SELECT ------------
|
|
749
749
|
|
|
750
750
|
|
|
751
|
-
def
|
|
752
|
-
"""First page
|
|
753
|
-
|
|
751
|
+
def test_select_keyset_first_page_emits_nulls_first_pg():
|
|
752
|
+
"""First page drops the cursor predicate and emits explicit
|
|
753
|
+
NULLS FIRST so iteration order is deterministic across backends."""
|
|
754
754
|
q = sql.select_keyset(User, placeholder=pg, by="id", batch_size=3)
|
|
755
|
-
assert q.sql == "SELECT id, name, email FROM users ORDER BY id LIMIT $1"
|
|
755
|
+
assert q.sql == "SELECT id, name, email FROM users ORDER BY id NULLS FIRST LIMIT $1"
|
|
756
756
|
assert q.params == [3]
|
|
757
757
|
|
|
758
758
|
|
|
759
|
-
def
|
|
760
|
-
"""
|
|
761
|
-
|
|
762
|
-
|
|
759
|
+
def test_select_keyset_by_pk_emits_scalar_cursor_pg():
|
|
760
|
+
"""Single-column cursor (by IS pk) degenerates to the scalar form
|
|
761
|
+
`id > $1`, not one-element row-value syntax."""
|
|
762
|
+
q = sql.select_keyset(User, placeholder=pg, by="id", batch_size=3, last_seen=[10])
|
|
763
|
+
assert q.sql == (
|
|
764
|
+
"SELECT id, name, email FROM users WHERE id > $1 ORDER BY id NULLS FIRST LIMIT $2"
|
|
765
|
+
)
|
|
763
766
|
assert q.params == [10, 3]
|
|
764
767
|
|
|
765
768
|
|
|
766
|
-
def
|
|
767
|
-
"""
|
|
768
|
-
|
|
769
|
-
q = sql.select_keyset(User, placeholder=pg, by="
|
|
769
|
+
def test_select_keyset_by_non_pk_emits_compound_cursor_pg():
|
|
770
|
+
"""`by` differs from pk: cursor is `(by, pk_tail)` row-value, and
|
|
771
|
+
ORDER BY chains the PK tail after `by`."""
|
|
772
|
+
q = sql.select_keyset(User, placeholder=pg, by="email", batch_size=3, last_seen=["a@x", 10])
|
|
770
773
|
assert q.sql == (
|
|
771
|
-
"SELECT id, name, email FROM users WHERE
|
|
774
|
+
"SELECT id, name, email FROM users WHERE (email, id) > ($1, $2) "
|
|
775
|
+
"ORDER BY email NULLS FIRST, id LIMIT $3"
|
|
776
|
+
)
|
|
777
|
+
assert q.params == ["a@x", 10, 3]
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def test_select_keyset_null_region_cursor_pg():
|
|
781
|
+
"""`last_seen[0] IS NULL`: emit OR-group that either advances through
|
|
782
|
+
more NULL-by rows via PK tail or unlocks the non-NULL tail."""
|
|
783
|
+
q = sql.select_keyset(User, placeholder=pg, by="email", batch_size=3, last_seen=[None, 7])
|
|
784
|
+
assert q.sql == (
|
|
785
|
+
"SELECT id, name, email FROM users "
|
|
786
|
+
"WHERE ((email IS NULL AND id > $1) OR email IS NOT NULL) "
|
|
787
|
+
"ORDER BY email NULLS FIRST, id LIMIT $2"
|
|
788
|
+
)
|
|
789
|
+
assert q.params == [7, 3]
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def test_select_keyset_composite_pk_emits_three_col_cursor_pg():
|
|
793
|
+
"""Composite PK with non-PK `by`: cursor extends through both PK
|
|
794
|
+
columns so ties resolve through the full unique key."""
|
|
795
|
+
q = sql.select_keyset(
|
|
796
|
+
UserRole, placeholder=pg, by="note", batch_size=2, last_seen=["x", 1, 10]
|
|
797
|
+
)
|
|
798
|
+
assert q.sql == (
|
|
799
|
+
"SELECT user_id, role_id, note FROM user_roles "
|
|
800
|
+
"WHERE (note, user_id, role_id) > ($1, $2, $3) "
|
|
801
|
+
"ORDER BY note NULLS FIRST, user_id, role_id LIMIT $4"
|
|
802
|
+
)
|
|
803
|
+
assert q.params == ["x", 1, 10, 2]
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
def test_select_keyset_composite_pk_null_region_pg():
|
|
807
|
+
"""Composite PK + null region: OR-group's PK side is itself a
|
|
808
|
+
row-value `(user_id, role_id) > ($1, $2)`."""
|
|
809
|
+
q = sql.select_keyset(
|
|
810
|
+
UserRole, placeholder=pg, by="note", batch_size=2, last_seen=[None, 1, 10]
|
|
811
|
+
)
|
|
812
|
+
assert q.sql == (
|
|
813
|
+
"SELECT user_id, role_id, note FROM user_roles "
|
|
814
|
+
"WHERE ((note IS NULL AND (user_id, role_id) > ($1, $2)) OR note IS NOT NULL) "
|
|
815
|
+
"ORDER BY note NULLS FIRST, user_id, role_id LIMIT $3"
|
|
816
|
+
)
|
|
817
|
+
assert q.params == [1, 10, 2]
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def test_select_keyset_filter_with_cursor_parenthesizes_or_pg():
|
|
821
|
+
"""Filters AND'd with the cursor: the OR-group must be parenthesized
|
|
822
|
+
so AND/OR precedence does not break the predicate. Placeholders
|
|
823
|
+
thread through filter binds first."""
|
|
824
|
+
q = sql.select_keyset(
|
|
825
|
+
User, placeholder=pg, by="email", batch_size=2, last_seen=[None, 5], name="alice"
|
|
826
|
+
)
|
|
827
|
+
assert q.sql == (
|
|
828
|
+
"SELECT id, name, email FROM users "
|
|
829
|
+
"WHERE name = $1 AND ((email IS NULL AND id > $2) OR email IS NOT NULL) "
|
|
830
|
+
"ORDER BY email NULLS FIRST, id LIMIT $3"
|
|
772
831
|
)
|
|
773
832
|
assert q.params == ["alice", 5, 2]
|
|
774
833
|
|
|
775
834
|
|
|
776
|
-
def
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
assert q.
|
|
835
|
+
def test_select_keyset_sqlite_placeholders():
|
|
836
|
+
"""SQLite uses `?` placeholders; emitter is otherwise identical."""
|
|
837
|
+
q = sql.select_keyset(User, placeholder=lite, by="email", batch_size=2, last_seen=["a@x", 5])
|
|
838
|
+
assert q.sql == (
|
|
839
|
+
"SELECT id, name, email FROM users WHERE (email, id) > (?, ?) "
|
|
840
|
+
"ORDER BY email NULLS FIRST, id LIMIT ?"
|
|
841
|
+
)
|
|
842
|
+
assert q.params == ["a@x", 5, 2]
|
|
780
843
|
|
|
781
844
|
|
|
782
845
|
def test_select_keyset_rejects_non_db_column():
|
|
@@ -789,6 +852,13 @@ def test_select_keyset_rejects_by_in_filters():
|
|
|
789
852
|
sql.select_keyset(User, placeholder=pg, by="id", batch_size=1, id=5)
|
|
790
853
|
|
|
791
854
|
|
|
855
|
+
def test_select_keyset_rejects_last_seen_length_mismatch():
|
|
856
|
+
"""`last_seen` must have one value per cursor column; a mismatch is
|
|
857
|
+
a caller bug, caught at emit time rather than at SQL execute time."""
|
|
858
|
+
with pytest.raises(ValueError, match="last_seen has"):
|
|
859
|
+
sql.select_keyset(User, placeholder=pg, by="email", batch_size=1, last_seen=["only-one"])
|
|
860
|
+
|
|
861
|
+
|
|
792
862
|
# --- update_where: bulk update scoped by where= -------------------------
|
|
793
863
|
|
|
794
864
|
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
"""Integration tests for db.iter_rows_keyset across all three backends.
|
|
2
|
-
|
|
3
|
-
The keyset iterator emits `WHERE <by> > <last_seen>` per page, so total
|
|
4
|
-
cost stays O(N) rather than O(N^2) like `iter_rows`. Tests pin: full
|
|
5
|
-
ordered yield, batch boundaries, filter propagation, default `by`
|
|
6
|
-
column, explicit `by` override, and the input validation."""
|
|
7
|
-
|
|
8
|
-
import pytest
|
|
9
|
-
|
|
10
|
-
from etchdb import DB
|
|
11
|
-
from tests._models import User
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
async def test_iter_rows_keyset_yields_all_rows_ordered(db: DB):
|
|
15
|
-
for i in range(1, 8):
|
|
16
|
-
await db.insert(User(id=i, name=f"u{i}"))
|
|
17
|
-
|
|
18
|
-
rows = [u async for u in db.iter_rows_keyset(User, batch_size=3)]
|
|
19
|
-
|
|
20
|
-
assert [u.id for u in rows] == [1, 2, 3, 4, 5, 6, 7]
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
async def test_iter_rows_keyset_uses_pk_by_default(db: DB):
|
|
24
|
-
"""`by=None` defaults to `model.__pk__[0]`; pagination still
|
|
25
|
-
works when the user doesn't specify the column."""
|
|
26
|
-
for i in range(1, 4):
|
|
27
|
-
await db.insert(User(id=i, name=f"u{i}"))
|
|
28
|
-
|
|
29
|
-
rows = [u async for u in db.iter_rows_keyset(User)]
|
|
30
|
-
|
|
31
|
-
assert [u.id for u in rows] == [1, 2, 3]
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
async def test_iter_rows_keyset_filter_propagates(db: DB):
|
|
35
|
-
"""Extra filter kwargs are AND'd with the keyset cursor on every
|
|
36
|
-
page. Only rows that match the filter are yielded."""
|
|
37
|
-
await db.insert(User(id=1, name="alice"))
|
|
38
|
-
await db.insert(User(id=2, name="bob"))
|
|
39
|
-
await db.insert(User(id=3, name="alice"))
|
|
40
|
-
await db.insert(User(id=4, name="bob"))
|
|
41
|
-
|
|
42
|
-
rows = [u async for u in db.iter_rows_keyset(User, batch_size=2, name="alice")]
|
|
43
|
-
|
|
44
|
-
assert [u.id for u in rows] == [1, 3]
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
async def test_iter_rows_keyset_empty_table_yields_nothing(db: DB):
|
|
48
|
-
rows = [u async for u in db.iter_rows_keyset(User)]
|
|
49
|
-
assert rows == []
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
async def test_iter_rows_keyset_rejects_non_positive_batch_size(db: DB):
|
|
53
|
-
with pytest.raises(ValueError, match="batch_size"):
|
|
54
|
-
async for _ in db.iter_rows_keyset(User, batch_size=0):
|
|
55
|
-
pass
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
async def test_iter_rows_keyset_rejects_by_in_filters(db: DB):
|
|
59
|
-
"""If the user already constrains the keyset column via a filter,
|
|
60
|
-
the cursor's `>` predicate plus their `=` predicate would be
|
|
61
|
-
over-determined. Reject up front."""
|
|
62
|
-
with pytest.raises(ValueError, match="cannot also appear in filters"):
|
|
63
|
-
async for _ in db.iter_rows_keyset(User, by="id", id=5):
|
|
64
|
-
pass
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
async def test_iter_rows_keyset_empty_list_filter_short_circuits(db: DB):
|
|
68
|
-
"""Empty-list filter follows the same short-circuit convention as
|
|
69
|
-
iter_rows / query / get; nothing is yielded, no round trip."""
|
|
70
|
-
await db.insert(User(id=1, name="alice"))
|
|
71
|
-
rows = [u async for u in db.iter_rows_keyset(User, id=[])]
|
|
72
|
-
assert rows == []
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
async def test_iter_rows_keyset_composite_pk_requires_explicit_by(db: DB):
|
|
76
|
-
"""Defaulting `by` to `__pk__[0]` on a composite PK can silently
|
|
77
|
-
duplicate or skip rows when the leading column ties. Refuse and
|
|
78
|
-
point the user at the explicit `by=` form."""
|
|
79
|
-
from tests._models import UserRole
|
|
80
|
-
|
|
81
|
-
with pytest.raises(ValueError, match="composite PK"):
|
|
82
|
-
async for _ in db.iter_rows_keyset(UserRole):
|
|
83
|
-
pass
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
async def test_iter_rows_keyset_rejects_non_db_column(db: DB):
|
|
87
|
-
"""If the user passes `by=<col>` for a field that isn't a DB
|
|
88
|
-
column (e.g. excluded via __fields_not_in_db__), the row dict
|
|
89
|
-
won't carry it and the cursor advance would KeyError mid-loop.
|
|
90
|
-
Catch the misuse before the first query."""
|
|
91
|
-
with pytest.raises(ValueError, match="not a DB column"):
|
|
92
|
-
async for _ in db.iter_rows_keyset(User, by="nonexistent_col"):
|
|
93
|
-
pass
|
|
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
|
|
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
|
|
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
|