Coverage for src/scixplorer/model.py: 98%

441 statements  

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

1"""Models (classes of records with fields), relations between them, and collections of records.""" 

2 

3from __future__ import annotations 

4 

5from collections.abc import Callable, Iterable, Mapping 

6from dataclasses import dataclass 

7from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, NoReturn, TypeVar, cast, overload 

8 

9from . import exceptions 

10from .expr import BOOL_ERROR, And, Constant, Expr, Func, In, InLibrary, Like, Match, Not, Or, Quantified, Range, Raw, Related 

11from .fields import Field, FieldExpr, FieldInfo, Scope, _quantifier_hint, noun, parse_positions 

12 

13if TYPE_CHECKING: 

14 from .query import Backend, Query 

15 

16__all__ = [ 

17 "Collection", 

18 "CollectionExpr", 

19 "Model", 

20 "ModelMeta", 

21 "RecordExpr", 

22 "Relation", 

23 "RelationExpr", 

24 "Source", 

25 "check_predicate", 

26] 

27 

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

29R = TypeVar("R") 

30H = TypeVar("H", bound="RecordExpr") 

31 

32 

33class Relation(Generic[R]): 

34 """A link from one model (the owner) to another (the related model). 

35 

36 ``R`` is what ``resolve`` returns: instance access gives an ``R``, class 

37 access gives a :class:`RelationExpr`. 

38 

39 :param model: the related model, or a zero-argument callable returning it 

40 (for models defined later). 

41 :param key: the owner's field holding the key(s) of the related object(s). 

42 :param related_key: the related model's field those keys refer to. 

43 :param resolve: called with an owner instance; returns the related 

44 object(s) or ``None``. Called at most once per instance. 

45 :param doc: help text. 

46 """ 

47 

48 name: str 

49 owner: type[Model] 

50 

51 def __init__( 

52 self, 

53 model: type[Model] | Callable[[], type[Model]], 

54 *, 

55 key: str, 

56 related_key: str, 

57 resolve: Callable[[Any], R], 

58 doc: str = "", 

59 ) -> None: 

60 self._model = model 

61 self.key = key 

62 self.related_key = related_key 

63 self.resolve = resolve 

64 self.__doc__ = doc 

65 

66 def __set_name__(self, owner: type, name: str) -> None: 

67 if hasattr(self, "owner"): 

68 raise TypeError( 

69 f"Relation {self.owner.__name__}.{self.name} cannot also be " 

70 f"{owner.__name__}.{name}; create a separate relation for each class" 

71 ) 

72 self.owner = owner 

73 self.name = name 

74 

75 @property 

76 def related_model(self) -> type[Model]: 

77 """The related model class.""" 

78 if not isinstance(self._model, type): 

79 self._model = self._model() 

80 return self._model 

81 

82 @property 

83 def related_field(self) -> Field[Any, Any]: 

84 """The field of the related model that ``key`` values refer to.""" 

85 model = self.related_model 

86 try: 

87 return model._fields[self.related_key] 

88 except KeyError: 

89 raise TypeError( 

90 f"{self!r}: related_key {self.related_key!r} is not a field of {model.__name__}" 

91 ) from None 

92 

93 @overload 

94 def __get__(self, instance: None, owner: type | None = None) -> RelationExpr: ... 

95 

96 @overload 

97 def __get__(self, instance: object, owner: type | None = None) -> R: ... 

98 

99 def __get__(self, instance: Any, owner: type | None = None) -> RelationExpr | R: 

100 if instance is None: 

101 return RelationExpr(self) 

102 cache: dict[str, Any] = instance._related 

103 if self.name not in cache: 

104 cache[self.name] = self.resolve(instance) 

105 return cast(R, cache[self.name]) 

106 

107 def __set__(self, instance: Any, value: Any) -> None: 

108 raise AttributeError(f"{self!r} is derived from {self.key!r} and cannot be set") 

109 

110 def __repr__(self) -> str: 

111 owner = getattr(self, "owner", None) 

112 return f"<Relation {owner.__name__ if owner else '?'}.{getattr(self, 'name', '?')}>" 

113 

114 

115class RelationExpr: 

116 """A handle on a relation, used to build expressions over related objects. 

117 

118 ``Document.journal.title`` is a handle on the related model's field, and 

119 ``Document.journal == journal`` matches by the related object's key. Each 

120 such condition is about any related object; :meth:`any` combines several 

121 conditions about the same one. 

122 """ 

123 

124 __slots__ = ("_relation", "_scope") 

125 

126 def __init__(self, relation: Relation[Any], *, scope: Scope | None = None) -> None: 

127 self._relation = relation 

128 self._scope = scope 

129 

