httk.data.db¶
The SQL storage layer of httk-data: store frozen dataclasses in relational databases.
This subpackage turns plain frozen dataclasses — declared storable with the
stdlib-only marker vocabulary in httk-core (Indexed, Unique, Skip,
Shape, StorageInfo, stored_property) — into relational storage.
The pure-Python foundation lives here:
httk.data.db.schema—resolve_schema()reads a storable class into aTableSchema, the single source of truth for DDL, inserts, selects, and reconstruction;httk.data.db.codecs— theValueCodecregistry with exact, round-trippable encodings for rationals, surds, and datetimes;httk.data.db.identity—canonical_form()andcontent_id(), the content identity used for deduplication.
These modules import cleanly without sqlalchemy. The SQL layer proper builds
on them and requires the httk-data[db] extra (sqlalchemy):
Database— the engine wrapper naming where data lives (Database.sqlite(...),Database.duckdb(...));SqlStore— save/fetch/dedup/transactions for storable instances, on top of the schema-to-table mapping inhttk.data.db.mapping;SqlSearcher(fromsearcher()) — the query DSL implementing thehttk.data.querysearch protocols, withSqlVariable,SqlColumnandSqlExpression;StoreEntryProvider— the bridge that serves stored classes through the neutralEntryProvidercontract (e.g. as an OPTIMADE API via httk-optimade);optimade_filter_searcher()— OPTIMADE-filter querying over storable classes, tying the generic filter translation inhttk.data.optimade_queryto the SQL layer.
The sqlalchemy-backed names are imported lazily on first attribute access, so
import httk.data.db keeps working without sqlalchemy; touching them
without sqlalchemy installed raises ImportError naming the extra.
Submodules¶
Attributes¶
The canonical exact text of a rational — reduced |
|
The canonical exact text of a rational tensor — common denominator, then numerators row-major. |
|
The canonical exact text of a surd scalar — |
|
The five scalar column kinds a storage backend must provide. |
|
How a stored field maps onto the relational model. |
Exceptions¶
A class or field cannot be resolved into a storage schema; the message names both. |
Classes¶
An exact encoding of one Python value type across one or more scalar columns. |
|
The out-of-line child table backing a variable-length field. |
|
One scalar column of a table. |
|
The resolved storage shape of one stored field (or stored property). |
|
The resolved relational schema of one storable class. |
Functions¶
|
Return the codec for |
|
Return the codec registered as |
|
Parse |
|
Parse |
|
Parse |
|
The canonical |
|
The canonical |
|
The elements of a rational tensor as a flat row-major tuple of nearest floats. |
|
The canonical |
|
Return the registered value-codec names, in registration order. |
|
Register |
|
The deterministic canonical JSON text of a storable instance's stored values. |
|
The SHA-256 hex digest (64 hex characters) of |
|
Register an external |
|
Resolve (and cache) the |
|
The default table name for a class name: CamelCase to camel_case (acronym-aware). |
Package Contents¶
- httk.data.db.FRACTION_EXACT_FORMAT: Final = 'p/q'[source]¶
The canonical exact text of a rational — reduced
"p/q", always with the/qpart.
- httk.data.db.FRACVECTOR_EXACT_FORMAT: Final = 'd;n0,n1,n2,...'[source]¶
The canonical exact text of a rational tensor — common denominator, then numerators row-major.
- httk.data.db.SURD_EXACT_FORMAT: Final = 'r1:p1/q1;r2:p2/q2;...'[source]¶
The canonical exact text of a surd scalar —
radicand:coefficientterms sorted by radicand.
- type httk.data.db.ScalarKind = Literal['int', 'float', 'str', 'bool', 'bytes'][source]¶
The five scalar column kinds a storage backend must provide.
- class httk.data.db.ValueCodec[source]¶
An exact encoding of one Python value type across one or more scalar columns.
The
columnstuple gives(suffix, kind)pairs: the empty suffix names the field’s own column (by convention the query column), non-empty suffixes are appended to the field name by the schema layer (e.g."_exact").encodeanddecodemap a value to and from the column-value tuple, incolumnsorder, and must round-trip exactly.- columns: tuple[tuple[str, ScalarKind], Ellipsis]¶
The
(column name suffix, scalar kind)pairs the codec encodes into.
- encode: collections.abc.Callable[[Any], tuple[Any, Ellipsis]]¶
Encode a value into one scalar per entry of
columns, in order.
- decode: collections.abc.Callable[[tuple[Any, Ellipsis]], Any]¶
Recover the exact value from the tuple produced by
encode.
- httk.data.db.codec_for(python_type: Any) ValueCodec | None[source]¶
Return the codec for
python_type, or None if no codec covers it.An exact type match wins; otherwise the registered codecs are scanned once in registration order and the first whose
python_typeis a base class ofpython_typeis returned (deterministic by registration order).
- httk.data.db.codec_named(name: str) ValueCodec[source]¶
Return the codec registered as
name; raiseValueErrorlisting the known names.
- httk.data.db.decode_fraction_exact(text: str) fractions.Fraction[source]¶
Parse
FRACTION_EXACT_FORMATtext back into an exactfractions.Fraction.
- httk.data.db.decode_fracvector_exact(text: str, rows: int, cols: int) httk.core.FracVector[source]¶
Parse
FRACVECTOR_EXACT_FORMATtext into arowsxcolsFracVector.The numerators are laid out row-major into a tensor of shape
(rows, cols); their count must equalrows * cols. RaisesValueErroron malformed text or a count/shape mismatch.
- httk.data.db.decode_surdscalar_exact(text: str) httk.core.SurdScalar[source]¶
Parse
SURD_EXACT_FORMATtext back into an exactSurdScalar.
- httk.data.db.encode_fraction_exact(value: fractions.Fraction) str[source]¶
The canonical
FRACTION_EXACT_FORMATtext ofvalue(e.g."-7/3","1/1").
- httk.data.db.encode_fracvector_exact(value: httk.core.FracVector) str[source]¶
The canonical
FRACVECTOR_EXACT_FORMATtext of a rational tensor.The tensor is flattened row-major and normalized through
to_fractions():dis the least positive common denominator of the (reduced) elements and the numerators are the elements scaled byd. The text is therefore canonical — independent of the internal denominator the input happened to carry — and lossless at arbitrary precision. The shape itself is not encoded; fixed-shape schema fields carry it in their declaration.
- httk.data.db.encode_fracvector_floats(value: httk.core.FracVector) tuple[float, Ellipsis][source]¶
The elements of a rational tensor as a flat row-major tuple of nearest floats.
This is the (documented approximate) companion of
encode_fracvector_exact(), used to fill the per-element float query/index columns of fixed-shape fields.
- httk.data.db.encode_surdscalar_exact(value: httk.core.SurdScalar) str[source]¶
The canonical
SURD_EXACT_FORMATtext ofvalue("0"for zero).The terms are the canonical radicand map of the surd — squarefree radicands in increasing order, each with its reduced rational coefficient — so the text is unique per value and round-trips exactly.
- httk.data.db.known_value_codecs() list[str][source]¶
Return the registered value-codec names, in registration order.
- httk.data.db.register_value_codec(codec: ValueCodec) None[source]¶
Register
codec; raiseValueErroron a duplicate name or Python type.
- httk.data.db.canonical_form(obj: Any) str[source]¶
The deterministic canonical JSON text of a storable instance’s stored values.
Resolves the schema of
obj’s class (so the class must be storable) and serializes[table_name, [[field, canonical value], ...]]over the non-derived stored fields, sorted by field name, as compact JSON.
- httk.data.db.content_id(obj: Any) str[source]¶
The SHA-256 hex digest (64 hex characters) of
canonical_form()ofobj.
- class httk.data.db.ChildTableSpec[source]¶
The out-of-line child table backing a variable-length field.
Only the per-element value columns are listed; the store layer adds the
<parent>_sidforeign key and<name>_indexordering columns.- element_columns: tuple[ColumnSpec, Ellipsis]¶
The value column(s) of one element row.
- class httk.data.db.ColumnSpec[source]¶
One scalar column of a table.
- kind: httk.data.db.codecs.ScalarKind¶
The scalar kind of the column.
- type httk.data.db.FieldRole = Literal['scalar', 'encoded', 'fixed_array', 'child', 'reference'][source]¶
How a stored field maps onto the relational model.
- class httk.data.db.FieldSpec[source]¶
The resolved storage shape of one stored field (or stored property).
- python_type: Any¶
The field’s value type with markers and optionality stripped.
- columns: tuple[ColumnSpec, Ellipsis] = ()¶
The field’s columns in the parent table (empty for the child role).
- shape: httk.core.Shape | None = None¶
The
Shapemarker for tensor-valued fields, if any.
- child: ChildTableSpec | None = None¶
The child table specification for the child role, else None.
- target: type | None = None¶
The referenced storable class for reference (and child-of-storable) fields.
The
Relatedrelationship marker of the field, if any.Only reference fields and child fields of storable elements can carry one; the marker’s metadata flows into the relationships an entry provider emits for the field.
- derived: bool = False¶
stored and queryable, recomputed rather than passed to
__init__on reconstruction.- Type:
True for
stored_propertyvalues
- exception httk.data.db.SchemaError[source]¶
Bases:
ExceptionA class or field cannot be resolved into a storage schema; the message names both.
- class httk.data.db.TableSchema[source]¶
The resolved relational schema of one storable class.
- table_name: str¶
The table name (
storage_nameor the snake-cased class name).
- fields: tuple[FieldSpec, Ellipsis]¶
The stored fields, dataclass fields first (in declaration order), then stored properties.
The store-managed
sidandcontent_idcolumns are not fields and do not appear here.
- composite_indexes: tuple[tuple[str, Ellipsis], Ellipsis]¶
The
indexesdeclarations, resolved to column names.
- dedup: httk.core.DedupPolicy¶
The deduplication policy applied when instances are saved.
- links: tuple[httk.core.RelationshipLink, Ellipsis] = ()¶
The class’s
linksrelationship declarations.Each link is validated: every non-
Noneendpoint names an existing reference field of the class (child fields are not valid endpoints — a link row expresses exactly one FROM→TO pair).
- httk.data.db.register_schema_override(cls: type, info: httk.core.StorageInfo) None[source]¶
Register an external
StorageInfofor a class that cannot declare one.The registered info is used by
resolve_schema()whenever no explicitoverrideargument is passed, and takes precedence over a__httk_storage__declaration on the class itself.
- httk.data.db.resolve_schema(cls: type, *, override: httk.core.StorageInfo | None = None) TableSchema[source]¶
Resolve (and cache) the
TableSchemaof a storable dataclass.The effective
StorageInfois, in order of precedence: the explicitoverrideargument, an info registered viaregister_schema_override(), the class’s own__httk_storage__attribute, or defaults. Results are cached per(class, effective override), so repeated calls return the sameTableSchemaobject. Reference cycles (a class referencing itself, or mutually referencing classes) are allowed and resolve without recursion loops.- Raises:
SchemaError – If the class is not a frozen dataclass or any field cannot be resolved; the message names the class and field.