使用 dbt_utils.generate_surrogate_key 宏时如何修复 linter 错误“行太长”?

问题描述 投票:0回答:1

我是 DBT 的新手。我使用了 dbt_utils.geenrate_surrogate_key() 宏,它编译正确,但在一行中生成所有输出 sql。这反过来会导致 linter (sqlfluff) 抱怨长行。

我可以手动编辑宏来添加一些换行符,但这将是一个不可维护的黑客行为。 有没有既定的方法来处理这个问题?

macros dbt sqlfluff
1个回答
0
投票

我最终编写了自己的宏,将代码行分割成缩进块。

{#
    Split a single line of code into multiple lines indented by nesting depth according to opening and closing characters (round parens by default)
    Optionally split into lines the parts separated by a `separator` (usually a comma)
#}
{%- macro line_to_code_block(the_line, open_char = '(', close_char = ')', sep = '') -%}
    {%- set x = the_line.replace(open_char, open_char + '\n') -%}
    {%- if sep != '' -%}
        {%- set x = x.replace(sep, sep + '\n') -%}
    {%- endif -%}
    {%- set x = x.replace(close_char, '\n' + close_char) -%}
    {%- set lines = x.splitlines() -%}
    {%- set indent = '    ' -%} {# indentation string #}
    {%- set indentation = [''] -%} 
    {%- for line in lines -%}
        {%- if indentation|length > 1 and line.startswith(close_char) == True -%}
            {%- do indentation.pop() -%}
        {%- endif -%}
        {{ indentation|join(indent) }}{{ line|trim }}{{ '\n' }}
        {%- if line.endswith(open_char) == True  -%}
            {%- do indentation.append('') -%}
        {%- endif -%}
    {%- endfor -%}
{%- endmacro -%}
© www.soinside.com 2019 - 2024. All rights reserved.