|
| 1 | +import pathlib |
| 2 | +import tempfile |
| 3 | +from configparser import ConfigParser |
| 4 | +from typing import List |
| 5 | + |
| 6 | +import click |
| 7 | +import yaml |
| 8 | + |
| 9 | +from ..cli_constants import BUILD_DIR |
| 10 | +from ..cli_utils import echo_info, echo_subinfo, echo_warning, subprocess_run |
| 11 | +from ..config_generation import ( |
| 12 | + generate_profiles_yml, |
| 13 | + read_dictionary_from_config_directory, |
| 14 | +) |
| 15 | +from ..errors import SQLLintError, SubprocessNonZeroExitError |
| 16 | + |
| 17 | +SQLFLUFF_FIX_NOT_EVERYTHING_ERROR = 1 |
| 18 | +SQLFLUFF_LINT_ERROR = 65 # according to `sqlfluff.core.linter.LintingResult.stats` |
| 19 | +SQLFLUFF_DIALECT_LOADING_ERROR = 66 # according to `sqlfluff.cli.commands.get_config` |
| 20 | + |
| 21 | + |
| 22 | +def _get_dialect_or_default() -> str: |
| 23 | + """Read ``dbt.yml`` config file and return its ``target_type`` or just the ``ansi``.""" |
| 24 | + env, dbt_filename = "base", "dbt.yml" |
| 25 | + dbt_env_config = read_dictionary_from_config_directory( |
| 26 | + BUILD_DIR.joinpath("dag"), env, dbt_filename |
| 27 | + ) or read_dictionary_from_config_directory(pathlib.Path.cwd(), env, dbt_filename) |
| 28 | + try: |
| 29 | + dialect = dbt_env_config["target_type"] |
| 30 | + echo_subinfo(f'Found target_type "{dialect}", attempting to use it as the SQL dialect.') |
| 31 | + except KeyError: |
| 32 | + dialect = "ansi" |
| 33 | + echo_warning( |
| 34 | + 'Could not find `target_type` in `dbt.yml`. Using the default SQL dialect ("ansi").' |
| 35 | + ) |
| 36 | + return dialect |
| 37 | + |
| 38 | + |
| 39 | +def _get_source_tests_paths() -> List[pathlib.Path]: |
| 40 | + with open(pathlib.Path.cwd().joinpath("dbt_project.yml"), "r") as f: |
| 41 | + dbt_project_config = yaml.safe_load(f) |
| 42 | + dir_names: List[str] = ( |
| 43 | + dbt_project_config.get("source-paths", []) |
| 44 | + + dbt_project_config.get("model-paths", []) |
| 45 | + + dbt_project_config.get("test-paths", []) |
| 46 | + ) |
| 47 | + return list(map(lambda dir_name: pathlib.Path.cwd().joinpath(dir_name), dir_names)) |
| 48 | + |
| 49 | + |
| 50 | +def _create_temporary_sqlfluff_config(env: str) -> ConfigParser: |
| 51 | + config = ConfigParser() |
| 52 | + config["sqlfluff"] = {"templater": "dbt"} |
| 53 | + config["sqlfluff:templater:dbt"] = { |
| 54 | + "profiles_dir": str(generate_profiles_yml(env, copy_config_dir=True).absolute()) |
| 55 | + } |
| 56 | + return config |
| 57 | + |
| 58 | + |
| 59 | +def _run_sqlfluff(command: str, dialect: str, env: str, additional_args: List[str]) -> None: |
| 60 | + with tempfile.TemporaryDirectory() as tmp_dir: |
| 61 | + tmp_config_path = pathlib.Path(tmp_dir).joinpath("sqlfluff.config") |
| 62 | + with open(tmp_config_path, "w") as tmp_config: |
| 63 | + _create_temporary_sqlfluff_config(env).write(tmp_config) |
| 64 | + |
| 65 | + def sqlfluff_args(sql_dialect: str) -> List[str]: |
| 66 | + return [ |
| 67 | + "sqlfluff", |
| 68 | + command, |
| 69 | + "--dialect", |
| 70 | + sql_dialect, |
| 71 | + "--config", |
| 72 | + str(tmp_config_path), |
| 73 | + *additional_args, |
| 74 | + *map(str, _get_source_tests_paths()), |
| 75 | + ] |
| 76 | + |
| 77 | + try: |
| 78 | + subprocess_run(sqlfluff_args(dialect)) |
| 79 | + except SubprocessNonZeroExitError as err: |
| 80 | + if err.exit_code == SQLFLUFF_DIALECT_LOADING_ERROR and dialect != "ansi": |
| 81 | + subprocess_run(sqlfluff_args("ansi")) |
| 82 | + else: |
| 83 | + raise err |
| 84 | + |
| 85 | + |
| 86 | +def _run_fix_sqlfluff(dialect: str, env: str) -> None: |
| 87 | + try: |
| 88 | + echo_subinfo("Attempting to fix SQLs. Not every error can be automatically fixed.") |
| 89 | + _run_sqlfluff("fix", dialect, env, ["--force"]) |
| 90 | + except SubprocessNonZeroExitError as err: |
| 91 | + if err.exit_code != SQLFLUFF_FIX_NOT_EVERYTHING_ERROR: |
| 92 | + raise err |
| 93 | + |
| 94 | + |
| 95 | +def _run_lint_sqlfluff(dialect: str, env: str) -> None: |
| 96 | + try: |
| 97 | + echo_subinfo("Linting SQLs.") |
| 98 | + _run_sqlfluff("lint", dialect, env, []) |
| 99 | + except SubprocessNonZeroExitError as err: |
| 100 | + if err.exit_code == SQLFLUFF_LINT_ERROR: |
| 101 | + raise SQLLintError |
| 102 | + else: |
| 103 | + raise err |
| 104 | + |
| 105 | + |
| 106 | +def lint(fix: bool, env: str) -> None: |
| 107 | + """ |
| 108 | + Lint and format SQL. |
| 109 | +
|
| 110 | + :param fix: Whether to lint and fix linting errors, or just lint. |
| 111 | + :type fix: bool |
| 112 | + :param env: Name of the environment |
| 113 | + :type env: str |
| 114 | + """ |
| 115 | + echo_info("Linting SQLs:") |
| 116 | + dialect = _get_dialect_or_default() |
| 117 | + if fix: |
| 118 | + _run_fix_sqlfluff(dialect, env) |
| 119 | + _run_lint_sqlfluff(dialect, env) |
| 120 | + |
| 121 | + |
| 122 | +@click.command( |
| 123 | + name="lint", |
| 124 | + short_help="Lint and format SQL", |
| 125 | + help="Lint and format SQL using SQLFluff.\n\n" |
| 126 | + "For more information on rules and the workings of SQLFluff, " |
| 127 | + "refer to https://docs.sqlfluff.com/", |
| 128 | +) |
| 129 | +@click.option( |
| 130 | + "--no-fix", |
| 131 | + is_flag=True, |
| 132 | + default=False, |
| 133 | + type=bool, |
| 134 | + help="Whether to lint and fix linting errors, or just lint.", |
| 135 | +) |
| 136 | +@click.option( |
| 137 | + "--env", |
| 138 | + default="local", |
| 139 | + type=str, |
| 140 | + show_default=True, |
| 141 | + help="Name of the environment", |
| 142 | +) |
| 143 | +def lint_command(no_fix: bool, env: str) -> None: |
| 144 | + lint(not no_fix, env) |
0 commit comments