使用 dbt 中的星形宏获取列名称和类型

bri*_*akh 5 sql dbt

使用星形宏,除了列名之外,是否还有办法获取列数据类型(布尔值、数值等)?

例如,此查询使用星号宏从引用表中收集列名,将其保存为数组变量column_names,然后循环该数组并将 max 函数应用于所有列。

{% set column_names = star(
    from=ref_table,
    except=["a", "b", "c"],
    as_list=True)
%}

select 
    date_trunc('week', day) as week,
    name,

    {%- for col in column_names %}  
    max({{ col|lower }}) as {{ col | lower }}{%- if not loop.last %},{{ '\n  ' }}{% endif %}
    {%- endfor %}

from {{ ref('my_table_name') }}    
group by 1, 2
Run Code Online (Sandbox Code Playgroud)

我想有条件地将 max 函数仅应用于布尔列。

这可能看起来像

{%- for col in column_names %}  
    {% if is_boolean(col) %}  
    max({{ col|lower }}) as {{ col | lower }}{%- if not loop.last %},{{ '\n  ' }}{% endif %}
    {% endif %}
{%- endfor %}
Run Code Online (Sandbox Code Playgroud)

但问题是星形宏将列名作为字符串传递,因此它不携带任何元数据。

我如何在这里获取列数据类型?

数据仓库:雪花

tco*_*eer 7

您可以在此处查看源代码dbt_utils.star

在幕后,它使用dbt_utils.get_filtered_columns_in_relation. 该宏也只返回列名称。然而!该宏使用内置的,它返回具有属性的Columnadapter.get_columns_in_relation对象的列表。data_type

所以你的代码变成:

{% set all_columns = adapter.get_columns_in_relation(
    ref("my_table")
) %}
{% set except_col_names=["a", "b", "c"] %}

select 
    date_trunc('week', day) as week,
    name,

    {%- for col in all_columns if col.name not in except_col_names %}  
    {% if col.data_type == 'BOOLEAN' %}  
    max({{ col.name|lower }}) as {{ col.name|lower }}{%- if not loop.last %},{{ '\n  ' }}{% endif %}
    {% endif %}
    {%- endfor %}

from {{ ref('my_table_name') }}    
group by 1, 2
Run Code Online (Sandbox Code Playgroud)