Models and ref()

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 9:20 on Monday. Tess opens the daily revenue dashboard and Sunday shows 0 orders. The shop sold all day Sunday. Nothing crashed. Eleven SQL scripts feed that dashboard, run by hand in the order written on a wiki page, and this morning script 7 ran before script 4.

You'll learn to

  • Write a dbt model as one SELECT and build it
  • Use ref() and source() so dbt works out the build order
  • Read the dependency graph and the compiled SQL
  • Say which schema ref() points at in dev, CI and production

Learn

Eleven scripts and a wiki page

One script cleans the orders. The next sums them per day from the cleaned table. A third builds the dashboard table from that sum.

Each script needs the ones before it. But that knowledge is not in the scripts. It lives on a wiki page, or in someone's head.

So the trouble grows with every script:

  • Run two out of order and you get stale or missing numbers.
  • Every file repeats the same DROP TABLE and CREATE TABLE lines.
  • Nothing checks the results.
  • A reviewer cannot see what depends on what.

Nora reads the wiki page and says: "The scripts already know the order. Make them say it."

Monday morning, in the wrong order

Three scripts in a row: one cleans the orders, one sums them per day, and the dashboard reads the sums. In the right order the dashboard shows Sunday; with the sum run first, Sunday is missing.

  1. Three of the eleven scripts. Say script 4 cleans the orders, script 7 sums the cleaned orders per day, and the dashboard reads those sums. Each one reads the table the one before it wrote.

  2. The order on the wiki page. Script 4 runs first, so the cleaned table has Sunday in it. Script 7 sums it next. The dashboard shows Sunday's orders.

  3. Monday's order. Script 7 runs first. It sums the cleaned table as it stood yesterday, which stops at Saturday. Script 4 adds Sunday a minute later, too late. The dashboard says 0 orders.

Both runs finished without an error. Nothing in the scripts themselves knows which one must go first.

One SELECT per file, dbt does the rest

The most common fix is a tool called dbt (data build tool).

You write each transformation as one SELECT in its own .sql file. dbt calls that file a model. dbt wraps your SELECT in the CREATE VIEW or CREATE TABLE, works out the order from the models themselves, runs them inside your warehouse and tests the results.

Think of a kitchen. You write one recipe per dish. The head chef reads all the recipes and decides what to cook first.

One thing dbt does not do: move data between systems. A loader (Fivetran, Airbyte, an Azure Data Factory copy, your own Python) lands the raw data in the warehouse first. dbt transforms it where it sits. It is the T in ELT.

Where dbt sits

Five steps in a row: the shop's systems, a loader, the raw tables in the warehouse, the dbt models, and the dashboard. Only the dbt step is highlighted.

Read it left to right. Only the green step is dbt: everything before it is the loader's job.

Never type a table name

Here is how a model says what it needs. Inside a model you never type a table name. You call one of two functions.

  • {{ source('shop', 'orders') }} points at a raw table that a loader put in the warehouse.
  • {{ ref('stg_orders') }} points at another model.

The double curly braces are Jinja, a template language. dbt fills them in with real table names before it sends the SQL to the warehouse.

Why bother? Because now every dependency is written down as a function call. dbt can read all your models and see who needs whom.

Run the two-model project below.

A two-model project

import duckdb
import minidbt

models = {
    'stg_orders': """
select order_id, customer_id, cast(order_ts as date) as order_date, status
from {{ source('shop', 'orders') }}
""",
    'fct_daily_orders': """
{{ config(materialized='table') }}
select order_date, count(*) as orders
from {{ ref('stg_orders') }}
group by order_date
""",
}

project = minidbt.Project(models=models)
project.build()
duckdb.sql("select * from fct_daily_orders order by order_date limit 3").show()

minidbt is a small copy of dbt written for this course (open minidbt.py to read it). It builds into DuckDB and prints a log shaped like dbt's. Here source('shop', 'orders') loads data/orders.csv as the raw table shop.orders. By habit, stg_ marks a model that cleans one raw table and fct_ a table people read, often called a mart (Lesson 8.2).

