Skip to content

Utils

Utility functions for koality data quality checks.

SqlDialect

How filter conditions are written in SQL; DuckDB's by default.

Checks run in DuckDB and use these defaults. The query that fetches the data from the source uses the source's backend instead (koality.backends.Backend subclasses this), so a backend can override how filter values, date columns and date literals are written for its database.

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)

execute_query

execute_query(query: str, duckdb_client: DuckDBPyConnection, database_accessor: str | None, database_provider: DatabaseProvider | None) -> DuckDBPyRelation

Run query against the attached database database_provider (on the connection if there is none).

Delegates to the database's backend (see koality.backends), e.g. BigQuery runs it through bigquery_query / bigquery_execute.

Source code in src/koality/utils.py
def execute_query(
    query: str,
    duckdb_client: duckdb.DuckDBPyConnection,
    database_accessor: str | None,
    database_provider: DatabaseProvider | None,
) -> duckdb.DuckDBPyRelation:
    """Run `query` against the attached database `database_provider` (on the connection if there is none).

    Delegates to the database's backend (see `koality.backends`), e.g. BigQuery runs it through
    `bigquery_query` / `bigquery_execute`.
    """
    if database_provider is None:
        return duckdb_client.query(query)
    from koality.backends import backend_for  # noqa: PLC0415 - backends import this module

    return backend_for(duckdb_client, database_accessor or "", database_provider).query(query)

format_filter_value

format_filter_value(value: object, operator: str, *, literal: Callable[[object], str] = sql_literal) -> str

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

Parameters:

Name Type Description Default
value object

The filter value (can be a single value or list for IN/NOT IN).

required
operator str

The SQL operator being used.

required
literal Callable[[object], str]

Formats a single value; DuckDB's sql_literal by default (backends pass their dialect's).

sql_literal

Returns:

Type Description
str

Formatted SQL value string.

Source code in src/koality/utils.py
def format_filter_value(
    value: object,
    operator: str,
    *,
    literal: Callable[[object], str] = sql_literal,
) -> str:
    """Format a filter value as an SQL literal (or a parenthesized list for IN/NOT IN).

    Args:
        value: The filter value (can be a single value or list for IN/NOT IN).
        operator: The SQL operator being used.
        literal: Formats a single value; DuckDB's `sql_literal` by default (backends pass their dialect's).

    Returns:
        Formatted SQL value string.

    """
    if operator in ("IN", "NOT IN"):
        values = value if isinstance(value, (list, tuple, set)) else [value]
        return "(" + ", ".join(literal(v) for v in values) + ")"
    return literal(value)

format_sql

format_sql(sql: str, margin: str = '') -> str

Return sql re-indented for reading (e.g. in koality explain and verbose logs); it is not run.

koality assembles each check's SQL from fragments that are indented differently. Here every line is indented by its clause and bracket depth: a clause keyword (SELECT, FROM, WHERE, AND, JOIN, ...) at its block's level, other lines 4 spaces deeper (the AND of a BETWEEN too), the lines inside a bracket that ends a line 4 further than its opening line, and a closing bracket's line at its opening line's indent. Blank lines are dropped. Whitespace inside a string literal or quoted identifier, also one spanning lines, is kept as it is, so the values shown are those the query compares. Quotes are escaped by doubling them, or, if that leaves a literal open (e.g. BigQuery's 'O\'Brien'), by a backslash. margin prefixes every line except those continuing a literal (e.g. to indent the SQL in a block of text, which textwrap.indent would do inside the literal too).

Examples:

>>> print(format_sql("        SELECT\n            COUNT(*) AS n\n        FROM t\nWHERE\n    x = 'a  b'"))
SELECT
    COUNT(*) AS n
FROM t
WHERE
    x = 'a  b'
