What Are Hooks?
Hooks are snippets of SQL that run at predefined moments during the dbt execution process. They help automate operational tasks like:- Granting permissions on objects
- Setting table properties or attributes
- Adding comments or metadata
- Creating indexes or optimizing data structures
- Executing database-specific operations
Using Model-Level Hooks
Pre-hooks and Post-hooks You can define pre-hooks and post-hooks directly in your model SQL files using theconfig() function:
- The pre-hook deletes invalid records before the model builds
- The post-hook grants select permissions after the model is created
Project and Folder-Level Hooks
You can configure hooks that apply to groups of models in yourdbt_project.yml file:
Hook Context VariablesIn hooks, you can access several useful context variables:
{{ this }}- The relation being built (table/view){{ target }}- Information about the current target database{{ run_started_at }}- Timestamp when the run started{{ invocation_id }}- Unique ID for the current dbt run
Using Macros in Hooks
You can make your hooks more reusable by calling macros:Common Hook Use Cases
Permission Management A common use for hooks is automating permission grants:Operations with run-operation
Operations are a way to execute standalone macros using therun-operation command. This is useful for administrative tasks that you want to run on demand, rather than as part of a model build.
Creating an Operation Macro
To create an operation, define a macro that performs the desired actions:
- The SQL is defined within a
{% set sql %}block - The
run_query()function is used to actually execute the SQL
Key Difference Between Hooks and Operations
- Hooks are automatically executed at specific times during dbt runs
- Operations are explicitly run on-demand using the
run-operationcommand - With operations, you must use
run_query()or a statement block to execute the SQL
Operation Examples
Refreshing a Snowflake PipeBest Practices
Hooks
Operations
When to Use Hooks vs. OperationsUse hooks when you need to:
- Execute SQL automatically at specific points in your dbt workflow
- Apply consistent actions across multiple models
- Implement pre/post processing that’s tightly coupled to models
- Run administrative tasks on-demand
- Perform one-off database maintenance
- Execute complex logic that doesn’t fit into the model build process
- Create setup/teardown scripts for your environment