Skip to content

Backends

Choosing a backend (koality.backends)

Backends: how koality reads source tables from, and writes results to, the database behind database_accessor.

Koality picks the backend registered for the attached database's type in duckdb_databases(), and falls back to DuckDBBackend, which handles every database DuckDB attaches as a catalog. Third-party packages can add backends with register_backend or through the koality.backends entry point group, whose entries load a Backend subclass.

ENTRY_POINT_GROUP module-attribute

ENTRY_POINT_GROUP = 'koality.backends'

backend_for

backend_for(duckdb_client: DuckDBPyConnection, database_accessor: str, database_provider: DatabaseProvider | None, *, owns_connection: bool = False) -> Backend

Return the backend for the attached database database_provider.

Without an attached database, or for a type without its own backend, the backend registered for "duckdb" is used (DuckDBBackend unless replaced), since DuckDB attaches those databases as catalogs.

Source code in src/koality/backends/__init__.py
def backend_for(
    duckdb_client: duckdb.DuckDBPyConnection,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    *,
    owns_connection: bool = False,
) -> Backend:
    """Return the backend for the attached database `database_provider`.

    Without an attached database, or for a type without its own backend, the backend registered for "duckdb"
    is used (`DuckDBBackend` unless replaced), since DuckDB attaches those databases as catalogs.
    """
    _load_entry_points()
    default = _BACKENDS.get(DuckDBBackend.type, DuckDBBackend)
    backend = default
    if database_provider is not None:
        backend = _BACKENDS.get(str(database_provider.type).lower(), default)
    return backend(duckdb_client, database_accessor, database_provider, owns_connection=owns_connection)

register_backend

register_backend(backend: type[Backend]) -> type[Backend]

Use backend for attached databases of type backend.type; usable as a class decorator.

Source code in src/koality/backends/__init__.py
def register_backend(backend: type[Backend]) -> type[Backend]:
    """Use `backend` for attached databases of type `backend.type`; usable as a class decorator."""
    _check_backend(backend, repr(backend))
    # Waits for entry points being loaded in another thread, which would otherwise overwrite this registration
    with _entry_points_lock:
        _BACKENDS[backend.type.lower()] = backend
    return backend

Backend interface (koality.backends.base)

The interface between koality and the database attached as database_accessor.

Backend

Backend(duckdb_client: DuckDBPyConnection, database_accessor: str, database_provider: DatabaseProvider | None, *, owns_connection: bool = False)

Bases: SqlDialect, ABC

How koality reads source tables from, and writes results to, one kind of attached database.

Koality copies the rows its checks need into DuckDB and runs every check there, so a backend only covers the source side: naming a source table, writing filter values, date columns and date literals for the source's SQL (SqlDialect, DuckDB's by default), running SQL against the source, and appending results to result_table.

A backend is chosen by the attached database's type in duckdb_databases() (e.g. "bigquery"); register one with koality.backends.register_backend or the koality.backends entry point group. The type comes from the database attached in database_setup, so a source needs a DuckDB extension that attaches it with its own type. A backend may still fetch the data another way (e.g. through the source's API) as long as query returns a DuckDB relation on duckdb_client, for instance self.duckdb_client.from_arrow(...); a relation from another connection (such as duckdb.from_arrow) cannot be staged. Failures should be raised as duckdb.Error or koality.exceptions.DatabaseError, which koality reports as database errors.

Parameters:

Name Type Description Default
duckdb_client DuckDBPyConnection

The DuckDB connection koality runs on.

required
database_accessor str

The name of the attached database ("" if there is none).

required
database_provider DatabaseProvider | None

The attached database's entry in duckdb_databases(), if any.

required
owns_connection bool

Whether koality created the connection, so that in-memory data is lost when koality exits.

False
Source code in src/koality/backends/base.py
def __init__(
    self,
    duckdb_client: duckdb.DuckDBPyConnection,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    *,
    owns_connection: bool = False,
) -> None:
    """Bind the backend to a connection and the attached database named `database_accessor`.

    Args:
        duckdb_client: The DuckDB connection koality runs on.
        database_accessor: The name of the attached database ("" if there is none).
        database_provider: The attached database's entry in `duckdb_databases()`, if any.
        owns_connection: Whether koality created the connection, so that in-memory data is lost when
            koality exits.

    """
    self.duckdb_client = duckdb_client
    self.database_accessor = database_accessor
    self.database_provider = database_provider
    self.owns_connection = owns_connection

columns

columns(table: str) -> list[str]

Return the column names of the source table, e.g. to check a config's columns against the database.

