Coverage for src/scixplorer/fields.py: 99%
431 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"""Field definitions (descriptors on model classes) and field handles.
3A :class:`Field` is the definition: it lives on the model class, converts
4values to and from the API, and is what expression nodes refer to. Accessing a
5field on the model class (``Document.year``) returns a :class:`FieldExpr`
6handle, whose overloaded operators build expressions. The two are kept separate
7so that fields keep plain identity equality while handles overload ``==``.
9Fields are generic in their value type, so type checkers know that
10``paper.year`` is ``int | None`` and ``paper.title`` (multivalued) is
11``list[str] | None``. Values read from the API are converted to exactly that
12type or to ``None`` (see :meth:`Field.to_python`).
14Matching. Each field class declares how ADS matches its values
15(``Field.match_kind``):
17- ``"keyword"`` (:class:`StringField` and all numeric, boolean and date fields):
18 the value is matched literally; there is nothing to expand.
19- ``"text"`` (:class:`TextField`, :class:`VirtualField`): tokenized; ``==``
20 matches the phrase, and ADS also matches its synonyms and acronyms.
21- ``"name"`` (:class:`NameField`): personal names, ``"Last, First M"``; ``==``
22 also matches name variants, so ``author == "Rubin, V"`` matches
23 ``"Rubin, Vera C."`` and ``"Rubin, Victoria"``.
25``.exact(value)`` and ``.in_(values, exact=True)`` mean "match this value with
26no expansion" (Solr ``=field:``). On a keyword field that is the same as ``==``.
27"""
29from __future__ import annotations
31import math
32import re
33import sys
34import warnings
35from collections.abc import Callable, Iterable
36from dataclasses import dataclass
37from datetime import date, datetime, timezone
38from decimal import Decimal
39from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, NoReturn, Protocol, TypeVar, cast, overload
41from .exceptions import DataWarning, QueryError, QueryWarning
42from .expr import (
43 BOOL_ERROR,
44 Expr,
45 Func,
46 In,
47 Like,
48 Match,
49 Order,
50 Range,
51 Related,
52 SolrLiteral,
53 escape_pattern,
54 format_pattern,
55 parse_pattern,
56)
58if TYPE_CHECKING:
59 from .model import Relation
61__all__ = [
62 "BooleanField",
63 "DateField",
64 "DateTimeField",
65 "Field",
66 "FieldExpr",
67 "FieldInfo",
68 "FloatField",
69 "IntegerField",
70 "NameField",
71 "NumericExpr",
72 "NumericStringField",
73 "Scope",
74 "StringField",
75 "TextExpr",
76 "TextField",
77 "VirtualField",
78 "noun",
79 "parse_positions",
80]
83class FieldExpr:
84 """A handle on a field, used to build expressions with Python operators.
86 :param field: the field definition.
87 :param via: the relation through which the field is reached, if any; the
88 resulting expressions are wrapped in :class:`~scixplorer.expr.Related`.
89 :param position: 1-indexed inclusive ``(start, end)`` positions within a
90 multivalued field; the resulting expressions are wrapped in ``pos()``.
91 :param scope: the record(s) of a collection the field belongs to, such as
92 ``Document.authors[0]`` for ``Document.authors[0].name``; the resulting
93 expressions are wrapped in :class:`~scixplorer.expr.Quantified` by it.
94 """
96 def __init__(
97 self,
98 field: Field[Any, Any],
99 *,
100 via: Relation[Any] | None = None,
101 position: tuple[int, int] | None = None,
102 scope: Scope | None = None,
103 ):
104 self.field = field
105 self.via = via
106 self.position = position
107 self.scope = scope
108 self.__doc__ = field.__doc__
110 def _searchable(self) -> None:
111 """Refuse a field that is not indexed: it can be returned but not searched or sorted by."""
112 if not self.field.indexed:
113 label = self.field._label()
114 raise QueryError(
115 f"{label} can be returned but not searched or sorted by: SciX does not index it. "
116 f"To read it, select it: {_model_name(self.field)}.select({label}, ...)"
117 )
119 def _wrap(self, node: Expr) -> Expr:
120 """Apply this handle's position and relation to a node built on its field.
122 Every expression a handle builds passes through here, so this is also
123 where a field that cannot be searched is refused.
124 """
125 self._searchable()
126 if self.position is not None:
127 node = Func("pos", (node, *self.position))
128 if self.via is not None:
129 node = Related(self.via, node)
130 if self.scope is not None:
131 node = self.scope._enclose(node)
132 return node
134 def _check(self, value: Any) -> Any:
135 """Validate a value for this field and return it unchanged."""
136 if value is None:
137 raise QueryError(f"Comparing {self!r} with None is not supported")
138 if isinstance(value, (FieldExpr, Expr)):
139 raise TypeError(f"{self!r} can only be compared with values, not with {value!r}")
140 self.field.to_solr(value)
141 advice = self.field.advice
142 if advice is not None and not isinstance(value, SolrLiteral):
143 problem = advice(value)
144 if problem is not None:
145 warnings.warn(
146 f"{self.field._label()}: {value!r} {problem}. The search is sent as written.",
147 QueryWarning,
148 stacklevel=outside_package_stacklevel(),
149 )
150 return self.field.normalise(value)
152 def __eq__(self, value: object) -> Expr: # type: ignore[override] # builds an Expr, not a bool
153 return self._wrap(Match(self.field, self._check(value)))
155 def __ne__(self, value: object) -> Expr: # type: ignore[override] # builds an Expr, not a bool
156 return ~(self == value)
158 __hash__ = object.__hash__
160 def _values(self, values: Iterable[Any]) -> tuple[Any, ...]:
161 """Validate the collection given to ``in_`` and return its values."""
162 if isinstance(values, (str, bytes)):
163 raise TypeError(
164 f"{self!r}.in_() needs a collection of values, not a single string; "
165 f"use == to compare with one value"
166 )
167 if isinstance(values, (FieldExpr, Expr)) or not isinstance(values, Iterable):
168 raise TypeError(f"{self!r}.in_() needs a collection of values, not {values!r}")
169 return tuple(self._check(v) for v in values)
171 def in_(self, values: Iterable[Any]) -> Expr:
172 """Match any of ``values``."""
173 return self._wrap(In(self.field, self._values(values)))
175 def not_in(self, values: Iterable[Any]) -> Expr:
176 """Match none of ``values``."""
177 return ~self.in_(values)
179 def _order(self, descending: bool) -> Order:
180 self._searchable()
181 if self.via is not None or self.position is not None or self.scope is not None:
182 raise QueryError(f"Cannot sort by {self!r}; sort by a field of the model itself")
183 return Order(self.field, descending)
185 def asc(self) -> Order:
186 """Sort key, ascending."""
187 return self._order(False)
189 def desc(self) -> Order:
190 """Sort key, descending."""
191 return self._order(True)
193 def __bool__(self) -> bool:
194 raise TypeError(BOOL_ERROR.format(name=f"Field {self!r}"))
196 def __iter__(self) -> Any:
197 raise TypeError(f"{self!r} is not iterable; use .in_(values) to match several values")
199 if not TYPE_CHECKING: 199 ↛ 206line 199 didn't jump to line 206 because the condition on line 199 was always true
200 # Runtime only, so that type checkers still flag unknown attributes.
201 def __getattr__(self, name: str) -> NoReturn:
202 if name in ("any", "all"):
203 raise AttributeError(_quantifier_hint(self.__dict__.get("field"), name, self.__dict__.get("via")))
204 raise AttributeError(f"{type(self).__name__!r} object has no attribute {name!r}")
206 def __repr__(self) -> str:
207 if self.via is not None:
208 owner = self.via.owner.__name__ + "." + self.via.name
209 if self.scope is not None:
210 owner = f"{self.scope._label()}.{self.via.name}"
211 else:
212 owner = _model_name(self.field) if self.scope is None else self.scope._label()
213 text = f"{owner}.{self.field.name}"
214 if self.position is not None:
215 start, end = self.position
216 text += f"[{start - 1}]" if start == end else f"[{start - 1}:{end}]"
217 return f"<{text}>"
220class TextExpr(FieldExpr):
221 """Handle on a text, name or string field: equality, wildcard and position queries."""
223 def __eq__(self, value: object) -> Expr: # type: ignore[override] # builds an Expr, not a bool
224 """Match ``value`` with ADS's default expansion for the field's kind.
226 A text field matches the phrase and its synonyms; a name field also
227 matches name variants (``author == "Rubin, V"`` matches
228 ``"Rubin, Vera C."`` and ``"Rubin, Victoria"``); a string field
229 matches the whole value literally.
230 """
231 return super().__eq__(value)
233 __hash__ = FieldExpr.__hash__
235 def exact(self, value: str) -> Expr:
236 """Match ``value`` with no expansion (Solr ``=field:"value"``).
238 A text field then matches the phrase without synonyms; a name field
239 matches only that form of the name, ignoring case and the periods after
240 initials (``author.exact("Rubin, V")`` matches ``"Rubin, V."`` but not
241 ``"Rubin, Vera"``). On a string field this is the same as ``==``.
242 """
243 return self._wrap(Match(self.field, self._check(value), exact=True))
245 def in_(self, values: Iterable[Any], *, exact: bool = False) -> Expr:
246 """Match any of ``values``: each as ``==`` would, or as :meth:`exact` would if ``exact``."""
247 return self._wrap(In(self.field, self._values(values), exact=exact))
249 def not_in(self, values: Iterable[Any], *, exact: bool = False) -> Expr:
250 """Match none of ``values`` (compared as by :meth:`in_`)."""
251 return ~self.in_(values, exact=exact)
253 def like(self, pattern: str) -> Expr:
254 """Wildcard match: ``*`` (or ``%``) is any run of characters, ``?`` is one character.
256 Precede a wildcard character or a backslash with a backslash to match it literally.
257 """
258 if not isinstance(pattern, str):
259 raise TypeError(f"{self!r}.like() needs a str pattern, not {pattern!r}")
260 return self._wrap(Like(self.field, format_pattern(parse_pattern(pattern, percent=True))))
262 def startswith(self, prefix: str) -> Expr:
263 """Match values starting with ``prefix`` (taken literally)."""
264 if not isinstance(prefix, str):
265 raise TypeError(f"{self!r}.startswith() needs a str, not {prefix!r}")
266 return self._wrap(Like(self.field, escape_pattern(prefix) + "*"))
268 def contains(self, text: str) -> Expr:
269 """Match values containing ``text`` (taken literally)."""
270 if not isinstance(text, str):
271 raise TypeError(f"{self!r}.contains() needs a str, not {text!r}")
272 return self._wrap(Like(self.field, "*" + escape_pattern(text) + "*"))
274 def __getitem__(self, index: int | slice) -> TextExpr:
275 """Restrict to positions of a multivalued field: ``author[0]``, ``author[0:3]``."""
276 if not self.field.multivalued:
277 raise TypeError(f"{self!r} is not multivalued, so it cannot be indexed")
278 if self.position is not None:
279 raise TypeError(f"{self!r} is already restricted to a position")
280 return type(self)(self.field, via=self.via, position=parse_positions(index), scope=self.scope)
283class NumericExpr(FieldExpr):
284 """Handle on a numeric or date field: equality and range queries."""
286 def __lt__(self, value: Any) -> Expr:
287 return self._wrap(Range(self.field, None, self._check(value), include_hi=False))
289 def __le__(self, value: Any) -> Expr:
290 return self._wrap(Range(self.field, None, self._check(value)))
292 def __gt__(self, value: Any) -> Expr:
293 return self._wrap(Range(self.field, self._check(value), None, include_lo=False))
295 def __ge__(self, value: Any) -> Expr:
296 return self._wrap(Range(self.field, self._check(value), None))
298 def between(self, lo: Any, hi: Any) -> Expr:
299 """Match values from ``lo`` to ``hi`` inclusive."""
300 return self._wrap(Range(self.field, self._check(lo), self._check(hi)))
303def outside_package_stacklevel() -> int:
304 """The ``stacklevel`` for a warning raised by the caller, pointing at the first frame outside ``scixplorer``."""
305 level = 1
306 frame = sys._getframe(1)
307 while frame.f_back is not None and frame.f_globals.get("__name__", "").split(".")[0] == "scixplorer":
308 frame = frame.f_back
309 level += 1
310 return level
313def parse_positions(index: int | slice) -> tuple[int, int]:
314 """The 1-indexed inclusive ``(start, end)`` positions selected by ``index``: ``[0]``, ``[0:3]``.
316 Raises ``TypeError`` for an index that is not an int or a slice of ints, and
317 :class:`~scixplorer.exceptions.QueryError` for a negative or open-ended one (ADS
318 cannot search by position from the end), an empty slice or a step.
319 """
320 if isinstance(index, slice):
321 start, stop, step = index.start, index.stop, index.step
322 if step not in (None, 1):
323 raise QueryError("Position slices cannot have a step")
324 start = 0 if start is None else start
325 if not isinstance(start, int) or not isinstance(stop, (int, type(None))):
326 raise TypeError(f"Position slice bounds must be ints, not {index!r}")
327 if start < 0 or stop is None or stop < 0:
328 raise QueryError("ADS cannot search by position from the end")
329 if stop <= start:
330 raise QueryError(f"Empty position slice [{start}:{stop}]")
331 return (start + 1, stop)
332 if isinstance(index, int) and not isinstance(index, bool):
333 if index < 0:
334 raise QueryError("ADS cannot search by position from the end")
335 return (index + 1, index + 1)
336 raise TypeError(f"Positions must be ints or slices, not {index!r}")
339def _model_name(field: Field[Any, Any]) -> str:
340 model = getattr(field, "model", None)
341 return model.__name__ if model is not None else "?"
344def noun(model: type) -> str:
345 """A model's name as words for messages: ``"planetary feature"``, ``"UAT concept"``, ``"author"``."""
346 words = re.findall(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z0-9]+|[A-Z]+", model.__name__)
347 return " ".join(word if word.isupper() else word.lower() for word in words)
350def _quantifier_hint(field: Field[Any, Any] | None, name: str, via: Relation[Any] | None = None) -> str:
351 """Why a handle has no ``.any()``/``.all()`` (a relation handle: no ``.all()``), and what to write instead.
353 ``via`` is the relation the handle goes through, if any; ``field`` is
354 ``None`` for a relation handle itself.
355 """
356 if via is not None:
357 owner: Any = via.owner
358 relation = f"{owner.__name__}.{via.name}"
359 related = via.related_model
360 words = noun(related)
361 name_on_owner = via.key
362 if field is None:
363 message = (
364 f'{relation} has no .{name}(): a condition on "every related {words}" cannot be searched. '
365 f"Use {relation}.any(...) for conditions on one {words}: everything inside it is "
366 f"about the same {words}, e.g. {relation}.any(({related.__name__}.<field> == x) & "
367 f"({related.__name__}.<field> == y))."
368 )
369 else:
370 label = f"{relation}.{field.name}"
371 message = (
372 f"{label} has no .{name}(): a comparison through a relation already means "
373 f'"any related {words}" ({label} == x matches when any of them does). '
374 f"To say several things about the same {words}, use {relation}.any(...) with "
375 f"conditions on {related.__name__} fields."
376 )
377 elif field is not None: 377 ↛ 388line 377 didn't jump to line 388 because the condition on line 377 was always true
378 owner = getattr(field, "model", None)
379 label = field._label()
380 name_on_owner = field.name
381 message = (
382 f"{label} has no .{name}(): a comparison on a multivalued field already means "
383 f'"any value" ({label} == x matches when any of its values does).'
384 if field.multivalued
385 else f"{label} has no .{name}(): it holds a single value, so compare it directly."
386 )
387 else:
388 return f"no attribute {name!r}"
389 collections = [
390 collection
391 for collection in getattr(owner, "_collections", {}).values()
392 if name_on_owner in collection.owner_fields()
393 or any(source.search == name_on_owner for source in collection.sources.values())
394 ]
395 if collections and field is not None and via is None and not field.multivalued:
396 message = (
397 f"{label} has no .{name}(): a comparison on it already means "
398 f'"any value" ({label} == x matches when any of its values does).'
399 )
400 for collection in collections:
401 record = collection.record_model.__name__
402 message += (
403 f" To say several things about the same {record.lower()}, or about every one, use "
404 f"{owner.__name__}.{collection.name}.{name}(...) with conditions on {record} fields: "
405 f"everything inside one .{name}(...) is about one {record.lower()}."
406 )
407 return message
410T = TypeVar("T")
411H = TypeVar("H", bound=FieldExpr)
413_UNCONVERTIBLE = (ValueError, TypeError, ArithmeticError)
416class _Record(Protocol):
417 """What a field's owner instances provide (``Model`` does)."""
419 def _get_value(self, field: Field[Any, Any], /) -> Any: ...
422class Scope(Protocol):
423 """Record(s) of a collection that a field handle is restricted to (``Document.authors[0]``)."""
425 def _enclose(self, node: Expr, /) -> Expr:
426 """Wrap a condition on one record's field into a condition on the owner."""
427 ...
429 def _label(self) -> str:
430 """How the scope is written, e.g. ``"Document.authors[0]"``."""
431 ...
434@dataclass(frozen=True)
435class FieldInfo:
436 """A readable description of one field of a model (see ``Model.describe()``)."""
438 name: str
439 type: str
440 multivalued: bool
441 stored: bool
442 solr_name: str
443 doc: str
444 match_kind: str
445 indexed: bool = True
448class Field(Generic[T, H]):
449 """A field of a model: a data descriptor and the definition used in expressions.
451 ``T`` is the type of the value on an instance (``list[...]`` for a
452 multivalued field) and ``H`` the type of handle returned by class access.
453 Instance access gives ``T | None``; class access gives an ``H``.
455 :param doc: help text, shown by ``help()``.
456 :param multivalued: the field holds a list of values.
457 :param stored: the field can be returned by the API (``False`` for search-only fields).
458 :param indexed: the field can be searched and sorted by (``False`` for fields that
459 are only returned); building an expression or sort key on it raises
460 :class:`~scixplorer.exceptions.QueryError`.
461 :param solr_name: the field's name in Solr, if different from the attribute name.
462 """
464 expr_class: ClassVar[type[FieldExpr]] = FieldExpr
465 #: The Python type of one value (one element, for a multivalued field).
466 python_type: ClassVar[type] = object
467 #: How ADS matches values: ``"keyword"`` (literally), ``"text"`` (tokenized,
468 #: with synonyms) or ``"name"`` (with name variants). See the module docstring.
469 match_kind: ClassVar[str] = "keyword"
470 #: Given a value compared with the field (by ``==``, ``exact()`` or ``in_()``),
471 #: returns why it is probably a mistake, or ``None``. A reason is reported
472 #: as a :class:`~scixplorer.exceptions.QueryWarning`; the condition is still
473 #: built. Set with :func:`advised`.
474 advice: Callable[[Any], str | None] | None = None
475 name: str
476 model: type
478 def __init__(
479 self,
480 doc: str = "",
481 *,
482 multivalued: bool = False,
483 stored: bool = True,
484 indexed: bool = True,
485 solr_name: str | None = None,
486 ) -> None:
487 self.__doc__ = doc
488 self.multivalued = multivalued
489 self.stored = stored
490 self.indexed = indexed
491 self._solr_name = solr_name
493 def __set_name__(self, owner: type, name: str) -> None:
494 if hasattr(self, "model"):
495 raise TypeError(
496 f"{type(self).__name__} {self.model.__name__}.{self.name} cannot also be "
497 f"{owner.__name__}.{name}; create a separate field instance for each class"
498 )
499 self.model = owner
500 self.name = name
502 @property
503 def solr_name(self) -> str:
504 """The field's name in Solr queries and API responses."""
505 return self._solr_name or self.name
507 @property
508 def type_name(self) -> str:
509 """The value type as text, e.g. ``"int"`` or ``"list[str]"``."""
510 name = self.python_type.__name__
511 return f"list[{name}]" if self.multivalued else name
513 def info(self) -> FieldInfo:
514 """Describe this field."""
515 return FieldInfo(
516 name=self.name,
517 type=self.type_name,
518 multivalued=self.multivalued,
519 stored=self.stored,
520 solr_name=self.solr_name,
521 doc=self.__doc__ or "",
522 match_kind=self.match_kind,
523 indexed=self.indexed,
524 )
526 @overload
527 def __get__(self, instance: None, owner: type | None = None) -> H: ...
529 @overload
530 def __get__(self, instance: _Record, owner: type | None = None) -> T | None: ...
532 # Only for type checkers: mypy applies ``__get__`` to the value of a property
533 # that returns a field (e.g. ``Relation.related_field``); this keeps that a field.
534 @overload
535 def __get__(self, instance: object, owner: type | None = None) -> Field[T, H]: ...
537 def __get__(self, instance: Any, owner: type | None = None) -> H | T | None | Field[T, H]:
538 if instance is None:
539 return cast(H, self.expr_class(self))
540 return cast("T | None", instance._get_value(self))
542 def __set__(self, instance: Any, value: T | None) -> None:
543 instance._set_value(self, value)
545 def to_python(self, raw: Any) -> T | None:
546 """Convert a value from the API to ``T | None``; never returns anything else.
548 Safe, lossless coercions are applied (see each field class). A scalar
549 given for a multivalued field becomes a one-element list, and a
550 one-element list given for a scalar field becomes its element. A value
551 that still cannot be converted, including a list with any unconvertible
552 or ``None`` element, becomes ``None`` with a
553 :class:`~scixplorer.exceptions.DataWarning`.
554 """
555 if raw is None:
556 return None
557 try:
558 if self.multivalued:
559 items = raw if isinstance(raw, (list, tuple)) else [raw]
560 return cast(T, [self._convert(item) for item in items])
561 if isinstance(raw, (list, tuple)):
562 if len(raw) != 1:
563 raise ValueError("expected a single value")
564 if raw[0] is None:
565 return None
566 raw = raw[0]
567 return cast(T, self._convert(raw))
568 except _UNCONVERTIBLE:
569 text = repr(raw)
570 if len(text) > 80:
571 text = text[:77] + "..."
572 warnings.warn(
573 f"{self._label()}: cannot convert {text} to {self.type_name}; using None",
574 DataWarning,
575 stacklevel=2,
576 )
577 return None
579 def _convert(self, raw: Any) -> Any:
580 """Convert one non-list value, raising ValueError/TypeError if it cannot be."""
581 if raw is None:
582 raise TypeError("None is not a value")
583 value = self._to_python(raw)
584 if not isinstance(value, self.python_type): 584 ↛ 585line 584 didn't jump to line 585 because the condition on line 584 was never true
585 raise TypeError(f"converted to {type(value).__name__}")
586 return value
588 def _to_python(self, raw: Any) -> Any:
589 return raw
591 def normalise(self, value: Any) -> Any:
592 """The form in which this field holds ``value``, in expressions and on instances.
594 Most fields hold values exactly as given; a field accepting several
595 spellings of one value (:class:`NumericStringField`) returns its canonical form.
596 """
597 return value
599 def step(self, value: Any, direction: int) -> Any:
600 """The adjacent value above (``direction=1``) or below (``-1``) ``value``.
602 Returns ``None`` for fields whose values are not discrete; discrete
603 fields override this so exclusive range bounds can be made inclusive.
604 """
605 return None
607 def to_solr(self, value: Any) -> str:
608 """Format one value as bare Solr text (unquoted, unescaped).
610 Raises :class:`~scixplorer.exceptions.QueryError` if the value has the wrong type.
611 """
612 if isinstance(value, SolrLiteral):
613 return value.text
614 if value is None:
615 raise QueryError(f"{self._label()} cannot be compared with None")
616 return self._to_solr(value)
618 def _to_solr(self, value: Any) -> str:
619 return str(value)
621 def _reject(self, value: Any, expected: str) -> QueryError:
622 return QueryError(f"{self._label()} needs {expected}, not {value!r}")
624 def _label(self) -> str:
625 return f"{_model_name(self)}.{getattr(self, 'name', '?')}"
627 def __repr__(self) -> str:
628 return f"<{type(self).__name__} {self._label()}>"
631# Each concrete field class repeats two ``__init__`` overloads for the type
632# checker only: ``multivalued=True`` makes the value type ``list[...]``. The
633# overloads must name the concrete class, because type checkers cannot infer a
634# subclass's type parameter from self-typed overloads inherited from a base.
637_F = TypeVar("_F", bound=Field[Any, Any])
640def advised(field: _F, advice: Callable[[Any], str | None]) -> _F:
641 """Return ``field``, set to warn about compared values that ``advice`` gives a reason to doubt.
643 See :attr:`Field.advice`.
644 """
645 field.advice = advice
646 return field
649class _StringLikeField(Field[T, TextExpr]):
650 """Shared behaviour of fields holding strings."""
652 expr_class = TextExpr
653 python_type = str
655 def _to_python(self, raw: Any) -> Any:
656 """Accept a str, or an int/float (ADS sometimes returns numbers for string fields)."""
657 if isinstance(raw, str):
658 return raw
659 if isinstance(raw, (int, float)) and not isinstance(raw, bool):
660 return str(raw)
661 raise TypeError("not a string")
663 def _to_solr(self, value: Any) -> str:
664 if not isinstance(value, str):
665 raise self._reject(value, "a str")
666 if not value.strip():
667 raise self._reject(value, "a non-empty str")
668 return value
671class TextField(_StringLikeField[T]):
672 """Tokenized full text (title, abstract, ...); match kind ``"text"``.
674 ``==`` matches the phrase, and ADS also matches its synonyms and acronyms
675 (``title == "star"`` also finds synonyms of "star"); ``exact`` turns that
676 expansion off.
677 """
679 match_kind = "text"
681 if TYPE_CHECKING:
683 @overload
684 def __init__(
685 self: TextField[str],
686 doc: str = ...,
687 *,
688 multivalued: Literal[False] = ...,
689 stored: bool = ...,
690 indexed: bool = ...,
691 solr_name: str | None = ...,
692 ) -> None: ...
694 @overload
695 def __init__(
696 self: TextField[list[str]],
697 doc: str = ...,
698 *,
699 multivalued: Literal[True],
700 stored: bool = ...,
701 indexed: bool = ...,
702 solr_name: str | None = ...,
703 ) -> None: ...
705 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
708class StringField(_StringLikeField[T]):
709 """An untokenized keyword (bibcode, doctype, ...); match kind ``"keyword"``.
711 ``==`` matches the whole value literally, so ``exact`` changes nothing
712 (and no ``=`` is sent: ADS returns nothing for ``=bibcode:...``).
713 """
715 match_kind = "keyword"
717 if TYPE_CHECKING:
719 @overload
720 def __init__(
721 self: StringField[str],
722 doc: str = ...,
723 *,
724 multivalued: Literal[False] = ...,
725 stored: bool = ...,
726 indexed: bool = ...,
727 solr_name: str | None = ...,
728 ) -> None: ...
730 @overload
731 def __init__(
732 self: StringField[list[str]],
733 doc: str = ...,
734 *,
735 multivalued: Literal[True],
736 stored: bool = ...,
737 indexed: bool = ...,
738 solr_name: str | None = ...,
739 ) -> None: ...
741 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
744class NumericStringField(StringField[str]):
745 """A string of digits, such as ``Document.id``; queries also accept a non-negative int.
747 The value is a ``str`` (as the API returns it), and an int given in a query
748 or set on an instance is held as its decimal string, so
749 ``Document.id == 12312494`` is the same condition as ``Document.id == "12312494"``.
750 Bools, floats and negative ints are refused.
751 """
753 def __init__(
754 self,
755 doc: str = "",
756 *,
757 stored: bool = True,
758 indexed: bool = True,
759 solr_name: str | None = None,
760 ) -> None:
761 super().__init__(doc, stored=stored, indexed=indexed, solr_name=solr_name)
763 def normalise(self, value: Any) -> Any:
764 if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
765 return str(value)
766 return value
768 def _to_solr(self, value: Any) -> str:
769 value = self.normalise(value)
770 if not isinstance(value, str):
771 raise self._reject(value, "a str or a non-negative int")
772 return super()._to_solr(value)
775class NameField(_StringLikeField[T]):
776 """A personal name, ``"Last, First M"`` (author, editor, ...); match kind ``"name"``.
778 ``==`` matches name variants as ADS does: ``"Rubin, V"`` matches
779 ``"Rubin, Vera C."`` and ``"Rubin, Victoria"``, while ``"Rubin, Vera"``
780 matches ``"Rubin, V. D."`` but not ``"Rubin, Victoria"``. ``exact`` matches
781 only that form of the name, ignoring case and the periods after initials:
782 ``exact("Rubin, V")`` matches ``"Rubin, V."`` and nothing else above.
783 """
785 match_kind = "name"
787 if TYPE_CHECKING:
789 @overload
790 def __init__(
791 self: NameField[str],
792 doc: str = ...,
793 *,
794 multivalued: Literal[False] = ...,
795 stored: bool = ...,
796 indexed: bool = ...,
797 solr_name: str | None = ...,
798 ) -> None: ...
800 @overload
801 def __init__(
802 self: NameField[list[str]],
803 doc: str = ...,
804 *,
805 multivalued: Literal[True],
806 stored: bool = ...,
807 indexed: bool = ...,
808 solr_name: str | None = ...,
809 ) -> None: ...
811 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
814class VirtualField(_StringLikeField[NoReturn]):
815 """A search-only text field (such as ``full``); it never has a value on an instance.
817 Matched like a :class:`TextField` (match kind ``"text"``).
818 """
820 match_kind = "text"
822 def __init__(self, doc: str = "", *, multivalued: bool = False, solr_name: str | None = None) -> None:
823 super().__init__(doc, multivalued=multivalued, stored=False, solr_name=solr_name)
825 @overload
826 def __get__(self, instance: None, owner: type | None = None) -> TextExpr: ...
828 @overload
829 def __get__(self, instance: object, owner: type | None = None) -> NoReturn: ...
831 def __get__(self, instance: Any, owner: type | None = None) -> TextExpr:
832 if instance is None:
833 return self.expr_class(self)
834 raise AttributeError(f"{self._label()} is search-only and has no value on an instance")
836 def __set__(self, instance: Any, value: Any) -> None:
837 raise AttributeError(f"{self._label()} is search-only and cannot be set")
840class IntegerField(Field[T, NumericExpr]):
841 """An integer. Integral floats and strings from the API (``12.0``, ``"12"``) are accepted."""
843 expr_class = NumericExpr
844 python_type = int
846 if TYPE_CHECKING:
848 @overload
849 def __init__(
850 self: IntegerField[int],
851 doc: str = ...,
852 *,
853 multivalued: Literal[False] = ...,
854 stored: bool = ...,
855 indexed: bool = ...,
856 solr_name: str | None = ...,
857 ) -> None: ...
859 @overload
860 def __init__(
861 self: IntegerField[list[int]],
862 doc: str = ...,
863 *,
864 multivalued: Literal[True],
865 stored: bool = ...,
866 indexed: bool = ...,
867 solr_name: str | None = ...,
868 ) -> None: ...
870 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
872 def _to_python(self, raw: Any) -> Any:
873 if isinstance(raw, bool):
874 raise TypeError("a bool is not an int")
875 if isinstance(raw, int):
876 return raw
877 if isinstance(raw, float):
878 if raw.is_integer():
879 return int(raw)
880 raise ValueError("not integral")
881 if isinstance(raw, str):
882 number = Decimal(raw)
883 if number.is_finite() and number == number.to_integral_value():
884 return int(number)
885 raise ValueError("not integral")
886 raise TypeError("not a number")
888 def _to_solr(self, value: Any) -> str:
889 if isinstance(value, bool) or not isinstance(value, int):
890 raise self._reject(value, "an int")
891 return str(value)
893 def step(self, value: Any, direction: int) -> Any:
894 if isinstance(value, bool) or not isinstance(value, int):
895 return None
896 return value + direction
899class FloatField(Field[T, NumericExpr]):
900 """A floating-point number. Ints and numeric strings from the API are accepted."""
902 expr_class = NumericExpr
903 python_type = float
905 if TYPE_CHECKING:
907 @overload
908 def __init__(
909 self: FloatField[float],
910 doc: str = ...,
911 *,
912 multivalued: Literal[False] = ...,
913 stored: bool = ...,
914 indexed: bool = ...,
915 solr_name: str | None = ...,
916 ) -> None: ...
918 @overload
919 def __init__(
920 self: FloatField[list[float]],
921 doc: str = ...,
922 *,
923 multivalued: Literal[True],
924 stored: bool = ...,
925 indexed: bool = ...,
926 solr_name: str | None = ...,
927 ) -> None: ...
929 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
931 def _to_python(self, raw: Any) -> Any:
932 if isinstance(raw, bool) or not isinstance(raw, (int, float, str)):
933 raise TypeError("not a number")
934 return float(raw)
936 def _to_solr(self, value: Any) -> str:
937 if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
938 raise self._reject(value, "a finite number")
939 return repr(value)
942class BooleanField(Field[T, FieldExpr]):
943 """A boolean. ``"true"``/``"false"`` strings (any case) from the API are accepted."""
945 python_type = bool
947 if TYPE_CHECKING:
949 @overload
950 def __init__(
951 self: BooleanField[bool],
952 doc: str = ...,
953 *,
954 multivalued: Literal[False] = ...,
955 stored: bool = ...,
956 indexed: bool = ...,
957 solr_name: str | None = ...,
958 ) -> None: ...
960 @overload
961 def __init__(
962 self: BooleanField[list[bool]],
963 doc: str = ...,
964 *,
965 multivalued: Literal[True],
966 stored: bool = ...,
967 indexed: bool = ...,
968 solr_name: str | None = ...,
969 ) -> None: ...
971 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
973 def _to_python(self, raw: Any) -> Any:
974 if isinstance(raw, bool):
975 return raw
976 if isinstance(raw, str) and raw.lower() in ("true", "false"):
977 return raw.lower() == "true"
978 raise TypeError("not a boolean")
980 def _to_solr(self, value: Any) -> str:
981 if not isinstance(value, bool):
982 raise self._reject(value, "a bool")
983 return "true" if value else "false"
986def as_utc(value: date) -> datetime:
987 """Return ``value`` as an aware UTC datetime; dates and naive datetimes are taken as UTC."""
988 if not isinstance(value, datetime):
989 return datetime(value.year, value.month, value.day, tzinfo=timezone.utc)
990 if value.tzinfo is None:
991 return value.replace(tzinfo=timezone.utc)
992 return value.astimezone(timezone.utc)
995class DateTimeField(Field[T, NumericExpr]):
996 """A timestamp, held as an aware UTC ``datetime``."""
998 expr_class = NumericExpr
999 python_type = datetime
1001 if TYPE_CHECKING:
1003 @overload
1004 def __init__(
1005 self: DateTimeField[datetime],
1006 doc: str = ...,
1007 *,
1008 multivalued: Literal[False] = ...,
1009 stored: bool = ...,
1010 indexed: bool = ...,
1011 solr_name: str | None = ...,
1012 ) -> None: ...
1014 @overload
1015 def __init__(
1016 self: DateTimeField[list[datetime]],
1017 doc: str = ...,
1018 *,
1019 multivalued: Literal[True],
1020 stored: bool = ...,
1021 indexed: bool = ...,
1022 solr_name: str | None = ...,
1023 ) -> None: ...
1025 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
1027 def _to_python(self, raw: Any) -> Any:
1028 if isinstance(raw, date):
1029 return as_utc(raw)
1030 if not isinstance(raw, str):
1031 raise TypeError("not a timestamp")
1032 text = raw[:-1] if raw.endswith("Z") else raw
1033 for fmt in ("%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d"):
1034 try:
1035 return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc)
1036 except ValueError:
1037 pass
1038 raise ValueError(f"{self._label()}: unrecognised timestamp {raw!r}")
1040 def _to_solr(self, value: Any) -> str:
1041 if not isinstance(value, date):
1042 raise self._reject(value, "a date or datetime")
1043 return as_utc(value).strftime("%Y-%m-%dT%H:%M:%SZ")
1046_PUBDATE = re.compile(r"(\d{4})-(\d{2})(?:-(\d{2}))?")
1049class DateField(Field[T, NumericExpr]):
1050 """A date with month precision in queries (ADS ``pubdate``), held as a ``date``."""
1052 expr_class = NumericExpr
1053 python_type = date
1055 if TYPE_CHECKING:
1057 @overload
1058 def __init__(
1059 self: DateField[date],
1060 doc: str = ...,
1061 *,
1062 multivalued: Literal[False] = ...,
1063 stored: bool = ...,
1064 indexed: bool = ...,
1065 solr_name: str | None = ...,
1066 ) -> None: ...
1068 @overload
1069 def __init__(
1070 self: DateField[list[date]],
1071 doc: str = ...,
1072 *,
1073 multivalued: Literal[True],
1074 stored: bool = ...,
1075 indexed: bool = ...,
1076 solr_name: str | None = ...,
1077 ) -> None: ...
1079 def __init__(self, *args: Any, **kwargs: Any) -> None: ...
1081 def _to_python(self, raw: Any) -> Any:
1082 if isinstance(raw, datetime):
1083 return raw.date()
1084 if isinstance(raw, date):
1085 return raw
1086 match = _PUBDATE.fullmatch(raw) if isinstance(raw, str) else None
1087 if match is None:
1088 raise ValueError(f"{self._label()}: unrecognised date {raw!r}")
1089 year, month, day = (int(part or 0) for part in match.groups())
1090 return date(year, month or 1, day or 1)
1092 def _to_solr(self, value: Any) -> str:
1093 if isinstance(value, datetime):
1094 value = as_utc(value)
1095 if isinstance(value, date):
1096 return f"{value.year:04d}-{value.month:02d}"
1097 if isinstance(value, str):
1098 match = _PUBDATE.fullmatch(value)
1099 if match and match.group(3) is None and 1 <= int(match.group(2)) <= 12:
1100 return value
1101 raise self._reject(value, "a date, a datetime or a 'YYYY-MM' string")
1103 def step(self, value: Any, direction: int) -> Any:
1104 if isinstance(value, SolrLiteral):
1105 return None
1106 year, month = (int(part) for part in self.to_solr(value).split("-"))
1107 months = year * 12 + (month - 1) + direction
1108 return date(months // 12, months % 12 + 1, 1)