dbt Jinja是否存在所有有效数据库与schema组合的变量列表?
问题根源
问题出在两个核心点:
- 宏本身存在参数不匹配问题:你定义的宏入参是
role,但代码内部循环了未定义的roles变量,会触发变量未找到的隐藏错误。 - 逻辑缺陷:你传入宏的
schemas列表仅包含schema名称,未绑定对应归属的数据库,dbt执行SQL时会默认拼接target.database作为库名,因此会去错误的库下查找不存在的schema,触发你遇到的报错。
修复方案
步骤1:修正宏代码
调整宏参数支持多角色,同时接收完整的数据库.schema格式的schema路径:
-- macros/grants/grant_select_on_schemas.sql {% macro grant_select_on_schemas(schema_list, role_list) %} {% for schema_full_name in schema_list %} {% for role in role_list %} grant usage on schema {{ schema_full_name }} to role {{ role }}; grant select on all tables in schema {{ schema_full_name }} to role {{ role }}; grant select on all views in schema {{ schema_full_name }} to role {{ role }}; grant select on future tables in schema {{ schema_full_name }} to role {{ role }}; grant select on future views in schema {{ schema_full_name }} to role {{ role }}; {% endfor %} {% endfor %} {% endmacro %}
步骤2:获取项目所有有效数据库+schema组合
两种合法获取全量库-schema组合的方式,任选其一即可:
方式一:使用dbt内置上下文变量
dbt的on-run-end钩子自带schemas变量,会自动识别项目中所有跨库的schema,自动拼接为数据库.schema的完整格式,直接调用即可。
在dbt_project.yml中添加钩子配置:on-run-end: - "{{ grant_select_on_schemas(schemas, ['你的授权角色名1', '你的授权角色名2']) }}"方式二:自定义遍历模型生成组合
如果内置变量不符合需求,可以自定义宏遍历项目所有模型,提取去重后的库-schema组合:-- macros/get_all_db_schemas.sql {% macro get_all_db_schemas() %} {% set db_schema_set = set() %} {% for node in graph.nodes.values() %} {% if node.resource_type == 'model' %} {% set full_schema_path = node.database ~ '.' ~ node.schema %} {% do db_schema_set.add(full_schema_path) %} {% endif %} {% endfor %} {{ return(db_schema_set | list) }} {% endmacro %}对应钩子配置改为:
on-run-end: - "{{ grant_select_on_schemas(get_all_db_schemas(), ['你的授权角色名1', '你的授权角色名2']) }}"
前置校验
确保你profiles.yml中配置的运行角色my-role,已经拥有所有目标数据库的USAGE权限,否则授权操作会触发权限不足报错。
内容的提问来源于stack exchange,提问作者sgdata
相关产品推荐
相关产品推荐