Source code in src/koality/utils.py
def format_sql(sql: str, margin: str = "") -> str:
    r"""Return `sql` re-indented for reading (e.g. in `koality explain` and verbose logs); it is not run.

    koality assembles each check's SQL from fragments that are indented differently. Here every line is indented by
    its clause and bracket depth: a clause keyword (`SELECT`, `FROM`, `WHERE`, `AND`, `JOIN`, ...) at its block's
    level, other lines 4 spaces deeper (the `AND` of a `BETWEEN` too), the lines inside a bracket that ends a line 4
    further than its opening line, and a closing bracket's line at its opening line's indent. Blank lines are
    dropped. Whitespace inside a string literal or quoted identifier, also one spanning lines, is kept as it is, so
    the values shown are those the query compares. Quotes are escaped by doubling them, or, if that leaves a literal
    open (e.g. BigQuery's `'O\'Brien'`), by a backslash. `margin` prefixes every line except those continuing a
    literal (e.g. to indent the SQL in a block of text, which `textwrap.indent` would do inside the literal too).

    Examples:
        >>> print(format_sql("        SELECT\n            COUNT(*) AS n\n        FROM t\nWHERE\n    x = 'a  b'"))
        SELECT
            COUNT(*) AS n
        FROM t
        WHERE
            x = 'a  b'

    """
    formatted, quote_open = _indent_sql(sql, backslash_escapes=False, margin=margin)
    if quote_open:
        formatted, _ = _indent_sql(sql, backslash_escapes=True, margin=margin)
    return formatted

identify_database_provider

identify_database_provider(duckdb_client: DuckDBPyConnection, database_accessor: str) -> DatabaseProvider

Identify the database provider type from a DuckDB database accessor.

Parameters:

Name Type Description Default
duckdb_client DuckDBPyConnection

DuckDB client connection.

required
database_accessor str

The name of the attached database.

required

Returns:

Type Description
DatabaseProvider

DatabaseProvider with type information (e.g., 'bigquery', 'postgres').

Raises:

Type Description
DatabaseError

If the database accessor is not found in DuckDB databases.

Source code in src/koality/utils.py
def identify_database_provider(
    duckdb_client: duckdb.DuckDBPyConnection,
    database_accessor: str,
) -> DatabaseProvider:
    """Identify the database provider type from a DuckDB database accessor.

    Args:
        duckdb_client: DuckDB client connection.
        database_accessor: The name of the attached database.

    Returns:
        DatabaseProvider with type information (e.g., 'bigquery', 'postgres').

    Raises:
        DatabaseError: If the database accessor is not found in DuckDB databases.

    """
    # Check if the database accessor is of type bigquery
    result = duckdb_client.query(
        f"SELECT * FROM duckdb_databases() WHERE database_name = {sql_literal(database_accessor)}",  # noqa: S608
    )
    column_names = [desc[0] for desc in result.description]
    rows = result.fetchall()
    if not rows:
        msg = f"Database accessor '{database_accessor}' not found in duckdb databases."
        raise DatabaseError(msg)
    return DatabaseProvider(**dict(zip(column_names, rows[0], strict=False)))

literal_with

literal_with(value: object, quote: Callable[[str], str], float_type: str) -> str

Return value as an SQL literal; quote turns a string into a quoted string literal.

Source code in src/koality/utils.py
def literal_with(value: object, quote: Callable[[str], str], float_type: str) -> str:
    """Return `value` as an SQL literal; `quote` turns a string into a quoted string literal."""
    if value is None:
        return "NULL"
    if isinstance(value, float) and not math.isfinite(value):
        special = "NaN" if math.isnan(value) else ("+Infinity" if value > 0 else "-Infinity")
        return f"CAST('{special}' AS {float_type})"
    if isinstance(value, bool):
        return str(value).upper()
    # Plain numbers, also for subclasses such as IntEnum or numpy.float64
    if isinstance(value, int):
        return str(int(value))
    if isinstance(value, float):
        return repr(float(value))
    return quote(str(value))

parse_date

parse_date(date: str) -> str

Parse a date string to an ISO format date.

Supports relative terms like "today", "yesterday", or "tomorrow", actual dates, or relative dates with offsets like "today-2", "yesterday+1".

Parameters:

Name Type Description Default
date str

The date string to be parsed. Supports: - "today", "yesterday", "tomorrow" - "today+N", "today-N" (e.g., "today-2" for 2 days ago) - "yesterday+N", "yesterday-N" (e.g., "yesterday-2" for 3 days ago) - "tomorrow+N", "tomorrow-N" - ISO format dates like "2023-01-15"