130 @property 

131 def relation(self) -> Relation[Any]: 

132 """The relation this handle is on.""" 

133 return self._relation 

134 

135 def __getattr__(self, name: str) -> FieldExpr: 

136 if name.startswith("_"): 

137 raise AttributeError(name) 

138 model = self._relation.related_model 

139 field = model._fields.get(name) 

140 if field is None: 

141 if name in ("any", "all"): 

142 raise AttributeError(_quantifier_hint(None, name, self._relation)) 

143 raise AttributeError( 

144 f"{model.__name__} has no field {name!r}; fields are: {', '.join(model._fields)}" 

145 ) 

146 return field.expr_class(field, via=self._relation, scope=self._scope) 

147 

148 def __dir__(self) -> Iterable[str]: 

149 return sorted({*object.__dir__(self), *self._relation.related_model._fields}) 

150 

151 def any(self, predicate: Expr) -> Expr: 

152 """Rows with at least one related object satisfying ``predicate``, a condition on the related model's fields. 

153 

154 Everything inside is about the same related object, so :: 

155 

156 Document.planetary_features.any( 

157 (PlanetaryFeature.target == "Mars") & (PlanetaryFeature.feature_type == "Crater") 

158 ) 

159 

160 finds documents mentioning a Mars crater, whereas 

161 ``(Document.planetary_features.target == "Mars") & (Document.planetary_features.feature_type == "Crater")`` 

162 finds those mentioning some Mars feature and some crater (perhaps elsewhere). 

163 A condition on "every related object" cannot be searched, so there is no ``all``. 

164 """ 

165 call = f"{self._label()}.any" 

166 check_predicate(predicate, self._relation.related_model, owner=self._relation.owner, call=call) 

167 node: Expr = Related(self._relation, predicate) 

168 return node if self._scope is None else self._scope._enclose(node) 

169 

170 def _label(self) -> str: 

171 owner = self._relation.owner.__name__ if self._scope is None else self._scope._label() 

172 return f"{owner}.{self._relation.name}" 

173 

174 def _key_handle(self) -> FieldExpr: 

175 field = self._relation.related_field 

176 return field.expr_class(field, via=self._relation, scope=self._scope) 

177 

178 def _key_of(self, other: Any) -> Any: 

179 model = self._relation.related_model 

180 if isinstance(other, Model): 

181 if not isinstance(other, model): 

182 raise TypeError(f"{self!r} relates to {model.__name__}, not {type(other).__name__}") 

183 key = other._data.get(self._relation.related_key) 

184 if key is None: 

185 raise exceptions.QueryError( 

186 f"{other!r} has no {self._relation.related_key!r}, so it cannot be matched" 

187 ) 

188 return key 

189 if isinstance(other, (RelationExpr, FieldExpr, Expr)): 

190 raise TypeError(f"{self!r} can only be compared with {model.__name__} objects or keys") 

191 return other 

192 

193 def __eq__(self, other: object) -> Expr: # type: ignore[override] # builds an Expr, not a bool 

194 key: object = self._key_of(other) 

195 return self._key_handle() == key 

196 

197 def __ne__(self, other: object) -> Expr: # type: ignore[override] # builds an Expr, not a bool 

198 return ~(self == other) 

199 

200 __hash__ = object.__hash__ 

201 

202 def in_(self, objs: Iterable[Any]) -> Expr: 

203 """Match related objects that are any of ``objs`` (objects or keys).""" 

204 if isinstance(objs, (str, bytes)) or not isinstance(objs, Iterable): 

205 raise TypeError(f"{self!r}.in_() needs a collection of objects or keys, not {objs!r}") 

206 return self._key_handle().in_([self._key_of(obj) for obj in objs]) 

207 

208 def not_in(self, objs: Iterable[Any]) -> Expr: 

209 """Match unless the related object is one of ``objs``.""" 

210 return ~self.in_(objs) 

211 

212 def __bool__(self) -> bool: 

213 raise TypeError(BOOL_ERROR.format(name=f"Relation {self!r}")) 

214 

215 def __iter__(self) -> Any: 

216 raise TypeError(f"{self!r} is not iterable; use .in_(objects) to match several objects") 

217 

218 def __repr__(self) -> str: 

219 return f"<{self._label()}>" 

220 

221 

222def check_predicate(predicate: Any, model: type[Model], *, owner: type | None, call: str, positions: str = "") -> Expr: 

