Coverage for src/scixplorer/cli/session.py: 93%
73 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""Running the searches of the ``scix`` command: one request gives a page of documents and their total."""
3from __future__ import annotations
5from dataclasses import dataclass
6from typing import Any
8from ..client import Request, Response, get_default_client
9from ..models.document import Document
10from ..query import Query, Sender
11from .interpret import Interpretation
12from .output import FIELDS, SORTS
14__all__ = ["Found", "Session"]
17@dataclass(frozen=True)
18class Found:
19 """The answer to a search: the documents fetched, and how many match in all.
21 ``interpretation`` is the reading that was searched. It is the wider one
22 (``widened``) when the search as first read matched nothing.
23 """
25 interpretation: Interpretation
26 documents: list[Document]
27 total: int
28 widened: bool = False
31class _Counting:
32 """Sends requests with a client, and remembers how many documents the last search matched."""
34 def __init__(self, client: Sender | None) -> None:
35 self._given = client
36 self.found: int | None = None
38 @property
39 def client(self) -> Sender:
40 return self._given if self._given is not None else get_default_client()
42 def _note(self, request: Request, response: Response) -> None:
43 if not request.path.startswith("/search/"): 43 ↛ 44line 43 didn't jump to line 44 because the condition on line 43 was never true
44 return
45 body: Any = response.data.get("response") if isinstance(response.data, dict) else None
46 found = body.get("numFound") if isinstance(body, dict) else None
47 if isinstance(found, int) and not isinstance(found, bool): 47 ↛ exitline 47 didn't return from function '_note' because the condition on line 47 was always true
48 self.found = found
50 def send(self, request: Request) -> Response:
51 response = self.client.send(request)
52 self._note(request, response)
53 return response
55 async def asend(self, request: Request) -> Response:
56 response = await self.client.asend(request)
57 self._note(request, response)
58 return response
61class Session:
62 """Runs searches with one client (``None`` for the default client)."""
64 def __init__(self, client: Sender | None = None) -> None:
65 self._sender = _Counting(client)
67 @property
68 def client(self) -> Sender:
69 """The client requests are sent with."""
70 return self._sender.client
72 def query(self, interpretation: Interpretation, sort: str) -> Query[Document]:
73 """The document query for a search as it was read, in the order ``sort`` names."""
74 expr = interpretation.expr
75 if expr is None:
76 raise ValueError("there is nothing to search for")
77 field, descending, _ = SORTS[sort]
78 handle = getattr(Document, field)
79 return Document.select(*FIELDS).where(expr).order_by(handle.desc() if descending else handle.asc())
81 def fetch(
82 self, interpretation: Interpretation, sort: str, *, limit: int | None, offset: int = 0
83 ) -> tuple[list[Document], int]:
84 """``limit`` documents from position ``offset``, and the number that match in all."""
85 self._sender.found = None
86 query = self.query(interpretation, sort).offset(offset).limit(limit).using(self._sender)
87 documents = query.all()
88 found = self._sender.found
89 return documents, max(found if found is not None else 0, offset + len(documents))
91 def bibcodes(self, interpretation: Interpretation, sort: str, *, limit: int | None) -> tuple[list[str], int]:
92 """The bibcodes of the first ``limit`` documents, and the number that match in all.
94 Nothing but the bibcodes is fetched, so this is the way to hand many
95 documents to a service.
96 """
97 self._sender.found = None
98 query = self.query(interpretation, sort)
99 fetched = Document.select(Document.bibcode).where(*([query.expr] if query.expr is not None else []))
100 documents = fetched.order_by(*query.order).limit(limit).using(self._sender).all()
101 found = self._sender.found
102 bibcodes = [document.bibcode for document in documents if document.bibcode]
103 return bibcodes, max(found if found is not None else 0, len(documents))
105 def find(self, interpretation: Interpretation, sort: str, *, limit: int | None) -> Found:
106 """Search, and if nothing matches, search again with the wider reading if there is one."""
107 documents, total = self.fetch(interpretation, sort, limit=limit)
108 if total == 0:
109 wider = interpretation.relaxed()
110 if wider is not None:
111 documents, total = self.fetch(wider, sort, limit=limit)
112 if total:
113 return Found(wider, documents, total, widened=True)
114 return Found(interpretation, documents, total)