You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置SQLFluff对模型配置代码进行Lint检查

用SQLFluff检查dbt模型配置块的方法

一、先启用SQLFluff的dbt插件

SQLFluff对dbt config块的检查依赖官方dbt插件,按以下步骤配置:

  1. 安装插件:pip install sqlfluff-plugin-dbt
  2. 在项目根目录的sqlfluff.cfg中添加配置:
[sqlfluff]
# 替换为你的数据方言,比如postgres/bigquery/snowflake
dialect = bigquery
plugins = sqlfluff-plugin-dbt

二、用内置规则检查基础格式

dbt插件自带针对config块的内置规则,覆盖缩进、参数顺序、引号一致性等常见规范:

  • 缩进检查:通过dbt.config.indentation规则配置缩进单位和长度
  • 参数排序:通过dbt.config.ordering规则指定config参数的优先顺序
  • 引号统一:配合通用规则LT05强制引号格式一致

示例配置(添加到sqlfluff.cfg的[sqlfluff]区块下):

rules =
  dbt.config.indentation:
    indent_unit = space
    indent_size = 4
  dbt.config.ordering:
    preferred_order = ['materialized', 'schema', 'alias', 'unique_key', 'incremental_strategy']

运行检查命令:

sqlfluff lint path/to/your/model.sql

三、自定义规则检查业务规范

如果内置规则满足不了业务要求(比如检查schema是否在指定列表、materialized值是否合规),可以编写自定义规则:

  1. 在项目根目录新建sqlfluff_rules文件夹
  2. 创建规则文件(比如allowed_schemas.py),内容如下:
from sqlfluff.core.rules import BaseRule, LintResult, RuleContext
from sqlfluff.core.rules.crawlers import SegmentSeekerCrawler
from sqlfluff.plugins.dbt.segments import DbtConfigSegment

class Rule_Dbt_Allowed_Schemas(BaseRule):
    name = "dbt.config.allowed_schemas"
    description = "检查config中的schema是否属于允许的列表"
    crawler = SegmentSeekerCrawler({"dbt_config"})

    def _eval(self, context: RuleContext) -> LintResult:
        config_segment = context.segment
        for config_arg in config_segment.configs:
            if config_arg.key.raw == "schema":
                schema_value = config_arg.value.raw.strip("'\"")
                # 替换为你的允许schema列表
                allowed_schemas = {"RAW_DATA", "ANALYTICS", "STAGING"}
                if schema_value not in allowed_schemas:
                    return LintResult(
                        anchor=config_arg.value,
                        description=f"Schema '{schema_value}'不允许使用,允许的列表:{', '.join(allowed_schemas)}"
                    )
        return LintResult()
  1. 在sqlfluff.cfg中添加规则路径:
[sqlfluff]
rules_path = ./sqlfluff_rules
  1. 重新运行lint命令,即可触发自定义规则检查

内容的提问来源于stack exchange,提问作者Adriana J. Ambel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 19:56:08