dbt this macro 处理简单说明

dbt this macro提供了一种方便的对于当前模型展现的方法,可以使用在增量模型以及pre&post hooks 中
this 实际是就类似ref('<the_current_model>') 是一个relation 包含了database,schema 以及模型标识

使用示例

一个增量处理的,基于this 可以方便的引用模型

{{ config(materialized='incremental') }}
 
select
    *,
    my_slow_function(my_column)
 
from raw_app_data.events
 
{% if is_incremental() %}
  where event_time > (select max(event_time) from {{ this }})
{% endif %}

内部实现

基于dbt 标准的装饰器 (ModelContext 类中的属性)

@contextproperty()
def this(self) -> Optional[RelationProxy]:
    """`this` makes available schema information about the currently
    executing model. It's is useful in any context in which you need to
    write code that references the current model, for example when defining
    a `sql_where` clause for an incremental model and for writing pre- and
    post-model hooks that operate on the model in some way. Developers have
    options for how to use `this`:
 
        |------------------|------------------|
        | dbt Model Syntax | Output           |
        |------------------|------------------|
        |     {{this}}     | "schema"."table" |
        |------------------|------------------|
        |  {{this.schema}} | schema           |
        |------------------|------------------|
        |  {{this.table}}  | table            |
        |------------------|------------------|
        |  {{this.name}}   | table            |
        |------------------|------------------|
 
    Here's an example of how to use `this` in `dbt_project.yml` to grant
    select rights on a table to a different db user.
 
    > example.yml:
 
        models:
          project-name:
            post-hook:
              - "grant select on {{ this }} to db_reader"
    """
    if self.model.resource_type == NodeType.Operation:
        return None
   # 结合方便的模型配置,通过db_wrapper 进行relation 的创建
    return self.db_wrapper.Relation.create_from(self.config, self.model)

说明

dbt this macro 实现了方便的对于当前模型的使用,可以提升模型的灵活性

参考资料

core/dbt/context/providers.py
https://docs.getdbt.com/reference/dbt-jinja-functions/this

posted on 2024-03-31 10:27  荣锋亮  阅读(12)  评论(0编辑  收藏  举报

导航