DBT - 获取宏内的参考模型配置变量

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

我正在使用宏来自动化并制作通用 DBT 增量程序。

问题:

我尝试从一个模型中获取一些配置变量,并将其用作另一个模型中的参考。对于我的每个模型,我在配置中保留一个

timestamp_column
。 我希望能够在需要时从配置中获取
timestamp_column
值。我没有找到任何合适的方法来做到这一点。

代码示例:

例如在我的 _models.yml 中:

  - name: L0__game_runs
    config:
      materialized: incremental
      time_interval: hour
      timestamp_column: time_started

  - name: L1__drafts
    config:
      materialized: incremental
      time_interval: hour
      timestamp_column: created_at

L1__drafts
模型查询指的是
L0__game_runs
,例如:

with
    {% if is_incremental() %}
        {% set self_max_timestamp = get_table_max_timestamp(this) %}
         drafts as {{ (generate_source_query(ref('L0__game_runs'), self_max_timestamp)) }}
    {% else %}
          drafts as (select * from {{ ref('L0__game_runs') }}),
      {% endif %}
    
    <REST OF SQL COMES HERE...>

generate_source_query.sql
宏:

{% macro generate_source_query(source_model, self_max_timestamp) %}
    {%- set source_timestamp_column = source_model.get('timestamp_column') -%}
    <REST OF MACRO COMES HERE...> 
{% endmacro %}

但是

source_timestamp_column
返回空字符串结果。没有找到任何其他方法来修复它。 有什么想法吗?

macros jinja2 config dbt
2个回答
0
投票

经过大量挖掘,我找到了解决该问题的方法 - 使用 DBT 图形上下文 获取所有 DBT 模型配置(以及更多)。

我编写了一个宏来检索参考模型配置值。这有点天真,但现在对我来说已经足够了:

{% macro get_model_config_values(model_ref) %}
    {%- set table_name = model_ref.identifier -%}

    {% for node in graph.nodes.values() %}
        {%- set model_name = node.unique_id.split('.')[-1] -%}
        {%- if table_name == model_name -%}
            {%- set model_config = node.config -%}
            {{ return(model_config) }}
        {%- endif -%}
    {% endfor %}
{% endmacro %}


0
投票

对于任何偶然发现同样问题的人,您可以使用更简洁的语法来实现相同的目的:

{% macro get_model(relation) -%}
    {% for node in graph.nodes.values()
        | selectattr("resource_type", "equalto", "model")
        | selectattr("name", "equalto", relation.identifier) %}
        {% do return(node) %}
    {% endfor %}
{%- endmacro %}
© www.soinside.com 2019 - 2024. All rights reserved.