Skip to content

CLI

Command-line interface for Koality.

This module provides the CLI for running, validating, and inspecting Koality data quality check configurations.

Example
$ koality run --config_path checks.yaml
$ koality validate --config_path checks.yaml
$ koality explain --config_path checks.yaml
$ koality setup --config_path checks.yaml
$ koality print --config_path checks.yaml --format json
Commands
  • run: Execute data quality checks from a configuration file.
  • validate: Validate a configuration file without executing checks (--connect: check tables and columns).
  • explain: Show the resolved checks, their filters and thresholds, and the SQL a run executes.
  • setup: Install the DuckDB extensions a configuration declares, without executing checks.
  • print: Print the resolved configuration in various formats.

RunError

Bases: ClickException

A configuration, connection or execution error of a koality command; exits with 2.

cli

cli() -> None

Koality - Data quality monitoring CLI.

Koality provides commands to run, validate, and inspect data quality check configurations. Use --help on any command for more details.

Source code in src/koality/cli.py
@click.group(cls=_Group)
def cli() -> None:
    """Koality - Data quality monitoring CLI.

    Koality provides commands to run, validate, and inspect data quality
    check configurations. Use --help on any command for more details.
    """

explain

explain(config_path: Path, overwrites: tuple[str, ...], database_setup_variable: tuple[str, ...], bundles: tuple[str, ...], check_types: tuple[str, ...], output_format: str, connect_database: bool) -> None

Show what koality run would do, without reading data.

For each check: its bundle, type and name, the tables it reads, its thresholds, its filters after defaults and overwrites (-o), the query that checks its data exists, and the query that computes its result. With a database_accessor, a run first fetches each source table's rows into an in-memory staging catalog, once for all checks, and the checks read them there; those fetch queries follow the checks.

Without --connect, no database is contacted, and the SQL is written for DuckDB; a source with its own backend (e.g. BigQuery) gets its own SQL in a run. With --connect, database_setup runs (as for koality run), the SQL is written by the attached database's backend, and each fetch query (or, without a database_accessor, each check's query) gets DuckDB's plan where DuckDB reads the source itself (not for e.g. BigQuery, which would receive the query).

Exit codes:

0: The configuration was explained.

2: The configuration is invalid, a variable is undefined, a bundle doesn't exist, or (with --connect)
database_setup fails or a query can't be planned (the explanation is still printed, with the error).

130: Interrupted.

Usage examples:

koality explain --config_path checks.yaml

koality explain --config_path checks.yaml --bundle orders --check-type NullRatioCheck

koality explain --config_path checks.yaml -o partition_date=2023-01-01 --format json