223 """``predicate``, checked to be a condition on one ``model`` object, for ``call`` (``"Document.authors.any"``). 

224 

225 Its leaves must be on ``model``'s fields, or go through ``model``'s 

226 relations. Raises ``TypeError`` for something other than an expression 

227 (with the and/or/not hint for a ``bool``) and 

228 :class:`~scixplorer.exceptions.QueryError` for a condition on another model's 

229 field, or an operator, ``pos()``, raw query or library condition. 

230 ``owner`` is the model whose rows the call selects, named in the message 

231 about its fields; ``positions`` is advice on choosing positions, if any. 

232 """ 

233 name = model.__name__ 

234 if isinstance(predicate, bool): 

235 raise TypeError( 

236 f"{call}(...) got the bool {predicate!r} instead of an expression. This usually means " 

237 f"and/or/not, `is` or a comparison between plain values was used: combine expressions " 

238 f"with & | ~ and wrap each comparison in parentheses, e.g. " 

239 f"{call}(({name}.<field> == x) & ({name}.<field> == y))." 

240 ) 

241 if not isinstance(predicate, Expr): 

242 raise TypeError(f"{call}(...) needs an expression over {name} fields, not {predicate!r}") 

243 _check_node(predicate, model, owner, f"{call}(...)", positions) 

244 return predicate 

245 

246 

247def _check_node(node: Expr, model: type[Model], owner: type | None, call: str, positions: str) -> None: 

248 if isinstance(node, (And, Or)): 

249 for operand in node.operands: 

250 _check_node(operand, model, owner, call, positions) 

251 elif isinstance(node, Not): 

252 _check_node(node.operand, model, owner, call, positions) 

253 elif isinstance(node, Related): 

254 if model._relations.get(node.relation.name) is not node.relation: 

255 raise exceptions.QueryError( 

256 f"{call}: {node.relation!r} is not a relation of {model.__name__}; inside it, " 

257 f"use {model.__name__}'s fields and relations ({', '.join([*model._fields, *model._relations])})" 

258 ) 

259 elif isinstance(node, (Match, In, Like, Range)): 

260 if model._fields.get(node.field.name) is not node.field: 

261 raise exceptions.QueryError(_foreign(node.field, model, owner, call)) 

262 elif isinstance(node, Func) and node.name == "pos": 

263 raise exceptions.QueryError( 

264 f"{call} cannot restrict positions within one {noun(model)}'s values" + (f"; {positions}" if positions else "") 

265 ) 

266 elif not isinstance(node, Constant): 

267 kind = {Func: "an operator", Raw: "raw Solr text", InLibrary: "a library condition"} 

268 raise exceptions.QueryError( 

269 f"{call} cannot contain {kind.get(type(node), 'a nested .any()/.all()')} ({node!r}): " 

270 f"everything inside it is a condition on one {noun(model)}, built from " 

271 f"{model.__name__} fields and relations." 

272 ) 

273 

274 

275def _foreign(field: Field[Any, Any], model: type[Model], owner: type | None, call: str) -> str: 

276 """Why a leaf on ``field`` (not a field of ``model``) cannot be in ``call``.""" 

277 other = getattr(field, "model", None) 

278 name = f"{other.__name__ if other else '?'}.{field.name}" 

279 if other is not None and owner is not None and issubclass(owner, other): 

280 return ( 

281 f"{name} is a field of {other.__name__}, not of {model.__name__}: everything inside " 

282 f"{call} is about one {noun(model)}. Put conditions on the " 

283 f"{noun(other)} outside it, e.g. {call} & ({name} == ...)" 

284 ) 

285 through = [rel for rel in model._relations.values() if rel.related_model is other] 

286 if through: 

287 return ( 

288 f"{name} is not a field of {model.__name__}; reach it through the relation " 

289 f"{model.__name__}.{through[0].name}, e.g. {model.__name__}.{through[0].name}.{field.name} == ..." 

290 ) 

291 return f"{name} is not a field of {model.__name__}; inside {call} use: {', '.join(model._fields)}" 

292 

293 

294@dataclass(frozen=True) 

295class Source: 

296 """Where the value of one record field of a :class:`Collection` comes from on the owner. 

297 

298 :param fields: the owner's array fields holding the value, index-aligned 

299 with the records; with several, the first that has a value for the 

300 record wins. 

301 :param search: the owner field that a condition on the record field is 

302 searched through, or ``None`` if the server cannot search it (such a 

303 condition is then checked client-side). 

304 """ 

305 

306 fields: tuple[str, ...] 

307 search: str | None = None 

308 

309 

310class Collection(Generic[M, H]): 

