dbt var 简单说明

dbt 的var 可以进行变量的定义以及变量的引用,以下简单说明下

参考使用

  • 引用定义的
    参考定义
name: my_dbt_project
version: 1.0.0
 
config-version: 2
 
# Define variables here
vars:
  event_type: activation
 
select * from events where event_type = '{{ var("event_type") }}'
  • 定义
    包含了默认值
select * from events where event_type = '{{ var("event_type", "activation") }}'
{%- set concat_string = var('concat_string', '||') -%}

内部处理

实际上就是一个属性,会包含cli 以及context 中的一些信息

@contextproperty()
def var(self) -> Var:
    """Variables can be passed from your `dbt_project.yml` file into models
    during compilation. These variables are useful for configuring packages
    for deployment in multiple environments, or defining values that should
    be used across multiple models within a package.
 
    To add a variable to a model, use the `var()` function:
 
    > my_model.sql:
 
        select * from events where event_type = '{{ var("event_type") }}'
 
    If you try to run this model without supplying an `event_type`
    variable, you'll receive a compilation error that looks like this:
 
        Encountered an error:
        ! Compilation error while compiling model package_name.my_model:
        ! Required var 'event_type' not found in config:
        Vars supplied to package_name.my_model = {
        }
 
    To supply a variable to a given model, add one or more `vars`
    dictionaries to the `models` config in your `dbt_project.yml` file.
    These `vars` are in-scope for all models at or below where they are
    defined, so place them where they make the most sense. Below are three
    different placements of the `vars` dict, all of which will make the
    `my_model` model compile.
 
    > dbt_project.yml:
 
        # 1) scoped at the model level
        models:
          package_name:
            my_model:
              materialized: view
              vars:
                event_type: activation
        # 2) scoped at the package level
        models:
          package_name:
            vars:
              event_type: activation
            my_model:
              materialized: view
        # 3) scoped globally
        models:
          vars:
            event_type: activation
          package_name:
            my_model:
              materialized: view
 
    ## Variable default values
 
    The `var()` function takes an optional second argument, `default`. If
    this argument is provided, then it will be the default value for the
    variable if one is not explicitly defined.
 
    > my_model.sql:
 
        -- Use 'activation' as the event_type if the variable is not
        -- defined.
        select *
        from events
        where event_type = '{{ var("event_type", "activation") }}'
    """
    return Var(self._ctx, self.cli_vars)

参考资料

https://docs.getdbt.com/reference/dbt-jinja-functions/var

posted on 2024-05-24 08:00  荣锋亮  阅读(8)  评论(0编辑  收藏  举报

导航