koality explain --config_path checks.yaml --connect -dsv PROJECT_ID=my-gcp-project
Source code in src/koality/cli.py
@cli.command()
@click.option(
    "--config_path",
    required=True,
    type=click.Path(exists=True, dir_okay=False),
    help="Path to the YAML configuration file.",
)
@click.option(
    "--overwrites",
    "-o",
    multiple=True,
    help="Override filter values in defaults, as for `koality run`. Format: filter_name=value. "
    "Can be used multiple times. Example: -o partition_date=2023-01-01 -o shop_id=SHOP02",
)
@click.option(
    "--database_setup_variable",
    "-dsv",
    multiple=True,
    help="Set variables for database_setup substitution, as for `koality run`. Format: VAR_NAME=value. "
    "Can be used multiple times. Also reads from DATABASE_SETUP_VARIABLES env var "
    "(format: VAR1=value1,VAR2=value2). CLI options override env vars.",
)
@click.option(
    "--bundle",
    "bundles",
    multiple=True,
    help="Only explain the checks of this bundle. Can be used multiple times.",
)
@click.option(
    "--check-type",
    "check_types",
    multiple=True,
    type=click.Choice(sorted(CHECK_MAP)),
    help="Only explain checks of this type. Can be used multiple times.",
)
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    help="Output format: 'text' (default) or 'json'.",
)
@click.option(
    "--connect",
    "connect_database",
    is_flag=True,
    default=False,
    help="Also run database_setup, write the SQL for the attached database's backend, and add DuckDB's plan "
    "(EXPLAIN, which doesn't run the query) of each fetch query (or, without a database_accessor, each check's query).",
)
def explain(  # noqa: C901, PLR0912
    config_path: Path,
    overwrites: tuple[str, ...],
    database_setup_variable: tuple[str, ...],
    bundles: tuple[str, ...],
    check_types: tuple[str, ...],
    output_format: str,
    connect_database: bool,  # noqa: FBT001
) -> None:
    """Show what `koality run` would do, without reading data.

    For each check: its bundle, type and name, the tables it reads, its thresholds, its filters after defaults
    and overwrites (-o), the query that checks its data exists, and the query that computes its result. With a
    database_accessor, a run first fetches each source table's rows into an in-memory staging catalog, once for
    all checks, and the checks read them there; those fetch queries follow the checks.

    Without --connect, no database is contacted, and the SQL is written for DuckDB; a source with its own
    backend (e.g. BigQuery) gets its own SQL in a run. With --connect, database_setup runs (as for `koality run`),
    the SQL is written by the attached database's backend, and each fetch query (or, without a database_accessor,
    each check's query) gets DuckDB's plan where DuckDB reads the source itself (not for e.g. BigQuery, which would
    receive the query).

    Exit codes:

        0: The configuration was explained.

        2: The configuration is invalid, a variable is undefined, a bundle doesn't exist, or (with --connect)
        database_setup fails or a query can't be planned (the explanation is still printed, with the error).

        130: Interrupted.

    Usage examples:

        koality explain --config_path checks.yaml

        koality explain --config_path checks.yaml --bundle orders --check-type NullRatioCheck

        koality explain --config_path checks.yaml -o partition_date=2023-01-01 --format json

        koality explain --config_path checks.yaml --connect -dsv PROJECT_ID=my-gcp-project

    """
    variables: dict[str, str] = {}
    executor = None
    try:
        variables = _get_variables_with_env(database_setup_variable)
        config = _load_config_with_overwrites(config_path, overwrites, variables)
        # Before database_setup runs, so a mistyped --bundle doesn't wait for (or change) the database
        check_bundle_names(config, bundles)
        if connect_database:
            executor = CheckExecutor(config=config)
        explanation = explain_config(config, executor, bundles=bundles, check_types=check_types)
    except click.UsageError:
        raise
    except click.ClickException as e:
        raise RunError(_mask_variables(e.format_message(), variables)) from e
    except (ValidationError, yaml.YAMLError) as e:
        msg = f"Configuration '{config_path}' is invalid:\n{e}"
        raise RunError(msg) from e
    except (OSError, UnicodeDecodeError) as e:
        msg = f"Configuration '{config_path}' could not be read: {e}"
        raise RunError(msg) from e
    except duckdb.InterruptException:
        _exit_interrupted()
    except (KoalityError, ValueError, duckdb.Error) as e:
        cause = f": {e.__cause__}" if isinstance(e, DatabaseError) and e.__cause__ else ""
        msg = f"Could not explain '{config_path}': {e}{cause}"
        raise RunError(_mask_variables(msg, variables)) from e
    except KeyboardInterrupt:
        _exit_interrupted()
    except Exception as e:
        # DuckDB turns SIGINT during a query into RuntimeError("Query interrupted") instead of KeyboardInterrupt
        if isinstance(e, RuntimeError) and str(e) == "Query interrupted":
            _exit_interrupted()
        # Keep the traceback, but exit with 2 like `koality run` instead of Click's 1
        click.echo(_mask_variables(traceback.format_exc(), variables), err=True)
        raise SystemExit(EXIT_ERROR) from e
    finally:
        if executor is not None:
            executor.duckdb_client.close()
    # Plans and plan errors may repeat what database_setup attached, so variable values are masked in them as in
    # error messages; masking the whole output would also hide the config's own text and could break the JSON
    for entry in [*explanation["checks"], *explanation["fetch_queries"]]:
        for key in ("plan", "plan_error"):
            if entry.get(key):
                entry[key] = _mask_variables(entry[key], variables)
    click.echo(to_json(explanation) if output_format == "json" else to_text(explanation))
    if failed := failed_plans(explanation):
        msg = (
            f"{failed} quer{'y' if failed == 1 else 'ies'} of '{config_path}' could not be planned (see 'Plan failed')"
        )
        raise RunError(_mask_variables(msg, variables))

