Dataform for SQL-Based Data Transformation
What You'll Learn
- 1Explain what Dataform owns and what BigQuery still does at runtime
- 2Lay out a repository with declared sources, staging, intermediate, and mart layers
- 3Write assertions and incremental models that protect the marts a business reads
- 4Schedule compiled graphs with Composer or Cloud Scheduler and keep runs selective
Dataform is a SQL transformation IDE and scheduler that compiles a repository of SQLX files into a BigQuery execution graph. BigQuery still runs every query; Dataform decides what runs, in what order, with which table names, and what tests must pass before a downstream model is allowed to refresh. Teams reach for it when a collection of scheduled console queries has outgrown the ability to reason about dependencies, ownership, and data quality.
Repository Layout and Configuration
A Dataform project mirrors the layering of the warehouse. Sources are declared tables owned by other systems, staging models clean them one-to-one, intermediate models join and reshape, and marts expose business grain tables. One root configuration file carries the warehouse target, default schemas, and environment variables that templating reads.
warehouse/
dataform.json
definitions/
sources/raw_events.sqlx
staging/stg_events.sqlx
staging/stg_accounts.sqlx
intermediate/int_sessions.sqlx
marts/daily_active_users.sqlx
tests/assert_session_integrity.sqlx
{
"warehouse": "bigquery",
"defaultDatabase": "analytics-project",
"defaultSchema": "dataform",
"assertionSchema": "dataform_assertions",
"defaultLocation": "US",
"variables": {
"environment": "production",
"lookback_days": "30"
}
}
Compile reads every file in definitions, so naming conventions are the only directory structure the tool respects: put files where the layer discipline says they belong, and the graph will match the architecture diagram on the wall. Repositories connect to a Git remote, which means every change to a model is a reviewable diff and every production run can be pinned to a commit rather than to whatever happened to be on the branch. The default schema in dataform.json becomes the namespace for compiled relations, so promotion between environments is a matter of overriding the database and schema at compile time instead of rewriting table names.
Local Compilation Loop
Before anything reaches BigQuery, the compiler runs locally and in CI with the same logic the service uses. The Dataform CLI installs from npm against the repository, reads dataform.json, and emits compiled SQL plus a resolved graph you can inspect. Compilation catches missing refs, cyclic dependencies, and malformed config blocks in seconds, which is the entire point: a warehouse refactor should fail on a laptop, not two hours into a nightly run.
# Install the CLI, compile the graph, and list what would run.
npm install -g @dataform/cli
dataform compile --project-path=.
dataform run --project-path=. --tags=daily
Teams that wire compile into pull request checks stop a whole class of merge accidents, including the classic rename that updates the definition file but forgets the three models that ref the old name. Once compilation is a gate, refactoring becomes mechanical: change the name, run compile, fix every error the compiler lists, and the graph is consistent again.
Sources and Staging
Declared sources register externally owned tables so models can ref them without hardcoding fully qualified names. Staging models then normalise: consistent types, trimmed strings, standard null handling, and a loaded_at column. Staging views are cheap because BigQuery views do not store data; they compile inline into the queries that read them.
-- definitions/sources/raw_events.sqlx
config {
type: "declaration",
database: "ops-replica",
schema: "events",
name: "raw_events",
description: "Product event stream replicated from the operational database"
}
-- definitions/staging/stg_events.sqlx
config {
type: "view",
schema: "staging",
description: "Typed and trimmed product events"
}
SELECT
CAST(event_id AS STRING) AS event_id,
LOWER(TRIM(CAST(user_id AS STRING))) AS user_id,
CAST(event_name AS STRING) AS event_name,
CAST(event_ts AS TIMESTAMP) AS event_ts,
CAST(device_type AS STRING) AS device_type,
CURRENT_TIMESTAMP() AS loaded_at
FROM {{ ref("raw_events") }}
WHERE event_id IS NOT NULL
Keeping staging one-to-one with sources makes bugs easy to bisect: if a mart looks wrong, compare its intermediate parent, then the staging parent, then the raw table, and the first hop where numbers diverge is the broken layer.
Intermediate Models and Marts
Intermediate models do the expensive joins and window functions once, so many marts can read a single enriched surface. Marts are the public interface: stable grain, documented columns, and only the columns consumers were promised. Wide tables with speculative columns become maintenance debt the first time upstream renames something.
-- definitions/intermediate/int_sessions.sqlx
config {
type: "table",
schema: "intermediate",
tags: ["hourly"],
description: "Sessions built from raw events with a 30-minute gap rule"
}
WITH ordered AS (
SELECT
user_id,
event_ts,
event_name,
TIMESTAMP_DIFF(
event_ts,
LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts),
MINUTE
) AS minutes_since_prev
FROM {{ ref("stg_events") }}
),
sessionised AS (
SELECT
user_id,
event_ts,
event_name,
SUM(CASE WHEN minutes_since_prev IS NULL OR minutes_since_prev >= 30 THEN 1 ELSE 0 END)
OVER (PARTITION BY user_id ORDER BY event_ts) AS session_num
FROM ordered
)
SELECT
user_id,
session_num,
MIN(event_ts) AS session_start,
MAX(event_ts) AS session_end,
COUNT(*) AS event_count,
COUNT(DISTINCT event_name) AS distinct_events
FROM sessionised
GROUP BY 1, 2
-- definitions/marts/daily_active_users.sqlx
config {
type: "table",
schema: "marts",
tags: ["daily", "product"],
description: "One row per user per day with session rollups"
}
SELECT
user_id,
DATE(session_start) AS activity_date,
COUNT(*) AS sessions,
SUM(event_count) AS events,
MAX(session_end) AS last_seen
FROM {{ ref("int_sessions") }}
WHERE session_start >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 90 DAY)
GROUP BY 1, 2
Assertions
Assertions are the regression suite of a warehouse. Each one is a query whose result rows are violations; zero rows means the check passed. Write them next to the layer they protect and tag them so selective runs are possible.
-- definitions/tests/assert_sessions_have_ends.sqlx
config {
type: "assertion",
dataset: "intermediate",
tags: ["hourly", "quality"],
description: "Sessions must close and contain at least one event"
}
SELECT
user_id,
session_num,
session_start,
session_end,
event_count
FROM {{ ref("int_sessions") }}
WHERE session_end IS NULL
OR session_end < session_start
OR event_count <= 0
The highest-value assertions are the ones that catch upstream breaks before consumers do: primary key uniqueness on marts, non-null foreign keys into dimension tables, and volume checks that fire when row counts fall off a cliff after an upstream deploy. A practical starting set for every mart is three assertions: uniqueness of the declared grain, non-null on the key columns, and a freshness check that fails when the newest partition is older than the service level promises. Beyond those, add domain rules as they encode real invariants, such as status values inside a known enum or amounts within a plausible range, and retire rules that fire on legitimate edge cases so the team keeps trusting the suite. Assertion failures should page the owning team, not merely colour a dashboard, because a silent quality gate is indistinguishable from no gate at all.
Incremental Models
Full rebuilds of large event tables stop being affordable somewhere in the low terabytes. Incremental models maintain a table by appending or merging only the partition window that changed, guided by a unique key that defines merge identity.
-- definitions/marts/event_rollups.sqlx
config {
type: "incremental",
schema: "marts",
uniqueKey: ["event_date", "event_name"],
incrementalStrategy: "merge",
tags: ["daily"]
}
SELECT
DATE(event_ts) AS event_date,
event_name,
COUNT(*) AS event_count,
COUNT(DISTINCT user_id) AS users
FROM {{ ref("stg_events") }}
WHERE DATE(event_ts) >= DATE_SUB(CURRENT_DATE(), INTERVAL {{ var("lookback_days") }} DAY)
GROUP BY 1, 2
Merge on event_date and event_name means late-arriving rows for a past day rewrite that day's rollup instead of double-counting it. The lookback window bounds how far back each run reprocesses, which is the operational dial between freshness and cost.
JavaScript Templating
SQLX accepts JavaScript between SQL fragments, which is how one model serves several environments or generates repetitive SQL without a macro language. Temptation is to write clever generators; restraint keeps the repository compilable by humans who are debugging at midnight.
-- definitions/marts/recent_activity.sqlx
config {
type: "view",
schema: "marts",
description: "Environment-aware recent activity view"
}
SELECT *
FROM {{ ref("daily_active_users") }}
WHERE activity_date >= DATE_SUB(
CURRENT_DATE(),
INTERVAL {{ 1 * parseInt(dataform.projectConfig.vars.lookback_days, 10) }} DAY
)
Scheduling
Compiled graphs run through workflow invocations: the Dataform API accepts a workflow config with a cron schedule, or Cloud Composer's Dataform operators compile a commit and invoke it with tag filters. Cloud Scheduler with an OIDC-authenticated HTTP call is enough when the warehouse run has no upstream dependencies to sense.
# Trigger a tag-scoped workflow invocation with the Dataform API.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://dataform.googleapis.com/v1beta1/projects/analytics-project/locations/us-central1/repositories/warehouse/workflowInvocations" \
-d '{
"compilationResult": "projects/analytics-project/locations/us-central1/repositories/warehouse/compilationResults/latest",
"invocationConfig": {
"includedTags": ["daily"],
"transitiveDependenciesIncluded": true
}
}'
Pair the invocation with BigQuery job failure alerts, and treat a green workflow with an empty output table as a failure worth paging on. Data quality is a property of the data, not only of the scheduler's exit code.
Cost Behaviour
Dataform itself is free of per-query charges; BigQuery bills every compiled SQL statement the invocation runs. That means view-heavy designs pay at query time while table designs pay at refresh time, and incremental models sit in between, scanning only the lookback window. Profile the compilation graph with BigQuery execution statistics after every material change to grain, because a new group-by key that explodes cardinality will show up first as a longer refresh, then as a bill. As a worked shape: a full rebuild of a 500 GB events table nightly costs the scan of 500 GB per night, while an incremental model with a three-day lookback on a partitioned table scans a fraction of that, typically the partitions touched plus the merge targets. The trade-off is operational rather than purely financial, because incremental models need unique keys and late-arriving data discipline that full rebuilds never demand. Choose them when the arithmetic forces the choice, not because incrementality sounds mature.
Common Mistakes
Hardcoding dataset and table names in model SQL
Fix: Declare sources and use ref so environment promotion is a configuration change rather than a find-and-replace across files.
Skipping transitive dependencies on scheduled invocations
Fix: Enable them so changed staging models rebuild the intermediates and marts that read them, or accept stale marts after upstream fixes.
Treating a green workflow as proof the data is right
Fix: Pair every important mart with assertions on grain, nulls, and volume; execution success only proves SQL ran, not that it ran on sane input.
Best Practices
- Enforce layering in the repository layout so ownership and blast radius stay obvious
- Tag models and assertions together and invoke nightly runs by tag for fast feedback
- Review compiled SQL diffs in pull requests, not only the SQLX source, because templating hides the final query
Key Takeaways
- Dataform compiles SQLX into a dependency graph and executes it against BigQuery; the warehouse still does the work
- Ref creates graph edges and resolves names, which turns layering mistakes into compile failures
- Assertions pass by returning zero rows, so tests read as lists of violations
- Incremental models with merge keys and lookback windows keep big event tables affordable to refresh
Interview Questions
Interview Questions
Q1: What does ref actually do at compile time?
It resolves a model name into its database, schema, and relation per the current compilation target, records a dependency edge, and fails compilation if the target model does not exist or would create a cycle.
Q2: How do assertions differ from BigQuery tests written by hand?
They live in the repository next to models, compile into the graph, run as part of invocations with tag scoping, and fail the workflow when they return rows, so quality gates cannot be forgotten.
Q3: When is an incremental model the wrong choice?
When the logic is not append-friendly, such as window functions over full history or frequent historical corrections; those need full rebuilds or partition-scoped rebuilds driven by an external backfill list.
Q4: How does Dataform compare to dbt for a BigQuery shop?
The modelling concepts are equivalent; Dataform adds managed git integration, releases, and native BigQuery scheduling, while dbt brings a larger plugin ecosystem and more community momentum.