httk.serve.optimade.backend¶
Public backend adapters, stores, and filter translation helpers.
Submodules¶
- httk.serve.optimade.backend.adapter
- httk.serve.optimade.backend.execution
- httk.serve.optimade.backend.handlers
- httk.serve.optimade.backend.memory_store
- httk.serve.optimade.backend.partial
- httk.serve.optimade.backend.protocols
- httk.serve.optimade.backend.providers
- httk.serve.optimade.backend.stores
- httk.serve.optimade.backend.translation
Classes¶
Build one query and iterate its results. |
|
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. |
|
Require a store that can create a query searcher. |
|
Bind a store to the OPTIMADE entry endpoints it serves. |
|
Describe one queryable source behind an OPTIMADE entry endpoint. |
|
Results of a query over one or more searchers. |
|
Provide a store over dictionary rows. |
|
Describe one list axis of a |
|
Describe a property value provided lazily, one slice at a time. |
|
The callback seam through which the request engine runs queries on a backend. |
|
The results of a query against a backend, as consumed by the entry endpoints. |
|
Serve one data federation per OPTIMADE entry type. |
Functions¶
|
Execute a translated query across the adapter's sources. |
|
Build a filter handler table for an entry type from a property-key map. |
|
Build a |
Return the registered entry-provider factories keyed by their registered name. |
|
|
Build a lazy OPTIMADE adapter from every described family in one store. |
|
Build a lazy store-backed adapter from durable entry sources. |
|
Build one searcher per entry source, with the filter applied to each. |
|
Translate one filter node against an OPTIMADE entry-info property mapping. |
Package Contents¶
- class httk.serve.optimade.backend.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.serve.optimade.backend.SearchExpression¶
Bases:
ProtocolRequire composable backend search expressions.
- class httk.serve.optimade.backend.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.serve.optimade.backend.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.serve.optimade.backend.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.serve.optimade.backend.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.
- class httk.serve.optimade.backend.BackendAdapter¶
Bind a store to the OPTIMADE entry endpoints it serves.
sourcesmaps entry endpoint names (e.g.'structures') to the sources queried for that endpoint; an endpoint with several sources (e.g. several calculation result types) is queried across all of them.schemais required: it declares the served entry types and properties.field_handlersmaps each entry type to its filter-handler table. When omitted (left empty) it is derived fromschemaviasimple_property_handlers(), using an identity property-key map (each property is filtered against a backend field of the same name); a backend whose field names differ, or that wants finer control, supplies its own tables instead.- Parameters:
store – Store implementing the neutral query protocol.
sources – Queryable sources keyed by entry endpoint.
schema – Required schema describing served entries and properties.
field_handlers – Optional filter handlers keyed by entry endpoint.
- store: httk.store.query.Store¶
- field_handlers: collections.abc.Mapping[str, httk.store.query.optimade_filters.HandlerTable]¶
- query_function()¶
Return the callback that executes queries through this adapter.
- Returns:
Query callback consumed by the OPTIMADE request engine.
- Return type:
- class httk.serve.optimade.backend.EntrySource¶
Describe one queryable source behind an OPTIMADE entry endpoint.
targetis what gets passed tosearcher.variable();fieldsmaps OPTIMADE response-field names to extractors applied to matched row objects.relationships, when set, is an extractor mapping a matched row to a dictionary keyed by related entry type, each value a list of{'id': str, 'description': str?, 'role': str?}dictionaries.sort_keysmaps response-field names to the backend field names to sort on.property_metadatamaps response-field names to extractors returning the per-property metadata dictionary for a matched row (orNonewhen there is no metadata for that row).- Parameters:
target – Store-specific target passed to
searcher.variable.fields – Response-field extractors applied to matched rows.
sort_keys – Response-field to backend-sort-field mappings.
relationships – Optional extractor for related-resource data.
property_metadata – Optional per-property metadata extractors.
- target: Any¶
- fields: collections.abc.Mapping[str, FieldExtractor]¶
- sort_keys: collections.abc.Mapping[str, str]¶
- relationships: FieldExtractor | None = None¶
- property_metadata: collections.abc.Mapping[str, FieldExtractor]¶
- class httk.serve.optimade.backend.StoreResults(pairs, response_fields, unknown_response_fields, limit, offset, total_count, recognized_prefixes)¶
Results of a query over one or more searchers.
Implements the
QueryResultsprotocol. Iteration yields oneResultRowper entry, whose values map response-field names to values extracted from the matched row objects.- Parameters:
pairs (list[tuple[httk.serve.optimade.backend.adapter.EntrySource, httk.store.query.Searcher]]) – Sources and already-configured searchers to iterate.
unknown_response_fields (list[str]) – Unknown fields to return as null.
limit (int | None) – Maximum number of results to yield.
offset (int) – Number of results to skip.
total_count (int) – Total matches before pagination.
recognized_prefixes (tuple[str, Ellipsis]) – Prefixes for dynamic row attributes.
- pairs¶
- recognized_prefixes¶
- limit¶
- response_fields¶
- unknown_response_fields¶
- offset¶
- more_data_available = True¶
- count()¶
Return all current-filter matches, before pagination.
The endpoint metadata needs the filtered total even after execution has applied page limits and offsets to its searchers. Retaining it here also keeps the value stable once this one-shot result iterator is consumed.
- httk.serve.optimade.backend.execute_query(adapter, entries, response_fields, unknown_response_fields, response_limit, response_offset, filter_ast=None, *, sort=None, debug=False)¶
Execute a translated query across the adapter’s sources.
- Parameters:
adapter (httk.serve.optimade.backend.adapter.BackendAdapter) – Backend adapter providing sources and schema.
unknown_response_fields (list[str]) – Unknown fields to return as null.
response_limit (int | None) – Maximum number of returned rows.
response_offset (int | None) – Number of matching rows to skip.
filter_ast (httk.core.optimade.FilterAst | None) – Parsed filter, when one was requested.
sort (collections.abc.Sequence[tuple[str, bool]] | None) – Fields and directions to sort by.
debug (bool) – Enable backend diagnostics.
- Returns:
Lazy results for the requested page.
- Raises:
httk.serve.optimade.model.errors.TranslatorError – If sorting across multiple sources is requested.
- Return type:
- httk.serve.optimade.backend.simple_property_handlers(entry_type, property_keys, property_fulltypes)¶
Build a filter handler table for an entry type from a property-key map.
Provides default handlers for standard
id(matched against theID_FIELDfield) andtype(a constant equal toentry_type). Entries inproperty_keysreplace those defaults when their names overlap. For every property named inproperty_keys(which maps property names to backend field names), handlers are generated from the property’s fulltype inproperty_fulltypes(default"string"): string properties get comparison and stringmatching handlers; integer and float properties get a numeric comparison handler;list of ...properties get a HAS (set membership) handler. Every generated property also gets aknownunknown handler.- Parameters:
entry_type (str) – The served entry type used by the constant
typehandler.property_keys (collections.abc.Mapping[str, str]) – Mapping from served property names to backend field names.
property_fulltypes (collections.abc.Mapping[str, str]) – Fulltypes keyed by served property name.
- Returns:
A handler table keyed by served property name.
- Return type:
dict[str, collections.abc.Mapping[str, collections.abc.Callable[Ellipsis, Any]]]
- class httk.serve.optimade.backend.InMemoryStore(tables)¶
Provide a store over dictionary rows.
- tables¶
- searcher(*, as_of=None)¶
Create a searcher over this store’s tables.
- Parameters:
as_of (object) – Optional historic timestamp cutoff; unsupported here.
- Returns:
Fresh in-memory searcher.
- Raises:
ValueError – If a historic cutoff is requested.
- Return type:
- class httk.serve.optimade.backend.PartialDimension¶
Describe one list axis of a
PartialValue.lengthis the number of items along the axis (Nonewhen unknown or entry-dependent and not declared).sliceableindicates whether the server can honour a slice request for this axis.- Parameters:
name – Dimension name used in response metadata.
length – Number of items, or
Nonewhen unknown.sliceable – Whether the server accepts slices on this axis.
- class httk.serve.optimade.backend.PartialValue¶
Describe a property value provided lazily, one slice at a time.
fetchtakes a tuple of Python slices (one per dimension, with the usual exclusive stop) and returns the corresponding nested lists.- Parameters:
dimensions – Axes describing the value.
fetch – Slice retrieval operation.
- dimensions: tuple[PartialDimension, Ellipsis]¶
- fetch: collections.abc.Callable[[tuple[slice, Ellipsis]], Any]¶
- class httk.serve.optimade.backend.QueryFunction¶
Bases:
ProtocolThe callback seam through which the request engine runs queries on a backend.
- class httk.serve.optimade.backend.QueryResults¶
Bases:
ProtocolThe results of a query against a backend, as consumed by the entry endpoints.
Iteration yields one
ResultRowper entry; itsvaluesmap OPTIMADE response-field names to values, and theidandtypekeys are always present.- count()¶
Return the total number of matches before pagination.
- httk.serve.optimade.backend.adapter_from_providers(providers, **options)¶
Build a
BackendAdapterserving the given entry providers.Every provider’s
entry_types()become served entry types (described by theirEntryTypeDefinition), itsproperty_keys()name the served subset and drive both the filter handlers (viasimple_property_handlers()) and the response-field extractors, and itsrecords()are loaded into anInMemoryStore. Every served property MUST be described by the entry type’s definition (a custom property must therefore live in anextended()definition); aValueErrornames any offender. All served properties beyondid/typeare marked default-response. Extra keywordoptions(e.g.sortable,recognized_prefixes) are forwarded tobuild_served_schema(); every served property is sortable-capable, since the provider’s property-key map is passed through as the source’ssort_keys.Declared relationships (
relationships()) are fully auto-wired for serving and filtering: for each entry type with declared relationships, a synthetic__rel_<related_type>id-list field is materialized on EVERY row of that entry type (an empty list when the row has no related entries of that type, so inverse set semantics are well-defined), and a'<related_type>.id'entry built withrelationship_id_handler()is merged into the entry type’s derived filter-handler table (never overwriting an entry already present, mirroring howBackendAdapterrespects explicitly supplied handler tables).<related_type>.id HAS ...filters — and, through the related-property resolver oftranslate_filter(), depth-1 relationship-property filters such asreferences.doi CONTAINS "10.1"— therefore work without any hand-wiring.A provider’s reverse relationships (
EntryProvider.reverse_relationships()) are consumed too: their target-keyed related entries are append-merged into each served target entry’s relationships (never clobbering the forward entries), so a derived reverse edge is served on the entry it points at.- Parameters:
providers (collections.abc.Iterable[httk.core.EntryProvider]) – Generic entry providers supplying definitions, keys, records, and relationships.
**options (Any) – Schema options forwarded to
build_served_schema().
- Returns:
Fully wired in-memory backend adapter.
- Raises:
ValueError – If provider keys or served properties are invalid.
- Return type:
- httk.serve.optimade.backend.providers_from_registry()¶
Return the registered entry-provider factories keyed by their registered name.
Resolves each factory registered via
httk.core.register_entry_provider()(throughhttk.registry.*self-registration) into a callable. Providers need data, so applications instantiate them:providers_from_registry()["atomistic-structures"](data).- Returns:
Registered provider factories keyed by registry name.
- Return type:
dict[str, collections.abc.Callable[Ellipsis, httk.core.EntryProvider]]
- class httk.serve.optimade.backend.StoredBackendAdapter¶
Serve one data federation per OPTIMADE entry type.
- Parameters:
federations – Durable federations keyed by entry endpoint.
schema – Schema describing the federations’ served entries.
- federations: collections.abc.Mapping[str, Any]¶
- snapshot_cutoff_ns(entry_type, now_ns)¶
Return the resolution-aware snapshot cutoff for one entry type.
- query_function()¶
Return the callback that queries the configured federations.
- Returns:
Query callback consumed by the OPTIMADE request engine.
- Return type:
- httk.serve.optimade.backend.adapter_from_store(store, **options)¶
Build a lazy OPTIMADE adapter from every described family in one store.
Families declared without an entry-type definition are deliberately ignored. This lets application-specific records, such as DSP publication declarations, coexist with OPTIMADE records in one durable layout.
- Parameters:
store (httk.store.EntryStore) – Entry store whose configured layout is discovered.
**options (Any) – Schema options forwarded to
adapter_from_stores().
- Returns:
Lazy adapter over all configured OPTIMADE families.
- Raises:
TypeError – If
storedoes not implementEntryStore.ValueError – If the store contains no OPTIMADE-described family.
- Return type:
- httk.serve.optimade.backend.adapter_from_stores(sources, **options)¶
Build a lazy store-backed adapter from durable entry sources.
Sources with the same exact logical family are federated under one entry endpoint. The data layer owns all source/backing traversal and global pagination; this adapter advertises the family’s definition and turns only the returned page into OPTIMADE result rows.
- Parameters:
sources (collections.abc.Sequence[httk.store.backend.sql.StoredEntrySource]) – Durable entry sources to federate by entry type.
**options (Any) – Schema options forwarded to
build_served_schema().
- Returns:
Lazy adapter over the supplied durable sources.
- Raises:
ValueError – If sources conflict or expose incomplete sort mappings.
TypeError – If a source is not a stored entry source.
- Return type:
- httk.serve.optimade.backend.translate_filter(filter_ast, entries, adapter, sort=None)¶
Build one searcher per entry source, with the filter applied to each.
Relationship-property filters (dotted identifiers over served entry types) are resolved through the adapter’s related-property resolver (built by
_related_property_resolver), so filteringreferences.doibehaves exactly like filtering/referencesdirectly.- Parameters:
filter_ast (httk.core.optimade.FilterAst | None) – Parsed filter, or
Nonefor an unfiltered query.adapter (httk.serve.optimade.backend.adapter.BackendAdapter) – Backend adapter supplying sources and handlers.
sort (collections.abc.Sequence[tuple[str, bool]] | None) – Response fields and descending flags for sorting.
- Returns:
Source/searcher pairs with the filter and sort applied.
- Raises:
httk.serve.optimade.model.errors.TranslatorError – If the filter cannot be translated.
- Return type:
list[tuple[httk.serve.optimade.backend.adapter.EntrySource, httk.store.query.Searcher]]
- httk.serve.optimade.backend.translate_filter_node(node, search_variable, entry, entry_info, handlers, recognized_prefixes, served_entries=())¶
Translate one filter node against an OPTIMADE entry-info property mapping.
An OPTIMADE-side adaptation of
translate_filter_ast():entry_infomaps property names to their property dictionaries (only their'fulltype'keys are read) rather than straight to fulltypes,served_entriesnames the relationship targets, and failures surface asTranslatorErrorinstead of the upstream neutralFilterTranslationError.No related-property resolver is threaded through, so relationship-property filters other than
<type>.id HAS ...raise a not-implemented (501) error. Usetranslate_filter()(which builds the resolver from its adapter) for full relationship-property filtering.- Parameters:
node (httk.core.optimade.FilterAst) – Filter node to translate.
search_variable (httk.store.query.SearchVariable) – Backend variable used by the expression.
entry (str) – Entry endpoint being filtered.
entry_info (collections.abc.Mapping[str, Any]) – Simplified property metadata for the entry.
handlers (httk.store.query.optimade_filters.HandlerTable) – Property handlers used for translation.
recognized_prefixes (tuple[str, Ellipsis]) – Property-definition prefixes accepted by the filter.
served_entries (tuple[str, Ellipsis]) – Entry types available as relationship targets.
- Returns:
Backend search expression.
- Raises:
httk.serve.optimade.model.errors.TranslatorError – If the filter cannot be translated.
- Return type: