How to Use the Codegen Package in dbt for Model Generation
To use the
codegen package in dbt, first install it via dbt deps after adding it to your packages.yml. Then run commands like dbt run-operation generate_model --args '{name: my_model}' to create model files automatically.Syntax
The codegen package provides dbt macros to generate model, seed, and test files quickly. You use it by running dbt run-operation with the macro name and passing arguments as YAML or JSON.
Common macros include:
generate_model: creates a new model SQL file.generate_seed: creates a new seed CSV file.generate_test: creates a new test SQL file.
Arguments typically include name for the file name and optional columns for seeds or tests.
bash
dbt run-operation generate_model --args '{name: my_new_model}'Example
This example shows how to generate a new model file named sales_summary using the codegen package.
bash
1. Add codegen to <code>packages.yml</code>: packages: - package: dbt-labs/codegen version: 0.7.0 2. Run to install the package: $ dbt deps 3. Generate a model file: $ dbt run-operation generate_model --args '{name: sales_summary}' 4. Check your <code>models/</code> folder for <code>sales_summary.sql</code> created with a basic template.
Output
Running with dbt=1.4.6
Executing operation: generate_model
Created models/sales_summary.sql
Common Pitfalls
Common mistakes when using the codegen package include:
- Not adding the package to
packages.ymlbefore runningdbt deps. - Passing incorrect argument formats; arguments must be valid YAML or JSON.
- Expecting the generated files to be fully complete; they provide templates that need editing.
- Running commands outside the dbt project directory.
bash
Wrong usage example: $ dbt run-operation generate_model --args 'name: my_model' Right usage example: $ dbt run-operation generate_model --args '{name: my_model}'
Quick Reference
| Macro | Purpose | Required Arguments |
|---|---|---|
| generate_model | Creates a new model SQL file | name: model_name |
| generate_seed | Creates a new seed CSV file | name: seed_name, columns: {col1: type, col2: type} |
| generate_test | Creates a new test SQL file | name: test_name, test_type: type |
Key Takeaways
Add the codegen package to packages.yml and run dbt deps before using it.
Use dbt run-operation with generate_model, generate_seed, or generate_test macros to create files.
Pass arguments as valid YAML or JSON strings with the --args flag.
Generated files are templates; customize them to fit your project needs.
Run commands inside your dbt project directory to avoid errors.