print_config

print_config(config_path: Path, output_format: str, indent: int, overwrites: tuple[str, ...], database_setup_variable: tuple[str, ...], show_secrets: bool) -> None

Print the resolved koality configuration.

Displays the fully resolved configuration after default propagation. This shows the effective configuration that would be used during execution. Filter values can be overridden using --overwrites (-o) options. Overwrites are applied to defaults before validation, so they propagate to all checks automatically.

Database setup variables can be provided using --database_setup_variable (-dsv) or the DATABASE_SETUP_VARIABLES environment variable (comma-separated VAR=value pairs). They must all be defined, but database_setup is printed as written, with its ${VAR_NAME} placeholders, unless --show-secrets is given.

Output formats:

model: Pydantic model representation (Python repr).

yaml: YAML formatted output (default).

json: JSON formatted output.

Exit codes:

0: The configuration was printed.

2: The configuration is invalid or can't be read, or a variable is undefined.

Usage examples:

koality print --config_path checks.yaml

koality print --config_path checks.yaml --format json

koality print --config_path checks.yaml --format yaml --indent 4

koality print --config_path checks.yaml -o partition_date=2023-01-01

koality print --config_path checks.yaml -dsv PROJECT_ID=my-gcp-project --show-secrets

DATABASE_SETUP_VARIABLES="PROJECT_ID=my-project" koality print --config_path checks.yaml
Source code in src/koality/cli.py
@cli.command(name="print")
@click.option(
    "--config_path",
    required=True,
    type=click.Path(exists=True, dir_okay=False),
    help="Path to the YAML configuration file.",
)
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["model", "yaml", "json"]),
    default="yaml",
    help="Output format: 'model' (Pydantic repr), 'yaml', or 'json'.",
)
@click.option(
    "--indent",
    default=2,
    type=int,
    help="Indentation level for yaml/json output.",
)
@click.option(
    "--overwrites",
    "-o",
    multiple=True,
    help="Override filter values in defaults. Format: filter_name=value. "
    "Overwrites propagate to all checks. Can be used multiple times. "
    "Example: -o partition_date=2023-01-01 -o shop_id=SHOP02",
)
@click.option(
    "--database_setup_variable",
    "-dsv",
    multiple=True,
    help="Set variables for database_setup substitution. Format: VAR_NAME=value. "
    "Variables are substituted in database_setup using ${VAR_NAME} syntax. "
    "Can be used multiple times. Also reads from DATABASE_SETUP_VARIABLES env var "
    "(format: VAR1=value1,VAR2=value2). CLI options override env vars. "
    "Example: -dsv PROJECT_ID=my-gcp-project",
)
@click.option(
    "--show-secrets",
    is_flag=True,
    default=False,
    help="Print database_setup with variables substituted. By default it is printed as written, "
    "with ${VAR_NAME} placeholders, so values passed as variables (e.g. tokens) don't end up in logs.",
)
def print_config(
    config_path: Path,
    output_format: str,
    indent: int,
    overwrites: tuple[str, ...],
    database_setup_variable: tuple[str, ...],
    show_secrets: bool,  # noqa: FBT001
) -> None:
    """Print the resolved koality configuration.

    Displays the fully resolved configuration after default propagation.
    This shows the effective configuration that would be used during execution.
    Filter values can be overridden using --overwrites (-o) options.
    Overwrites are applied to defaults before validation, so they
    propagate to all checks automatically.

    Database setup variables can be provided using --database_setup_variable (-dsv)
    or the DATABASE_SETUP_VARIABLES environment variable (comma-separated VAR=value
    pairs). They must all be defined, but database_setup is printed as written, with
    its ${VAR_NAME} placeholders, unless --show-secrets is given.

    Output formats:

        model: Pydantic model representation (Python repr).

        yaml: YAML formatted output (default).

        json: JSON formatted output.

    Exit codes:

        0: The configuration was printed.

        2: The configuration is invalid or can't be read, or a variable is undefined.

    Usage examples:

        koality print --config_path checks.yaml

        koality print --config_path checks.yaml --format json

        koality print --config_path checks.yaml --format yaml --indent 4

        koality print --config_path checks.yaml -o partition_date=2023-01-01

        koality print --config_path checks.yaml -dsv PROJECT_ID=my-gcp-project --show-secrets

        DATABASE_SETUP_VARIABLES="PROJECT_ID=my-project" koality print --config_path checks.yaml

    """
    variables: dict[str, str] = {}
    # Reported as the other commands report them: a message, no traceback, and exit code 2
    try:
        variables = _get_variables_with_env(database_setup_variable)
        config = _load_config_with_overwrites(config_path, overwrites, variables, substitute=show_secrets)
    except click.UsageError:
        raise
    except click.ClickException as e:
        raise RunError(_mask_variables(e.format_message(), variables)) from e
    except (ValidationError, yaml.YAMLError) as e:
        msg = f"Configuration '{config_path}' is invalid:\n{e}"
        raise RunError(msg) from e
    except (OSError, UnicodeDecodeError) as e:
        msg = f"Configuration '{config_path}' could not be read: {e}"
        raise RunError(msg) from e
    except ValueError as e:
        # e.g. a YAML date that doesn't exist (2023-02-30)
        msg = f"Configuration '{config_path}' is invalid: {e}"
        raise RunError(msg) from e
    except Exception as e:
        # Keep the traceback, but exit with 2 like the other commands instead of Click's 1
        click.echo(_mask_variables(traceback.format_exc(), variables), err=True)
        raise SystemExit(EXIT_ERROR) from e

    if output_format == "model":
        click.echo(config)
    elif output_format == "json":
        click.echo(config.model_dump_json(indent=indent))
    else:  # yaml
        click.echo(_dump_yaml(config.model_dump(), indent=indent))

