Coverage for src/scixplorer/query.py: 99%

325 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-18 23:06 +0000

1"""Queries over models, the sans-IO backend protocol, and the drivers that run it. 

2 

3A :class:`Query` is an immutable description of what to fetch. Executing it asks 

4the model's backend for a generator that yields :class:`~scixplorer.client.Request` 

5objects (to be sent, with the :class:`~scixplorer.client.Response` sent back in) and 

6lists of model instances (batches of results). The drivers :func:`drive` and 

7:func:`adrive` run such a generator with a sync or async ``send`` callable, so 

8pagination and merging logic is written once in the backend and works both ways. 

9""" 

10 

11from __future__ import annotations 

12 

13import copy 

14import json 

15from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterable, Iterator 

16from contextlib import aclosing, closing 

17from dataclasses import dataclass 

18from typing import Any, Generic, Protocol, TypeVar, overload 

19 

20from . import client as _http 

21from . import evaluate 

22from .client import Request, Response 

23from .expr import Expr, Order 

24from .fields import Field, FieldExpr 

25from .model import Model 

26 

27__all__ = [ 

28 "Backend", 

29 "Explanation", 

30 "MemoryBackend", 

31 "Query", 

32 "Sender", 

33 "adrive", 

34 "drive", 

35 "filter_rows", 

36 "select_rows", 

37] 

38 

39M = TypeVar("M", bound=Model) 

40 

41 

42@dataclass(frozen=True) 

43class Explanation: 

44 """What executing a query would do. 

45 

46 ``requests`` are the first request(s) that would be sent (empty if the query 

47 is answered without any), and ``notes`` are further details worth showing. 

48 """ 

49 

50 summary: str 

51 requests: tuple[Request, ...] = () 

52 notes: tuple[str, ...] = () 

53 

54 def __str__(self) -> str: 

55 lines = [self.summary] 

56 for request in self.requests: 

57 lines.append(f"{request.method.upper()} {request.path}") 

58 for key, value in (request.params or {}).items(): 

59 if value is not None: 

60 shown = str(value).lower() if isinstance(value, bool) else value 

61 lines.append(f" {key} = {shown}") 

62 size = _body_size(request) 

63 if size is not None: 

64 lines.append(f" (body: {size} bytes)") 

65 lines.extend(f"- {note}" for note in self.notes) 

66 return "\n".join(lines) 

67 

68 

69def _body_size(request: Request) -> int | None: 

70 if request.content is not None: 

71 content = request.content 

72 return len(content.encode("utf-8") if isinstance(content, str) else content) 

73 if request.json is not None: 

74 return len(json.dumps(request.json).encode("utf-8")) 

75 return None 

76 

77 

78class Sender(Protocol): 

79 """What a query needs from a client to send requests; :class:`~scixplorer.client.Client` is one.""" 

80 

81 def send(self, request: Request) -> Response: 

82 """Send a request and return its response.""" 

83 ... 

84 

85 async def asend(self, request: Request) -> Response: 

86 """Send a request asynchronously and return its response.""" 

87 ... 

88 

89 

90class Backend(Protocol): 

91 """Executes queries for a model without performing any I/O itself.""" 

92 

93 def run(self, query: Query[Any]) -> Generator[Request | list[Any], Response | None, None]: 

94 """Yield a Request to have it executed (the Response is sent back in), or 

95 yield a list of model instances (a batch of results; None is sent back).""" 

96 ... 

97 

98 def count(self, query: Query[Any]) -> Generator[Request, Response, int]: 

99 """Yield Requests as ``run`` does and return the number of matching rows, 

100 ignoring the query's offset and limit.""" 

101 ... 

102 

103 def explain(self, query: Query[Any]) -> Explanation: 

104 """Describe how the query would be executed.""" 

105 ... 

106 

107 

108def drive(gen: Generator[Any, Any, Any], send: Callable[[Request], Response]) -> Generator[Any, None, Any]: 

109 """Run a backend generator synchronously. 

110 

111 Each yielded :class:`Request` is passed to ``send`` and the response sent 

112 back in; if ``send`` raises, the exception is thrown into the generator so 

113 the backend can clean up or translate it. Every other yielded item (a batch 

114 of rows) is yielded to the caller. Returns the generator's return value. 

115 Closing this generator closes the backend generator. 

116 """ 

117 try: 

118 reply: Response | None = None 