The default binds SELECT * ... LIMIT 0 through query, which DuckDB catalogs answer from their metadata without reading rows; override it for a source that would scan the table instead.

Raises:

Type Description
Error | DatabaseError

If the table doesn't exist or can't be read.

Source code in src/koality/backends/base.py
def columns(self, table: str) -> list[str]:
    """Return the column names of the source `table`, e.g. to check a config's columns against the database.

    The default binds `SELECT * ... LIMIT 0` through `query`, which DuckDB catalogs answer from their
    metadata without reading rows; override it for a source that would scan the table instead.

    Raises:
        duckdb.Error | koality.exceptions.DatabaseError: If the table doesn't exist or can't be read.

    """
    return self.query(f"SELECT * FROM {self.table_ref(table)} LIMIT 0").columns  # noqa: S608

date_column

date_column(column: str) -> str

Return column converted to a date, as compared by date filters.

Source code in src/koality/utils.py
def date_column(self, column: str) -> str:
    """Return `column` converted to a date, as compared by date filters."""
    return f"CAST({column} AS DATE)"

date_literal

date_literal(value: object) -> str

Return the date value (an ISO date string) as a date literal.

Source code in src/koality/utils.py
def date_literal(self, value: object) -> str:
    """Return the date `value` (an ISO date string) as a date literal."""
    return f"DATE {self.format_filter_value(value, '=')}"

format_filter_value

format_filter_value(value: object, operator: str) -> str

Format a filter value (or the parenthesized list for IN / NOT IN) as an SQL literal.

Source code in src/koality/utils.py
def format_filter_value(self, value: object, operator: str) -> str:
    """Format a filter value (or the parenthesized list for IN / NOT IN) as an SQL literal."""
    return format_filter_value(value, operator)

plan

plan(sql: str) -> str | None

Return the source's plan of sql without running it (for koality explain --connect), or None.

