Skip to content

Hooks

前提了解

hooks操作入门

有效的数据库管理有时需要运行额外的SQL语句,例如: - 创建UDFs - 管理行或列级别的权限 - 在Redshift清空表 - 在Redshift Spectrum外部表中创建分区 - 在Snowflake中恢复/暂停/调整仓库大小 - 在Snowflake中刷新管道 - 在Snowflake上创建共享 - 在Snowflake上克隆数据库

dbt提供了hooks和操作,因此您可以将这些语句作为dbt项目的一部分进行版本控制和执行。

关于hooks

Hooks是在不同时间执行的SQL片段:

  • pre-hook: 在模型、种子或快照构建 之前 执行.
  • post-hook: 在模型、种子或快照构建 之后 执行.
  • on-run-start: 在dbt rundbt seeddbt snapshot命令 开始 时执行
  • on-run-end: 在dbt rundbt seeddbt snapshot命令 结束 时执行

Hooks是一种更高级的功能,它使您能够运行自定义SQL,并利用特定于数据库的操作,而不仅仅是dbt通过标准物化和配置提供的开箱即用功能。

如果(并且仅当)您不能利用grants resource-config,则可以使用post-hook执行更高级的工作流:

  • 需要以一种更复杂的方式应用grants,而dbt Core v1.2的grants配置(尚未)支持这种方式。
  • 需要执行dbt不支持的开箱即用的后处理。例如,analyze tablealter table set propertyalter table …添加行访问策略等。

hooks使用示例

在运行操作或构建模型、种子或快照时,可以使用hook在特定时间触发操作。

有关何时可以触发hook的更多信息,请参阅on-run starton-run endhookpre-hooks and post-hooks

您可以使用hook来提供dbt无法开箱即用的特定于数据库的功能。例如,您可以在使用post-hook在构建单个模型后立即使用config块来运行ALTER TABLE语句:

{{ config(
    post_hook=[
      "alter table {{ this }} ..."
    ]
) }}

hooks使用示例

下面是一个使用hook授予特权的最小示例。有关更多信息,请参阅on-run start&on-run endhookpre-hook & post-hook

on-run-end:
  - "grant usage on {{ target.schema }} to role reporter"

models:
  +post-hook:
    - "grant select on {{ this }} to role reporter"

您还可以使用config块将post-hook应用于各个模型:

{{ config(
    post_hook=[
      "grant select on {{ this }} to role reporter"
    ]
) }}

select ...

您应该在适当的时候使用特定于数据库的语法:

{{ config(
    post_hook=[
      'grant `roles/bigquery.dataViewer` on {{ this.type }} {{ this }} to "user:someone@yourcompany.com"'
    ]
) }}

select ...
{{ config(
    post_hook=[
      "grant select on {{ this }} to `someone@yourcompany.com`"
    ]
) }}

select ...
{{ config(
    post_hook=[
      "grant select on {{ this }} to reporter"
    ]
) }}

select ...
{{ config(
    post_hook=[
      "grant select on {{ this }} to role reporter"
    ]
) }}

select ...

在hook中调用宏

您也可以使用来捆绑hook逻辑。查看参考部分中的on-run-start 和 on-run-end hookspre- and post-hooks.。

关于operations

Operations是可以使用run operation命令运行的。因此,Operations实际上并不是dbt项目中的一个单独资源——它们只是调用宏的一种方便方式,无需运行模型。

在operation中显示执行SQL

与hook不同,您需要在宏中显式执行查询,方法是使用语句块或像run_query 宏这样的辅助宏。否则,dbt将在不执行查询的情况下以字符串形式返回查询。

此宏执行与上述hooks类似的操作:

{% macro grant_select(role) %}
{% set sql %}
    grant usage on schema {{ target.schema }} to role {{ role }};
    grant select on all tables in schema {{ target.schema }} to role {{ role }};
    grant select on all views in schema {{ target.schema }} to role {{ role }};
{% endset %}

{% do run_query(sql) %}
{% do log("Privileges granted", info=True) %}
{% endmacro %}

若要将此宏作为操作调用,请执行dbt run-operation grant_select --args '{role: reporter}'

$ dbt run-operation grant_select --args '{role: reporter}'
Running with dbt=0.16.1
Privileges granted

可以在此处找到run-operation命令的完整使用文档.