119 error: Exception | None = None 

120 while True: 

121 try: 

122 item = gen.send(reply) if error is None else gen.throw(error) 

123 except StopIteration as stop: 

124 return stop.value 

125 reply = error = None 

126 if isinstance(item, Request): 

127 try: 

128 reply = send(item) 

129 except Exception as exc: 

130 error = exc 

131 else: 

132 yield item 

133 finally: 

134 gen.close() 

135 

136 

137async def adrive( 

138 gen: Generator[Any, Any, Any], asend: Callable[[Request], Awaitable[Response]] 

139) -> AsyncGenerator[Any, None]: 

140 """Run a backend generator asynchronously; the async counterpart of :func:`drive`. 

141 

142 Async generators cannot return a value, so the backend generator's return 

143 value is discarded. To receive it, wrap the backend generator in one that 

144 yields the value as its last item, as :meth:`Query.acount` does. 

145 """ 

146 try: 

147 reply: Response | None = None 

148 error: Exception | None = None 

149 while True: 

150 try: 

151 item = gen.send(reply) if error is None else gen.throw(error) 

152 except StopIteration: 

153 return 

154 reply = error = None 

155 if isinstance(item, Request): 

156 try: 

157 reply = await asend(item) 

158 except Exception as exc: 

159 error = exc 

160 else: 

161 yield item 

162 finally: 

163 gen.close() 

164 

165 

166@dataclass(frozen=True) 

167class _Returned: 

168 """The return value of a backend generator, yielded as its final item.""" 

169 

170 value: Any 

171 

172 

173def _returning(gen: Generator[Any, Any, Any]) -> Generator[Any, Any, None]: 

174 """Re-yield everything ``gen`` yields, then yield its return value as :class:`_Returned`.""" 

175 value = yield from gen 

176 yield _Returned(value) 

177 

178 

179def _total(item: Any, backend: Any) -> int: 

180 """Unwrap the first item of a ``_returning(backend.count(...))`` run, which must be its result.""" 

181 if isinstance(item, _Returned): 

182 value = item.value 

183 if isinstance(value, int) and not isinstance(value, bool): 183 ↛ 185line 183 didn't jump to line 185 because the condition on line 183 was always true

184 return value 

185 raise TypeError(f"{backend!r}.count() must only yield Requests and return an int; got {item!r}") 

186 

187 

188def _describe_order(orders: Iterable[Order]) -> str: 

189 return ", ".join(f"{o.field.name} {'desc' if o.descending else 'asc'}" for o in orders) 

190 

191 

192class Query(Generic[M]): 

193 """An immutable query over a model; build it with :meth:`Model.select`. 

194 

195 Builder methods (:meth:`where`, :meth:`order_by`, :meth:`limit`, 

196 :meth:`offset`, :meth:`using`) return a new query. Iterating streams results 

197 as the backend produces them; once an iteration completes, the results are 

198 cached on this query, and later iterations, :meth:`all`, :meth:`count`, 

199 ``len()`` and indexing make no further requests. 

200 """ 

201 

202 __slots__ = ("_model", "_fields", "_expr", "_order", "_limit", "_offset", "_client", "_rows") 

203 

204 def __init__(self, model: type[M], fields: Iterable[str | Field[Any, Any] | FieldExpr] = ()) -> None: 

205 if not (isinstance(model, type) and issubclass(model, Model)): 

206 raise TypeError(f"Query needs a Model subclass, not {model!r}") 

207 self._model = model 

208 self._fields: tuple[Field[Any, Any], ...] = tuple(model._field(field) for field in fields) 

209 self._expr: Expr | None = None 

210 self._order: tuple[Order, ...] = () 

211 self._limit: int | None = None 

212 self._offset = 0 

213 self._client: Sender | None = None 

214 self._rows: tuple[M, ...] | None = None 

215 

216 @property 

217 def model(self) -> type[M]: 

218 """The model being queried.""" 

219 return self._model 

220 

221 @property 

222 def fields(self) -> tuple[Field[Any, Any], ...]: 

223 """The fields to fetch; empty means all stored fields.""" 

224 return self._fields 

225 

226 @property 

227 def expr(self) -> Expr | None: 

228 """The filter expression, or ``None`` to match everything.""" 

229 return self._expr 

230 

231 @property 

232 def order(self) -> tuple[Order, ...]: 

233 """The sort keys, most significant first.""" 