required
Source code in src/koality/utils.py
def parse_date(date: str) -> str:
    """Parse a date string to an ISO format date.

    Supports relative terms like "today", "yesterday", or "tomorrow",
    actual dates, or relative dates with offsets like "today-2", "yesterday+1".

    Args:
        date: The date string to be parsed. Supports:
            - "today", "yesterday", "tomorrow"
            - "today+N", "today-N" (e.g., "today-2" for 2 days ago)
            - "yesterday+N", "yesterday-N" (e.g., "yesterday-2" for 3 days ago)
            - "tomorrow+N", "tomorrow-N"
            - ISO format dates like "2023-01-15"

    """
    date = str(date).lower()

    # Handle relative dates with optional offset: today, yesterday, tomorrow with +/- N
    if regex_match := re.match(r"(today|yesterday|tomorrow)([+-]\d+)?$", date):
        base = regex_match[1]
        offset_str = regex_match[2]
        offset_days = int(offset_str) if offset_str else 0

        if base == "yesterday":
            offset_days -= 1
        elif base == "tomorrow":
            offset_days += 1

        return (dt.datetime.now(tz=dt.UTC) + dt.timedelta(days=offset_days)).date().isoformat()

    # Handle ISO format dates
    return dt.datetime.fromisoformat(date).date().isoformat()

qualify_table_name

qualify_table_name(database_accessor: str, table: str) -> str

Return a quoted reference to table inside the attached database_accessor catalog.

