Macros, packages and real dbt
Part of the free LogicWiz Data Engineering course, Module 8: Transformation as code: dbt. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:15 on Tuesday. Tess has two dashboards open, and they show different revenue for the same week. Five models each carry their own copy of the rule that decides whether an order counts as revenue. Finance changed the rule last week. Three copies were updated. Two were not.
You'll learn to
- Read Jinja: what {{ }} prints and what {% %} decides
- Write a macro once and call it from several models
- Explain why dbt renders a model twice, and guard run_query()
- Install packages and run real dbt on a laptop with DuckDB
Learn
Five copies of one rule
The rule for "does this order count as revenue?" is a short piece of SQL. It was copied into five models. When finance changed it, someone had to find all five copies, and missed two.
The fix is to write the rule once and let a tool paste it into every model that needs it.
dbt can do that with something you have used since Lesson 8.1. {{ ref(...) }} is not SQL. It is a blank in a template, and dbt fills it in before the warehouse sees the query. Filling in the blanks is called rendering, and the template language is Jinja. Think of a form letter: one text, with blanks filled in before it is printed.
Jinja first, SQL second
Four steps in a row: your model with its tags, Jinja rendering it without seeing any rows, the plain SQL text that comes out, and the warehouse running that SQL on the rows.
Read it left to right. Everything Jinja does happens in the second box, before a single row is read.
Two kinds of tags
Jinja has two kinds of tags.
{{ ... }}prints. Whatever is inside is worked out and written into the SQL:{{ 6 * 7 }}becomes42.{% ... %}decides. It is logic that prints nothing itself:if,for,set,macro.
Keep the order from the picture in mind. Jinja never sees a single row of your data. It only writes the query that will.
The next card runs Jinja on its own, with no warehouse at all.
Jinja on its own
import minidbt
print(minidbt.render("select {{ 6 * 7 }} as answer"))
print(minidbt.render("{% if full %}select *{% else %}select order_id{% endif %} from orders", full=False))
print(minidbt.render(
"{% for s in statuses %}'{{ s }}'{% if not loop.last %}, {% endif %}{% endfor %}",
statuses=['placed', 'shipped', 'delivered'],
))
render() fills in a template with the names you pass. Inside a for, loop.first, loop.last and loop.index tell you where you are, which is how the last line avoids a trailing comma. (minidbt evaluates Jinja expressions as Python; real Jinja is very close.)
Jinja cannot decide anything per row. {% if status == 'cancelled' %} 0 {% else %} order_total {% endif %} looks right, but to Jinja status is an undefined name. The condition is false and every row gets order_total. Per-row logic belongs in SQL, in a case when. When a model misbehaves, read the compiled SQL first: real dbt writes it to target/compiled/.
One rule, one macro
A macro is a named piece of Jinja that takes arguments and gives back SQL text. Think of a rubber stamp: you carve the rule once, then stamp it into any model.
You define it in a file under macros/:
{% macro is_revenue(status_column) %}
{{ status_column }} in ('placed', 'shipped', 'delivered')
{% endmacro %}
A model calls it with {{ is_revenue('o.status') }}. Change the rule in this one file, and every model that calls it follows on the next build.
dbt itself ships hundreds of macros. is_incremental is one, which is why dbt run reports a count of macros when it starts.
A macro call becomes SQL
Three boxes side by side, the macro file, two models that call the macro, and the compiled SQL: the call is found, the text o.status is passed into the macro, and the macro's body is printed into both compiled queries.
The models call the macro. Neither model contains the rule. Each has the same call:
{{ is_revenue('o.status') }}. Nothing is compiled yet.Jinja passes the text in. The argument
'o.status'is text, not a column value. Inside the macro,status_columnnow stands for those eight characters.The macro's body is printed into each query. Jinja pastes the text where
{{ status_column }}was and writes the result into both models. The warehouse receives plain SQL and never sees the wordis_revenue.
Read each step left to right: the macro, the two models that call it, then the SQL that comes out. Change the list in the left box and both green lines change with it.
One rule, two models
import duckdb
import minidbt
project = minidbt.Project('models') # reads models/*.sql and macros/*.sql
print(project.compile('fct_customer_revenue'))
project.build()
duckdb.sql("select * from fct_customer_revenue order by revenue desc limit 3").show()
The first print is the compiled SQL of one mart: look for the two lines the macros wrote. Then open macros/revenue.sql under the code, change the list inside is_revenue and run again. Both marts change together.
What each call becomes
| In the model | After compiling |
|---|---|
| {{ isrevenue('o.status') }} | o.status in ('placed', 'shipped', 'delivered') |
| {{ money('sum(i.lineamount)') }} | round(sum(i.lineamount), 2) |
| {{ money('avg(qty)', places=1) }} | round(avg(qty), 1) |
The arguments are text: 'o.status' is passed in quotes and pasted into the SQL. A macro builds a query. It never receives column values.
A loop writes the repetitive lines
Tess wants one row per order, with a column for each payment method. In plain SQL that is the same sum(case ...) line four times. Add a method and you must remember to add a line.
With {% set %} and {% for %} you write the line once, and Jinja repeats it for each method in a list.
One small detail: the - in {%- trims the spaces and newlines before a tag, so the compiled SQL stays tidy.
Run the next card and read the compiled query before the result.
Pivot payments with a loop
import duckdb
import minidbt
project = minidbt.Project(models={'fct_order_payments': """
{{ config(materialized='table') }}
{% set methods = ['card', 'wallet', 'bank_transfer', 'gift_card'] %}
select
order_id,
{%- for m in methods %}
sum(case when method = '{{ m }}' then amount else 0 end) as {{ m }}_usd
{%- if not loop.last %},{% endif %}
{%- endfor %}
from {{ source('shop', 'payments') }}
where status = 'captured'
group by order_id
"""})
print(project.compile('fct_order_payments'))
project.build()
duckdb.sql("select * from fct_order_payments where order_id in (1005, 1033)").show()
Four sum(case ...) lines came out of one line of template. Notice the quotes in '{{ m }}': Jinja prints the bare word, and SQL needs quotes around a text value. Without them the query would say method = card and look for a column named card. Order 1033 shows card_usd of 182.50: it was charged twice, which the singular test from Lesson 8.3 would catch.
dbt reads every model twice
The list of methods is still typed by hand. Nora asks: could it come from the data? A macro can ask the warehouse, with run_query(). But there is a catch.
dbt renders every model twice. Think of a recipe: you read it once to write the shopping list, and again to cook.
- Parse: dbt renders the Jinja only to collect
ref(),source()andconfig()and build the DAG. No SQL runs. A variable calledexecuteis false. - Execute: dbt renders the chosen models again, with
executetrue. Now a macro may query the warehouse.
At parse time run_query() returns nothing. Code that reads its result stops the whole project:
Compilation Error in model order_payment_methods (models/order_payment_methods.sql)
'None' has no attribute 'table'
Two renders of one model
A sequence between dbt, Jinja and the warehouse in three steps: a parse that crashes because a query result is read when there is none, the same parse with an execute guard that returns an empty list, and the execute render that queries the warehouse for the payment methods and builds the table.
Parse, with no guard. dbt renders the model only to collect its refs.
run_query()runs nothing now, so there is no result. The next line reads the result anyway, and the project stops before any model is built.Parse, with
{% if execute %}. The guard skips the line that reads the result and uses an empty list instead. Parsing only needs thesource()call, and it gets it.Execute. When the model's turn comes, dbt renders it again with
executetrue. Now the query really runs, the four methods come back, and the loop writes one column for each.
Read each step top to bottom: an arrow is a message, a loop on one line is work done inside it. Nothing reaches the warehouse until the last step.
The guarded model: its columns come from the data
Runs with dbt:
{% set methods_query %}
select distinct method from {{ source('shop', 'payments') }} order by 1
{% endset %}
{% set results = run_query(methods_query) %}
{% if execute %}
{% set methods = results.columns[0].values() %}
{% else %}
{% set methods = [] %}
{% endif %}
select
order_id,
{%- for m in methods %}
sum(case when method = '{{ m }}' then amount else 0 end) as {{ m }}_usd,
{%- endfor %}
sum(amount) as total_usd
from {{ source('shop', 'payments') }}
where status = 'captured'
group by order_id
This is models/marts/fct_order_payments.sql in real dbt. Find the {% if execute %} block: the query result is only touched when execute is true.
Remember: dbt renders every model twice. Guard anything that reads a query result with {% if execute %}. Package macros that read data, such as dbt_utils.get_column_values, guard themselves the same way.
Macros other people wrote
You do not have to write every macro yourself. A package is a dbt project full of macros (and sometimes models) that someone else maintains. dbt_utils is in almost every project.
You list packages in packages.yml and install them with dbt deps. They are not stored in your repo: dbt deps downloads them into a folder called dbt_packages/, which Git ignores. So a teammate who clones the repo must run dbt deps first, or every package macro is undefined.
dbt deps also writes a file called package-lock.yml: the exact versions it picked. Commit that file. Then CI and every laptop install the same macro code.
What dbt deps does
Four steps in a row: packages.yml asks for a version range of dbt_utils, dbt deps resolves it to one release, writes that exact version to package-lock.yml, and downloads the macro code into the dbt_packages folder.
Read it left to right. The next dbt deps skips the second box and installs exactly what the lock file says. dbt deps --upgrade moves the pins.
A package macro in a model
Runs with dbt:
-- packages.yml
-- packages:
-- - package: dbt-labs/dbt_utils
-- version: [">=1.1.0", "<2.0.0"]
-- then install it with: dbt deps
-- models/marts/fct_order_lines.sql
select
{{ dbt_utils.generate_surrogate_key(['order_id', 'line_no']) }} as order_line_key,
order_id,
line_no,
product_id,
qty,
unit_price
from {{ ref('stg_order_items') }}
generate_surrogate_key hashes several columns into one, so the table has a one-column key. Other dbt_utils macros you will meet: date_spine, pivot, star, union_relations. dbt-expectations adds dozens of tests; codegen writes YAML for you.
One macro, every warehouse
Warehouses disagree on SQL: date arithmetic, joining strings, qualify. So how does one package work on all of them?
dbt talks to each warehouse through a plug-in called an adapter. A package macro such as concat is a front desk: it hands the call on with adapter.dispatch('concat', 'dbt_utils'), and dbt looks for the right version by name:
- one for your adapter:
postgres__concaton Postgres; - one for a parent adapter (Redshift tries
redshift__, thenpostgres__); - the fallback,
default__concat.
A dispatch block in the root dbt_project.yml can make dbt search your project first. Then you can fix one package macro for your warehouse without keeping your own copy of the package. Package order beats adapter order: your default__concat wins over the package's postgres__concat.
Dispatching concat on Postgres, project first
Four candidate macros tried in order: the project's Postgres version, the project's default, the package's Postgres version, and the package's default, which is found and used.
Read it top to bottom: dbt tries each name in turn and calls the first one that exists. This is the order with dispatch: [{macro_namespace: dbt_utils, search_order: [swiftkart, dbt_utils]}]. Define swiftkart.default__concat and it would win from step 2.
Real dbt on your laptop, with DuckDB
Runs on your laptop:
python -m venv .venv && source .venv/bin/activate
pip install dbt-duckdb
dbt init swiftkart # asks which database: choose duckdb
cd swiftkart
dbt debug # checks profiles.yml and the connection
# put your models in models/ (and delete the two examples dbt init made)
dbt build # models, tests, snapshots, in order
dbt docs generate && dbt docs serve # the docs site with the lineage graph
$ dbt debug
...
Connection test: [OK connection ok]
All checks passed!
$ dbt build
...
Done. PASS=12 WARN=0 ERROR=0 SKIP=0 TOTAL=12
The connection lives outside the project, in ~/.dbt/profiles.yml: for DuckDB, type: duckdb and a path to the database file. Add a second target and the same project runs against Snowflake or Databricks (dbt build --target prod). This is how to practise dbt for free.
Two ways teams run dbt in production
| dbt Core, run by an orchestrator | dbt Cloud (now the dbt platform) |
|---|---|
| An Airflow task. Astronomer's Cosmos turns each model into a task. | A browser IDE and a job scheduler |
| A Dagster asset | CI that builds only what a pull request changed |
| A dbt task in a Databricks job | Hosted docs and the semantic layer for metrics |
Numbers to remember
| Name | Value | What it is |
|---|---|---|
| {{ ... }} | prints | An expression: its value is written into the SQL. |
| {% ... %} | prints nothing | Logic: if, for, set, macro. |
| {%- | trims | The - removes the spaces and newlines before the tag. |
| execute | false at parse, true at execute | Guard query results with {% if execute %}. |
| target/compiled/ | real dbt | Where real dbt writes the compiled SQL of every model. dbt compile shows it. |
| package-lock.yml | commit it | Later dbt deps runs install exactly the lock. Prereleases are left out unless you ask for one. |
| generatesurrogatekey | MD5 on most adapters | Casts each column to text, replaces NULLs with dbtutilssurrogatekeynull, joins the parts with - and hashes them: the same key on every warehouse (Lesson 5.1). |
| adapter.dispatch search | packages first, then names | In each package of the search order: the adapter's name, a parent adapter's, then default. |
| searchorder | ['swiftkart', 'dbtutils'] | In the dispatch block of the root dbtproject.yml: your project is searched before the package. |
What changed at SwiftKart
The revenue rule now lives in one macro, is_revenue. Every model that needs it calls it, so Tess's two dashboards agree again, and the next rule change is one line in one file.
Nora's rule of thumb: write a macro when the same logic appears three or more times, or when a rule must stay in one place. A model that is more {% %} than select is hard to review.
The project keeps growing, though. It now has 400 models, and every pull request builds all of them. Lesson 8.6 opens dbt up: how it parses a project, picks what to build and runs models in parallel.
In one line
Jinja writes the SQL before the warehouse runs it, so put a repeated rule in one macro, reuse packages like dbt_utils, and practise on real dbt with dbt-duckdb.
Interview corner
What is a dbt macro, and when would you write one?
A macro is a Jinja function in the macros/ folder that returns SQL text; models call it like {{ is_revenue('status') }}. Write one when logic repeats across models or a business rule must have one definition, such as what counts as revenue, currency conversion or a surrogate key. Avoid it for one-off logic, where plain SQL is clearer.
What is the difference between {{ }} and {% %} in dbt?
{{ }} is an expression: its value is printed into the compiled SQL, as with {{ ref('stg_orders') }}. {% %} is a statement: control flow and definitions such as if, for, set and macro, which print nothing themselves. Both run at compile time, before the warehouse sees the query.
How would you run dbt in production?
Keep the project in Git. On every pull request, CI runs dbt build on the changed models and their children in a separate schema. After merging, an orchestrator or a dbt Cloud job runs dbt build --target prod after each load, with alerts on failure. Dev and prod use different targets and schemas, and secrets come from the environment, never the repo.
How do you write one macro that works on Snowflake, BigQuery and Postgres?
I write a thin public macro that returns adapter.dispatch('name', 'my_package')(args), a default__name with portable SQL, and adapter-specific versions only where the dialects differ, such as snowflake__name or bigquery__name. dbt tries the current adapter, then its parent adapters, then default__. Consumers can override one implementation with a dispatch search_order in their root dbt_project.yml without forking the package, and I test each adapter in CI.