234 return self._order 

235 

236 @property 

237 def limit_(self) -> int | None: 

238 """The maximum number of rows, or ``None`` for no limit.""" 

239 return self._limit 

240 

241 @property 

242 def offset_(self) -> int: 

243 """The number of leading rows to skip.""" 

244 return self._offset 

245 

246 @property 

247 def client(self) -> Sender | None: 

248 """The client requests are sent with; ``None`` means the default client.""" 

249 return self._client 

250 

251 def _replace(self, **changes: Any) -> Query[M]: 

252 new = copy.copy(self) 

253 for name, value in changes.items(): 

254 setattr(new, "_" + name, value) 

255 new._rows = None 

256 return new 

257 

258 def where(self, *exprs: Expr) -> Query[M]: 

259 """Return a query also requiring every one of ``exprs`` (AND-ed with any existing filter).""" 

260 for expr in exprs: 

261 if isinstance(expr, bool): 

262 raise TypeError( 

263 f"where() got the bool {expr!r} instead of an expression. This usually " 

264 "means and/or/not, `is` or a comparison between plain values was used: " 

265 "combine expressions with & | ~ and wrap each comparison in parentheses, " 

266 "e.g. .where((Journal.title == 'x') | (Journal.abbreviation == 'y'))." 

267 ) 

268 if not isinstance(expr, Expr): 

269 raise TypeError(f"where() needs expressions, not {expr!r}") 

270 combined = self._expr 

271 for expr in exprs: 

272 combined = expr if combined is None else combined & expr 

273 return self._replace(expr=combined) 

274 

275 def order_by(self, *keys: Order | str | Field[Any, Any] | FieldExpr) -> Query[M]: 

276 """Return a query sorted by ``keys`` (replacing any previous ordering). 

277 

278 Each key is an :class:`~scixplorer.expr.Order` (from ``.asc()``/``.desc()``) or a 

279 field handle or name, meaning ascending. No keys removes the ordering. 

280 """ 

281 orders = [] 

282 for key in keys: 

283 if isinstance(key, Order): 

284 orders.append(Order(self._model._field(key.field), key.descending)) 

285 else: 

286 orders.append(Order(self._model._field(key))) 

287 return self._replace(order=tuple(orders)) 

288 

289 def limit(self, n: int | None) -> Query[M]: 

290 """Return a query yielding at most ``n`` rows (``None`` for no limit).""" 

291 if n is not None: 

292 _check_count("limit", n) 

293 return self._replace(limit=n) 

294 

295 def offset(self, n: int) -> Query[M]: 

296 """Return a query skipping the first ``n`` rows.""" 

297 _check_count("offset", n) 

298 return self._replace(offset=n) 

299 

300 def using(self, client: Sender | None) -> Query[M]: 

301 """Return a query sending requests with ``client`` (``None`` for the default client).""" 

302 return self._replace(client=client) 

303 

304 def _backend(self) -> Backend: 

305 backend: Backend | None = getattr(self._model, "_backend", None) 

306 if backend is None: 

307 raise TypeError(f"{self._model.__name__} has no backend, so it cannot be queried") 

308 return backend 

309 

310 def _resolve_client(self) -> Sender: 

311 return self._client if self._client is not None else _http.get_default_client() 

312 

313 def _send(self, request: Request) -> Response: 

314 return self._resolve_client().send(request) 

315 

316 async def _asend(self, request: Request) -> Response: 

317 return await self._resolve_client().asend(request) 

318 

319 def _check_batch(self, batch: Any) -> list[M]: 

320 if not isinstance(batch, list): 

321 raise TypeError(f"{self._backend()!r} yielded {batch!r}; expected a Request or a list of rows") 

322 return batch 

323 

324 def __iter__(self) -> Iterator[M]: 

325 return self._stream() 

326 

327 def _stream(self) -> Iterator[M]: 

328 # The cache is checked when iteration starts, not when the iterator is 

329 # created: list(query) creates the iterator, then calls len(query) for a 

330 # size hint, which runs and caches the query; the iterator then reuses it. 

331 if self._rows is not None: 

332 yield from self._rows 

333 return 

334 rows: list[M] = [] 

335 with closing(drive(self._backend().run(self), self._send)) as batches: 

336 for batch in batches: 

337 batch = self._check_batch(batch) 

338 rows.extend(batch) 

339 yield from batch 

340 self._rows = tuple(rows) 