311 """Records that an owner holds as index-aligned arrays, such as the authors of a document. 

312 

313 ADS stores per-author values as parallel arrays on the document (author 

314 names, affiliations, ORCIDs, ...), entry ``i`` of each describing author 

315 ``i``. A collection turns them into one record (an instance of ``model``) 

316 per entry, and lets a query say several things about the *same* record: 

317 ``Document.authors.any((Author.name == x) & (Author.aff == y))``. 

318 

319 Instance access gives ``list[M]`` (cached on the instance until any of its 

320 fields changes); class access gives a :class:`CollectionExpr`. 

321 

322 :param model: the record model (a model with no backend of its own). 

323 :param sources: for each record field, the owner field it comes from (a 

324 name: read and searched), or a :class:`Source`. Record fields left out 

325 have no value, except ``index``. 

326 :param length: the owner field whose number of values is the number of records. 

327 :param handle: the handle class for one record (``Document.authors[0]``): a 

328 :class:`RecordExpr` subclass, which may declare the handle type of each 

329 record field for type checkers. 

330 :param index: the record field set to the record's 0-based position, if any. 

331 :param placeholder: an array entry meaning "no value". 

332 :param separator: separates several values in one entry, for a multivalued record field. 

333 :param doc: help text. 

334 """ 

335 

336 name: str 

337 owner: type[Model] 

338 

339 def __init__( 

340 self, 

341 model: type[M], 

342 *, 

343 sources: Mapping[str, str | Source], 

344 length: str, 

345 handle: type[H], 

346 index: str | None = None, 

347 placeholder: str = "-", 

348 separator: str = ";", 

349 doc: str = "", 

350 ) -> None: 

351 self.record_model = model 

352 self.sources = { 

353 name: Source((source,), source) if isinstance(source, str) else source for name, source in sources.items() 

354 } 

355 self.length = length 

356 self.handle = handle 

357 self.index = index 

358 self.placeholder = placeholder 

359 self.separator = separator 

360 self.__doc__ = doc 

361 for name in (*self.sources, *([index] if index else [])): 

362 if name not in model._fields: 362 ↛ 363line 362 didn't jump to line 363 because the condition on line 362 was never true

363 raise TypeError(f"Collection of {model.__name__}: {name!r} is not a field of {model.__name__}") 

364 

365 def __set_name__(self, owner: type, name: str) -> None: 

366 if hasattr(self, "owner"): 366 ↛ 367line 366 didn't jump to line 367 because the condition on line 366 was never true

367 raise TypeError( 

368 f"Collection {self.owner.__name__}.{self.name} cannot also be " 

369 f"{owner.__name__}.{name}; create a separate collection for each class" 

370 ) 

371 self.owner = owner 

372 self.name = name 

373 

374 def owner_fields(self, names: Iterable[str] | None = None) -> tuple[str, ...]: 

375 """The owner fields read to build records with the record fields ``names`` (all if ``None``). 

376 

377 Always includes :attr:`length`; each name appears once, in first-use order. 

378 """ 

379 wanted = self.sources if names is None else {n: self.sources[n] for n in names if n in self.sources} 

380 return tuple(dict.fromkeys([self.length, *(f for source in wanted.values() for f in source.fields)])) 

381 

382 def fields_read(self, predicate: Expr) -> tuple[str, ...]: 

383 """The record fields that evaluating ``predicate`` on a record reads (a relation reads its key).""" 

384 found: dict[str, None] = {} 

385 

386 def visit(node: Expr) -> None: 

387 if isinstance(node, (And, Or)): 

388 for operand in node.operands: 

389 visit(operand) 

390 elif isinstance(node, Not): 

391 visit(node.operand) 

392 elif isinstance(node, Related): 

393 found.setdefault(node.relation.key) 

394 elif isinstance(node, (Match, In, Like, Range)): 

395 found.setdefault(node.field.name) 

396 

397 visit(predicate) 

398 return tuple(found) 

399 

400 def label(self, positions: tuple[int, int] | None = None) -> str: 

401 """How the collection (restricted to ``positions``) is written: ``Document.authors[0]``.""" 

402 owner = getattr(self, "owner", None) 

403 text = f"{owner.__name__ if owner else '?'}.{getattr(self, 'name', '?')}" 

404 if positions is not None: 

405 start, end = positions 

406 text += f"[{start - 1}]" if start == end else f"[{start - 1}:{end}]" 

407 return text 

408 

409 @overload 

410 def __get__(self, instance: None, owner: type | None = None) -> CollectionExpr[H]: ... 

411 

412 @overload 

413 def __get__(self, instance: object, owner: type | None = None) -> list[M]: ... 

414 

415 def __get__(self, instance: Any, owner: type | None = None) -> CollectionExpr[H] | list[M]: 

416 if instance is None: 

417 return CollectionExpr(self) 

418 cache: dict[str, Any] = instance._related 

419 if self.name not in cache: 

420 records = self.records(instance) 

421 instance._related[self.name] = records 

