# `sc_crawler.table_bases`

> Tiny helper classes for the most commonly used fields to be inherited by sc_crawler.tables.

# `sc_crawler.table_bases`

Tiny helper classes for the most commonly used fields to be inherited by [sc_crawler.tables](https://docs.sparecores.com/crawler/reference/tables.md).

**Classes:**

- [**ScMetaModel**](#scmetamodel) – Custom class factory to auto-update table models.
- [**ScModel**](#scmodel) – Custom extensions to SQLModel objects and tables.
- [**MetaColumns**](#metacolumns) – Helper class to add the `status` and `observed_at` columns.
- [**HasPriceFieldsBase**](#haspricefieldsbase) – 
- [**ServerFields**](#serverfields) – 
- [**BenchmarkFields**](#benchmarkfields) – 
- [**ResourceIdComparator**](#resourceidcomparator) – Compile server_id/database_id to CASE + typed filter.
- [**BenchmarkScoreFields**](#benchmarkscorefields) – 
- [**BenchmarkScoreBase**](#benchmarkscorebase) – 
- [**ArchiveRuleFields**](#archiverulefields) – 

## class <code class="doc-name">ScMetaModel</code> [table_bases.py:57–129](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L57-L129)

Bases: `__class__`

Custom class factory to auto-update table models.

- Reuse description of the table and its fields as SQL comment.

    Checking if the table and its fields have explicit comment set
    to be shown in the `CREATE TABLE` statements, and if not,
    reuse the optional table and field descriptions. Table
    docstrings are truncated to first line.

- Reuse description of the fields to dynamically append to the
    docstring in the Attributes section.

- Set `__validator__` to the parent Pydantic model without
    `table=True`, which is useful for running validations.
    The Pydantic model is found by the parent class' name ending in "Base".

- Auto-generate SCD table docs from the non-SCD table docs.

## class <code class="doc-name">ScModel</code> [table_bases.py:132–398](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L132-L398)

Bases: `SQLModel`

Custom extensions to SQLModel objects and tables.

Extra features:

- auto-generated table names using [snake_case](https://docs.sparecores.com/crawler/reference/str_utils.md#snake_case),
- support for hashing table rows,
- reuse description field of tables/columns as SQL comment,
- reuse description field of columns to extend the `Attributes` section of the docstring.

**Functions:**

- [**get_columns**](#scmodelget_columns) – Return the table's column names in a dict for all, primary keys, and attributes.
- [**get_table_name**](#scmodelget_table_name) – Return the SQLModel object's table name.
- [**get_validator**](#scmodelget_validator) – Return the parent Base Pydantic model (without a table definition).
- [**get_scd**](#scmodelget_scd) – Return the SCD version of the SQLModel table.
- [**get_parent_tables**](#scmodelget_parent_tables) – Names of the tables that the records of this table belong to.
- [**get_key_filters**](#scmodelget_key_filters) – Translate the `match` or `successor` of an archive rule into column filters on the table.
- [**get_filters_condition**](#scmodelget_filters_condition) – SQL condition selecting the rows of the table with the given column values.
- [**matches_rule**](#scmodelmatches_rule) – Check if an archive rule archives the record with the given primary key.
- [**is_archived**](#scmodelis_archived) – Check if any of the archive rules archives the record with the given primary key.
- [**archive_condition**](#scmodelarchive_condition) – SQL condition selecting the rows of the table archived by the rules.
- [**archived_by**](#scmodelarchived_by) – List the archive rules archiving a record, including the rules on its parent tables.
- [**pk_key**](#scmodelpk_key) – JSON dump of the primary key columns of a row, as used in [hash](#scmodelhash).
- [**hash**](#scmodelhash) – Hash the content of the rows.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">get_columns</code> [table_bases.py:148–154](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L148-L154)

```python
get_columns()
```

Return the table's column names in a dict for all, primary keys, and attributes.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">get_table_name</code> [table_bases.py:156–159](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L156-L159)

```python
get_table_name()
```

Return the SQLModel object's table name.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">get_validator</code> [table_bases.py:161–166](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L161-L166)

```python
get_validator()
```

Return the parent Base Pydantic model (without a table definition).

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">get_scd</code> [table_bases.py:168–179](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L168-L179)

```python
get_scd()
```

Return the SCD version of the SQLModel table.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">get_parent_tables</code> [table_bases.py:181–205](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L181-L205)

```python
get_parent_tables()
```

Names of the tables that the records of this table belong to.

These are the tables referenced by a foreign key made up of primary
key columns of this table, and (recursively) the parents of those
tables. So a record cannot exist without its parent records, e.g. a
server price without its vendor, region, zone and server.

**Examples:**

```pycon
>>> from sc_crawler.tables import Zone
>>> sorted(Zone.get_parent_tables())
['region', 'vendor']
```

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">get_key_filters</code> [table_bases.py:207–228](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L207-L228)

```python
get_key_filters(rule_table_name, keys)
```

Translate the `match` or `successor` of an archive rule into column filters on the table.

This defines which records an [ArchiveRule](https://docs.sparecores.com/crawler/reference/tables.md#archiverule)
refers to, for both the SQL conditions and matching primary keys in
Python. Tables referencing a parent without a foreign key override it.

**Parameters:**

- **rule_table_name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The `table_name` of the rule.
- **keys** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – The `match` or `successor` of the rule.

**Returns:**

- [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)`[`[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)`]` – Dict of column names and values of the table, or `None` if the
rule does not apply to the table.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">get_filters_condition</code> [table_bases.py:230–235](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L230-L235)

```python
get_filters_condition(filters)
```

SQL condition selecting the rows of the table with the given column values.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">matches_rule</code> [table_bases.py:237–251](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L237-L251)

```python
matches_rule(rule, primary_key)
```

Check if an archive rule archives the record with the given primary key.

**Parameters:**

- **rule** ([`ArchiveRule`](https://docs.sparecores.com/crawler/reference/tables.md#archiverule)) – An [ArchiveRule](https://docs.sparecores.com/crawler/reference/tables.md#archiverule).
- **primary_key** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – Primary key columns of the record with their values.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">is_archived</code> [table_bases.py:253–263](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L253-L263)

```python
is_archived(primary_key, rules=None)
```

Check if any of the archive rules archives the record with the given primary key.

**Parameters:**

- **primary_key** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – Primary key columns of the record with their values.
- **rules** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)`[`[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)`]`) – [ArchiveRule](https://docs.sparecores.com/crawler/reference/tables.md#archiverule)s to check. Defaults to all current rules.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">archive_condition</code> [table_bases.py:265–286](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L265-L286)

```python
archive_condition(rules=None)
```

SQL condition selecting the rows of the table archived by the rules.

Child records are selected by the key columns of the rules instead of
looking up their parents, so it also finds the child records of parents
that are not in the database.

**Parameters:**

- **rules** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)`[`[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)`]`) – [ArchiveRule](https://docs.sparecores.com/crawler/reference/tables.md#archiverule)s to apply. Defaults to all current rules.

**Returns:**

- [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)`[ColumnElement]` – SQLAlchemy condition, or `None` if no rule applies to the table.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">archived_by</code> [table_bases.py:288–335](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L288-L335)

```python
archived_by(session, primary_key)
```

List the archive rules archiving a record, including the rules on its parent tables.

Reads the rules from the `archive_rule` table of the database, so it also
returns the rules that were removed from the code since (stored with
`INACTIVE` status), and uses the same matching as `pull` and `sync`.
It does not look up the record itself.

**Parameters:**

- **session** (`Session`) – Database connection.
- **primary_key** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – All primary key columns of the record with their values.
Other keys (e.g. `observed_at` of an SCD record) are ignored.

**Returns:**

- [`list`](https://docs.python.org/3/builtins/stdtypes.html#list) – The matching [ArchiveRule](https://docs.sparecores.com/crawler/reference/tables.md#archiverule)s, ordered
by table name, `match` and `successor`.

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">pk_key</code> [table_bases.py:337–341](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L337-L341)

```python
pk_key(values)
```

JSON dump of the primary key columns of a row, as used in [hash](#scmodelhash).

### meth <code class="doc-parent">ScModel.</code><code class="doc-name">hash</code> [table_bases.py:343–398](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L343-L398)

```python
hash(session, ignored=['observed_at'], progress=None)
```

Hash the content of the rows.

**Parameters:**

- **session** (`Session`) – Database connection to use for object lookups.
- **ignored** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)`[`[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)`]`) – List of column names to exclude from hashing.
- **progress** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)`[`[`Progress`](https://rich.readthedocs.io/en/stable/reference/progress.html#rich.progress.Progress)`]`) – Optional progress bar to track the status of the hashing.

**Returns:**

- [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) – Dictionary of the row hashes keyed by the JSON dump of primary keys.

## class <code class="doc-name">MetaColumns</code> [table_bases.py:401–422](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L401-L422)

Bases: [`ScModel`](#scmodel)

Helper class to add the `status` and `observed_at` columns.

## class <code class="doc-name">HasPriceFieldsBase</code> [table_bases.py:579–612](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L579-L612)

Bases: [`ScModel`](#scmodel)

## class <code class="doc-name">ServerFields</code> [table_bases.py:819–1129](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L819-L1129)

Bases: `HasDisplayName`, `HasApiReferenceObject`, `HasApiReference`, `HasName`, `HasServerIdPK`, `HasVendorPKFK`

## class <code class="doc-name">BenchmarkFields</code> [table_bases.py:1460–1535](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1460-L1535)

Bases: `HasBenchmarkIdPK`

## class <code class="doc-name">ResourceIdComparator</code> [table_bases.py:1658–1676](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1658-L1676)

Bases: [`Comparator`](https://docs.sqlalchemy.org/en/20/orm/extensions/hybrid.html#sqlalchemy.ext.hybrid.Comparator)

Compile server_id/database_id to CASE + typed filter.

## class <code class="doc-name">BenchmarkScoreFields</code> [table_bases.py:1679–1789](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1679-L1789)

Bases: `HasBenchmarkPKFK`, `HasVendorPKFK`

**Functions:**

- [**update_config_to_hashable**](#benchmarkscorefieldsupdate_config_to_hashable) – Accept ``server_id`` / ``database_id`` keys; hashably sort config.

### meth <code class="doc-parent">BenchmarkScoreFields.</code><code class="doc-name">update_config_to_hashable</code> [table_bases.py:1694–1708](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1694-L1708)

```python
update_config_to_hashable(values)
```

Accept ``server_id`` / ``database_id`` keys; hashably sort config.

## class <code class="doc-name">BenchmarkScoreBase</code> [table_bases.py:1792–1816](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1792-L1816)

Bases: [`MetaColumns`](#metacolumns), [`BenchmarkScoreFields`](#benchmarkscorefields)

**Functions:**

- [**get_parent_tables**](#benchmarkscorebaseget_parent_tables) – Parent tables of the scores, including the resources they refer to.
- [**get_key_filters**](#benchmarkscorebaseget_key_filters) – Map a rule on a resource onto `resource_type` and `resource_id`.

### meth <code class="doc-parent">BenchmarkScoreBase.</code><code class="doc-name">get_parent_tables</code> [table_bases.py:1796–1800](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1796-L1800)

```python
get_parent_tables()
```

Parent tables of the scores, including the resources they refer to.

### meth <code class="doc-parent">BenchmarkScoreBase.</code><code class="doc-name">get_key_filters</code> [table_bases.py:1802–1816](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1802-L1816)

```python
get_key_filters(rule_table_name, keys)
```

Map a rule on a resource onto `resource_type` and `resource_id`.

## class <code class="doc-name">ArchiveRuleFields</code> [table_bases.py:1819–1859](https://github.com/SpareCores/sc-crawler/blob/81bb61ea164dda526de4aa6de298810007274f21/src/sc_crawler/table_bases.py#L1819-L1859)

Bases: [`ScModel`](#scmodel)