What you wrote, and what dbt sent

Model fileYou wrotedbt compiled it toand ran
stgorders.sqlfrom {{ source('shop', 'orders') }}from shop.orderscreate view main.stgorders as select ...
fctdailyorders.sqlfrom {{ ref('stgorders') }}from main.stgorderscreate table main.fctdailyorders as select ...

You wrote only the SELECT. dbt added the schema (main here; analytics or dbt_alex in a real warehouse) and the CREATE statement. With no config() line a model becomes a view. The config() line in the second model asked for a table.

Remember: you write the SELECT. dbt writes the CREATE around it and fills in the table names.

Every ref() is an arrow

Now the part that fixes Monday.

When dbt starts, it reads every model and collects its ref() and source() calls. Each call is an arrow: stg_orders → fct_daily_orders means "build the first before the second".

Together the arrows form a graph. They point one way and never loop back. That kind of graph is called a DAG, a directed acyclic graph.

dbt then builds each model only after everything it reads. You never write the order down, so you cannot get it wrong. Models that do not depend on each other can run at the same time: that is dbt's threads setting.

dbt run, one model at a time

A graph of two raw tables, two staging models and one mart. Step by step dbt reads all files, builds stg_customers, then stg_orders, then fct_daily_orders, which waits for stg_orders.

  1. Read everything first. dbt reads the three model files and draws an arrow for every source() and ref(). Nothing has run yet.

  2. 1 of 3: stg_customers. It reads only a raw table, and raw tables are already there. So it is ready, and dbt builds it.

  3. 2 of 3: stg_orders. Also ready, for the same reason. With one thread, dbt builds the ready models one after the other.

  4. 3 of 3: fct_daily_orders. Its parent stg_orders is built, so now it may run. The sum can never jump ahead of the cleaning again.

Follow the arrows: a model turns green only after everything that points into it. The counts match the log of real dbt in the next card.

The same run in real dbt

Runs with dbt:

$ find models -name '*.sql'
models/staging/stg_orders.sql
models/staging/stg_customers.sql
models/marts/fct_daily_orders.sql
$ dbt run
12:01:07  Running with dbt=1.x.x
12:01:07  Registered adapter: duckdb=1.x.x
12:01:08  Found 3 models, 2 sources, 416 macros
12:01:08
12:01:08  Concurrency: 1 threads (target='dev')
12:01:08
12:01:08  1 of 3 START sql view model main.stg_customers ................ [RUN]
12:01:08  1 of 3 OK created sql view model main.stg_customers ........... [OK in 0.05s]
12:01:08  2 of 3 START sql view model main.stg_orders ................... [RUN]
12:01:08  2 of 3 OK created sql view model main.stg_orders .............. [OK in 0.03s]
12:01:08  3 of 3 START sql table model main.fct_daily_orders ............ [RUN]
12:01:08  3 of 3 OK created sql table model main.fct_daily_orders ....... [OK in 0.06s]
12:01:08
12:01:08  Finished running 2 view models, 1 table model in 0 hours 0 minutes and 0.31 seconds (0.31s).
12:01:08
12:01:08  Completed successfully
12:01:08
12:01:08  Done. PASS=3 WARN=0 ERROR=0 SKIP=0 TOTAL=3

Each model is a file, and the file name is the model's name. Real dbt prints a START line and a time for every step; minidbt leaves those out so its output is the same on every run. The version numbers, the macro count and the times depend on your install.

Build one model and what it needs

You do not have to rebuild the whole project every time. Because dbt holds the graph, you can point at one model and ask for its neighbours too. A plus sign does it:

  • +fct_daily_revenue means the model and everything before it: all it reads, back to the raw tables.
  • stg_orders+ means the model and everything after it: all that reads it.

In real dbt you write dbt run --select stg_orders+.

Try it in the picture, then in code. The code also prints the compiled SQL: your model with the Jinja filled in, exactly as the warehouse will get it.

SwiftKart's models as a graph