422 return cast("list[M]", instance._related[self.name]) 

423 

424 def __set__(self, instance: Any, value: Any) -> None: 

425 raise AttributeError(f"{self!r} is derived from {', '.join(self.owner_fields())} and cannot be set") 

426 

427 def records(self, owner: Model, names: Iterable[str] | None = None) -> list[M]: 

428 """The records of ``owner``, in order, with the record fields ``names`` set (all if ``None``). 

429 

430 Missing owner fields are loaded first, all at once (see 

431 ``Model._load_fields``). Entry ``i`` of each source array gives record 

432 ``i``'s value; a missing or short array, or the placeholder, gives no 

433 value (``None``, or an empty list for a multivalued record field, whose 

434 entries are split on the separator). Records already built for the 

435 instance (by attribute access) are returned as they are. 

436 """ 

437 if not isinstance(owner, self.owner): 

438 raise TypeError(f"{self!r} holds records of {self.owner.__name__} objects, not of {owner!r}") 

439 if self.name in owner._related: 439 ↛ 440line 439 didn't jump to line 440 because the condition on line 439 was never true

440 return cast("list[M]", owner._related[self.name]) 

441 wanted = self.sources if names is None else {n: self.sources[n] for n in names if n in self.sources} 

442 fields = [owner._fields[name] for name in self.owner_fields(wanted)] 

443 owner._load_fields(fields) 

444 arrays = {field.name: owner._get_value(field) for field in fields} 

445 lengths = arrays[self.length] 

446 model = self.record_model 

447 records: list[M] = [] 

448 for i in range(len(lengths) if isinstance(lengths, (list, tuple)) else 0): 

449 record = model() 

450 if self.index is not None: 450 ↛ 452line 450 didn't jump to line 452 because the condition on line 450 was always true

451 record._data[self.index] = i 

452 for name, source in wanted.items(): 

453 field = model._fields[name] 

454 values = [self._convert(field, _entry(arrays[f], i)) for f in source.fields] 

455 present = [value for value in values if value is not None] 

456 record._data[name] = next((v for v in present if v != []), present[0] if present else None) 

457 records.append(record) 

458 return records 

459 

460 def _convert(self, field: Field[Any, Any], raw: Any) -> Any: 

461 """One array entry as the value of the record field ``field``.""" 

462 if raw is None: 

463 return None 

464 if isinstance(raw, str): 464 ↛ 470line 464 didn't jump to line 470 because the condition on line 464 was always true

465 if field.multivalued: 

466 parts = (part.strip() for part in raw.split(self.separator)) 

467 raw = [part for part in parts if part and part != self.placeholder] 

468 elif raw.strip() in ("", self.placeholder): 

469 return None 

470 return field.to_python(raw) 

471 

472 def quantify(self, predicate: Any, quantifier: Literal["any", "all"], positions: tuple[int, int] | None) -> Expr: 

473 """``Quantified(self, predicate, quantifier, positions)``, after checking ``predicate``. 

474 

475 Raises ``TypeError`` for something other than an expression and 

476 :class:`~scixplorer.exceptions.QueryError` for an expression that is not 

477 about one record: a condition on another model's field (other than 

478 through a relation of the record model), or an operator, raw query or 

479 library condition. 

480 """ 

481 record = noun(self.record_model) 

482 advice = ( 

483 f"choose {record}s by position by indexing the collection: " 

484 f"{self.label()}[0].any(...), {self.label()}[0:3].any(...)" 

485 ) 

486 call = f"{self.label(positions)}.{quantifier}" 

487 check_predicate(predicate, self.record_model, owner=self.owner, call=call, positions=advice) 

488 return Quantified(self, predicate, quantifier, positions) 

489 

490 def __repr__(self) -> str: 

491 return f"<Collection {self.label()}>" 

492 

493 

494def _entry(array: Any, i: int) -> Any: 

495 """Entry ``i`` of an owner's array value, or ``None`` if it is missing or too short.""" 

496 if isinstance(array, (list, tuple)) and i < len(array): 

497 return array[i] 

498 return None 

499 

500 

501class CollectionExpr(Generic[H]): 

502 """A handle on a :class:`Collection` (``Document.authors``), used to build per-record conditions. 

503 

504 ``any(predicate)`` / ``all(predicate)`` match owners for which some / every 

505 record satisfies ``predicate`` (``all`` needs at least one record). 

506 Everything inside one call is about the same record. Index to restrict the 

507 records by position: ``[0]`` (one record: also allows attribute shorthand, 

508 ``Document.authors[0].name == x``) or ``[0:3]``. 

509 """ 

510 

511 __slots__ = ("_collection", "_positions") 

512 