Each dot-separated part is quoted separately; quote a part that contains a dot, e.g. '"my.orders"'. Accepted forms:

  • "orders" -> "accessor"."orders" (catalog's default schema)
  • "sales.orders" -> "accessor"."sales"."orders"
  • "accessor.orders" -> "accessor"."orders"
  • "catalog.schema.orders" -> used as given

Without an accessor, the parts are only quoted.

Examples:

>>> qualify_table_name("warehouse", "sales.orders")
'"warehouse"."sales"."orders"'
Source code in src/koality/utils.py
def qualify_table_name(database_accessor: str, table: str) -> str:
    """Return a quoted reference to `table` inside the attached `database_accessor` catalog.

    Each dot-separated part is quoted separately; quote a part that contains a dot, e.g. '"my.orders"'.
    Accepted forms:

    - "orders" -> "accessor"."orders" (catalog's default schema)
    - "sales.orders" -> "accessor"."sales"."orders"
    - "accessor.orders" -> "accessor"."orders"
    - "catalog.schema.orders" -> used as given

    Without an accessor, the parts are only quoted.

    Examples:
        >>> qualify_table_name("warehouse", "sales.orders")
        '"warehouse"."sales"."orders"'

    """
    catalog, rest = split_catalog(database_accessor, table)
    catalog = catalog or database_accessor
    return ".".join(quote_identifier(part) for part in ([catalog] if catalog else []) + rest)

quote_identifier

quote_identifier(name: str) -> str

Quote name as a SQL identifier, escaping embedded double quotes.

Source code in src/koality/utils.py
def quote_identifier(name: str) -> str:
    """Quote `name` as a SQL identifier, escaping embedded double quotes."""
    return '"' + name.replace('"', '""') + '"'

split_catalog

split_catalog(database_accessor: str, table: str) -> tuple[str | None, list[str]]

Split table into its catalog (None if it names none) and the remaining name parts.

A two-part name counts as catalog.table only if its first part is the accessor; otherwise it is schema.table. Three or more parts always start with the catalog.

Examples:

>>> split_catalog("warehouse", "warehouse.orders")
('warehouse', ['orders'])
>>> split_catalog("warehouse", "sales.orders")
(None, ['sales', 'orders'])
Source code in src/koality/utils.py
def split_catalog(database_accessor: str, table: str) -> tuple[str | None, list[str]]:
    """Split `table` into its catalog (None if it names none) and the remaining name parts.

    A two-part name counts as `catalog.table` only if its first part is the accessor; otherwise it is
    `schema.table`. Three or more parts always start with the catalog.

    Examples:
        >>> split_catalog("warehouse", "warehouse.orders")
        ('warehouse', ['orders'])
        >>> split_catalog("warehouse", "sales.orders")
        (None, ['sales', 'orders'])

    """
    parts = split_table_name(table)
    names_accessor = bool(database_accessor) and parts[0].lower() == database_accessor.lower()
    if len(parts) >= _FULLY_QUALIFIED_PARTS or (len(parts) == _FULLY_QUALIFIED_PARTS - 1 and names_accessor):
        return parts[0], parts[1:]
    return None, parts

split_table_name

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

Split a dotted table name into its parts; double-quoted parts may contain dots.

Examples:

>>> split_table_name('sales."my.orders"')
['sales', 'my.orders']
Source code in src/koality/utils.py
def split_table_name(table: str) -> list[str]:
    """Split a dotted table name into its parts; double-quoted parts may contain dots.

    Examples:
        >>> split_table_name('sales."my.orders"')
        ['sales', 'my.orders']

    """
    parts: list[str] = []
    pos = 0
    while True:
        match = _NAME_PART.match(table, pos)
        if (
            match is None
            or (match.end() < len(table) and table[match.end()] != ".")
            or match.group(1) == ""
            or (match.group(1) is None and (not match.group(2).strip() or match.group(2).lstrip().startswith('"')))
        ):
            msg = f"Invalid table name: {table!r}"
            raise ValueError(msg)
        quoted, plain = match.group(1), match.group(2)
        parts.append(quoted.replace('""', '"') if quoted is not None else plain.strip())
        pos = match.end()
        if pos >= len(table):
            return parts
        pos += 1

sql_literal

sql_literal(value: object) -> str

Return value as a DuckDB SQL literal.

Strings are single-quoted with embedded quotes doubled; DuckDB takes backslashes literally, so they need no escaping. Infinite or NaN floats are cast from their string form.

Source code in src/koality/utils.py
def sql_literal(value: object) -> str:
    """Return `value` as a DuckDB SQL literal.

    Strings are single-quoted with embedded quotes doubled; DuckDB takes backslashes literally, so
    they need no escaping. Infinite or NaN floats are cast from their string form.
    """
    return literal_with(value, _duckdb_quote, "DOUBLE")

substitute_variables

substitute_variables(text: str, variables: dict[str, str]) -> str

Substitute ${VAR} placeholders in text with variable values.

Parameters:

Name Type Description Default
text str

The text containing ${VAR} placeholders to substitute.

required
variables dict[str, str]

Dict of variable name -> value mappings.

required

Returns:

Type Description
str

The text with all ${VAR} placeholders substituted.

Raises:

Type Description
ValueError

If a variable is referenced but not defined.

Examples:

>>> substitute_variables("project=${PROJECT_ID}", {"PROJECT_ID": "my-project"})
'project=my-project'
Source code in src/koality/utils.py
def substitute_variables(text: str, variables: dict[str, str]) -> str:
    """Substitute ${VAR} placeholders in text with variable values.

    Args:
        text: The text containing ${VAR} placeholders to substitute.
        variables: Dict of variable name -> value mappings.

    Returns:
        The text with all ${VAR} placeholders substituted.

    Raises:
        ValueError: If a variable is referenced but not defined.

    Examples:
        >>> substitute_variables("project=${PROJECT_ID}", {"PROJECT_ID": "my-project"})
        'project=my-project'

    """
    # Find all ${VAR} patterns
    pattern = re.compile(r"\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}")

    def replace(match: re.Match) -> str:
        var_name = match.group(1)
        if var_name not in variables:
            msg = (
                f"Variable '${{{var_name}}}' is not defined. "
                f"Provide it via --database_setup_variable {var_name}=<value>"
            )
            raise ValueError(msg)
        return variables[var_name]

    return pattern.sub(replace, text)

to_set

to_set(value: object) -> set[Any]

Convert the input value to a set.

The special case of one single string is also covered. Duplicates are also removed and for deterministic behavior, the values are sorted.

Convert input as follows: - 1 -> {1} - True -> {True} - "toys" / '"toys"' -> {"toys"} - ("toys") / '("toys")' -> {"toys"} - ("toys", "shirt") / '("toys", "shirt")' -> {"shirt", "toys"} - ["toys"] -> {"toys"} - {"toys"} -> {"toys"}

Source code in src/koality/utils.py
def to_set(value: object) -> set[Any]:
    """Convert the input value to a set.

    The special case of one single string is also covered. Duplicates are also
    removed and for deterministic behavior, the values are sorted.

    Convert input as follows:
    - 1 -> {1}
    - True -> {True}
    - "toys" / '"toys"' -> {"toys"}
    - ("toys") / '("toys")' -> {"toys"}
    - ("toys", "shirt") / '("toys", "shirt")' -> {"shirt", "toys"}
    - ["toys"] -> {"toys"}
    - {"toys"} -> {"toys"}

    """
    if isinstance(value, str):
        # Not a Python literal (e.g. O'Brien): use the string itself
        with contextlib.suppress(ValueError, SyntaxError):
            value = literal_eval(value)
    if not isinstance(value, Iterable) or isinstance(value, (str, bytes)):
        return {value}
    if isinstance(value, set):
        return value
    return set(value)