SwiftKart's dbt models drawn from the raw sources on the left, through staging models, to the marts on the right, built in dependency order; a failing test stops the models after it.

Press Build and watch the order. Then select +fct_daily_revenue to build one model and everything it needs.

Read the graph and the compiled SQL

import minidbt

models = {
    'fct_customer_orders': """
select c.customer_id, c.name, count(o.order_id) as orders
from {{ ref('stg_customers') }} as c
left join {{ ref('stg_orders') }} as o on o.customer_id = c.customer_id
group by c.customer_id, c.name
""",
    'stg_orders': "select order_id, customer_id, status from {{ source('shop', 'orders') }}",
    'stg_customers': "select customer_id, name, country from {{ source('shop', 'customers') }}",
}
project = minidbt.Project(models=models)
project.lineage()
print(project.ls())
print(project.ls('stg_orders+'))
print(project.compile('fct_customer_orders'))

lineage() prints who reads whom; dbt people call that graph the lineage. The dictionary lists the mart first, but ls() returns the models in build order (real dbt ls lists the same models, sorted by name). ls('stg_orders+') picks stg_orders and the mart that reads it. compile(), like dbt compile, prints the plain SQL and runs nothing.

Remember: the build order comes from the ref() calls. Not from the file names, and not from the order you typed them.

A typo stops the run before it starts

What if a model points at something that is not there?

With a folder of scripts you find out halfway: three tables rebuilt, then an error, and a warehouse that is half new and half old.

dbt works differently. Before it runs anything, it reads every file and collects every ref(), source() and config() into one list of the whole project. The reading is called parsing, and the list is the manifest. Only then does it fill in the Jinja, which is called compiling, and send SQL to the warehouse.

So a typo in a ref(), or two models that read each other, is found while parsing. The picture follows one model through all the stages.

One model file, start to finish

Five steps for one model: the SQL file, parsing it into the manifest, compiling its Jinja into plain SQL, running it wrapped in a CREATE statement, and recording the result in run_results.json.

Read it left to right. dbt parses every file before it runs any of them, which is why a broken ref() or a loop stops the whole run at the start. Lesson 8.6 opens up each stage.

Caught before anything runs

import minidbt

minidbt.Project(models={
    'stg_orders': "select * from {{ source('shop', 'orders') }}",
    'fct_daily_orders': "select count(*) as n from {{ ref('stg_order') }}",
})

It stops with an error, and that is the point: no table was touched. Real dbt says almost the same: Model 'model.swiftkart.fct_daily_orders' depends on a node named 'stg_order' which was not found.

The mistake dbt cannot catch: a hard-coded table name. from main.stg_orders works on your laptop. But dbt no longer sees the dependency. It may build the mart before the staging model, or read yesterday's copy, and the same code cannot build into both dev and prod. Read models through ref() and raw tables through source(), always.

The same files, three places to build

ref('stg_orders') becomes a full table name, schema included. Which schema?

That depends on where you run. dbt calls the place a target. A developer's target builds into their own schema, such as dbt_alex. Each pull request, a proposed change that is tested automatically (that testing is called CI), gets a fresh schema. Production uses analytics.

A folder can also ask for a custom schema, with +schema: staging. dbt does not use staging alone. A built-in helper, the macro generate_schema_name, glues it onto the target's schema: dbt_alex_staging for the developer, analytics_staging in production.

It appends on purpose. With plain staging, every developer would build into one schema and overwrite each other's work.

generate_schema_name, for three targets

from types import SimpleNamespace
import minidbt

# dbt's default generate_schema_name, as the docs print it (minus the trim filter)
MACRO = """
{% macro generate_schema_name(custom_schema_name) %}
{%- if custom_schema_name is none -%}{{ target.schema }}{%- else -%}{{ target.schema }}_{{ custom_schema_name }}{%- endif -%}
{% endmacro %}
"""
for env in ['dbt_alex', 'dbt_cloud_pr_123_456', 'analytics']:
    target = SimpleNamespace(schema=env)
    staging = minidbt.render(MACRO + "{{ generate_schema_name('staging') }}", target=target)
    default = minidbt.render(MACRO + "{{ generate_schema_name(none) }}", target=target)
    print(f'{env:<22} +schema: staging -> {staging:<30} no custom schema -> {default}')