513 def __init__(self, collection: Collection[Any, H], positions: tuple[int, int] | None = None) -> None: 

514 self._collection = collection 

515 self._positions = positions 

516 

517 @property 

518 def collection(self) -> Collection[Any, H]: 

519 """The collection this handle is on.""" 

520 return self._collection 

521 

522 @property 

523 def positions(self) -> tuple[int, int] | None: 

524 """The 1-indexed inclusive positions selected, or ``None`` for all records.""" 

525 return self._positions 

526 

527 def any(self, predicate: Expr) -> Expr: 

528 """Owners for which at least one (selected) record satisfies ``predicate``.""" 

529 return self._collection.quantify(predicate, "any", self._positions) 

530 

531 def all(self, predicate: Expr) -> Expr: 

532 """Owners that have (selected) records and for which every one satisfies ``predicate``.""" 

533 return self._collection.quantify(predicate, "all", self._positions) 

534 

535 @overload 

536 def __getitem__(self, index: int) -> H: ... 

537 

538 @overload 

539 def __getitem__(self, index: slice) -> CollectionExpr[H]: ... 

540 

541 def __getitem__(self, index: int | slice) -> H | CollectionExpr[H]: 

542 """Restrict to positions: ``[0]`` (one record) or ``[0:3]``; as for field positions.""" 

543 if self._positions is not None: 

544 raise TypeError(f"{self!r} is already restricted to positions") 

545 selected = parse_positions(index) 

546 if isinstance(index, slice): 

547 return CollectionExpr(self._collection, selected) 

548 return self._collection.handle(self._collection, selected) 

549 

550 if not TYPE_CHECKING: 550 ↛ 566line 550 didn't jump to line 566 because the condition on line 550 was always true

551 # Runtime only, so that type checkers still flag unknown attributes. 

552 def __getattr__(self, name: str) -> NoReturn: 

553 if name.startswith("_"): 

554 raise AttributeError(name) 

555 model = self._collection.record_model 

556 if name not in model._fields and name not in model._relations: 

557 raise AttributeError(f"{self!r} has no attribute {name!r}; use .any(...) or .all(...)") 

558 label, record = self._label(), model.__name__ 

559 raise AttributeError( 

560 f"{label}.{name}: say which {record.lower()}s the condition is about. Use " 

561 f"{label}.any({record}.{name} == ...) for any {record.lower()}, " 

562 f"{label}.all({record}.{name} == ...) for every one, or index one position, " 

563 f"e.g. {self._collection.label()}[0].{name} == ..." 

564 ) 

565 

566 def _label(self) -> str: 

567 if self._positions is None: 

568 return self._collection.label() 

569 start, end = self._positions 

570 return f"{self._collection.label()}[{start - 1}:{end}]" 

571 

572 def __dir__(self) -> Iterable[str]: 

573 return sorted({*object.__dir__(self), "any", "all"}) 

574 

575 def __eq__(self, other: object) -> NoReturn: 

576 raise TypeError( 

577 f"{self!r} cannot be compared with a value; compare a field of one record inside " 

578 f".any(...) or .all(...), e.g. {self._label()}.any({self._collection.record_model.__name__}.<field> == x)" 

579 ) 

580 

581 def __ne__(self, other: object) -> NoReturn: 

582 self.__eq__(other) 

583 

584 __hash__ = object.__hash__ 

585 

586 def __bool__(self) -> bool: 

587 raise TypeError(BOOL_ERROR.format(name=f"Collection {self!r}")) 

588 

589 def __iter__(self) -> Any: 

590 raise TypeError(f"{self!r} is not iterable; use .any(...) or .all(...) to build a condition") 

591 

592 def __repr__(self) -> str: 

593 return f"<{self._label()}>" 

594 

595 

596class RecordExpr(CollectionExpr[Any]): 

597 """A handle on one record of a collection, by position: ``Document.authors[0]``. 

598 

599 Attribute access gives handles on the record's fields and relations, whose 

600 conditions are about that record: ``Document.authors[0].name == x`` is 

601 ``Document.authors[0].any(Author.name == x)``. Subclasses may declare those 

602 attributes' types for type checkers. 

603 """ 

604 

605 __slots__ = () 

606 

607 if not TYPE_CHECKING: 607 ↛ 624line 607 didn't jump to line 624 because the condition on line 607 was always true

608 

609 def __getattr__(self, name: str) -> FieldExpr | RelationExpr: 

610 if name.startswith("_"): 

611 raise AttributeError(name) 

612 model = self._collection.record_model 

613 field = model._fields.get(name) 

614 if field is not None: 

615 return field.expr_class(field, scope=self) 

616 relation = model._relations.get(name) 

617 if relation is not None: 