run

run(config_path: Path, overwrites: tuple[str, ...], database_setup_variable: tuple[str, ...], verbose: bool | None, exit_zero: bool) -> None

Run koality checks from a configuration file.

Executes all data quality checks defined in the configuration file. Filter values can be overridden using --overwrites (-o) options. Overwrites are applied to defaults before validation, so they propagate to all checks automatically.

Database setup variables can be provided using --database_setup_variable (-dsv) to substitute ${VAR_NAME} placeholders in the database_setup SQL. Variables can also be set via the DATABASE_SETUP_VARIABLES environment variable using comma-separated VAR=value pairs.

Usage examples:

koality run --config_path checks.yaml

koality run --config_path checks.yaml -o partition_date=2023-01-01

koality run --config_path checks.yaml -dsv PROJECT_ID=my-gcp-project

koality run --config_path checks.yaml -dsv PROJECT_ID=prod -dsv DATASET=analytics

DATABASE_SETUP_VARIABLES="PROJECT_ID=my-project,DATASET=prod" koality run --config_path checks.yaml

Exit codes:

0: All checks passed (monitor-only checks don't fail because of their thresholds).

1: At least one check failed, or its data is missing.

2: At least one check errored, the configuration or database setup is invalid, or a table is missing.

130: The run was interrupted.
Source code in src/koality/cli.py
@cli.command()
@click.option(
    "--config_path",
    required=True,
    type=click.Path(exists=True, dir_okay=False),
    help="Path to the YAML configuration file.",
)
@click.option(
    "--overwrites",
    "-o",
    multiple=True,
    help="Override filter values in defaults. Format: filter_name=value. "
    "Overwrites propagate to all checks. Can be used multiple times. "
    "Example: -o partition_date=2023-01-01 -o shop_id=SHOP02",
)
@click.option(
    "--database_setup_variable",
    "-dsv",
    multiple=True,
    help="Set variables for database_setup substitution. Format: VAR_NAME=value. "
    "Variables are substituted in database_setup using ${VAR_NAME} syntax. "
    "Can be used multiple times. Also reads from DATABASE_SETUP_VARIABLES env var "
    "(format: VAR1=value1,VAR2=value2). CLI options override env vars. "
    "Example: -dsv PROJECT_ID=my-gcp-project",
)
@click.option(
    "--verbose",
    "-v",
    is_flag=True,
    default=None,
    help="Enable verbose output, printing each check's SQL query before execution.",
)
@click.option(
    "--exit-zero",
    is_flag=True,
    default=False,
    help="Exit with code 0 even if checks fail or error. Configuration, database setup and data loading errors "
    "still exit with 2.",
)
def run(
    config_path: Path,
    overwrites: tuple[str, ...],
    database_setup_variable: tuple[str, ...],
    verbose: bool | None,  # noqa: FBT001
    exit_zero: bool,  # noqa: FBT001
) -> None:
    """Run koality checks from a configuration file.

    Executes all data quality checks defined in the configuration file.
    Filter values can be overridden using --overwrites (-o) options.
    Overwrites are applied to defaults before validation, so they
    propagate to all checks automatically.

    Database setup variables can be provided using --database_setup_variable (-dsv)
    to substitute ${VAR_NAME} placeholders in the database_setup SQL. Variables
    can also be set via the DATABASE_SETUP_VARIABLES environment variable using
    comma-separated VAR=value pairs.

    Usage examples:

        koality run --config_path checks.yaml

        koality run --config_path checks.yaml -o partition_date=2023-01-01

        koality run --config_path checks.yaml -dsv PROJECT_ID=my-gcp-project

        koality run --config_path checks.yaml -dsv PROJECT_ID=prod -dsv DATASET=analytics

        DATABASE_SETUP_VARIABLES="PROJECT_ID=my-project,DATASET=prod" koality run --config_path checks.yaml

    Exit codes:

        0: All checks passed (monitor-only checks don't fail because of their thresholds).

        1: At least one check failed, or its data is missing.

        2: At least one check errored, the configuration or database setup is invalid, or a table is missing.

        130: The run was interrupted.

    """
    # Error messages may repeat database_setup (e.g. a DuckDB syntax error), so variable values are masked
    variables: dict[str, str] = {}
    try:
        variables = _get_variables_with_env(database_setup_variable)
        config = _load_config_with_overwrites(config_path, overwrites, variables)
        check_executor = CheckExecutor(config=config, verbose=verbose)
        check_executor()
    except click.UsageError:
        raise
    except click.ClickException as e:
        raise RunError(_mask_variables(e.format_message(), variables)) from e
    except (ValidationError, yaml.YAMLError, KoalityError, duckdb.Error) as e:
        # ExtensionError's message already repeats its cause
        cause = (
            f": {e.__cause__}"
            if isinstance(e, KoalityError) and e.__cause__ and not isinstance(e, ExtensionError)
            else ""
        )
        raise RunError(_mask_variables(f"{e}{cause}", variables)) from e
    except Exception as e:
        # DuckDB turns SIGINT during a query into RuntimeError("Query interrupted") instead of KeyboardInterrupt
        if isinstance(e, RuntimeError) and str(e) == "Query interrupted":
            _exit_interrupted()
        # Keep the traceback, but don't exit with 1, which means "checks failed"
        click.echo(_mask_variables(traceback.format_exc(), variables), err=True)
        raise SystemExit(EXIT_ERROR) from e
    except KeyboardInterrupt:
        _exit_interrupted()

    exit_code = _exit_code(check_executor)
    if exit_code != EXIT_OK and not exit_zero:
        raise SystemExit(exit_code)

setup

setup(config_path: Path, force: bool) -> None

Install the DuckDB extensions a configuration declares, without running checks.

Installs each extension in extensions that isn't installed yet into extension_directory (DuckDB's default if not set), and loads it to check that it works with this DuckDB version. Run it while building a Docker image or in a cached CI step: koality run then loads the extensions without network access.