This is the macro dbt ships, run through minidbt's small Jinja (which has no | trim filter). target.schema comes from the profile, so the same project lands in different schemas with no code change.

One project, three targets

Three boxes for the dev, CI and production targets, each holding a staging schema built from the target schema plus the custom schema, and a schema for the marts.

Read each box as one place to build: its staging schema is the target's schema plus _staging. A pull request's schema starts empty, so a model there can only read parents that were built there too. Lesson 8.6 shows a shortcut, --defer.

Numbers to remember

NameWhat to remember
Default build of a modela view; {{ config(materialized='table') }} asks for a table (Lesson 8.2)
threadshow many models that do not depend on each other dbt runs at the same time
+name and name+the model with everything before it; the model with everything after it
profiles.ymlwhere each target and its schema are set
Custom schema<targetschema<customschema, built by generateschemaname; teams that want plain staging in production override the macro in their own project
A model's table namethe file name, unless alias says otherwise; a versioned model becomes namev2 (Lesson 8.3)
target/ foldercompiled/ holds the plain SQL, run/ what was sent, runresults.json the status and seconds
dbt Corefree and open source: a command-line tool you run on a laptop, in CI or from an orchestrator
dbt platformthe paid hosted service with a web editor and a scheduler; it used to be called dbt Cloud
dbt v2dbt Labs' current engine, written in Rust, first announced as Fusion; it understands SQL. The Python engine is maintained as dbt v1
Adaptershow dbt talks to Snowflake, BigQuery, Databricks, Redshift, Postgres, DuckDB and more

Models, ref(), tests and YAML work the same way on all of these. The job title analytics engineer grew up around dbt.

What changed at SwiftKart

The eleven scripts are now eleven models. Each one says what it reads, with ref() or source(), so the order lives in the code and not on a wiki page.

One dbt run builds every model after its parents, and a typo stops the run before a table is touched. On Tuesday Tess opens the dashboard and Sunday has its orders.

The project will not stay small. Soon there are 30 models in one folder, and three of them clean the raw orders, each a little differently. Lesson 8.2 sorts the models into layers and decides which become views and which become tables.

In one line

A dbt model is one SELECT in a file; ref() and source() say what it reads, so dbt builds every model in the right order, inside the warehouse.

Interview corner

What is dbt, and what does it not do?

dbt is a transformation framework: each model is a SELECT in a file, and dbt turns models into views and tables inside the warehouse in dependency order, with tests and docs. It is the T of ELT. It does not extract or load data; a loader such as Fivetran, Airbyte, Azure Data Factory or custom code lands the raw data first.

What does ref() do, and why not hard-code table names?

ref('stg_orders') returns the right relation name for the current environment and records an edge in the DAG, so dbt builds stg_orders before anything that reads it. A hard-coded name hides the dependency, can read a stale table, and breaks when the same project builds into a dev schema and a prod schema.

What happens when you type dbt run?

dbt parses every model and YAML file, builds the DAG from ref() and source(), compiles the Jinja into plain SQL, then runs each model in dependency order (in parallel threads where the graph allows), wrapping each SELECT in the DDL for its materialisation. It writes the results and artifacts such as manifest.json and run_results.json to the target/ folder.

Five developers run dbt against the same warehouse at once. Why do they not overwrite each other, and how does a model end up in analytics_marts in production?

Every target in profiles.yml has its own schema, and ref() resolves to the current target, so Alex builds into dbt_alex and production into analytics. A folder with +schema: marts goes through generate_schema_name, which by default appends the custom schema: dbt_alex_marts for Alex, analytics_marts in production. Appending is deliberate, because using the custom schema alone would put everyone in one schema. Teams that want exactly marts in production override the macro to use the custom schema only when the target is prod.