0
0
DbtHow-ToBeginner ยท 4 min read

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.yml before running dbt 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

MacroPurposeRequired Arguments
generate_modelCreates a new model SQL filename: model_name
generate_seedCreates a new seed CSV filename: seed_name, columns: {col1: type, col2: type}
generate_testCreates a new test SQL filename: 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.