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.
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
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
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted SQL value string. |
Source code in src/koality/utils.py
format_sql ¶
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
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
literal_with ¶
Return value as an SQL literal; quote turns a string into a quoted string literal.
Source code in src/koality/utils.py
parse_date ¶
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
qualify_table_name ¶
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:
Source code in src/koality/utils.py
quote_identifier ¶
split_catalog ¶
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
split_table_name ¶
Split a dotted table name into its parts; double-quoted parts may contain dots.
Examples:
Source code in src/koality/utils.py
sql_literal ¶
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
substitute_variables ¶
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
to_set ¶
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"}