341 

342 def __aiter__(self) -> AsyncIterator[M]: 

343 return self._astream() 

344 

345 async def _astream(self) -> AsyncIterator[M]: 

346 if self._rows is not None: 

347 for row in self._rows: 

348 yield row 

349 return 

350 rows: list[M] = [] 

351 async with aclosing(adrive(self._backend().run(self), self._asend)) as batches: 

352 async for batch in batches: 

353 batch = self._check_batch(batch) 

354 rows.extend(batch) 

355 for row in batch: 

356 yield row 

357 self._rows = tuple(rows) 

358 

359 def all(self) -> list[M]: 

360 """All rows, as a new list.""" 

361 return list(iter(self)) 

362 

363 async def aall(self) -> list[M]: 

364 """Asynchronous :meth:`all`.""" 

365 return [row async for row in self] 

366 

367 def _first_query(self) -> Query[M] | None: 

368 """The query that fetches only the first row, or ``None`` if there can be none.""" 

369 return None if self._limit == 0 else self.limit(1) 

370 

371 def first(self) -> M | None: 

372 """The first row, or ``None``. Fetches at most one row unless already cached.""" 

373 if self._rows is not None: 

374 return self._rows[0] if self._rows else None 

375 query = self._first_query() 

376 rows = [] if query is None else query.all() 

377 return rows[0] if rows else None 

378 

379 async def afirst(self) -> M | None: 

380 """Asynchronous :meth:`first`.""" 

381 if self._rows is not None: 

382 return self._rows[0] if self._rows else None 

383 query = self._first_query() 

384 rows = [] if query is None else await query.aall() 

385 return rows[0] if rows else None 

386 

387 def _require(self, row: M | None) -> M: 

388 if row is None: 

389 raise self._model.DoesNotExist(f"No {self._model.__name__} matched {self!r}") 

390 return row 

391 

392 def get(self) -> M: 

393 """The first row; raises ``model.DoesNotExist`` if there is none.""" 

394 return self._require(self.first()) 

395 

396 async def aget(self) -> M: 

397 """Asynchronous :meth:`get`.""" 

398 return self._require(await self.afirst()) 

399 

400 def exists(self) -> bool: 

401 """Whether there is at least one row. Fetches at most one row unless cached.""" 

402 return self.first() is not None 

403 

404 async def aexists(self) -> bool: 

405 """Asynchronous :meth:`exists`.""" 

406 return await self.afirst() is not None 

407 

408 def _window(self, total: int) -> int: 

409 """Apply offset and limit to the backend's total number of matches.""" 

410 n = max(0, total - self._offset) 

411 return n if self._limit is None else min(n, self._limit) 

412 

413 def count(self) -> int: 

414 """The number of rows iteration would yield, asking the backend unless cached.""" 

415 if self._rows is not None: 

416 return len(self._rows) 

417 backend = self._backend() 

418 with closing(drive(_returning(backend.count(self)), self._send)) as items: 

419 return self._window(_total(next(items), backend)) 

420 

421 async def acount(self) -> int: 

422 """Asynchronous :meth:`count`.""" 

423 if self._rows is not None: 

424 return len(self._rows) 

425 backend = self._backend() 

426 async with aclosing(adrive(_returning(backend.count(self)), self._asend)) as items: 

427 return self._window(_total(await anext(items), backend)) 

428 

429 def __len__(self) -> int: 

430 return len(self._fetched()) 

431 

432 def __bool__(self) -> bool: 

433 """Whether there is at least one row; like :meth:`exists`, fetches at most one.""" 

434 return self.exists() 

435 

436 def _fetched(self) -> tuple[M, ...]: 

437 return self._rows if self._rows is not None else tuple(self._stream()) 

438 

439 @overload 

440 def __getitem__(self, index: int) -> M: ... 

441 @overload 

442 def __getitem__(self, index: slice) -> list[M]: ... 

443 def __getitem__(self, index: int | slice) -> M | list[M]: 

444 rows = self._fetched() 

445 if isinstance(index, slice): 

446 return list(rows[index]) 

447 return rows[index] 

448 

449 def explain(self) -> Explanation: 

450 """Describe how this query would be executed, without executing it.""" 

451 return self._backend().explain(self) 

452 

453 def __repr__(self) -> str: 

454 parts = [] 

455 if self._fields: 

456 parts.append("fields " + ", ".join(field.name for field in self._fields)) 