618 return RelationExpr(relation, scope=self) 

619 raise AttributeError( 

620 f"{model.__name__} has no field {name!r}; fields are: " 

621 f"{', '.join([*model._fields, *model._relations])}" 

622 ) 

623 

624 def _enclose(self, node: Expr) -> Expr: 

625 """A condition on this record's field, as a condition on the owner.""" 

626 return self._collection.quantify(node, "any", self._positions) 

627 

628 def _label(self) -> str: 

629 return self._collection.label(self._positions) 

630 

631 def __dir__(self) -> Iterable[str]: 

632 model = self._collection.record_model 

633 return sorted({*super().__dir__(), *model._fields, *model._relations}) 

634 

635 

636class ModelMeta(type): 

637 """Metaclass collecting a model's fields and relations. 

638 

639 Sets ``_fields``, ``_relations`` and ``_collections`` (dicts in definition 

640 order, inherited entries first) and a per-model ``DoesNotExist`` exception class. 

641 """ 

642 

643 _fields: dict[str, Field[Any, Any]] 

644 _relations: dict[str, Relation[Any]] 

645 _collections: dict[str, Collection[Any, Any]] 

646 DoesNotExist: type[exceptions.DoesNotExist] 

647 

648 def __init__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs: Any) -> None: 

649 super().__init__(name, bases, namespace, **kwargs) 

650 fields: dict[str, Field[Any, Any]] = {} 

651 relations: dict[str, Relation[Any]] = {} 

652 collections: dict[str, Collection[Any, Any]] = {} 

653 for base in reversed(bases): 

654 fields.update(getattr(base, "_fields", {})) 

655 relations.update(getattr(base, "_relations", {})) 

656 collections.update(getattr(base, "_collections", {})) 

657 for attr, value in namespace.items(): 

658 if isinstance(value, Field): 

659 fields[attr] = value 

660 elif isinstance(value, Relation): 

661 relations[attr] = value 

662 elif isinstance(value, Collection): 

663 collections[attr] = value 

664 cls._fields = fields 

665 cls._relations = relations 

666 cls._collections = collections 

667 

668 key = namespace.get("_key") 

669 if key is not None and key not in fields: 

670 raise TypeError(f"{name}._key names {key!r}, which is not a field of {name}") 

671 for relation in relations.values(): 

672 if relation.key not in fields: 

673 raise TypeError( 

674 f"{name}.{relation.name} uses key {relation.key!r}, which is not a field of {name}" 

675 ) 

676 for collection in collections.values(): 

677 used = [*collection.owner_fields(), *(s.search for s in collection.sources.values() if s.search)] 

678 for field_name in used: 

679 if field_name not in fields: 679 ↛ 680line 679 didn't jump to line 680 because the condition on line 679 was never true

680 raise TypeError( 

681 f"{name}.{collection.name} reads {field_name!r}, which is not a field of {name}" 

682 ) 

683 

684 parent = next( 

685 (base.DoesNotExist for base in bases if isinstance(base, ModelMeta)), 

686 exceptions.DoesNotExist, 

687 ) 

688 cls.DoesNotExist = type( 

689 "DoesNotExist", 

690 (parent,), 

691 {"__module__": cls.__module__, "__qualname__": f"{cls.__qualname__}.DoesNotExist"}, 

692 ) 

693 

694 

695class Model(metaclass=ModelMeta): 

696 """Base class for models. Field values are passed as keyword arguments.""" 

697 

698 _key: ClassVar[str] 

699 _backend: ClassVar[Backend] 

700 _fields: ClassVar[dict[str, Field[Any, Any]]] 

701 _relations: ClassVar[dict[str, Relation[Any]]] 

702 _collections: ClassVar[dict[str, Collection[Any, Any]]] 

703 DoesNotExist: ClassVar[type[exceptions.DoesNotExist]] 

704 

705 def __init__(self, **values: Any) -> None: 

706 self._data: dict[str, Any] = {} 

707 self._related: dict[str, Any] = {} 

708 for name, value in values.items(): 

709 field = self._fields.get(name) 

710 if field is None: 

711 raise TypeError( 

712 f"{type(self).__name__}() got an unexpected field {name!r}; " 

713 f"fields are: {', '.join(self._fields)}" 

714 ) 

715 if not field.stored: 

716 raise TypeError(f"{type(self).__name__}.{name} is search-only and cannot be set") 

717 self._set_value(field, value) 

718 

719 @classmethod 

720 def _from_row(cls: type[M], row: Mapping[str, Any]) -> M: 

721 """Build an instance from an API mapping keyed by Solr field names. 

722 

723 Values are converted with ``Field.to_python``; unknown keys are ignored 

724 and only keys present in ``row`` are set. 

725 """ 

