如何配置SQLFluff规则禁止关键字间使用空行?
配置SQLFluff禁止SQL关键字间空行的实现方法
需求说明
需要禁止SQL关键字(如SELECT、FROM、JOIN)与后续/前置代码之间出现空行,示例如下:
不符合规范的代码(应触发报错)
SELECT * FROM source LEFT JOIN another_source
符合规范的代码
SELECT * FROM source LEFT JOIN another_source
实现方法
方法一:调整现有规则配置(快速实现)
SQLFluff内置了blank_lines相关规则,可通过配置限制关键字前后的空行数。在项目根目录的.sqlfluff文件中添加以下配置:
[sqlfluff:rules:blank_lines.before_keywords] # 指定需要检查的关键字 keywords = SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY # 允许的最大空行数,设为0则禁止空行 max_blank_lines = 0 [sqlfluff:rules:blank_lines.after_keywords] keywords = SELECT, FROM, JOIN max_blank_lines = 0
配置完成后,运行sqlfluff lint your_sql_file.sql即可检查违规代码。
方法二:自定义规则(精准控制)
如果内置规则无法满足更细致的需求,可编写自定义规则:
- 创建自定义规则文件(如
custom_rules.py),添加以下代码:
from sqlfluff.core.rules import BaseRule, LintResult, RuleContext from sqlfluff.core.rules.crawlers import SegmentSeekerCrawler from sqlfluff.core.parser import segments class Rule_NoBlankLinesBetweenKeywords(BaseRule): """禁止SQL关键字与相邻代码之间出现空行""" name = "custom.no_blank_lines_between_keywords" aliases = ["L099"] # 自定义规则编号,可自行修改 # 指定需要检查的语法节点 crawler = SegmentSeekerCrawler({"select_clause", "from_clause", "join_clause"}) def _eval(self, context: RuleContext) -> LintResult: segment = context.segment # 检查关键字节点前的空行 prev_seg = segment.previous_segment if prev_seg and isinstance(prev_seg, segments.WhitespaceSegment) and prev_seg.is_blank_line: keyword = segment.type.replace("_clause", "").upper() return LintResult( anchor=segment, description=f"关键字{keyword}前禁止出现空行" ) # 检查关键字节点后的空行 next_seg = segment.next_segment if next_seg and isinstance(next_seg, segments.WhitespaceSegment) and next_seg.is_blank_line: keyword = segment.type.replace("_clause", "").upper() return LintResult( anchor=segment, description=f"关键字{keyword}后禁止出现空行" ) return LintResult()
- 在
.sqlfluff中配置加载自定义规则:
[sqlfluff] # 启用自定义规则 rules = custom.no_blank_lines_between_keywords # 排除可能冲突的内置规则(如blank_lines相关) exclude_rules = blank_lines.before_keywords, blank_lines.after_keywords # 指定自定义规则文件路径 load_rules_from_path = ./
- 运行
sqlfluff lint your_sql_file.sql验证规则效果。
内容的提问来源于stack exchange,提问作者Fleur Lolkema
相关产品推荐
相关产品推荐

