dbt adapter macro 简单说明
dbt 的adapter macro 提供了方便的在macro 中对于db 操作的能力,让macro 具有了动态能力,默认包含了不少实现
而且在不少dbt 项目中经常看到
参考使用
结合了api 这个macro 提供了能力,进行ddl 的维护
{%- set target_relation = api.Relation.create(
database='database_name',
schema='schema_name',
identifier='table_name') -%}
{% for col in adapter.get_missing_columns(target_relation, this) %}
alter <Term id="table" /> {{this}} add column "{{col.name}}" {{col.data_type}};
{% endfor %}
参考处理
- 实现代码
# 基于dbt contextproperty装饰器处理的,包装的dbt 项目特定的adapter 操作,比如dispatch,create_schema,drop_schema,get_relation
。。。。
@contextproperty("adapter")
def ctx_adapter(self) -> BaseDatabaseWrapper:
"""`adapter` is a wrapper around the internal database adapter used by
dbt. It allows users to make calls to the database in their dbt models.
The adapter methods will be translated into specific SQL statements
depending on the type of adapter your project is using.
"""
# db_wrapper 实际上就是实现了adapter protocol 的实现,只是额外包装了一些新的功能
return self.db_wrapper
说明
dbt adapter macro 提供的一些能力比较方便,可以让macro 实现不少动态能力
参考资料
core/dbt/context/providers.py
https://docs.getdbt.com/reference/dbt-classes
https://docs.getdbt.com/reference/dbt-jinja-functions/adapter