726 instance = cls() 

727 for field in cls._fields.values(): 

728 if field.stored and field.solr_name in row: 

729 instance._data[field.name] = field.to_python(row[field.solr_name]) 

730 return instance 

731 

732 @classmethod 

733 def _field(cls, ref: str | Field[Any, Any] | FieldExpr) -> Field[Any, Any]: 

734 """Resolve a field name, definition or plain handle to a field of this model.""" 

735 if isinstance(ref, FieldExpr): 

736 if ref.via is not None or ref.position is not None or ref.scope is not None: 

737 raise TypeError(f"{ref!r} is not a plain field of {cls.__name__}") 

738 ref = ref.field 

739 if isinstance(ref, str): 

740 if ref not in cls._fields: 

741 raise AttributeError( 

742 f"{cls.__name__} has no field {ref!r}; fields are: {', '.join(cls._fields)}" 

743 ) 

744 return cls._fields[ref] 

745 if isinstance(ref, Field): 

746 if cls._fields.get(getattr(ref, "name", "")) is not ref: 

747 raise TypeError(f"{ref!r} is not a field of {cls.__name__}") 

748 return ref 

749 raise TypeError(f"Expected a field of {cls.__name__} or its name, not {ref!r}") 

750 

751 def _get_value(self, field: Field[Any, Any]) -> Any: 

752 """Return the stored value of ``field``, loading it if it is missing.""" 

753 try: 

754 return self._data[field.name] 

755 except KeyError: 

756 return self._load_missing(field) 

757 

758 def _load_missing(self, field: Field[Any, Any]) -> Any: 

759 """Return the value of a field that was never set. The default is ``None``.""" 

760 return None 

761 

762 def _load_fields(self, fields: Iterable[Field[Any, Any]]) -> None: 

763 """Load, at once where possible, those of ``fields`` that were never set. 

764 

765 Used before reading several fields together (as a :class:`Collection` 

766 does). The default loads nothing: unset fields read as ``None``. 

767 """ 

768 

769 def _set_value(self, field: Field[Any, Any], value: Any) -> None: 

770 """Store ``value`` (as the field normalises it) for ``field``, discarding cached related objects.""" 

771 self._data[field.name] = field.normalise(value) 

772 self._related.clear() 

773 

774 def _key_value(self) -> Any: 

775 key = getattr(type(self), "_key", None) 

776 return None if key is None else self._data.get(key) 

777 

778 def __eq__(self, other: object) -> bool: 

779 if type(other) is not type(self): 

780 return NotImplemented 

781 key = self._key_value() 

782 if key is None: 

783 return self is other 

784 return bool(key == other._key_value()) 

785 

786 def __hash__(self) -> int: 

787 key = self._key_value() 

788 return id(self) if key is None else hash((type(self), key)) 

789 

790 def to_dict(self) -> dict[str, Any]: 

791 """The values loaded on this instance, by field name in definition order. 

792 

793 Never loads missing values, and does not include relations. 

794 """ 

795 return {name: self._data[name] for name in self._fields if name in self._data} 

796 

797 @classmethod 

798 def describe(cls) -> list[FieldInfo]: 

799 """Describe the fields of this model, in definition order.""" 

800 return [field.info() for field in cls._fields.values()] 

801 

802 def __repr__(self) -> str: 

803 key = self._key_value() 

804 if key is None: 

805 return f"<{type(self).__name__}>" 

806 return f"<{type(self).__name__}: {self._key}={key!r}>" 

807 

808 @classmethod 

809 def select(cls: type[M], *fields: str | Field[Any, Any] | FieldExpr) -> Query[M]: 

810 """Start a query over this model, fetching ``fields`` (all stored fields if none).""" 

811 from .query import Query 

812 

813 return Query(cls, tuple(cls._field(field) for field in fields)) 

814 

815 @classmethod 

816 def get(cls: type[M], *exprs: Expr, **equals: Any) -> M: 

817 """Return the single object matching ``exprs`` and ``field=value`` keywords. 

818 

819 Raises ``cls.DoesNotExist`` if nothing matches. 

820 """ 

821 for name in equals: 

822 if name not in cls._fields and name not in cls._relations: 822 ↛ 823line 822 didn't jump to line 823 because the condition on line 822 was never true

823 raise TypeError(f"{cls.__name__}.get() got an unexpected field {name!r}") 

824 conditions = [*exprs, *(getattr(cls, name) == value for name, value in equals.items())] 

825 result: M | None = cls.select().where(*conditions).first() 

826 if result is None: 

827 raise cls.DoesNotExist(f"No {cls.__name__} matched {conditions!r}") 

828 return result