457 if self._expr is not None: 

458 parts.append(f"where {self._expr!r}") 

459 if self._order: 

460 parts.append("order by " + _describe_order(self._order)) 

461 if self._offset: 

462 parts.append(f"offset {self._offset}") 

463 if self._limit is not None: 

464 parts.append(f"limit {self._limit}") 

465 if self._client is not None: 

466 parts.append(f"using {self._client!r}") 

467 if self._rows is not None: 

468 parts.append(f"{len(self._rows)} rows cached") 

469 return f"<Query {self._model.__name__}{': ' if parts else ''}{'; '.join(parts)}>" 

470 

471 

472def _check_count(name: str, n: Any) -> None: 

473 if isinstance(n, bool) or not isinstance(n, int): 

474 raise TypeError(f"{name}() needs an int, not {n!r}") 

475 if n < 0: 

476 raise ValueError(f"{name}() needs a non-negative int, not {n}") 

477 

478 

479def filter_rows(rows: Iterable[M], query: Query[M]) -> list[M]: 

480 """The ``rows`` that satisfy the query's filter, evaluated in Python.""" 

481 if query.expr is None: 

482 return list(rows) 

483 test = evaluate.predicate(query.expr) 

484 return [row for row in rows if test(row)] 

485 

486 

487def select_rows(rows: Iterable[M], query: Query[M]) -> list[M]: 

488 """Apply the query's filter, ordering, offset and limit to ``rows`` in Python. 

489 

490 This is what a backend holding its whole collection in memory yields. 

491 """ 

492 selected = filter_rows(rows, query) 

493 if query.order: 

494 selected = evaluate.sort_rows(selected, query.order) 

495 start = query.offset_ 

496 stop = None if query.limit_ is None else start + query.limit_ 

497 return selected[start:stop] 

498 

499 

500class MemoryBackend(Generic[M]): 

501 """Evaluates queries in Python over a collection held in memory. 

502 

503 :param loader: zero-argument callable returning the whole collection. It is 

504 called on every execution, so it should cache its result. 

505 :param key: name of a field with unique values, enabling :meth:`lookup`. 

506 

507 The query's ``fields`` are ignored: rows are returned whole. 

508 """ 

509 

510 def __init__(self, loader: Callable[[], Iterable[M]], *, key: str | None = None): 

511 self._loader = loader 

512 self._key = key 

513 self._index: dict[Any, M] | None = None 

514 

515 def __repr__(self) -> str: 

516 return f"<MemoryBackend {getattr(self._loader, '__qualname__', self._loader)!r}>" 

517 

518 def run(self, query: Query[M]) -> Generator[Request | list[M], Response | None, None]: 

519 """Yield the matching rows, ordered, offset and limited, as a single batch.""" 

520 yield select_rows(self._loader(), query) 

521 

522 def count(self, query: Query[M]) -> Generator[Request, Response, int]: 

523 """Return the number of matching rows, ignoring offset and limit.""" 

524 yield from () 

525 return len(filter_rows(self._loader(), query)) 

526 

527 def explain(self, query: Query[M]) -> Explanation: 

528 """Say that the query is evaluated locally, over how many rows.""" 

529 total = sum(1 for _ in self._loader()) 

530 notes = [f"filter: {query.expr!r}" if query.expr is not None else "filter: none (all rows)"] 

531 if query.order: 

532 notes.append(f"order: {_describe_order(query.order)}") 

533 return Explanation( 

534 f"Evaluated locally over {total} {query.model.__name__} rows; no requests are made.", 

535 notes=tuple(notes), 

536 ) 

537 

538 def lookup(self, value: Any) -> M | None: 

539 """The row whose ``key`` field equals ``value``, or ``None``. 

540 

541 The index is built on first use; if several rows share a key, the first wins. 

542 """ 

543 if self._key is None: 

544 raise TypeError(f"{self!r} was created without key=..., so it does not support lookup()") 

545 if self._index is None: 

546 index: dict[Any, M] = {} 

547 for row in self._loader(): 

548 index.setdefault(getattr(row, self._key), row) 

549 self._index = index 

550 return self._index.get(value) 

551 

552 def clear(self) -> None: 

553 """Drop the lookup index, so the next :meth:`lookup` rebuilds it from the loader. 

554 

555 Call this when the data the loader returns has changed. 

556 """ 

557 self._index = None