httk.store.query¶
Define backend-agnostic query protocols and portable query capabilities.
The httk.store.query.optimade_filters module contains OPTIMADE filter-translation
machinery for serving layers and is intentionally not lifted here.
Submodules¶
Attributes¶
The backend field name used for the served entry identifier. |
Exceptions¶
Report that a store cannot provide an exact query count. |
|
Report that a result-set |
|
Report that a result-set |
|
Report that a continuation cursor is malformed, expired, or belongs to another result plan. |
|
Report that a valid query operation is outside a store's supported profile. |
Classes¶
Describe the query operations guaranteed by one property definition. |
|
Carry an opaque URL-safe continuation value. |
|
Order a continuation page by one named scalar result projection. |
|
Expose optional continuation-page capability on a frozen result set. |
|
Represent an immutable continuation-page result. |
|
Represent one named result row by position, name, or attribute. |
|
Require named access to one result row. |
|
Require the common operations of a materialized result set. |
|
Require composable backend search expressions. |
|
Expose a queryable field of a search variable. |
|
Represent one match with declared output values and names. |
|
Bind a query variable to a target type whose attributes yield fields. |
|
Build one query and iterate its results. |
|
Require a store that can create a query searcher. |
|
A pandas-style indexing view over one record class in a store. |
|
One field of a |
|
A boolean predicate over a |
|
The records of a |
Functions¶
|
Derive the portable operation subset for |
|
Return the ordered portable query fields described by |
Package Contents¶
- class httk.store.query.PortableQueryCapabilities¶
Describe the query operations guaranteed by one property definition.
query-supportexpresses a cross-provider guarantee, not a particular server’s implementation detail.all optionalis deliberately fail-closed here: it gives a portable client no operation it can rely on. A server may offer more, but that is not represented by the definition.- Parameters:
query_support – The normalized declared query-support level.
operations – The portable operation families guaranteed by the definition.
- httk.store.query.portable_query_capabilities(definition)¶
Derive the portable operation subset for
definition.The operation names are
"equality","ordering","stringmatching", and"set". They intentionally describe the query-language operation families rather than storage implementation.IS [NOT] KNOWNis part of the equality family because it is the NULL spelling of equality/inequality in the OPTIMADE filter language.- Parameters:
definition (httk.core.PropertyDefinition) – The OPTIMADE property definition to inspect.
- Returns:
The guaranteed portable query capabilities.
- Return type:
- httk.store.query.portable_query_fields(entry_type, *, include=(), exclude=())¶
Return the ordered portable query fields described by
entry_type.By default, this selects scalar fields and flat lists with at least one operation guaranteed by their definition.
includeis an explicit binding override for named existing properties; it is appended as a second ordered group after the derived fields, in entry-definition order among the included names, but does not manufacture query capabilities absent from that definition.excludealways wins. Both arguments reject unknown or duplicate names so binding mistakes cannot silently broaden a profile.- Parameters:
entry_type (httk.core.EntryTypeDefinition) – The entry definition whose properties are inspected.
include (collections.abc.Iterable[str]) – Existing property names to append to the derived selection.
exclude (collections.abc.Iterable[str]) – Existing property names to remove from the selection.
- Returns:
Derived property names followed by explicitly included names.
- Raises:
ValueError – If
includeorexcludecontains an unknown or duplicate property name.- Return type:
- httk.store.query.ID_FIELD: Final = '__id'¶
The backend field name used for the served entry identifier.
- class httk.store.query.ContinuationToken¶
Bases:
strCarry an opaque URL-safe continuation value.
It is a
strsubclass so normal JSON serializers preserve it as a scalar value. Applications should pass a token returned by a page back unchanged; data backends validate its version, structure, and result-plan fingerprint before using any decoded value as a bound parameter.- Parameters:
value – The opaque continuation value.
Bases:
RuntimeErrorReport that a store cannot provide an exact query count.
- exception httk.store.query.MultipleResultsError¶
Bases:
LookupErrorReport that a result-set
one()operation found multiple results.
- exception httk.store.query.NoResultError¶
Bases:
LookupErrorReport that a result-set
one()operation found no matching result.
- class httk.store.query.PageOrder¶
Order a continuation page by one named scalar result projection.
nameidentifies the name supplied toresults()(orSearcher.output()), never a backend column object. The result-set implementation validates that it is a root scalar projection before it generates SQL.- Parameters:
name – The declared scalar output name used for ordering.
descending – Whether to order this field in descending order.
nulls – Whether null values sort first or last.
- nulls: Literal['first', 'last'] = 'last'¶
- class httk.store.query.PageableResultSetLike¶
Bases:
ProtocolExpose optional continuation-page capability on a frozen result set.
This deliberately extends neither
ResultSetLikenorSearcher: stores that do not support seek pagination remain fully conforming to the required portable contracts.- page(*, size, order_by, cursor=None, include_total=False)¶
Return one ordered continuation page.
- exception httk.store.query.PaginationCursorError¶
Bases:
ValueErrorReport that a continuation cursor is malformed, expired, or belongs to another result plan.
- class httk.store.query.ResultPage¶
Represent an immutable continuation-page result.
rowsis always a tuple. Returned rows are ordinary persistent result rows, not the expiring proxies produced bySqlResultSet.cursor().totalis populated only when the caller explicitly asks for it.- Parameters:
rows – The persistent rows returned by the page.
next – The token for the next page, if one exists.
previous – The token for the previous page, if one exists.
total – The exact result count when requested, otherwise
None.
- rows: tuple[ResultRowLike, Ellipsis]¶
- next: ContinuationToken | None¶
- previous: ContinuationToken | None¶
- class httk.store.query.ResultRow(values, names, resolver=None, guard=None)¶
Represent one named result row by position, name, or attribute.
- Parameters:
- class httk.store.query.ResultRowLike¶
Bases:
ProtocolRequire named access to one result row.
- class httk.store.query.ResultSetLike¶
Bases:
ProtocolRequire the common operations of a materialized result set.
- first()¶
Return the first row, or
Nonewhen no row matches.
- one()¶
Return the only row, or raise when the count is not one.
- scalars(name=None)¶
Iterate over one named scalar output.
- class httk.store.query.SearchExpression¶
Bases:
ProtocolRequire composable backend search expressions.
- class httk.store.query.SearchField¶
Bases:
ProtocolExpose a queryable field of a search variable.
In addition to the methods below, fields support the rich comparison operators (
==,!=,<,<=,>,>=), returningSearchExpression. The handlers invoke those viagetattr(field, '__eq__')(value)since the comparison dunders cannot be typed as expression-returning.The three string-matching methods take literal text: no wildcard or pattern syntax whatsoever crosses this contract, so
%and_(and any other metacharacter) match themselves. A backend is therefore free to implement them with SQLLIKEover an escaped pattern, with a regular expression, or with a full-text index — the choice is invisible here.- has(value)¶
Match a list field containing
value.
- has_any(*values)¶
Match a list field containing any of
values.
- has_only(*values)¶
Match a list field containing no values outside
values.
- is_in(*values)¶
Match a root scalar field whose value is one of
values.Noneis an explicit member: it matches a null field value, and its negation excludes nulls rather than inheriting SQL’s three-valuedNOT IN (..., NULL)behavior.Backends define the corresponding semantics for child or set fields; for example, a backend may use the existing
has_only-style all-values reading for a child field.
- contains(text)¶
Match values containing
textas a literal substring.
- startswith(prefix)¶
Match values beginning with the literal
prefix.
- endswith(suffix)¶
Match values ending with the literal
suffix.
- class httk.store.query.SearchResult¶
Bases:
NamedTupleRepresent one match with declared output values and names.
valuesholds one entry perSearcher.output()call in declaration order; it is a tuple, sovalues, names = resultandresult[0][0]both work.
- class httk.store.query.SearchVariable¶
Bases:
ProtocolBind a query variable to a target type whose attributes yield fields.
always_true/always_falseare reserved names: they are real methods of the variable, never stored fields resolved through__getattr__. They exist so a translation layer can express a constant truth value without inventing a probe field. Afield == fieldprobe is NULL-unsound, since it yields NULL (not true) for a NULL field.- always_true()¶
An expression that matches every row.
- always_false()¶
An expression that matches no row.
- class httk.store.query.Searcher¶
Bases:
ProtocolBuild one query and iterate its results.
Iteration yields one
SearchResultper match, soitem[0][0]is the first declared output of the match (typically the matched row object). The expressions received byaddare always ones produced by this same backend’s search variables, so implementations may type them as their own expression class; a backend that needs a second (post-filter) evaluation position decides that from the expression itself, not from the caller.- variable(target)¶
Bind a query variable to
target.
- output(variable, name)¶
Declare
variableas a named result output.
- add(expression)¶
Add a filter expression to the query.
- count()¶
Return the exact count of the current query.
- set_limit(limit)¶
Set the query limit.
- add_offset(offset)¶
Add an offset to the query.
- add_sort(field, descending)¶
Add a field sort to the query.
- results(**outputs)¶
Return a result set for the requested named outputs.
- class httk.store.query.Store¶
Bases:
ProtocolRequire a store that can create a query searcher.
Implementations predating the
as_ofkeyword may omit it and remain usable for current-state queries, but cannot honor historic queries.
- exception httk.store.query.UnsupportedQueryError¶
Bases:
ValueErrorReport that a valid query operation is outside a store’s supported profile.
- class httk.store.query.Slicer(make_searcher, target)¶
A pandas-style indexing view over one record class in a store.
Index it with a field-name string to iterate that field’s values, or with a boolean
SlicerMaskto iterate the matching records. Iterating the slicer itself yields every record;len()counts them. Each operation runs against its own fresh searcher, so operations never share filter state.- Parameters:
make_searcher (collections.abc.Callable[[], Any]) – A zero-argument callable returning a fresh searcher.
target (Any) – The stored record class this slicer indexes.
- class httk.store.query.SlicerColumn(slicer, path)¶
One field of a
Slicer, iterable and comparable.Iterating yields the field’s decoded scalar values. Comparisons and the
isin/isna/notna/betweenhelpers, plus the.strliteral matchers, build aSlicerMaskfor use as a slicer index key.- Parameters:
- isin(values)¶
Match records whose field value is one of
values.- Parameters:
values (collections.abc.Iterable[Any]) – The membership set.
- Returns:
A mask matching records in the set.
- Return type:
- isna()¶
Match records whose field value is null.
- Returns:
A mask matching null field values.
- Return type:
- notna()¶
Match records whose field value is not null.
- Returns:
A mask matching non-null field values.
- Return type:
- between(low, high)¶
Match records whose field value lies in
[low, high]inclusive.- Parameters:
low (Any) – The inclusive lower bound.
high (Any) – The inclusive upper bound.
- Returns:
A mask matching the closed interval.
- Return type:
- property str: _SlicerStr¶
The literal string-matching accessor for this column.
- Returns:
The
contains/startswith/endswithaccessor.- Return type:
_SlicerStr
- class httk.store.query.SlicerMask(slicer, ast)¶
A boolean predicate over a
Slicer, combinable with& | ^ ~.A mask is not iterable and has no comparison operators; it is used only as a slicer index key or combined with another mask from the same slicer.
- Parameters:
slicer (Slicer) – The owning slicer.
ast (_Node) – The op tree the mask describes.
- class httk.store.query.SlicerSelection(slicer, ast)¶
The records of a
Slicermatching aSlicerMask.Iterating yields the reconstructed records;
len()counts them. Each runs against its own fresh searcher.- Parameters:
slicer (Slicer) – The owning slicer.
ast (_Node) – The op tree selecting the records.