The default is None: a backend that sends its queries to the source (e.g. BigQuery's) can't have them planned without sending them.

Raises:

Type Description
Error | DatabaseError

If sql can't be planned (e.g. a missing column).

Source code in src/koality/backends/base.py
def plan(self, sql: str) -> str | None:  # noqa: ARG002
    """Return the source's plan of `sql` without running it (for `koality explain --connect`), or None.

    The default is None: a backend that sends its queries to the source (e.g. BigQuery's) can't have them
    planned without sending them.

    Raises:
        duckdb.Error | koality.exceptions.DatabaseError: If `sql` can't be planned (e.g. a missing column).

    """
    return None

query abstractmethod

query(sql: str) -> DuckDBPyRelation

Run sql against the source database and return the result as a DuckDB relation.

Source code in src/koality/backends/base.py
@abc.abstractmethod
def query(self, sql: str) -> duckdb.DuckDBPyRelation:
    """Run `sql` against the source database and return the result as a DuckDB relation."""

table_ref abstractmethod

table_ref(table: str) -> str

Return the SQL reference to the source table, for use in queries passed to query.

Source code in src/koality/backends/base.py
@abc.abstractmethod
def table_ref(self, table: str) -> str:
    """Return the SQL reference to the source `table`, for use in queries passed to `query`."""

write_results abstractmethod

write_results(result_table: str, rows: list[dict], identifier_column: str, now: datetime) -> str

Append result rows to result_table, creating it if needed, and return where they were written.

Parameters:

Name Type Description Default
result_table str

The configured result_table.

required
rows list[dict]

Aggregated result dicts with the keys DATE, METRIC_NAME, TABLE, identifier_column, COLUMN, VALUE, LOWER_THRESHOLD, UPPER_THRESHOLD and RESULT.

required
identifier_column str

The name of the identifier field (e.g. IDENTIFIER).

required
now datetime

The insert timestamp (UTC).

required
Source code in src/koality/backends/base.py
@abc.abstractmethod
def write_results(self, result_table: str, rows: list[dict], identifier_column: str, now: dt.datetime) -> str:
    """Append result `rows` to `result_table`, creating it if needed, and return where they were written.

    Args:
        result_table: The configured `result_table`.
        rows: Aggregated result dicts with the keys DATE, METRIC_NAME, TABLE, `identifier_column`,
            COLUMN, VALUE, LOWER_THRESHOLD, UPPER_THRESHOLD and RESULT.
        identifier_column: The name of the identifier field (e.g. IDENTIFIER).
        now: The insert timestamp (UTC).

    """

result_columns

result_columns(identifier_column: str, type_names: dict[str, str]) -> dict[str, str]

Return the result_table columns in order, with their types named by type_names.

type_names maps each generic type ("date", "text", "float" and "timestamp") to the database's type name.

Source code in src/koality/backends/base.py
def result_columns(identifier_column: str, type_names: dict[str, str]) -> dict[str, str]:
    """Return the `result_table` columns in order, with their types named by `type_names`.

    `type_names` maps each generic type ("date", "text", "float" and "timestamp") to the database's type name.
    """
    columns = {
        "DATE": "date",
        "METRIC_NAME": "text",
        "TABLE": "text",
        identifier_column: "text",
        "COLUMN": "text",
        "VALUE": "float",
        "LOWER_THRESHOLD": "float",
        "UPPER_THRESHOLD": "float",
        "RESULT": "text",
        "INSERT_TIMESTAMP": "timestamp",
    }
    return {name: type_names[type_] for name, type_ in columns.items()}

DuckDB catalogs (koality.backends.duckdb_catalog)

The default backend: any database DuckDB attaches as a catalog (DuckDB files, Postgres, MySQL, SQLite, ...).

DuckDBBackend

DuckDBBackend(duckdb_client: DuckDBPyConnection, database_accessor: str, database_provider: DatabaseProvider | None, *, owns_connection: bool = False)

Bases: Backend

Reads and writes through DuckDB's catalog of the attached database, or the session's own tables.

Used for every attached database without a dedicated backend. table and result_table resolve inside the database_accessor catalog (see koality.utils.qualify_table_name).

Source code in src/koality/backends/base.py
def __init__(
    self,
    duckdb_client: duckdb.DuckDBPyConnection,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    *,
    owns_connection: bool = False,
) -> None:
    """Bind the backend to a connection and the attached database named `database_accessor`.

    Args:
        duckdb_client: The DuckDB connection koality runs on.
        database_accessor: The name of the attached database ("" if there is none).
        database_provider: The attached database's entry in `duckdb_databases()`, if any.
        owns_connection: Whether koality created the connection, so that in-memory data is lost when
            koality exits.

    """
    self.duckdb_client = duckdb_client
    self.database_accessor = database_accessor
    self.database_provider = database_provider
    self.owns_connection = owns_connection

plan

plan(sql: str) -> str | None

Return DuckDB's plan of sql (as EXPLAIN shows it), which binds the query without running it.

Source code in src/koality/backends/duckdb_catalog.py
def plan(self, sql: str) -> str | None:
    """Return DuckDB's plan of `sql` (as `EXPLAIN` shows it), which binds the query without running it."""
    # A subclass that reads another way (e.g. through an API) overrides `query`: DuckDB's plan wouldn't describe it
    if type(self).query is not DuckDBBackend.query:
        return None
    # An EXPLAIN statement, since `query` would run a statement that isn't a SELECT
    return "\n".join(plan for _, plan in self.duckdb_client.sql(f"EXPLAIN {sql}").fetchall())

query

query(sql: str) -> DuckDBPyRelation

Run sql on the DuckDB connection.

Source code in src/koality/backends/duckdb_catalog.py
def query(self, sql: str) -> duckdb.DuckDBPyRelation:
    """Run `sql` on the DuckDB connection."""
    return self.duckdb_client.query(sql)

table_ref

table_ref(table: str) -> str

Return table qualified with the accessor catalog, or a TEMP table of that name if only that exists.

Source code in src/koality/backends/duckdb_catalog.py
def table_ref(self, table: str) -> str:
    """Return `table` qualified with the accessor catalog, or a TEMP table of that name if only that exists."""
    table_ref = qualify_table_name(self.database_accessor, table)
    if not self._table_exists(table_ref):
        fallback = self._temp_table_ref(table)
        if fallback and self._table_exists(fallback):
            log.warning("Table %s not found as %s, using TEMP table %s", table, table_ref, fallback)
            return fallback
    return table_ref

write_results

write_results(result_table: str, rows: list[dict], identifier_column: str, now: datetime) -> str

Append rows to result_table in one INSERT with bound parameters.

Source code in src/koality/backends/duckdb_catalog.py
def write_results(self, result_table: str, rows: list[dict], identifier_column: str, now: dt.datetime) -> str:
    """Append `rows` to `result_table` in one INSERT with bound parameters."""
    target = qualify_table_name(self.database_accessor, result_table)
    columns = result_columns(
        identifier_column,
        {"date": "DATE", "text": "VARCHAR", "float": "DOUBLE", "timestamp": "TIMESTAMP"},
    )
    column_definitions = ", ".join(f"{quote_identifier(name)} {type_}" for name, type_ in columns.items())
    column_list = ", ".join(quote_identifier(name) for name in columns)
    row_placeholders = "(" + ", ".join("?" for _ in columns) + ")"
    # Stored as naive UTC
    insert_timestamp = now.replace(tzinfo=None)
    # One multi-row INSERT, so a failing row persists nothing and attached databases get a single statement
    values = [insert_timestamp if name == "INSERT_TIMESTAMP" else row.get(name) for row in rows for name in columns]
    try:
        self.duckdb_client.sql(f"CREATE TABLE IF NOT EXISTS {target} ({column_definitions})")
        self.duckdb_client.execute(
            f"INSERT INTO {target} ({column_list}) VALUES {', '.join(row_placeholders for _ in rows)}",  # noqa: S608
            values,
        ).fetchall()
    except duckdb.Error as e:
        msg = f"Could not persist results to {target}"
        raise DatabaseError(msg) from e

    if self.owns_connection and self._is_in_memory(result_table):
        log.warning(
            "Results were persisted to %s in an in-memory database and are lost when koality exits. "
            "Attach a database file in database_setup and point result_table at it.",
            target,
        )
    return target

BigQuery (koality.backends.bigquery)

Backend for BigQuery, attached through DuckDB's community bigquery extension.

BigQueryBackend

BigQueryBackend(duckdb_client: DuckDBPyConnection, database_accessor: str, database_provider: DatabaseProvider | None, *, owns_connection: bool = False)

Bases: Backend

Runs SQL in BigQuery itself, through bigquery_query (reads, which supports views) and bigquery_execute.

table and result_table are passed to BigQuery as written (dataset.table or project.dataset.table), and filter values are written as BigQuery literals. query_options are named arguments passed to every bigquery_query call; a subclass setting it to {"use_rest_api": True} reads results through the REST API instead of the Storage Read API (e.g. for an emulator, or without permission to create read sessions).

Source code in src/koality/backends/base.py
def __init__(
    self,
    duckdb_client: duckdb.DuckDBPyConnection,
    database_accessor: str,
    database_provider: DatabaseProvider | None,
    *,
    owns_connection: bool = False,
) -> None:
    """Bind the backend to a connection and the attached database named `database_accessor`.

    Args:
        duckdb_client: The DuckDB connection koality runs on.
        database_accessor: The name of the attached database ("" if there is none).
        database_provider: The attached database's entry in `duckdb_databases()`, if any.
        owns_connection: Whether koality created the connection, so that in-memory data is lost when
            koality exits.

    """
    self.duckdb_client = duckdb_client
    self.database_accessor = database_accessor
    self.database_provider = database_provider
    self.owns_connection = owns_connection

columns

columns(table: str) -> list[str]

Return the column names of table from its dataset's INFORMATION_SCHEMA, without reading its rows.

A SELECT * ... LIMIT 0 would be billed by BigQuery as a scan of the whole table. For a wildcard table (e.g. events_*), BigQuery uses the schema of the most recently created table it matches, so that table's columns are returned, with the _TABLE_SUFFIX pseudo-column.

Source code in src/koality/backends/bigquery.py
def columns(self, table: str) -> list[str]:
    """Return the column names of `table` from its dataset's INFORMATION_SCHEMA, without reading its rows.

    A `SELECT * ... LIMIT 0` would be billed by BigQuery as a scan of the whole table. For a wildcard
    table (e.g. `events_*`), BigQuery uses the schema of the most recently created table it matches, so
    that table's columns are returned, with the `_TABLE_SUFFIX` pseudo-column.
    """
    dataset, _, name = table.rpartition(".")
    if not dataset or "`" in table:
        msg = f"BigQuery table {table!r} must be written as dataset.table or project.dataset.table"
        raise DatabaseError(msg)
    wildcard = name.endswith("*")
    if wildcard:
        condition = (
            f"table_name = (SELECT table_name FROM `{dataset}`.INFORMATION_SCHEMA.TABLES "  # noqa: S608
            f"WHERE STARTS_WITH(table_name, {bigquery_literal(name[:-1])}) AND table_type = 'BASE TABLE' "
            "ORDER BY creation_time DESC LIMIT 1)"
        )
    else:
        condition = f"table_name = {bigquery_literal(name)}"
    rows = self.query(
        f"SELECT column_name FROM `{dataset}`.INFORMATION_SCHEMA.COLUMNS "  # noqa: S608
        f"WHERE {condition} ORDER BY ordinal_position",
    ).fetchall()
    if not rows:
        msg = f"Table {table!r} not found in BigQuery"
        raise DatabaseError(msg)
    columns = [column for (column,) in rows]
    # INFORMATION_SCHEMA lists _PARTITIONTIME of an ingestion-time partitioned table, but not _PARTITIONDATE
    if "_PARTITIONTIME" in (column.upper() for column in columns):
        columns.append("_PARTITIONDATE")
    return [*columns, "_TABLE_SUFFIX"] if wildcard else columns

format_filter_value

format_filter_value(value: object, operator: str) -> str

Format a filter value as a BigQuery literal.

Source code in src/koality/backends/bigquery.py
def format_filter_value(self, value: object, operator: str) -> str:
    """Format a filter value as a BigQuery literal."""
    if operator in ("LIKE", "NOT LIKE") and isinstance(value, str):
        # BigQuery's LIKE treats a backslash as an escape, DuckDB's (where checks run) does not:
        # escape it so BigQuery matches the same rows as the checks
        value = value.replace("\\", "\\\\")
    return format_filter_value(value, operator, literal=bigquery_literal)

query

query(sql: str) -> DuckDBPyRelation

Run sql in BigQuery: bigquery_execute for statements that write, bigquery_query otherwise.

Source code in src/koality/backends/bigquery.py
def query(self, sql: str) -> duckdb.DuckDBPyRelation:
    """Run `sql` in BigQuery: `bigquery_execute` for statements that write, `bigquery_query` otherwise."""
    # Dollar-quote the query, with a tag that cannot occur in it (e.g. inside a filter value);
    # "$tag" rather than "$tag$" also excludes a query ending in "$tag", which would close early
    tag = "bq"
    while f"${tag}" in sql:
        tag += "_"
    accessor = sql_literal(self.database_accessor)
    if sql.strip().upper().startswith(_WRITE_STATEMENTS):
        return self.duckdb_client.query(f"CALL bigquery_execute({accessor}, ${tag}${sql}${tag}$)")
    options = "".join(f", {name} := {sql_literal(value)}" for name, value in self.query_options.items())
    return self.duckdb_client.query(f"SELECT * FROM bigquery_query({accessor}, ${tag}${sql}${tag}${options})")  # noqa: S608

table_ref

table_ref(table: str) -> str

Return table in backticks, as BigQuery resolves it.

Source code in src/koality/backends/bigquery.py
def table_ref(self, table: str) -> str:
    """Return `table` in backticks, as BigQuery resolves it."""
    return f"`{table}`"

write_results

write_results(result_table: str, rows: list[dict], identifier_column: str, now: datetime) -> str

Append rows to result_table through BigQuery, with values as escaped BigQuery literals.

Source code in src/koality/backends/bigquery.py
def write_results(self, result_table: str, rows: list[dict], identifier_column: str, now: dt.datetime) -> str:
    """Append `rows` to `result_table` through BigQuery, with values as escaped BigQuery literals."""
    columns = result_columns(
        identifier_column,
        {"date": "DATE", "text": "STRING", "float": "FLOAT64", "timestamp": "TIMESTAMP"},
    )
    column_definitions = ", ".join(f"`{name}` {type_}" for name, type_ in columns.items())
    column_list = ", ".join(f"`{name}`" for name in columns)
    values = ", ".join(
        "("
        + ", ".join(bigquery_literal(str(now) if name == "INSERT_TIMESTAMP" else row.get(name)) for name in columns)
        + ")"
        for row in rows
    )
    try:
        self.query(f"CREATE TABLE IF NOT EXISTS {result_table} ({column_definitions})")
    except duckdb.Error as e:
        msg = f"Could not create or replace table {result_table}"
        raise DatabaseError(msg) from e
    try:
        self.query(f"INSERT INTO {result_table} ({column_list}) VALUES {values}")  # noqa: S608
    except duckdb.Error as e:
        msg = f"Could not insert rows into table {result_table}"
        raise DatabaseError(msg) from e
    return f"{self.database_accessor}.{result_table}"

bigquery_literal

bigquery_literal(value: object) -> str

Return value as a BigQuery SQL literal.

Strings are single-quoted with backslash escapes (BigQuery does not accept doubled quotes), and infinite or NaN floats are cast from their string form, as BigQuery has no literal for them. For example, O'Brien becomes 'O\'Brien' and -inf becomes CAST('-Infinity' AS FLOAT64).

Source code in src/koality/backends/bigquery.py
def bigquery_literal(value: object) -> str:
    r"""Return `value` as a BigQuery SQL literal.

    Strings are single-quoted with backslash escapes (BigQuery does not accept doubled quotes), and
    infinite or NaN floats are cast from their string form, as BigQuery has no literal for them.
    For example, `O'Brien` becomes `'O\'Brien'` and `-inf` becomes `CAST('-Infinity' AS FLOAT64)`.
    """
    return literal_with(value, _bigquery_quote, "FLOAT64")