Skip to content

table_bases

sc_crawler.table_bases #

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

Classes:

Name Description
ScMetaModel

Custom class factory to auto-update table models.

ScModel

Custom extensions to SQLModel objects and tables.

MetaColumns

Helper class to add the status and observed_at columns.

HasPriceFieldsBase
ServerFields
BenchmarkFields
ResourceIdComparator

Compile server_id/database_id to CASE + typed filter.

BenchmarkScoreFields
BenchmarkScoreBase
ArchiveRuleFields

ScMetaModel #

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.

Source code in sc_crawler/table_bases.py
class ScMetaModel(SQLModel.__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.
    """

    def __init__(subclass, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # early return for non-tables
        if subclass.model_config.get("table") is None:
            return
        satable = subclass.metadata.tables[subclass.__tablename__]

        # enforce auto-naming constrains as per
        # https://alembic.sqlalchemy.org/en/latest/naming.html
        subclass.metadata.naming_convention = {
            "ix": "ix_%(column_0_label)s",
            "uq": "uq_%(table_name)s_%(column_0_name)s",
            "ck": "ck_%(table_name)s_%(constraint_name)s",
            "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
            "pk": "pk_%(table_name)s",
        }

        # table comment
        if subclass.__doc__ and satable.comment is None:
            satable.comment = subclass.__doc__.splitlines()[0]

        # column comments
        for k, v in subclass.model_fields.items():
            comment = satable.columns[k].comment
            if v.description and comment is None:
                satable.columns[k].comment = v.description

        # generate docstring for SCD tables
        if subclass.__name__.endswith("Scd"):
            from .tables import tables

            nonscd = [t for t in tables if t.__name__ == subclass.__name__[:-3]][0]
            doclines = nonscd.__doc__.splitlines()
            # drop trailing dot and append SCD
            doclines[0] = doclines[0][:-1] + " (SCD Type 2)."
            subclass.__doc__ = "\n".join(doclines)
        else:
            # describe table columns as attributes in docstring
            subclass.__doc__ = subclass.__doc__ + "\n\nAttributes:\n"
            for k, v in subclass.model_fields.items():
                if not hasattr(v.annotation, "__args__"):
                    typehint = v.annotation.__name__
                else:
                    typehint = str(v.annotation)
                description = satable.columns[k].comment
                subclass.__doc__ = (
                    subclass.__doc__ + f"    {k} ({typehint}): {description}\n"
                )

        # find Pydantic model parent to be used for validating
        subclass.__validator__ = [
            m for m in subclass.__bases__ if m.__name__.endswith("Base")
        ][0]

ScModel #

Bases: SQLModel

Custom extensions to SQLModel objects and tables.

Extra features:

  • auto-generated table names using 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.

Methods:

Name Description
__tablename__

Override tables names using all-lowercase snake_case.

get_columns

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

get_table_name

Return the SQLModel object's table name.

get_validator

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

get_scd

Return the SCD version of the SQLModel table.

get_parent_tables

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

get_key_filters

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

get_filters_condition

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

matches_rule

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

is_archived

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

archive_condition

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

archived_by

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

pk_key

JSON dump of the primary key columns of a row, as used in hash.

hash

Hash the content of the rows.

Source code in sc_crawler/table_bases.py
class ScModel(SQLModel, metaclass=ScMetaModel):
    """Custom extensions to SQLModel objects and tables.

    Extra features:

    - auto-generated table names using [snake_case][sc_crawler.str_utils.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.
    """

    @declared_attr  # type: ignore
    def __tablename__(cls) -> str:
        """Override tables names using all-lowercase [snake_case][sc_crawler.str_utils.snake_case]."""
        return snake_case(cls.__name__)

    @classmethod
    def get_columns(cls) -> List[str]:
        """Return the table's column names in a dict for all, primary keys, and attributes."""
        columns = cls.__table__.columns.keys()
        pks = [pk.name for pk in inspect(cls).primary_key]
        attributes = [a for a in columns if a not in set(pks)]
        return {"all": columns, "primary_keys": pks, "attributes": attributes}

    @classmethod
    def get_table_name(cls) -> str:
        """Return the SQLModel object's table name."""
        return str(cls.__tablename__)

    @classmethod
    def get_validator(cls) -> Union["ScModel", None]:
        """Return the parent Base Pydantic model (without a table definition)."""
        if cls.model_config.get("table") is None:
            return None
        return cls.__validator__

    @classmethod
    def get_scd(cls) -> Union["ScModel", None]:
        """Return the SCD version of the SQLModel table."""
        if cls.model_config.get("table") is None:
            return None
        from .tables_scd import tables_scd

        validator = cls.get_validator()
        scds = [t for t in tables_scd if t.get_validator() == validator]
        if len(scds) != 1:
            raise ValueError("Not found SCD definition.")
        return scds[0]

    @classmethod
    @cache
    def get_parent_tables(cls) -> Set[str]:
        """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:
            >>> from sc_crawler.tables import Zone
            >>> sorted(Zone.get_parent_tables())
            ['region', 'vendor']
        """
        from .utils import table_name_to_model

        parents = {
            constraint.referred_table.name
            for constraint in cls.__table__.foreign_key_constraints
            if all(column.primary_key for column in constraint.columns)
        }
        for parent in list(parents):
            parents |= table_name_to_model(parent).get_parent_tables()
        return parents

    @classmethod
    def get_key_filters(cls, rule_table_name: str, keys: dict) -> Optional[dict]:
        """Translate the `match` or `successor` of an archive rule into column filters on the table.

        This defines which records an [ArchiveRule][sc_crawler.tables.ArchiveRule]
        refers to, for both the SQL conditions and matching primary keys in
        Python. Tables referencing a parent without a foreign key override it.

        Args:
            rule_table_name: The `table_name` of the rule.
            keys: The `match` or `successor` of the rule.

        Returns:
            Dict of column names and values of the table, or `None` if the
                rule does not apply to the table.
        """
        if (
            cls.get_table_name() != rule_table_name
            and rule_table_name not in cls.get_parent_tables()
        ):
            return None
        return dict(keys)

    @classmethod
    def get_filters_condition(cls, filters: dict) -> ColumnElement:
        """SQL condition selecting the rows of the table with the given column values."""
        return and_(
            *[getattr(cls, column) == value for column, value in filters.items()]
        )

    @classmethod
    def matches_rule(cls, rule: "ArchiveRule", primary_key: dict) -> bool:
        """Check if an archive rule archives the record with the given primary key.

        Args:
            rule: An [ArchiveRule][sc_crawler.tables.ArchiveRule].
            primary_key: Primary key columns of the record with their values.
        """
        filters = cls.get_key_filters(rule.table_name, rule.match)
        if filters is None:
            return False
        return all(
            column in primary_key and primary_key[column] == value
            for column, value in filters.items()
        )

    @classmethod
    def is_archived(cls, primary_key: dict, rules: Optional[list] = None) -> bool:
        """Check if any of the archive rules archives the record with the given primary key.

        Args:
            primary_key: Primary key columns of the record with their values.
            rules: [ArchiveRule][sc_crawler.tables.ArchiveRule]s to check. Defaults to all current rules.
        """
        if rules is None:
            from .archive_rules import archive_rules as rules
        return any(cls.matches_rule(rule, primary_key) for rule in rules)

    @classmethod
    def archive_condition(cls, rules: Optional[list] = None) -> Optional[ColumnElement]:
        """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.

        Args:
            rules: [ArchiveRule][sc_crawler.tables.ArchiveRule]s to apply. Defaults to all current rules.

        Returns:
            SQLAlchemy condition, or `None` if no rule applies to the table.
        """
        if rules is None:
            from .archive_rules import archive_rules as rules
        conditions = []
        for rule in rules:
            filters = cls.get_key_filters(rule.table_name, rule.match)
            if filters is not None:
                conditions.append(cls.get_filters_condition(filters))
        return or_(*conditions) if conditions else None

    @classmethod
    def archived_by(cls, session: Session, primary_key: dict) -> list:
        """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.

        Args:
            session: Database connection.
            primary_key: All primary key columns of the record with their values.
                Other keys (e.g. `observed_at` of an SCD record) are ignored.

        Returns:
            The matching [ArchiveRule][sc_crawler.tables.ArchiveRule]s, ordered
                by table name, `match` and `successor`.
        """
        from .tables import ArchiveRule

        columns = cls.get_columns()["primary_keys"]
        missing = [column for column in columns if column not in primary_key]
        if missing:
            raise ValueError(
                f"Missing primary key column(s) of {cls.get_table_name()}: "
                f"{', '.join(missing)}"
            )
        key = {}
        for column in columns:
            value = primary_key[column]
            # accept the name or value of enum members, which are stored by name
            column_type = cls.__table__.columns[column].type
            if isinstance(column_type, SaEnum) and column_type.enum_class is not None:
                enum_class = column_type.enum_class
                if isinstance(value, str) and value in enum_class.__members__:
                    value = enum_class[value]
                else:
                    value = enum_class(value)
            key[column] = value
        rules = [
            rule
            for rule in session.exec(select(ArchiveRule)).all()
            if cls.matches_rule(rule, key)
        ]
        return sorted(
            rules,
            key=lambda rule: (rule.table_name, str(rule.match), str(rule.successor)),
        )

    @classmethod
    def pk_key(cls, values: dict) -> str:
        """JSON dump of the primary key columns of a row, as used in [hash][sc_crawler.table_bases.ScModel.hash]."""
        pks = sorted(cls.get_columns()["primary_keys"])
        return dumps({pk: values.get(pk) for pk in pks}, sort_keys=True)

    @classmethod
    def hash(
        cls,
        session: Session,
        ignored: List[str] = ["observed_at"],
        progress: Optional[Progress] = None,
    ) -> dict:
        """Hash the content of the rows.

        Args:
            session: Database connection to use for object lookups.
            ignored: List of column names to exclude from hashing.
            progress: Optional progress bar to track the status of the hashing.

        Returns:
            Dictionary of the row hashes keyed by the JSON dump of primary keys.
        """
        pks = sorted(cls.get_columns()["primary_keys"])
        rows = session.exec(statement=select(cls))
        row_count = session.exec(select(func.count()).select_from(cls)).one()
        if progress:
            table_task_id = progress.add_task(
                cls.get_table_name(),
                total=row_count,
            )

        def json_default(value):
            # plain dates only, so datetime (a date subclass) is rejected too
            if type(value) is date:
                return value.isoformat()
            raise TypeError(f"Cannot hash {type(value).__name__} value: {value!r}")

        # no use of a generator as will need to serialize to JSON anyway
        hashes = {}
        for i, row in enumerate(rows):
            # NOTE Pydantic is warning when read Accelerator/Storage as dict
            # https://github.com/tiangolo/sqlmodel/issues/63#issuecomment-1081555082
            rowdict = row.model_dump(warnings=False)
            keys_id = cls.pk_key(rowdict)
            for dropkey in [*ignored, *pks]:
                rowdict.pop(dropkey, None)
            rowhash = sha1(
                dumps(rowdict, sort_keys=True, default=json_default).encode()
            ).hexdigest()
            hashes[keys_id] = rowhash
            if progress:
                # updating the progress bar is expensive, so limit with manu iterations
                if row_count > 1e3:
                    if (i + 1) % 1000 == 0:
                        progress.update(table_task_id, advance=1000)
                    if i == row_count - 1:
                        progress.update(table_task_id, advance=row_count % 1000)
                else:
                    progress.update(table_task_id, advance=1)

        return hashes

__tablename__ #

__tablename__()

Override tables names using all-lowercase snake_case.

Source code in sc_crawler/table_bases.py
@declared_attr  # type: ignore
def __tablename__(cls) -> str:
    """Override tables names using all-lowercase [snake_case][sc_crawler.str_utils.snake_case]."""
    return snake_case(cls.__name__)

get_columns classmethod #

get_columns()

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

Source code in sc_crawler/table_bases.py
@classmethod
def get_columns(cls) -> List[str]:
    """Return the table's column names in a dict for all, primary keys, and attributes."""
    columns = cls.__table__.columns.keys()
    pks = [pk.name for pk in inspect(cls).primary_key]
    attributes = [a for a in columns if a not in set(pks)]
    return {"all": columns, "primary_keys": pks, "attributes": attributes}

get_table_name classmethod #

get_table_name()

Return the SQLModel object's table name.

Source code in sc_crawler/table_bases.py
@classmethod
def get_table_name(cls) -> str:
    """Return the SQLModel object's table name."""
    return str(cls.__tablename__)

get_validator classmethod #

get_validator()

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

Source code in sc_crawler/table_bases.py
@classmethod
def get_validator(cls) -> Union["ScModel", None]:
    """Return the parent Base Pydantic model (without a table definition)."""
    if cls.model_config.get("table") is None:
        return None
    return cls.__validator__

get_scd classmethod #

get_scd()

Return the SCD version of the SQLModel table.

Source code in sc_crawler/table_bases.py
@classmethod
def get_scd(cls) -> Union["ScModel", None]:
    """Return the SCD version of the SQLModel table."""
    if cls.model_config.get("table") is None:
        return None
    from .tables_scd import tables_scd

    validator = cls.get_validator()
    scds = [t for t in tables_scd if t.get_validator() == validator]
    if len(scds) != 1:
        raise ValueError("Not found SCD definition.")
    return scds[0]

get_parent_tables cached classmethod #

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:

>>> from sc_crawler.tables import Zone
>>> sorted(Zone.get_parent_tables())
['region', 'vendor']
Source code in sc_crawler/table_bases.py
@classmethod
@cache
def get_parent_tables(cls) -> Set[str]:
    """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:
        >>> from sc_crawler.tables import Zone
        >>> sorted(Zone.get_parent_tables())
        ['region', 'vendor']
    """
    from .utils import table_name_to_model

    parents = {
        constraint.referred_table.name
        for constraint in cls.__table__.foreign_key_constraints
        if all(column.primary_key for column in constraint.columns)
    }
    for parent in list(parents):
        parents |= table_name_to_model(parent).get_parent_tables()
    return parents

get_key_filters classmethod #

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 refers to, for both the SQL conditions and matching primary keys in Python. Tables referencing a parent without a foreign key override it.

Parameters:

Name Type Description Default
rule_table_name str

The table_name of the rule.

required
keys dict

The match or successor of the rule.

required

Returns:

Type Description
Optional[dict]

Dict of column names and values of the table, or None if the rule does not apply to the table.

Source code in sc_crawler/table_bases.py
@classmethod
def get_key_filters(cls, rule_table_name: str, keys: dict) -> Optional[dict]:
    """Translate the `match` or `successor` of an archive rule into column filters on the table.

    This defines which records an [ArchiveRule][sc_crawler.tables.ArchiveRule]
    refers to, for both the SQL conditions and matching primary keys in
    Python. Tables referencing a parent without a foreign key override it.

    Args:
        rule_table_name: The `table_name` of the rule.
        keys: The `match` or `successor` of the rule.

    Returns:
        Dict of column names and values of the table, or `None` if the
            rule does not apply to the table.
    """
    if (
        cls.get_table_name() != rule_table_name
        and rule_table_name not in cls.get_parent_tables()
    ):
        return None
    return dict(keys)

get_filters_condition classmethod #

get_filters_condition(filters)

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

Source code in sc_crawler/table_bases.py
@classmethod
def get_filters_condition(cls, filters: dict) -> ColumnElement:
    """SQL condition selecting the rows of the table with the given column values."""
    return and_(
        *[getattr(cls, column) == value for column, value in filters.items()]
    )

matches_rule classmethod #

matches_rule(rule, primary_key)

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

Parameters:

Name Type Description Default
rule ArchiveRule required
primary_key dict

Primary key columns of the record with their values.

required
Source code in sc_crawler/table_bases.py
@classmethod
def matches_rule(cls, rule: "ArchiveRule", primary_key: dict) -> bool:
    """Check if an archive rule archives the record with the given primary key.

    Args:
        rule: An [ArchiveRule][sc_crawler.tables.ArchiveRule].
        primary_key: Primary key columns of the record with their values.
    """
    filters = cls.get_key_filters(rule.table_name, rule.match)
    if filters is None:
        return False
    return all(
        column in primary_key and primary_key[column] == value
        for column, value in filters.items()
    )

is_archived classmethod #

is_archived(primary_key, rules=None)

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

Parameters:

Name Type Description Default
primary_key dict

Primary key columns of the record with their values.

required
rules Optional[list]

ArchiveRules to check. Defaults to all current rules.

None
Source code in sc_crawler/table_bases.py
@classmethod
def is_archived(cls, primary_key: dict, rules: Optional[list] = None) -> bool:
    """Check if any of the archive rules archives the record with the given primary key.

    Args:
        primary_key: Primary key columns of the record with their values.
        rules: [ArchiveRule][sc_crawler.tables.ArchiveRule]s to check. Defaults to all current rules.
    """
    if rules is None:
        from .archive_rules import archive_rules as rules
    return any(cls.matches_rule(rule, primary_key) for rule in rules)

archive_condition classmethod #

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:

Name Type Description Default
rules Optional[list]

ArchiveRules to apply. Defaults to all current rules.

None

Returns:

Type Description
Optional[ColumnElement]

SQLAlchemy condition, or None if no rule applies to the table.

Source code in sc_crawler/table_bases.py
@classmethod
def archive_condition(cls, rules: Optional[list] = None) -> Optional[ColumnElement]:
    """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.

    Args:
        rules: [ArchiveRule][sc_crawler.tables.ArchiveRule]s to apply. Defaults to all current rules.

    Returns:
        SQLAlchemy condition, or `None` if no rule applies to the table.
    """
    if rules is None:
        from .archive_rules import archive_rules as rules
    conditions = []
    for rule in rules:
        filters = cls.get_key_filters(rule.table_name, rule.match)
        if filters is not None:
            conditions.append(cls.get_filters_condition(filters))
    return or_(*conditions) if conditions else None

archived_by classmethod #

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:

Name Type Description Default
session Session

Database connection.

required
primary_key dict

All primary key columns of the record with their values. Other keys (e.g. observed_at of an SCD record) are ignored.

required

Returns:

Type Description
list

The matching ArchiveRules, ordered by table name, match and successor.

Source code in sc_crawler/table_bases.py
@classmethod
def archived_by(cls, session: Session, primary_key: dict) -> list:
    """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.

    Args:
        session: Database connection.
        primary_key: All primary key columns of the record with their values.
            Other keys (e.g. `observed_at` of an SCD record) are ignored.

    Returns:
        The matching [ArchiveRule][sc_crawler.tables.ArchiveRule]s, ordered
            by table name, `match` and `successor`.
    """
    from .tables import ArchiveRule

    columns = cls.get_columns()["primary_keys"]
    missing = [column for column in columns if column not in primary_key]
    if missing:
        raise ValueError(
            f"Missing primary key column(s) of {cls.get_table_name()}: "
            f"{', '.join(missing)}"
        )
    key = {}
    for column in columns:
        value = primary_key[column]
        # accept the name or value of enum members, which are stored by name
        column_type = cls.__table__.columns[column].type
        if isinstance(column_type, SaEnum) and column_type.enum_class is not None:
            enum_class = column_type.enum_class
            if isinstance(value, str) and value in enum_class.__members__:
                value = enum_class[value]
            else:
                value = enum_class(value)
        key[column] = value
    rules = [
        rule
        for rule in session.exec(select(ArchiveRule)).all()
        if cls.matches_rule(rule, key)
    ]
    return sorted(
        rules,
        key=lambda rule: (rule.table_name, str(rule.match), str(rule.successor)),
    )

pk_key classmethod #

pk_key(values)

JSON dump of the primary key columns of a row, as used in hash.

Source code in sc_crawler/table_bases.py
@classmethod
def pk_key(cls, values: dict) -> str:
    """JSON dump of the primary key columns of a row, as used in [hash][sc_crawler.table_bases.ScModel.hash]."""
    pks = sorted(cls.get_columns()["primary_keys"])
    return dumps({pk: values.get(pk) for pk in pks}, sort_keys=True)

hash classmethod #

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

Hash the content of the rows.

Parameters:

Name Type Description Default
session Session

Database connection to use for object lookups.

required
ignored List[str]

List of column names to exclude from hashing.

['observed_at']
progress Optional[Progress]

Optional progress bar to track the status of the hashing.

None

Returns:

Type Description
dict

Dictionary of the row hashes keyed by the JSON dump of primary keys.

Source code in sc_crawler/table_bases.py
@classmethod
def hash(
    cls,
    session: Session,
    ignored: List[str] = ["observed_at"],
    progress: Optional[Progress] = None,
) -> dict:
    """Hash the content of the rows.

    Args:
        session: Database connection to use for object lookups.
        ignored: List of column names to exclude from hashing.
        progress: Optional progress bar to track the status of the hashing.

    Returns:
        Dictionary of the row hashes keyed by the JSON dump of primary keys.
    """
    pks = sorted(cls.get_columns()["primary_keys"])
    rows = session.exec(statement=select(cls))
    row_count = session.exec(select(func.count()).select_from(cls)).one()
    if progress:
        table_task_id = progress.add_task(
            cls.get_table_name(),
            total=row_count,
        )

    def json_default(value):
        # plain dates only, so datetime (a date subclass) is rejected too
        if type(value) is date:
            return value.isoformat()
        raise TypeError(f"Cannot hash {type(value).__name__} value: {value!r}")

    # no use of a generator as will need to serialize to JSON anyway
    hashes = {}
    for i, row in enumerate(rows):
        # NOTE Pydantic is warning when read Accelerator/Storage as dict
        # https://github.com/tiangolo/sqlmodel/issues/63#issuecomment-1081555082
        rowdict = row.model_dump(warnings=False)
        keys_id = cls.pk_key(rowdict)
        for dropkey in [*ignored, *pks]:
            rowdict.pop(dropkey, None)
        rowhash = sha1(
            dumps(rowdict, sort_keys=True, default=json_default).encode()
        ).hexdigest()
        hashes[keys_id] = rowhash
        if progress:
            # updating the progress bar is expensive, so limit with manu iterations
            if row_count > 1e3:
                if (i + 1) % 1000 == 0:
                    progress.update(table_task_id, advance=1000)
                if i == row_count - 1:
                    progress.update(table_task_id, advance=row_count % 1000)
            else:
                progress.update(table_task_id, advance=1)

    return hashes

MetaColumns #

Bases: ScModel

Helper class to add the status and observed_at columns.

Source code in sc_crawler/table_bases.py
class MetaColumns(ScModel):
    """Helper class to add the `status` and `observed_at` columns."""

    status: Status = Field(
        default=Status.ACTIVE,
        description="Status of the resource (active or inactive).",
    )
    observed_at: datetime = Field(
        default_factory=lambda: datetime.now(UTC),
        sa_column_kwargs={"onupdate": lambda: datetime.now(UTC)},
        description="Timestamp of the last observation.",
    )

    @field_validator("status")
    @classmethod
    def _validate_status(cls, value: Status) -> Status:
        if not value.is_general:
            raise ValueError(
                f"{value!r} is only valid for Server and Database. "
                f"Use ACTIVE, INACTIVE or ARCHIVED for {cls.__name__}."
            )
        return value

HasPriceFieldsBase #

Bases: ScModel

Source code in sc_crawler/table_bases.py
class HasPriceFieldsBase(ScModel):
    unit: PriceUnit = Field(description="Billing unit of the pricing model.")
    # set to max price if tiered
    price: float = Field(description="Actual price of a billing unit.")
    # e.g. setup fee for dedicated servers,
    # or upfront costs of a reserved instance type
    price_upfront: float = Field(
        default=0, description="Price to be paid when setting up the resource."
    )
    price_tiered: List[PriceTier] = Field(
        default=[],
        sa_type=JSON,
        description="List of pricing tiers with min/max thresholds and actual prices.",
    )
    currency: str = Field(default="USD", description="Currency of the prices.")

    @field_validator("price_tiered", mode="before")
    @classmethod
    def _deserialize_price_tiers(cls, value):
        """Deserialize price_tiered field, converting dicts to PriceTier instances."""
        if value is None:
            return []
        return [PriceTier(**item) if isinstance(item, dict) else item for item in value]

    @reconstructor
    def _reconstruct_price_tiers(self):
        """Ensure price_tiered is always a list of PriceTier instances after loading from the database."""
        if self.price_tiered is None:
            self.price_tiered = []
        else:
            self.price_tiered = [
                PriceTier(**item) if isinstance(item, dict) else item
                for item in self.price_tiered
            ]

ServerFields #

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

Source code in sc_crawler/table_bases.py
class ServerFields(
    HasDisplayName,
    HasApiReferenceObject,
    HasApiReference,
    HasName,
    HasServerIdPK,
    HasVendorPKFK,
):
    description: str = Field(description="Short description.", nullable=False)
    family: Optional[str] = Field(
        default=None,
        description=(
            "Broad workload class of the server in the vendor's own naming, "
            "e.g. General Purpose, Compute Optimized or Memory Optimized."
        ),
    )
    series: Optional[str] = Field(
        default=None,
        description=(
            "Hardware line and generation of the server, "
            "e.g. m5 (AWS), n2 (GCP) or b3 (OVH)."
        ),
    )
    # inspector_status: str = Field(
    #     default=None,
    #     description="Server family, e.g. General-purpose machine (GCP), or M5g (AWS).",
    # )
    vcpus: int = Field(
        default=None,
        description="Default number of virtual CPUs (vCPU) of the server.",
    )
    hypervisor: Optional[str] = Field(
        default=None,
        description="Hypervisor of the virtual server, e.g. Xen, KVM, Nitro or Dedicated.",
    )
    cpu_allocation: CpuAllocation = Field(
        default=None,
        description="Allocation of CPU(s) to the server, e.g. shared, burstable or dedicated.",
    )
    cpu_cores: Optional[int] = Field(
        default=None,
        description=(
            "Default number of CPU cores of the server. "
            "Equals to vCPUs when HyperThreading is disabled."
        ),
    )
    cpu_speed: Optional[float] = Field(
        default=None, description="Vendor-reported maximum CPU clock speed (GHz)."
    )
    cpu_architecture: CpuArchitecture = Field(
        default=None,
        description="CPU architecture (arm64, arm64_mac, i386, or x86_64).",
    )
    cpu_manufacturer: Optional[str] = Field(
        default=None,
        description="The manufacturer of the primary processor, e.g. Intel or AMD.",
    )
    cpu_family: Optional[str] = Field(
        default=None,
        description="The product line/family of the primary processor, e.g. Xeon, Core i7, Ryzen 9.",
    )
    cpu_model: Optional[str] = Field(
        default=None,
        description="The model number of the primary processor, e.g. 9750H.",
    )
    cpu_l1d_cache: Optional[int] = Field(
        default=None, description="L1 data cache size (KiB)."
    )
    cpu_l1d_cache_total: Optional[int] = Field(
        default=None, description="Total L1 data cache size (KiB) across all cores."
    )
    cpu_l1i_cache: Optional[int] = Field(
        default=None, description="L1 instruction cache size (KiB)."
    )
    cpu_l1i_cache_total: Optional[int] = Field(
        default=None,
        description="Total L1 instruction cache size (KiB) across all cores.",
    )
    cpu_l2_cache: Optional[int] = Field(
        default=None, description="L2 cache size (KiB)."
    )
    cpu_l2_cache_total: Optional[int] = Field(
        default=None, description="Total L2 cache size (KiB) across all cores."
    )
    cpu_l3_cache: Optional[int] = Field(
        default=None, description="L3 cache size (KiB)."
    )
    cpu_l3_cache_total: Optional[int] = Field(
        default=None, description="Total L3 cache size (KiB) across all cores."
    )
    cpu_flags: List[str] = Field(
        sa_type=JSON, default=[], description="CPU features/flags."
    )
    cpus: List[Cpu] = Field(
        default=[],
        sa_type=JSON,
        description=(
            "JSON array of known CPU details, e.g. the manufacturer, family, model; "
            "L1/L2/L3 cache size; microcode version; feature flags; bugs etc."
        ),
    )
    ecpus: Optional[float] = Field(
        default=None,
        description='The effective "real-world" core count, calculated by dividing the maximum multi-core SCore by the single-core SCore.',
    )
    scalability: Optional[float] = Field(
        default=None,
        description=(
            "Measures how efficiently the server scales from a single core performance to using multiple cores. "
            "A score of 100% means perfect linear scaling with zero performance loss."
        ),
    )
    hw_virt: Optional[bool] = Field(
        default=None,
        description="If hardware virtualization (e.g. KVM) is supported.",
    )
    memory_amount: int = Field(
        default=None,
        description="RAM amount (MiB) reported by the vendor.",
    )
    memory_amount_actual: Optional[int] = Field(
        default=None,
        description=(
            "Actual RAM amount (MiB) measured on the instance via lstopo or other tool. "
            "This amount might not match the vendor-reported memory due to the BIOS or the hypervisor reserving a small percentage."
        ),
    )
    memory_generation: Optional[DdrGeneration] = Field(
        default=None, description="Generation of the DDR SDRAM, e.g. DDR4 or DDR5."
    )
    memory_speed: Optional[int] = Field(
        default=None, description="DDR SDRAM clock rate (Mhz)."
    )
    memory_ecc: Optional[bool] = Field(
        default=None,
        description="If the DDR SDRAM uses error correction code to detect and correct n-bit data corruption.",
    )
    accelerator_count: float = Field(
        default=0,
        description="Number of accelerator(s), e.g. GPUs or NPUs.",
    )
    accelerator_memory_min: Optional[int] = Field(
        default=None,
        description="Memory (MiB) allocated to the lowest-end accelerator.",
    )
    accelerator_memory_total: Optional[int] = Field(
        default=None,
        description="Overall memory (MiB) allocated to all the accelerator(s).",
    )
    accelerator_type: Optional[AcceleratorType] = Field(
        default=None,
        description="The type of the primary accelerator, e.g. GPU or NPU.",
    )
    accelerator_manufacturer: Optional[str] = Field(
        default=None,
        description="The manufacturer of the primary accelerator, e.g. Nvidia or AMD.",
    )
    accelerator_family: Optional[str] = Field(
        default=None,
        description="The product family of the primary accelerator, e.g. Turing.",
    )
    accelerator_model: Optional[str] = Field(
        default=None,
        description="The model number of the primary accelerator, e.g. Tesla T4.",
    )
    accelerators: List[Accelerator] = Field(
        default=[],
        sa_type=JSON,
        description=(
            "JSON array of accelerator details, including "
            "the manufacturer, name, and memory (MiB) of each accelerator."
        ),
    )
    storage_size: int = Field(
        default=0,
        description="Overall size (GB) of the disk(s).",
    )
    storage_type: Optional[StorageType] = Field(
        default=None,
        description="Primary disk type, e.g. HDD, SSD, or NVMe SSD.",
    )
    storages: List[Disk] = Field(
        default=[],
        sa_type=JSON,
        description=(
            "JSON array of disks attached to the server, including "
            "the size (GB) and type of each disk."
        ),
    )
    storage_read_iops_max: Optional[int] = Field(
        default=None,
        description=(
            "The vendor-published maximum read IOPS of the bundled disk(s), "
            "summed over all disks, also of different types (e.g. temp disk and NVMe), "
            "so a theoretical total. Per-disk values are in storages."
        ),
    )
    storage_write_iops_max: Optional[int] = Field(
        default=None,
        description=(
            "The vendor-published maximum write IOPS of the bundled disk(s), "
            "summed over all disks, also of different types (e.g. temp disk and NVMe), "
            "so a theoretical total. Per-disk values are in storages."
        ),
    )
    storage_read_throughput_max: Optional[int] = Field(
        default=None,
        description=(
            "The vendor-published maximum read throughput (MB/s) of the bundled disk(s), "
            "summed over all disks, also of different types (e.g. temp disk and NVMe), "
            "so a theoretical total. Per-disk values are in storages."
        ),
    )
    storage_write_throughput_max: Optional[int] = Field(
        default=None,
        description=(
            "The vendor-published maximum write throughput (MB/s) of the bundled disk(s), "
            "summed over all disks, also of different types (e.g. temp disk and NVMe), "
            "so a theoretical total. Per-disk values are in storages."
        ),
    )
    compatible_storage_ids: Optional[List[str]] = Field(
        default=None,
        sa_type=JSON(none_as_null=True),
        description=(
            "List of storage_ids that can be attached to the server as extra storage."
        ),
    )
    network_speed_baseline: Optional[float] = Field(
        default=None,
        description="The baseline network performance (Gbps) of the server, aggregated over all network cards.",
    )
    network_speed_max: Optional[float] = Field(
        default=None,
        description="The maximum network performance (Gbps) of the server, aggregated over all network cards.",
    )
    network_storage_speed_baseline: Optional[float] = Field(
        default=None,
        description="The baseline bandwidth performance of network-attached storage (Gbps).",
    )
    network_storage_speed_max: Optional[float] = Field(
        default=None,
        description="The maximum bandwidth performance of network-attached storage (Gbps).",
    )
    inbound_traffic: float = Field(
        default=0,
        description="Amount of complimentary inbound traffic (GB) per month.",
    )
    outbound_traffic: float = Field(
        default=0,
        description="Amount of complimentary outbound traffic (GB) per month.",
    )
    ipv4: int = Field(
        default=0, description="Number of complimentary IPv4 address(es)."
    )
    average_time_to_start: Optional[float] = Field(
        default=None,
        description="Average time to start the server (seconds).",
    )

    @field_validator("cpus", mode="before")
    @classmethod
    def _deserialize_cpus(cls, value):
        """Deserialize cpus field, converting dicts to Cpu instances."""
        if value is None:
            return []
        return [Cpu(**item) if isinstance(item, dict) else item for item in value]

    @field_validator("accelerators", mode="before")
    @classmethod
    def _deserialize_accelerators(cls, value):
        """Deserialize accelerators field, converting dicts to Accelerator instances."""
        if value is None:
            return []
        return [
            Accelerator(**item) if isinstance(item, dict) else item for item in value
        ]

    @field_validator("storages", mode="before")
    @classmethod
    def _deserialize_storages(cls, value):
        """Deserialize storages field, converting dicts to Disk instances."""
        if value is None:
            return []
        return [Disk(**item) if isinstance(item, dict) else item for item in value]

    @reconstructor
    def _reconstruct_json_fields(self):
        """Ensure cpus, accelerators and storages are always a list of Cpu, Accelerator and Disk instances after loading from the database."""
        if self.cpus is None:
            self.cpus = []
        else:
            self.cpus = [
                Cpu(**item) if isinstance(item, dict) else item for item in self.cpus
            ]

        if self.accelerators is None:
            self.accelerators = []
        else:
            self.accelerators = [
                Accelerator(**item) if isinstance(item, dict) else item
                for item in self.accelerators
            ]

        if self.storages is None:
            self.storages = []
        else:
            self.storages = [
                Disk(**item) if isinstance(item, dict) else item
                for item in self.storages
            ]

BenchmarkFields #

Bases: HasBenchmarkIdPK

Source code in sc_crawler/table_bases.py
class BenchmarkFields(HasBenchmarkIdPK):
    category: Optional[str] = Field(description="Category of the resource.")
    subcategory: Optional[str] = Field(
        default=None,
        description="Subcategory of the benchmark within its category, e.g. the scope of an nvbandwidth test.",
    )
    source: BenchmarkSource = Field(
        default_factory=MeasuredSource,
        sa_type=JSON,
        description=(
            "How the benchmark score is produced. A discriminated object keyed by "
            "'kind': 'measured' (directly observed), 'extrapolated' (derived from this "
            "server's own measurements; carries 'derived_from' + 'note'), or 'compound' "
            "(aggregated across component benchmarks; carries 'aggregation', "
            "'normalization', and the 'components' recipe)."
        ),
    )
    name: str = Field(description="Human-friendly name.")
    description: Optional[str] = Field(description="Short description.")
    note: Optional[str] = Field(
        default=None,
        description=(
            "Optional caveat/comment on how to interpret the metric, surfaced as a "
            "warning/info badge (e.g. limited scaling on high vCPU counts, or "
            "independence from vCPU count). Null when there is nothing to flag."
        ),
    )
    framework: str = Field(
        description="The name of the benchmark framework/software/tool used.",
    )
    config_fields: dict = Field(
        default={},
        sa_type=JSON,
        description='A dictionary of descriptions on the framework-specific config options, e.g. {"bandwidth": "Memory amount to use for compression in MB."}.',
    )
    environment_fields: dict = Field(
        default={},
        sa_type=JSON,
        description='A dictionary of descriptions on the environment details recorded with the benchmark scores, e.g. {"kernel_version": "Linux kernel version of the server."}.',
    )
    measurement: Optional[str] = Field(
        default=None,
        description="The name of measurement recorded in the benchmark.",
    )
    unit: Optional[str] = Field(
        default=None,
        description="Optional unit of measurement for the benchmark score.",
    )
    higher_is_better: bool = Field(
        default=True,
        description="If higher benchmark score means better performance, or vica versa.",
    )

    @field_serializer("source")
    def _serialize_source(self, value: BenchmarkSource):
        if isinstance(value, dict):
            return value
        if hasattr(value, "__json__"):
            return value.__json__()
        return value

    @field_validator("source", mode="before")
    @classmethod
    def _deserialize_source(cls, value):
        """Coerce a dict to the right BenchmarkSource variant on construction."""
        if value is None:
            return MeasuredSource()
        if isinstance(value, dict):
            return _BENCHMARK_SOURCE_ADAPTER.validate_python(value)
        return value

    @reconstructor
    def _reconstruct_source(self):
        """Re-coerce source from the dict returned by a DB load."""
        if isinstance(self.source, dict):
            self.source = _BENCHMARK_SOURCE_ADAPTER.validate_python(self.source)

ResourceIdComparator #

Bases: Comparator

Compile server_id/database_id to CASE + typed filter.

Source code in sc_crawler/table_bases.py
class ResourceIdComparator(Comparator):
    """Compile server_id/database_id to CASE + typed filter."""

    def __init__(self, cls, resource_type, label):
        self.cls = cls
        self.resource_type = resource_type
        self.label = label

    def __clause_element__(self):
        return case(
            (self.cls.resource_type == self.resource_type, self.cls.resource_id),
            else_=None,
        ).label(self.label)

    def operate(self, op, *other, **kwargs):
        return and_(
            self.cls.resource_type == self.resource_type,
            op(self.cls.resource_id, *other, **kwargs),
        )

BenchmarkScoreFields #

Bases: HasBenchmarkPKFK, HasVendorPKFK

Methods:

Name Description
update_config_to_hashable

Accept server_id / database_id keys; hashably sort config.

Source code in sc_crawler/table_bases.py
class BenchmarkScoreFields(HasBenchmarkPKFK, HasVendorPKFK):
    model_config = ConfigDict(
        arbitrary_types_allowed=True,
        ignored_types=(hybrid_property,),
    )

    resource_type: ResourceType = Field(
        primary_key=True,
        description="Kind of resource the score refers to.",
    )
    resource_id: str = Field(
        primary_key=True,
        description="Reference to the resource (see resource_type).",
    )

    @model_validator(mode="before")
    def update_config_to_hashable(cls, values):
        """Accept ``server_id`` / ``database_id`` keys; hashably sort config."""
        has_server = "server_id" in values
        has_database = "database_id" in values
        if has_server and has_database:
            raise ValueError("Provide only one of server_id or database_id.")
        if has_server:
            values["resource_type"] = ResourceType.SERVER
            values["resource_id"] = values.pop("server_id")
        elif has_database:
            values["resource_type"] = ResourceType.DATABASE
            values["resource_id"] = values.pop("database_id")
        values["config"] = HashableDict(sorted(values.get("config", {}).items()))
        return values

    # use HashableDict as it's a primary key that needs to be hashable, but
    # fall back to dict to avoid PydanticInvalidForJsonSchema
    config: HashableDict | dict = Field(
        default={},
        sa_type=HashableJSON,
        primary_key=True,
        description='Dictionary of config parameters of the specific benchmark, e.g. {"bandwidth": 4096}',
    )
    framework_version: Optional[str] = Field(
        default=None,
        description="The version of the benchmark tool used.",
    )
    environment: Optional[dict] = Field(
        default=None,
        sa_type=JSON(none_as_null=True),
        description=(
            "Extensible environment details "
            "(e.g. kernel_version, database_engine_version)."
        ),
    )
    score: float = Field(
        description="The resulting score of the benchmark.",
    )
    score_breakdown: Optional[WorkloadScoreBreakdown] = Field(
        default=None,
        sa_type=JSON(none_as_null=True),
        description=(
            "Structured derivation of composite scores (e.g. workload profiles): "
            "per-component raw values, references, normalized values, weights, and "
            "coverage. Null for simple benchmark scores."
        ),
    )
    note: Optional[str] = Field(
        default=None,
        description="Optional note, comment or context on the benchmark score.",
    )

    @hybrid_property
    def server_id(self) -> Optional[str]:
        return self.resource_id if self.resource_type == ResourceType.SERVER else None

    @server_id.inplace.comparator
    @classmethod
    def _server_id_comparator(cls):
        return ResourceIdComparator(cls, ResourceType.SERVER, "server_id")

    @hybrid_property
    def database_id(self) -> Optional[str]:
        return self.resource_id if self.resource_type == ResourceType.DATABASE else None

    @database_id.inplace.comparator
    @classmethod
    def _database_id_comparator(cls):
        return ResourceIdComparator(cls, ResourceType.DATABASE, "database_id")

    def to_response(self) -> dict:
        data = self.model_dump(exclude={"resource_type", "resource_id"})
        resource_type = ResourceType(self.resource_type)
        data[f"{resource_type.value}_id"] = self.resource_id
        return data

    @field_serializer("score_breakdown")
    def _serialize_score_breakdown(self, value: Optional[WorkloadScoreBreakdown]):
        if value is None or isinstance(value, dict):
            return value
        if hasattr(value, "__json__"):
            return value.__json__()
        return value

    @field_validator("score_breakdown", mode="before")
    @classmethod
    def _deserialize_score_breakdown(cls, value):
        """Coerce a dict to WorkloadScoreBreakdown on construction."""
        return WorkloadScoreBreakdown(**value) if isinstance(value, dict) else value

    @reconstructor
    def _reconstruct_score_breakdown(self):
        """Re-coerce score_breakdown from the dict returned by a DB load."""
        if isinstance(self.score_breakdown, dict):
            self.score_breakdown = WorkloadScoreBreakdown(**self.score_breakdown)

update_config_to_hashable #

update_config_to_hashable(values)

Accept server_id / database_id keys; hashably sort config.

Source code in sc_crawler/table_bases.py
@model_validator(mode="before")
def update_config_to_hashable(cls, values):
    """Accept ``server_id`` / ``database_id`` keys; hashably sort config."""
    has_server = "server_id" in values
    has_database = "database_id" in values
    if has_server and has_database:
        raise ValueError("Provide only one of server_id or database_id.")
    if has_server:
        values["resource_type"] = ResourceType.SERVER
        values["resource_id"] = values.pop("server_id")
    elif has_database:
        values["resource_type"] = ResourceType.DATABASE
        values["resource_id"] = values.pop("database_id")
    values["config"] = HashableDict(sorted(values.get("config", {}).items()))
    return values

BenchmarkScoreBase #

Bases: MetaColumns, BenchmarkScoreFields

Methods:

Name Description
get_parent_tables

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

get_key_filters

Map a rule on a resource onto resource_type and resource_id.

Source code in sc_crawler/table_bases.py
class BenchmarkScoreBase(MetaColumns, BenchmarkScoreFields):
    # Scores refer to the resource of each ResourceType without a foreign key:
    # the value of the type is the parent table, and `<value>_id` its id column.

    @classmethod
    @cache
    def get_parent_tables(cls) -> Set[str]:
        """Parent tables of the scores, including the resources they refer to."""
        return super().get_parent_tables() | {rt.value for rt in ResourceType}

    @classmethod
    def get_key_filters(cls, rule_table_name: str, keys: dict) -> Optional[dict]:
        """Map a rule on a resource onto `resource_type` and `resource_id`."""
        filters = super().get_key_filters(rule_table_name, keys)
        # membership via `in` raises TypeError for plain strings on Python 3.11
        resource_type = {member.value: member for member in ResourceType}.get(
            rule_table_name
        )
        if filters is None or resource_type is None:
            return filters
        filters["resource_type"] = resource_type
        id_column = f"{rule_table_name}_id"
        if id_column in filters:
            filters["resource_id"] = filters.pop(id_column)
        return filters

get_parent_tables cached classmethod #

get_parent_tables()

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

Source code in sc_crawler/table_bases.py
@classmethod
@cache
def get_parent_tables(cls) -> Set[str]:
    """Parent tables of the scores, including the resources they refer to."""
    return super().get_parent_tables() | {rt.value for rt in ResourceType}

get_key_filters classmethod #

get_key_filters(rule_table_name, keys)

Map a rule on a resource onto resource_type and resource_id.

Source code in sc_crawler/table_bases.py
@classmethod
def get_key_filters(cls, rule_table_name: str, keys: dict) -> Optional[dict]:
    """Map a rule on a resource onto `resource_type` and `resource_id`."""
    filters = super().get_key_filters(rule_table_name, keys)
    # membership via `in` raises TypeError for plain strings on Python 3.11
    resource_type = {member.value: member for member in ResourceType}.get(
        rule_table_name
    )
    if filters is None or resource_type is None:
        return filters
    filters["resource_type"] = resource_type
    id_column = f"{rule_table_name}_id"
    if id_column in filters:
        filters["resource_id"] = filters.pop(id_column)
    return filters

ArchiveRuleFields #

Bases: ScModel

Source code in sc_crawler/table_bases.py
class ArchiveRuleFields(ScModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)

    table_name: str = Field(
        primary_key=True,
        description="Name of the table of the archived record(s), e.g. `region`.",
    )
    # use HashableDict as primary keys need to be hashable, but fall back
    # to dict to avoid PydanticInvalidForJsonSchema
    match: HashableDict | dict = Field(
        sa_type=HashableJSON,
        primary_key=True,
        description=(
            "Primary key of the record to archive, or a subset of its columns "
            "to archive all records with those values, "
            'e.g. {"region_id": "2", "vendor_id": "hcloud"}.'
        ),
    )
    successor: HashableDict | dict = Field(
        default={},
        sa_type=HashableJSON,
        primary_key=True,
        description=(
            "New values of the `match` columns identifying the successor of "
            "each archived record. Empty when there is no successor, or none "
            "that can be given as fixed values (see `reason`)."
        ),
    )
    reason: Optional[str] = Field(
        default=None,
        description="Why the record(s) got archived.",
    )

    @model_validator(mode="before")
    def _sort_keys(cls, values):
        """Store `match` and `successor` with sorted keys."""
        if not isinstance(values, dict):
            return values
        for field in ("match", "successor"):
            values[field] = HashableDict.sorted(values.get(field) or {})
        return values