sklink.database
Relational databases: tables, keys, relationships and their schema.
Classes:
- ColumnSchema: Name and types of one column.
- Database: Immutable, validated relational database used by scikit-link estimators.
- DetachedDatabase: Placeholder left by
detach: keeps the schema, holds no data. - Relationship: A foreign key of a child table that references the primary key of a parent.
- Schema: Immutable, data-free description of a database.
- TableSchema: Columns, primary key and optional time column of one table.
Functions:
- detach: Return a copy of a model in which every database keeps only its schema.
- rebind: Return a copy of a model that uses
databaseinstead of its current one.
Attributes:
- SemanticType: Semantic type of a column, which decides the primitives that apply to it.
sklink.database.ColumnSchema
ColumnSchema(name: str, semantic_type: SemanticType, physical_type: str, timezone: str | None = None) -> NoneName and types of one column.
Attributes:
- name (
str): - physical_type (
str): - semantic_type (
SemanticType): - timezone (
str | None):
sklink.database.ColumnSchema.name
name: strsklink.database.ColumnSchema.physical_type
physical_type: strsklink.database.ColumnSchema.semantic_type
semantic_type: SemanticTypesklink.database.ColumnSchema.timezone
timezone: str | None = Nonesklink.database.Database
Database(tables: Mapping[str, Any], *, primary_keys: Mapping[str, str | Sequence[str] | None], relationships: Sequence[RelationshipLike] = (), time_columns: Mapping[str, str] | None = None, column_types: Mapping[str, Mapping[str, SemanticType]] | None = None, exclude: Mapping[str, Sequence[str]] | None = None, orphans: Literal['error', 'warn', 'ignore'] = 'error', validate: Literal['full', 'schema', 'none'] = 'full') -> NoneImmutable, validated relational database used by scikit-link estimators.
A Database holds several tables linked by primary and foreign keys. It is passed to estimators as the database hyperparameter, while X holds one row per sample with the key of the entity to predict for. The object is never copied: sklearn.base.clone, copy.copy and copy.deepcopy return the same instance.
Time is optional. Declare time_columns only when rows become available at a given time and the estimator receives a cutoff (time=).
Guides: Describe your database, Load relational data
Parameters:
- tables (
mapping of str to table): Each table is a pandas, Polars or PyArrow table, a mapping of column name to one-dimensional array, or the path of a Parquet file. - primary_keys (
mapping of str to str, sequence of str or None): Primary key column(s) of every table.Nonedeclares a table without a key, which cannot be the parent of a relationship. - relationships (
sequence of Relationship or (child, parent) tuples): Foreign keys, written child first:("orders.customer_id", "customers.id"). - time_columns (
mapping of str to str): Datetime column that tells when each row of a table becomes available. - column_types (
mapping of str to mapping of str to str): Override inferred semantic types ("numeric","categorical","boolean","datetime","text"or"id") per table and column. Numeric values are stored asfloat64: an integer column with values beyond2**53in absolute value raises unless it is declared here, as"id"or"categorical"to keep it exact, or as"numeric"to accept rounding to the nearestfloat64. Strings that average 30 characters or more and are nearly all distinct (at least 100 distinct values and 90% of the present ones), such as reviews or descriptions, are inferred as"text"and feed no feature; declare them"categorical"to aggregate them as categories, or declare the type of a column near those limits so that every snapshot of the data reads it the same way. Columns of a categorical type (pandasCategorical, PolarsCategoricalorEnum, Arrow dictionaries, also in Parquet files when PyArrow is installed) stay categorical. - exclude (
mapping of str to sequence of str): Columns that must never feed a feature. - orphans (
(error, warn, ignore)): What to do with non-null foreign keys that have no parent row: raiseIntegrityError, emit aSklinkWarningwith the number of rows, or keep them silently. - validate (
(full, schema, none)):"full"checks keys and orphans."schema"and"none"skip the checks that scan data; with them, unique and non-null keys are the caller's responsibility. The declarations themselves (tables, columns, keys and relationships that exist and have compatible types) are always checked, because every later step relies on them, so"none"currently behaves like"schema".
Attributes:
- schema (
Schema): Data-free description of tables, keys and relationships. - table_names (
tuple of str): Names of the tables. - fingerprint (
str): Identity of this object and its content, used as cache key.
See Also
sklink.Schema : Data-free description of the tables, keys and relationships. sklink.Relationship : One foreign key between two tables. sklink.detach : Remove the databases of a fitted model before saving it. sklink.datasets.load_shop : A small example database.
Notes
The tables are read into canonical storage when the object is built. Changing the original data frames or files afterwards is undefined behaviour: build a new Database (or use with_tables) instead.
A database built only from Parquet files is pickled as a reference to its files, which are read again when it is loaded. A database held in memory is pickled with its data and emits a PerformanceWarning once above sklink.set_config(warn_pickle_bytes=...); use sklink.detach before saving a fitted model.
Loading a pickled database in a process that already holds a database with the same fingerprint returns that object instead of a copy. A model pickled and loaded again, or returned by a joblib worker process (cross_validate(..., n_jobs=2, return_estimator=True)), shares the original database, as clone and copy do.
Examples:
>>> import numpy as np
>>> from sklink import Database
>>> db = Database(
... tables={
... "customers": {"customer_id": np.array([1, 2, 3])},
... "orders": {
... "order_id": np.array([10, 11, 12]),
... "customer_id": np.array([1, 1, 3]),
... "amount": np.array([5.0, 7.5, 3.0]),
... },
... },
... primary_keys={"customers": "customer_id", "orders": "order_id"},
... relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> db.n_rows("orders")
3Functions:
- describe: Return a summary of tables, columns and relationships, without data.
- from_parquet_dir: Build a database from one Parquet file per table and a schema.
- n_rows: Return the number of rows of a table.
- table: Return the data of a table as a new object.
- with_tables: Return a new database with some tables replaced and the same declarations.
sklink.database.Database.describe
describe(*, statistics: bool = False) -> dict[str, Any]Return a summary of tables, columns and relationships, without data.
Parameters:
- statistics (
bool): Add the fan-out of every relationship, computed from its key index. The statistics count rows; they never contain row values.
Returns:
- description (
dict):"tables"maps every table name to a dict with"n_rows","primary_key"(list of column names orNone),"time_column"(name orNone) and"columns"(column name to semantic type)."relationships"lists one dict per relationship with"name","child_table","child_columns","parent_table"and"parent_columns".
With statistics=True every relationship dict also has "statistics", a dict with these keys. Children are the child rows whose foreign key matches a parent row.
"min","max"(int) and"mean"(float): number of children per parent row, over every row of the parent table, including those without children.Nonewhen the parent table is empty."n_parents_without_children"(int): parent rows with no child."n_orphans"(int): child rows whose foreign key is not null (no component is null) and matches no parent row. Rows with a null foreign key have no parent and are not orphans."children_per_parent"(list of[n_children, n_parents]pairs of int): histogram of the number of children per parent row, sorted byn_children, with only the counts that occur (n_parents > 0). It holds at most 32 pairs. When more than 32 distinct counts occur, the first 31 are kept and the last pair[k, n]counts thenparent rows withkor more children; this happens exactly whenkis less than"max". Then_parentsadd up to the number of parent rows.
The statistics depend only on the content of the tables, not on the order of their rows.
Examples:
>>> import numpy as np
>>> from sklink import Database
>>> db = Database(
... tables={
... "customers": {"customer_id": np.array([1, 2, 3])},
... "orders": {
... "order_id": np.array([10, 11, 12]),
... "customer_id": np.array([1, 1, 3]),
... },
... },
... primary_keys={"customers": "customer_id", "orders": "order_id"},
... relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> db.describe()["tables"]["orders"]["n_rows"]
3
>>> stats = db.describe(statistics=True)["relationships"][0]["statistics"]
>>> stats["min"], stats["max"], stats["mean"], stats["n_orphans"]
(0, 2, 1.0, 0)
>>> stats["children_per_parent"]
[[0, 1], [1, 1], [2, 1]]sklink.database.Database.fingerprint
fingerprint: strIdentity of this object and its content, used as cache key.
sklink.database.Database.from_parquet_dir
from_parquet_dir(path: str | os.PathLike[str], *, schema: Schema | str | os.PathLike[str]) -> DatabaseBuild a database from one Parquet file per table and a schema.
Parameters:
- path (
str or path - like): Folder with a<table>.parquetfile for every table of the schema. - schema (
Schema, JSON string or path of a JSON file): The schema, as written bySchema.to_json.
Returns:
- database (
Database):
sklink.database.Database.n_rows
n_rows(table: str) -> intReturn the number of rows of a table.
sklink.database.Database.schema
schema: SchemaData-free description of the database.
sklink.database.Database.table
table(name: str, *, output: Output = 'auto') -> AnyReturn the data of a table as a new object.
The columns keep their order, their type as read (integer, float, boolean, string or datetime with its unit), their missing values and the timezone of timezone-aware datetimes. Rows come in the canonical order of the database: sorted by primary key, or by every column for a table without one. The result never shares memory with the database, so changing it changes neither the database nor its fingerprint.
Parameters:
- name (
str): Name of the table. - output (
(auto, pandas, polars, pyarrow, numpy)): Format of the result, as insklink.datasets."auto"gives a pandasDataFramewhen pandas is installed and NumPy otherwise."numpy"gives adictof column name to one-dimensionalndarray.
Returns:
- table (
(DataFrame, DataFrame, Table or dict)): The table's data.
Raises:
SchemaError: If the database has no tablename.ValueError: Ifoutputis not one of the accepted values.ImportError: Ifoutputnames a library that is not installed.
Notes
Polars and PyArrow hold missing values as nulls in a column of the original type. NumPy has no null for every type, so with "numpy" and "pandas" a missing value is NaN in floats and NaT in datetimes; a numeric column of integer type with missing values becomes float64 with NaN, and any other column with missing values (keys, strings, booleans) an object column with None. Strings are object columns. NumPy datetimes have no timezone: with "numpy" a timezone-aware column is returned in UTC, and its timezone is in schema.
Key columns (primary and foreign keys) hold the normalized values the database matches on: int64 for integers (including integral floats), float64 for other numbers and strings otherwise.
Numeric columns are stored as float64, as the features computed from them. Integers beyond 2**53 in absolute value are refused unless the column is declared in column_types: as "id" or "categorical" they stay exact; declared "numeric", they come back rounded to the nearest float64.
Examples:
>>> import numpy as np
>>> from sklink import Database
>>> db = Database(
... tables={
... "customers": {"customer_id": np.array([2, 1])},
... "orders": {
... "order_id": np.array([10, 11, 12]),
... "customer_id": np.array([1, 1, 2]),
... "amount": np.array([5.0, np.nan, 3.0]),
... },
... },
... primary_keys={"customers": "customer_id", "orders": "order_id"},
... relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> orders = db.table("orders", output="numpy")
>>> list(orders)
['order_id', 'customer_id', 'amount']
>>> orders["amount"]
array([ 5., nan, 3.])
>>> db.table("customers", output="numpy")["customer_id"]
array([1, 2])sklink.database.Database.table_names
table_names: tuple[str, ...]Names of the tables.
sklink.database.Database.with_tables
with_tables(**tables: Any) -> DatabaseReturn a new database with some tables replaced and the same declarations.
Parameters:
- **tables (
Any): New data for existing tables, by name.
Returns:
- database (
Database): A new object, with a new fingerprint.
sklink.database.DetachedDatabase
DetachedDatabase(schema: Schema, fingerprint: str) -> NonePlaceholder left by detach: keeps the schema, holds no data.
Any attempt to evaluate a model bound to it raises DetachedDatabaseError.
Attributes:
- fingerprint:
- schema:
- table_names (
tuple[str, ...]): Names of the tables of the original database.
sklink.database.DetachedDatabase.fingerprint
fingerprint = fingerprintsklink.database.DetachedDatabase.schema
schema = schemasklink.database.DetachedDatabase.table_names
table_names: tuple[str, ...]Names of the tables of the original database.
sklink.database.Relationship
Relationship(child: str | tuple[str, ...], parent: str | tuple[str, ...], name: str | None = None) -> NoneA foreign key of a child table that references the primary key of a parent.
Parameters:
- child (
str or sequence of str):"table.column"of the foreign key, or several for a composite key. - parent (
str or sequence of str):"table.column"of the referenced primary key, in the same order. - name (
str): Unique name. Defaults to"{child_table}.{child_column}->{parent_table}".
Examples:
>>> from sklink import Relationship
>>> rel = Relationship("orders.customer_id", "customers.id")
>>> rel.name, rel.child_table, rel.parent_table
('orders.customer_id->customers', 'orders', 'customers')Functions:
- from_dict: Build a relationship from
to_dictoutput. - to_dict: Return a JSON-serializable description.
Attributes:
- child (
str | tuple[str, ...]): - child_columns (
tuple[str, ...]): - child_table (
str): - key (
str): Name of the relationship, neverNoneafter construction. - name (
str | None): - parent (
str | tuple[str, ...]): - parent_columns (
tuple[str, ...]): - parent_table (
str):
sklink.database.Relationship.child
child: str | tuple[str, ...]sklink.database.Relationship.child_columns
child_columns: tuple[str, ...] = field(init=False, repr=False, compare=False)sklink.database.Relationship.child_table
child_table: str = field(init=False, repr=False, compare=False)sklink.database.Relationship.from_dict
from_dict(data: Mapping[str, Any]) -> RelationshipBuild a relationship from to_dict output.
sklink.database.Relationship.key
key: strName of the relationship, never None after construction.
sklink.database.Relationship.name
name: str | None = Nonesklink.database.Relationship.parent
parent: str | tuple[str, ...]sklink.database.Relationship.parent_columns
parent_columns: tuple[str, ...] = field(init=False, repr=False, compare=False)sklink.database.Relationship.parent_table
parent_table: str = field(init=False, repr=False, compare=False)sklink.database.Relationship.to_dict
to_dict() -> dict[str, Any]Return a JSON-serializable description.
sklink.database.Schema
Schema(tables: Iterable[TableSchema], relationships: Iterable[Relationship] = ()) -> NoneImmutable, data-free description of a database.
A schema lists tables, their columns with semantic types, primary keys, optional time columns and relationships. It holds no data and no statistics, and round-trips through JSON.
Parameters:
- tables (
iterable of TableSchema): Table descriptions. - relationships (
iterable of Relationship): Foreign keys between tables.
Examples:
>>> from sklink import Schema
>>> from sklink.datasets import load_shop
>>> schema = load_shop().database.schema
>>> schema
Schema(tables=['customers', 'orders', 'order_items', 'products'], relationships=3)
>>> schema.table("orders").column("type").semantic_type
'categorical'
>>> Schema.from_json(schema.to_json()) == schema
TrueFunctions:
- children_of: Relationships whose parent is
table(one-to-many fromtable). - from_dict: Build a schema from
to_dictoutput. - from_json: Read a schema written by
to_json. - missing_from: List what this schema uses and
otherlacks (tables, columns, links). - parents_of: Relationships whose child is
table(many-to-one fromtable). - relationship: Return a relationship by name, or raise
SchemaError. - subset: Return the schema restricted to some tables and relationships.
- table: Return a table schema, or raise
SchemaError. - to_dict: Return a JSON-serializable description with
format_version. - to_json: Serialize to a JSON string.
Attributes:
- relationships (
tuple[Relationship, ...]): Relationships, in declaration order. - table_names (
tuple[str, ...]): Names of the tables, in declaration order.
sklink.database.Schema.children_of
children_of(table: str) -> tuple[Relationship, ...]Relationships whose parent is table (one-to-many from table).
sklink.database.Schema.from_dict
from_dict(data: Mapping[str, Any]) -> SchemaBuild a schema from to_dict output.
sklink.database.Schema.from_json
from_json(text: str) -> SchemaRead a schema written by to_json.
sklink.database.Schema.missing_from
missing_from(other: Schema) -> list[str]List what this schema uses and other lacks (tables, columns, links).
sklink.database.Schema.parents_of
parents_of(table: str) -> tuple[Relationship, ...]Relationships whose child is table (many-to-one from table).
sklink.database.Schema.relationship
relationship(name: str) -> RelationshipReturn a relationship by name, or raise SchemaError.
sklink.database.Schema.relationships
relationships: tuple[Relationship, ...]Relationships, in declaration order.
sklink.database.Schema.subset
subset(tables: Iterable[str], relationships: Iterable[str]) -> SchemaReturn the schema restricted to some tables and relationships.
sklink.database.Schema.table
table(name: str) -> TableSchemaReturn a table schema, or raise SchemaError.
sklink.database.Schema.table_names
table_names: tuple[str, ...]Names of the tables, in declaration order.
sklink.database.Schema.to_dict
to_dict() -> dict[str, Any]Return a JSON-serializable description with format_version.
sklink.database.Schema.to_json
to_json() -> strSerialize to a JSON string.
sklink.database.SemanticType
SemanticType = Literal['numeric', 'categorical', 'boolean', 'datetime', 'text', 'id']Semantic type of a column, which decides the primitives that apply to it.
One of "numeric", "categorical", "boolean", "datetime", "text" or "id". It is inferred from the data and can be overridden with Database(column_types=...).
sklink.database.TableSchema
TableSchema(name: str, columns: tuple[ColumnSchema, ...], primary_key: tuple[str, ...] | None, time_column: str | None = None, excluded: frozenset[str] = frozenset()) -> NoneColumns, primary key and optional time column of one table.
Functions:
- column: Return the schema of a column, or raise
SchemaError. - feature_columns: Columns that may feed a primitive: not keys, not excluded, not text.
Attributes:
- column_names (
tuple[str, ...]): Names of the columns, in storage order. - columns (
tuple[ColumnSchema, ...]): - excluded (
frozenset[str]): - name (
str): - primary_key (
tuple[str, ...] | None): - time_column (
str | None):
sklink.database.TableSchema.column
column(name: str) -> ColumnSchemaReturn the schema of a column, or raise SchemaError.
sklink.database.TableSchema.column_names
column_names: tuple[str, ...]Names of the columns, in storage order.
sklink.database.TableSchema.columns
columns: tuple[ColumnSchema, ...]sklink.database.TableSchema.excluded
excluded: frozenset[str] = frozenset()sklink.database.TableSchema.feature_columns
feature_columns() -> tuple[ColumnSchema, ...]Columns that may feed a primitive: not keys, not excluded, not text.
sklink.database.TableSchema.name
name: strsklink.database.TableSchema.primary_key
primary_key: tuple[str, ...] | Nonesklink.database.TableSchema.time_column
time_column: str | None = Nonesklink.database.detach
detach(estimator: T) -> TReturn a copy of a model in which every database keeps only its schema.
Use it before pickling a fitted model so that the file contains no table data, then call rebind after loading. The original object is not modified.
Guides: Save, load and deploy
Parameters:
- estimator (
(estimator, pipeline or meta - estimator)): Any object, fitted or not, that references aDatabase.
Returns:
- detached (
same type as): A copy whose databases are replaced by schema-only placeholders.estimator
See Also
sklink.rebind : Bind a database to the model again after loading it.
Examples:
>>> import pickle
>>> import sklink
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> saved = pickle.dumps(sklink.detach(tree))
>>> loaded = pickle.loads(saved)
>>> loaded.database
DetachedDatabase(tables=['customers', 'orders', 'order_items', 'products'])
>>> loaded = sklink.rebind(loaded, shop.database)
>>> loaded.predict(shop.X[:5])
array([1, 1, 1, 1, 0])sklink.database.rebind
rebind(estimator: T, database: Database) -> TReturn a copy of a model that uses database instead of its current one.
The fitted state is kept. The new database must contain every table, column and relationship that the fitted model uses; extra ones are allowed.
Guides: Save, load and deploy
Parameters:
- estimator (
(estimator, pipeline or meta - estimator)): A model that references aDatabaseor a detached placeholder. - database (
Database): The database to use from now on.
Returns:
- rebound (
same type as):estimator
Raises:
SchemaError: Ifdatabaselacks something the fitted model uses.
See Also
sklink.detach : Remove the databases of a model before saving it.
Examples:
>>> import pickle
>>> import sklink
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> saved = pickle.dumps(sklink.detach(tree))
>>> loaded = pickle.loads(saved)
>>> loaded.database
DetachedDatabase(tables=['customers', 'orders', 'order_items', 'products'])
>>> loaded = sklink.rebind(loaded, shop.database)
>>> loaded.predict(shop.X[:5])
array([1, 1, 1, 1, 0])