Exit codes:

0: All extensions are installed and load.

2: The configuration is invalid, or an extension could not be installed or loaded.

Usage examples:

koality setup --config_path checks.yaml

koality setup --config_path checks.yaml --force
Source code in src/koality/cli.py
@cli.command()
@click.option(
    "--config_path",
    required=True,
    type=click.Path(exists=True, dir_okay=False),
    help="Path to the YAML configuration file.",
)
@click.option(
    "--force",
    is_flag=True,
    default=False,
    help="Reinstall extensions that are already installed, e.g. one installed for another DuckDB version.",
)
def setup(config_path: Path, force: bool) -> None:  # noqa: FBT001
    """Install the DuckDB extensions a configuration declares, without running checks.

    Installs each extension in `extensions` that isn't installed yet into `extension_directory` (DuckDB's
    default if not set), and loads it to check that it works with this DuckDB version. Run it while building
    a Docker image or in a cached CI step: `koality run` then loads the extensions without network access.

    Exit codes:

        0: All extensions are installed and load.

        2: The configuration is invalid, or an extension could not be installed or loaded.

    Usage examples:

        koality setup --config_path checks.yaml

        koality setup --config_path checks.yaml --force

    """
    try:
        config_dict = load_yaml(Path(config_path).read_text()) or {}
        config = Config.model_validate(config_dict)
    except (ValidationError, yaml.YAMLError) as e:
        msg = f"Configuration '{config_path}' is invalid:\n{e}"
        raise RunError(msg) from e
    except (OSError, UnicodeDecodeError) as e:
        msg = f"Configuration '{config_path}' could not be read: {e}"
        raise RunError(msg) from e
    except ValueError as e:
        # e.g. a date that doesn't exist (2023-02-30), which the YAML reader raises as it builds the value
        msg = f"Configuration '{config_path}' is invalid: {e}"
        raise RunError(msg) from e
    if not config.extensions:
        click.echo(f"Configuration '{config_path}' declares no extensions.")
        return
    try:
        duckdb_client = connect(config.extension_directory)
        try:
            statuses = load_extensions(
                duckdb_client,
                config.extensions,
                force_install=force,
                install_hint=SETUP_INSTALL_HINT,
            )
        finally:
            duckdb_client.close()
    except (ExtensionError, duckdb.Error) as e:
        raise RunError(str(e)) from e
    except RuntimeError as e:
        # DuckDB turns SIGINT during a query into RuntimeError("Query interrupted") instead of KeyboardInterrupt
        if str(e) == "Query interrupted":
            _exit_interrupted()
        raise
    except KeyboardInterrupt:
        _exit_interrupted()
    for status in statuses:
        source = f" from {status.extension.repository}" if status.extension.repository else ""
        action = f"Installed{source}" if status.installed else "Already installed"
        click.echo(f"{status.extension.name}: {action}, loads with DuckDB {duckdb.__version__}")

