---
url: /stable/api/sklink.database.md
description: >-
  API reference of sklink.database. Relational databases: tables, keys,
  relationships and their schema.
---

::: v-pre

# `sklink.database` {#sklink.database}

Relational databases: tables, keys, relationships and their schema.

**Classes:**

* [**ColumnSchema**](#sklink.database.ColumnSchema): Name and types of one column.
* [**Database**](#sklink.database.Database): Immutable, validated relational database used by scikit-link estimators.
* [**DetachedDatabase**](#sklink.database.DetachedDatabase): Placeholder left by `detach`: keeps the schema, holds no data.
* [**Relationship**](#sklink.database.Relationship): A foreign key of a child table that references the primary key of a parent.
* [**Schema**](#sklink.database.Schema): Immutable, data-free description of a database.
* [**TableSchema**](#sklink.database.TableSchema): Columns, primary key and optional time column of one table.

**Functions:**

* [**detach**](#sklink.database.detach): Return a copy of a model in which every database keeps only its schema.
* [**rebind**](#sklink.database.rebind): Return a copy of a model that uses `database` instead of its current one.

**Attributes:**

* [**SemanticType**](#sklink.database.SemanticType): Semantic type of a column, which decides the primitives that apply to it.

## `sklink.database.ColumnSchema` {#sklink.database.ColumnSchema}

```python
ColumnSchema(name: str, semantic_type: SemanticType, physical_type: str, timezone: str | None = None) -> None
```

Name and types of one column.

**Attributes:**

* [**name**](#sklink.database.ColumnSchema.name) ([str](https://docs.python.org/3/library/stdtypes.html#str)):
* [**physical_type**](#sklink.database.ColumnSchema.physical_type) ([str](https://docs.python.org/3/library/stdtypes.html#str)):
* [**semantic_type**](#sklink.database.ColumnSchema.semantic_type) ([SemanticType](#sklink.database.SemanticType)):
* [**timezone**](#sklink.database.ColumnSchema.timezone) ([str](https://docs.python.org/3/library/stdtypes.html#str) | None):

### `sklink.database.ColumnSchema.name` {#sklink.database.ColumnSchema.name}

```python
name: str
```

### `sklink.database.ColumnSchema.physical_type` {#sklink.database.ColumnSchema.physical_type}

```python
physical_type: str
```

### `sklink.database.ColumnSchema.semantic_type` {#sklink.database.ColumnSchema.semantic_type}

```python
semantic_type: SemanticType
```

### `sklink.database.ColumnSchema.timezone` {#sklink.database.ColumnSchema.timezone}

```python
timezone: str | None = None
```

## `sklink.database.Database` {#sklink.database.Database}

```python
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') -> None
```

Immutable, 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`](https://scikit-learn.org/stable/modules/generated/sklearn.base.clone.html), `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](../tutorials/describe-your-database), [Load relational data](../cookbook/loading-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. `None` declares 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 as `float64`: an integer column with values
  beyond `2**53` in absolute value raises unless it is declared here,
  as `"id"` or `"categorical"` to keep it exact, or as `"numeric"`
  to accept rounding to the nearest `float64`.
  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 (pandas `Categorical`, Polars
  `Categorical` or `Enum`, 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:
  raise [`IntegrityError`](./sklink.exceptions#sklink.exceptions.IntegrityError), emit a
  [`SklinkWarning`](./sklink.exceptions#sklink.exceptions.SklinkWarning) with the number of rows, or
  keep them silently.
* **validate** ((full, [schema](#sklink.database.Database.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**](#sklink.database.Database.schema) ([Schema](#sklink.database.Schema)): Data-free description of tables, keys and relationships.
* [**table_names**](#sklink.database.Database.table_names) (tuple of str): Names of the tables.
* [**fingerprint**](#sklink.database.Database.fingerprint) ([str](https://docs.python.org/3/library/stdtypes.html#str)): Identity of this object and its content, used as cache key.

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.

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`](./sklink.exceptions#sklink.exceptions.PerformanceWarning) once above
`sklink.set_config(warn_pickle_bytes=...)`; use [`sklink.detach`](./sklink#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:**

```pycon
>>> 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")
3
```

**Functions:**

* [**describe**](#sklink.database.Database.describe): Return a summary of tables, columns and relationships, without data.
* [**from_parquet_dir**](#sklink.database.Database.from_parquet_dir): Build a database from one Parquet file per table and a schema.
* [**n\_rows**](#sklink.database.Database.n_rows): Return the number of rows of a table.
* [**table**](#sklink.database.Database.table): Return the data of a table as a new object.
* [**with_tables**](#sklink.database.Database.with_tables): Return a new database with some tables replaced and the same declarations.

### `sklink.database.Database.describe` {#sklink.database.Database.describe}

```python
describe(*, statistics: bool = False) -> dict[str, Any]
```

Return a summary of tables, columns and relationships, without data.

**Parameters:**

* **statistics** ([bool](https://docs.python.org/3/library/functions.html#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](https://docs.python.org/3/library/stdtypes.html#dict)): `"tables"` maps every table name to a dict with `"n_rows"`,
  `"primary_key"` (list of column names or `None`),
  `"time_column"` (name or `None`) 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. `None` when 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 by `n_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 the `n` parent rows with `k` or more
  children; this happens exactly when `k` is less than
  `"max"`. The `n_parents` add 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:**

```pycon
>>> 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` {#sklink.database.Database.fingerprint}

```python
fingerprint: str
```

Identity of this object and its content, used as cache key.

### `sklink.database.Database.from_parquet_dir` {#sklink.database.Database.from_parquet_dir}

```python
from_parquet_dir(path: str | os.PathLike[str], *, schema: Schema | str | os.PathLike[str]) -> Database
```

Build a database from one Parquet file per table and a schema.

**Parameters:**

* **path** ([str](https://docs.python.org/3/library/stdtypes.html#str) or path - like): Folder with a `<table>.parquet` file for every table of the schema.
* **schema** (Schema, JSON string or path of a JSON file): The schema, as written by `Schema.to_json`.

**Returns:**

* **database** ([Database](#sklink.database.Database)):

### `sklink.database.Database.n_rows` {#sklink.database.Database.n_rows}

```python
n_rows(table: str) -> int
```

Return the number of rows of a table.

### `sklink.database.Database.schema` {#sklink.database.Database.schema}

```python
schema: Schema
```

Data-free description of the database.

### `sklink.database.Database.table` {#sklink.database.Database.table}

```python
table(name: str, *, output: Output = 'auto') -> Any
```

Return 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](https://docs.python.org/3/library/stdtypes.html#str)): Name of the table.
* **output** ((auto, pandas, polars, pyarrow, numpy)): Format of the result, as in [`sklink.datasets`](./sklink.datasets#sklink.datasets). `"auto"`
  gives a pandas `DataFrame` when pandas is installed and NumPy
  otherwise. `"numpy"` gives a `dict` of column name to
  one-dimensional `ndarray`.

**Returns:**

* **table** ((DataFrame, DataFrame, Table or [dict](https://docs.python.org/3/library/stdtypes.html#dict))): The table's data.

**Raises:**

* [SchemaError](./sklink.exceptions#sklink.exceptions.SchemaError): If the database has no table `name`.
* [ValueError](https://docs.python.org/3/library/exceptions.html#ValueError): If `output` is not one of the accepted values.
* [ImportError](https://docs.python.org/3/library/exceptions.html#ImportError): If `output` names a library that is not installed.

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:**

```pycon
>>> 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` {#sklink.database.Database.table_names}

```python
table_names: tuple[str, ...]
```

Names of the tables.

### `sklink.database.Database.with_tables` {#sklink.database.Database.with_tables}

```python
with_tables(**tables: Any) -> Database
```

Return a new database with some tables replaced and the same declarations.

**Parameters:**

* \*\***tables** ([Any](https://docs.python.org/3/library/typing.html#typing.Any)): New data for existing tables, by name.

**Returns:**

* **database** ([Database](#sklink.database.Database)): A new object, with a new fingerprint.

## `sklink.database.DetachedDatabase` {#sklink.database.DetachedDatabase}

```python
DetachedDatabase(schema: Schema, fingerprint: str) -> None
```

Placeholder left by `detach`: keeps the schema, holds no data.

Any attempt to evaluate a model bound to it raises
[`DetachedDatabaseError`](./sklink.exceptions#sklink.exceptions.DetachedDatabaseError).

**Attributes:**

* [**fingerprint**](#sklink.database.DetachedDatabase.fingerprint):
* [**schema**](#sklink.database.DetachedDatabase.schema):
* [**table_names**](#sklink.database.DetachedDatabase.table_names) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]): Names of the tables of the original database.

### `sklink.database.DetachedDatabase.fingerprint` {#sklink.database.DetachedDatabase.fingerprint}

```python
fingerprint = fingerprint
```

### `sklink.database.DetachedDatabase.schema` {#sklink.database.DetachedDatabase.schema}

```python
schema = schema
```

### `sklink.database.DetachedDatabase.table_names` {#sklink.database.DetachedDatabase.table_names}

```python
table_names: tuple[str, ...]
```

Names of the tables of the original database.

## `sklink.database.Relationship` {#sklink.database.Relationship}

```python
Relationship(child: str | tuple[str, ...], parent: str | tuple[str, ...], name: str | None = None) -> None
```

A 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](https://docs.python.org/3/library/stdtypes.html#str)): Unique name. Defaults to `"{child_table}.{child_column}->{parent_table}"`.

**Examples:**

```pycon
>>> 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**](#sklink.database.Relationship.from_dict): Build a relationship from `to_dict` output.
* [**to_dict**](#sklink.database.Relationship.to_dict): Return a JSON-serializable description.

**Attributes:**

* [**child**](#sklink.database.Relationship.child) ([str](https://docs.python.org/3/library/stdtypes.html#str) | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]):
* [**child_columns**](#sklink.database.Relationship.child_columns) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]):
* [**child_table**](#sklink.database.Relationship.child_table) ([str](https://docs.python.org/3/library/stdtypes.html#str)):
* [**key**](#sklink.database.Relationship.key) ([str](https://docs.python.org/3/library/stdtypes.html#str)): Name of the relationship, never `None` after construction.
* [**name**](#sklink.database.Relationship.name) ([str](https://docs.python.org/3/library/stdtypes.html#str) | None):
* [**parent**](#sklink.database.Relationship.parent) ([str](https://docs.python.org/3/library/stdtypes.html#str) | [tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]):
* [**parent_columns**](#sklink.database.Relationship.parent_columns) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]):
* [**parent_table**](#sklink.database.Relationship.parent_table) ([str](https://docs.python.org/3/library/stdtypes.html#str)):

### `sklink.database.Relationship.child` {#sklink.database.Relationship.child}

```python
child: str | tuple[str, ...]
```

### `sklink.database.Relationship.child_columns` {#sklink.database.Relationship.child_columns}

```python
child_columns: tuple[str, ...] = field(init=False, repr=False, compare=False)
```

### `sklink.database.Relationship.child_table` {#sklink.database.Relationship.child_table}

```python
child_table: str = field(init=False, repr=False, compare=False)
```

### `sklink.database.Relationship.from_dict` {#sklink.database.Relationship.from_dict}

```python
from_dict(data: Mapping[str, Any]) -> Relationship
```

Build a relationship from `to_dict` output.

### `sklink.database.Relationship.key` {#sklink.database.Relationship.key}

```python
key: str
```

Name of the relationship, never `None` after construction.

### `sklink.database.Relationship.name` {#sklink.database.Relationship.name}

```python
name: str | None = None
```

### `sklink.database.Relationship.parent` {#sklink.database.Relationship.parent}

```python
parent: str | tuple[str, ...]
```

### `sklink.database.Relationship.parent_columns` {#sklink.database.Relationship.parent_columns}

```python
parent_columns: tuple[str, ...] = field(init=False, repr=False, compare=False)
```

### `sklink.database.Relationship.parent_table` {#sklink.database.Relationship.parent_table}

```python
parent_table: str = field(init=False, repr=False, compare=False)
```

### `sklink.database.Relationship.to_dict` {#sklink.database.Relationship.to_dict}

```python
to_dict() -> dict[str, Any]
```

Return a JSON-serializable description.

## `sklink.database.Schema` {#sklink.database.Schema}

```python
Schema(tables: Iterable[TableSchema], relationships: Iterable[Relationship] = ()) -> None
```

Immutable, 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:**

```pycon
>>> 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
True
```

**Functions:**

* [**children_of**](#sklink.database.Schema.children_of): Relationships whose parent is `table` (one-to-many from `table`).
* [**from_dict**](#sklink.database.Schema.from_dict): Build a schema from `to_dict` output.
* [**from_json**](#sklink.database.Schema.from_json): Read a schema written by `to_json`.
* [**missing_from**](#sklink.database.Schema.missing_from): List what this schema uses and `other` lacks (tables, columns, links).
* [**parents_of**](#sklink.database.Schema.parents_of): Relationships whose child is `table` (many-to-one from `table`).
* [**relationship**](#sklink.database.Schema.relationship): Return a relationship by name, or raise `SchemaError`.
* [**subset**](#sklink.database.Schema.subset): Return the schema restricted to some tables and relationships.
* [**table**](#sklink.database.Schema.table): Return a table schema, or raise `SchemaError`.
* [**to_dict**](#sklink.database.Schema.to_dict): Return a JSON-serializable description with `format_version`.
* [**to_json**](#sklink.database.Schema.to_json): Serialize to a JSON string.

**Attributes:**

* [**relationships**](#sklink.database.Schema.relationships) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[Relationship](#sklink.database.Relationship), ...]): Relationships, in declaration order.
* [**table_names**](#sklink.database.Schema.table_names) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]): Names of the tables, in declaration order.

### `sklink.database.Schema.children_of` {#sklink.database.Schema.children_of}

```python
children_of(table: str) -> tuple[Relationship, ...]
```

Relationships whose parent is `table` (one-to-many from `table`).

### `sklink.database.Schema.from_dict` {#sklink.database.Schema.from_dict}

```python
from_dict(data: Mapping[str, Any]) -> Schema
```

Build a schema from `to_dict` output.

### `sklink.database.Schema.from_json` {#sklink.database.Schema.from_json}

```python
from_json(text: str) -> Schema
```

Read a schema written by `to_json`.

### `sklink.database.Schema.missing_from` {#sklink.database.Schema.missing_from}

```python
missing_from(other: Schema) -> list[str]
```

List what this schema uses and `other` lacks (tables, columns, links).

### `sklink.database.Schema.parents_of` {#sklink.database.Schema.parents_of}

```python
parents_of(table: str) -> tuple[Relationship, ...]
```

Relationships whose child is `table` (many-to-one from `table`).

### `sklink.database.Schema.relationship` {#sklink.database.Schema.relationship}

```python
relationship(name: str) -> Relationship
```

Return a relationship by name, or raise `SchemaError`.

### `sklink.database.Schema.relationships` {#sklink.database.Schema.relationships}

```python
relationships: tuple[Relationship, ...]
```

Relationships, in declaration order.

### `sklink.database.Schema.subset` {#sklink.database.Schema.subset}

```python
subset(tables: Iterable[str], relationships: Iterable[str]) -> Schema
```

Return the schema restricted to some tables and relationships.

### `sklink.database.Schema.table` {#sklink.database.Schema.table}

```python
table(name: str) -> TableSchema
```

Return a table schema, or raise `SchemaError`.

### `sklink.database.Schema.table_names` {#sklink.database.Schema.table_names}

```python
table_names: tuple[str, ...]
```

Names of the tables, in declaration order.

### `sklink.database.Schema.to_dict` {#sklink.database.Schema.to_dict}

```python
to_dict() -> dict[str, Any]
```

Return a JSON-serializable description with `format_version`.

### `sklink.database.Schema.to_json` {#sklink.database.Schema.to_json}

```python
to_json() -> str
```

Serialize to a JSON string.

## `sklink.database.SemanticType` {#sklink.database.SemanticType}

```python
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` {#sklink.database.TableSchema}

```python
TableSchema(name: str, columns: tuple[ColumnSchema, ...], primary_key: tuple[str, ...] | None, time_column: str | None = None, excluded: frozenset[str] = frozenset()) -> None
```

Columns, primary key and optional time column of one table.

**Functions:**

* [**column**](#sklink.database.TableSchema.column): Return the schema of a column, or raise `SchemaError`.
* [**feature_columns**](#sklink.database.TableSchema.feature_columns): Columns that may feed a primitive: not keys, not excluded, not text.

**Attributes:**

* [**column_names**](#sklink.database.TableSchema.column_names) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...]): Names of the columns, in storage order.
* [**columns**](#sklink.database.TableSchema.columns) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[ColumnSchema](#sklink.database.ColumnSchema), ...]):
* [**excluded**](#sklink.database.TableSchema.excluded) ([frozenset](https://docs.python.org/3/library/stdtypes.html#frozenset)\[[str](https://docs.python.org/3/library/stdtypes.html#str)]):
* [**name**](#sklink.database.TableSchema.name) ([str](https://docs.python.org/3/library/stdtypes.html#str)):
* [**primary_key**](#sklink.database.TableSchema.primary_key) ([tuple](https://docs.python.org/3/library/stdtypes.html#tuple)\[[str](https://docs.python.org/3/library/stdtypes.html#str), ...] | None):
* [**time_column**](#sklink.database.TableSchema.time_column) ([str](https://docs.python.org/3/library/stdtypes.html#str) | None):

### `sklink.database.TableSchema.column` {#sklink.database.TableSchema.column}

```python
column(name: str) -> ColumnSchema
```

Return the schema of a column, or raise `SchemaError`.

### `sklink.database.TableSchema.column_names` {#sklink.database.TableSchema.column_names}

```python
column_names: tuple[str, ...]
```

Names of the columns, in storage order.

### `sklink.database.TableSchema.columns` {#sklink.database.TableSchema.columns}

```python
columns: tuple[ColumnSchema, ...]
```

### `sklink.database.TableSchema.excluded` {#sklink.database.TableSchema.excluded}

```python
excluded: frozenset[str] = frozenset()
```

### `sklink.database.TableSchema.feature_columns` {#sklink.database.TableSchema.feature_columns}

```python
feature_columns() -> tuple[ColumnSchema, ...]
```

Columns that may feed a primitive: not keys, not excluded, not text.

### `sklink.database.TableSchema.name` {#sklink.database.TableSchema.name}

```python
name: str
```

### `sklink.database.TableSchema.primary_key` {#sklink.database.TableSchema.primary_key}

```python
primary_key: tuple[str, ...] | None
```

### `sklink.database.TableSchema.time_column` {#sklink.database.TableSchema.time_column}

```python
time_column: str | None = None
```

## `sklink.database.detach` {#sklink.database.detach}

```python
detach(estimator: T) -> T
```

Return 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](../tutorials/save-and-deploy)

**Parameters:**

* **estimator** ((estimator, pipeline or meta - estimator)): Any object, fitted or not, that references a `Database`.

**Returns:**

* **detached** (same type as `estimator`): A copy whose databases are replaced by schema-only placeholders.

sklink.rebind : Bind a database to the model again after loading it.

**Examples:**

```pycon
>>> 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` {#sklink.database.rebind}

```python
rebind(estimator: T, database: Database) -> T
```

Return 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](../tutorials/save-and-deploy)

**Parameters:**

* **estimator** ((estimator, pipeline or meta - estimator)): A model that references a `Database` or a detached placeholder.
* **database** ([Database](#sklink.database.Database)): The database to use from now on.

**Returns:**

* **rebound** (same type as `estimator`):

**Raises:**

* [SchemaError](./sklink.exceptions#sklink.exceptions.SchemaError): If `database` lacks something the fitted model uses.

sklink.detach : Remove the databases of a model before saving it.

**Examples:**

```pycon
>>> 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])
```

:::
