dbt context 变量简单说明
dbt 的模型以及macro 中实际上是可以引用一个context 变量的,此变量没有在文档中有说明,但是官方一些macro 中使用了此变量
参考使用
dbt 的snapshots strategies 处理中基于配置的strategy 查找对应的macro
{% macro strategy_dispatch(name) -%}
{% set original_name = name %}
{% if '.' in name %}
{% set package_name, name = name.split(".", 1) %}
{% else %}
{% set package_name = none %}
{% endif %}
{% if package_name is none %}
{% set package_context = context %}
{% elif package_name in context %}
{% set package_context = context[package_name] %}
{% else %}
{% set error_msg %}
Could not find package '{{package_name}}', called with '{{original_name}}'
{% endset %}
{{ exceptions.raise_compiler_error(error_msg | trim) }}
{% endif %}
{%- set search_name = 'snapshot_' ~ name ~ '_strategy' -%}
{% if search_name not in package_context %}
{% set error_msg %}
The specified strategy macro '{{name}}' was not found in package '{{ package_name }}'
{% endset %}
{{ exceptions.raise_compiler_error(error_msg | trim) }}
{% endif %}
{{ return(package_context[search_name]) }}
{%- endmacro %}
说明
dbt 部分实现上使用的方法不是很统一,比如对于物化增量处理上就相对统一,基于了包装的context 通过adapter 的get_incremental_strategy_macro 方法处理的,部分可能因为缺少功能,使用了其他hack 模式
参考资料
core/dbt/include/global_project/macros/materializations/snapshots/strategies.sql
core/dbt/include/global_project/macros/materializations/snapshots/snapshot.sql
core/dbt/adapters/base/impl.py
https://docs.getdbt.com/reference/dbt-jinja-functions/
https://docs.getdbt.com/docs/build/snapshots