validate

validate(config_path: Path, overwrites: tuple[str, ...], database_setup_variable: tuple[str, ...], connect_database: bool) -> None

Validate a koality configuration file without executing checks.

The configuration is loaded as koality run loads it: overwrites (-o) are applied before validation, and every ${VAR_NAME} in database_setup must be defined through -dsv or the DATABASE_SETUP_VARIABLES environment variable.

With --connect, database_setup runs (as for koality run, including extensions), and each table the checks read is looked up in the database, with each check, filter, join and date column. All missing tables and columns are reported at once, naming the bundle, the check (its index in the bundle) and the column. No data is read.

Exit codes:

0: Configuration is valid (and, with --connect, its tables and columns exist).

2: Configuration is invalid, a variable is undefined, or (with --connect) database_setup fails or a table
or column is missing.

130: Validation was interrupted.

Usage examples:

koality validate --config_path checks.yaml

koality validate --config_path checks.yaml -o partition_date=2023-01-01

koality validate --config_path checks.yaml --connect -dsv PROJECT_ID=my-gcp-project
Source code in src/koality/cli.py
@cli.command()
@click.option(
    "--config_path",
    required=True,
    type=click.Path(exists=True, dir_okay=False),
    help="Path to the YAML configuration file.",
)
@click.option(
    "--overwrites",
    "-o",
    multiple=True,
    help="Override filter values in defaults, as for `koality run`. Format: filter_name=value. "
    "Can be used multiple times. Example: -o partition_date=2023-01-01 -o shop_id=SHOP02",
)
@click.option(
    "--database_setup_variable",
    "-dsv",
    multiple=True,
    help="Set variables for database_setup substitution, as for `koality run`. Format: VAR_NAME=value. "
    "Can be used multiple times. Also reads from DATABASE_SETUP_VARIABLES env var "
    "(format: VAR1=value1,VAR2=value2). CLI options override env vars.",
)
@click.option(
    "--connect",
    "connect_database",
    is_flag=True,
    default=False,
    help="Also run database_setup and check that every table and column the checks read exists.",
)
def validate(  # noqa: C901, PLR0912
    config_path: Path,
    overwrites: tuple[str, ...],
    database_setup_variable: tuple[str, ...],
    connect_database: bool,  # noqa: FBT001
) -> None:
    """Validate a koality configuration file without executing checks.

    The configuration is loaded as `koality run` loads it: overwrites (-o) are applied before validation, and
    every ${VAR_NAME} in database_setup must be defined through -dsv or the DATABASE_SETUP_VARIABLES
    environment variable.

    With --connect, database_setup runs (as for `koality run`, including `extensions`), and each table the
    checks read is looked up in the database, with each check, filter, join and date column. All missing tables
    and columns are reported at once, naming the bundle, the check (its index in the bundle) and the column.
    No data is read.

    Exit codes:

        0: Configuration is valid (and, with --connect, its tables and columns exist).

        2: Configuration is invalid, a variable is undefined, or (with --connect) database_setup fails or a table
        or column is missing.

        130: Validation was interrupted.

    Usage examples:

        koality validate --config_path checks.yaml

        koality validate --config_path checks.yaml -o partition_date=2023-01-01

        koality validate --config_path checks.yaml --connect -dsv PROJECT_ID=my-gcp-project

    """
    variables: dict[str, str] = {}
    try:
        variables = _get_variables_with_env(database_setup_variable)
        config = _load_config_with_overwrites(config_path, overwrites, variables)
        # Settings that don't work together (or values such as an unparsable date) are only found when the
        # checks are created, and result_table when the executor is
        create_checks(config)
        if config.defaults.result_table is not None:
            validate_table_name(config.defaults.result_table, "result_table")
    except click.UsageError:
        raise
    except click.ClickException as e:
        raise RunError(_mask_variables(e.format_message(), variables)) from e
    except (ValidationError, yaml.YAMLError) as e:
        msg = f"Configuration '{config_path}' is invalid:\n{e}"
        raise RunError(msg) from e
    except (OSError, UnicodeDecodeError) as e:
        msg = f"Configuration '{config_path}' could not be read: {e}"
        raise RunError(msg) from e
    except (KoalityError, ValueError) as e:
        msg = f"Configuration '{config_path}' is invalid: {e}"
        raise RunError(msg) from e
    except KeyboardInterrupt:
        _exit_interrupted()
    except Exception as e:
        # Keep the traceback, but exit with 2 like `koality run` instead of Click's 1
        click.echo(_mask_variables(traceback.format_exc(), variables), err=True)
        raise SystemExit(EXIT_ERROR) from e
    if not connect_database:
        click.echo(f"Configuration '{config_path}' is valid.")
        return

    try:
        problems = _find_missing_columns(config)
    except (KoalityError, duckdb.Error) as e:
        cause = f": {e.__cause__}" if isinstance(e, DatabaseError) and e.__cause__ else ""
        msg = f"Could not check the tables and columns of '{config_path}': {e}{cause}"
        raise RunError(_mask_variables(msg, variables)) from e
    except KeyboardInterrupt:
        _exit_interrupted()
    except Exception as e:
        # DuckDB turns SIGINT during a query into RuntimeError("Query interrupted") instead of KeyboardInterrupt
        if isinstance(e, RuntimeError) and str(e) == "Query interrupted":
            _exit_interrupted()
        # Keep the traceback, but exit with 2 like `koality run` instead of Click's 1
        click.echo(_mask_variables(traceback.format_exc(), variables), err=True)
        raise SystemExit(EXIT_ERROR) from e
    if problems:
        listed = "\n".join(f"- {problem}" for problem in problems)
        msg = f"Configuration '{config_path}' reads tables or columns that don't exist or can't be read:\n{listed}"
        raise RunError(_mask_variables(msg, variables))
    click.echo(f"Configuration '{config_path}' is valid, and all its tables and columns exist.")