🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Dataform: SQLX, Compilation, Assertions & Scheduling

GCP Data EngineeringDataformđŸŸĸ Free Lesson

Dataform Deep Dive

Master Dataform including SQLX transformations, compilation, assertions, scheduling, and BigQuery integration.

16 min readIntermediate

What You'll Learn

  • 1Trace how a SQLX file becomes a BigQuery job through compilation
  • 2Model dependencies with ref and declare so the graph enforces layering
  • 3Write assertions that catch nulls, duplicates, and broken referential integrity
  • 4Schedule selective runs with tags, releases, and workflow configs

Dataform is the managed transformation layer for BigQuery: you write SQLX files, Dataform compiles them into plain SQL with resolved table names, builds a dependency graph, and executes the graph in order as a workflow. The service is opinionated about correctness, which is why teams adopt it over hand-rolled SQL scripts: every model is declared, every dependency is explicit, and every business rule can ship as an executable assertion.

From SQLX to BigQuery Jobs

A SQLX file is a config block plus SQL, with optional JavaScript templating. Compilation reads the config, resolves every ref into a fully qualified relation such as project.dataset.model, checks that referenced models exist, and emits a compiled graph. Execution then runs that graph, creating or replacing views and tables and running assertion queries, inside the datasets named by the configs.

-- definitions/staging/stg_orders.sqlx
config {
  type: "view",
  schema: "staging",
  description: "Cleaned order records from the raw feed"
}

SELECT
  SAFE_CAST(order_id AS STRING) AS order_id,
  SAFE_CAST(customer_id AS STRING) AS customer_id,
  SAFE_CAST(amount AS FLOAT64) AS amount,
  SAFE_CAST(order_ts AS TIMESTAMP) AS order_ts,
  CURRENT_TIMESTAMP() AS loaded_at
FROM {{ ref("raw_orders") }}
WHERE order_id IS NOT NULL

The ref call does two jobs at once: it provides the relation name at compile time and it creates a graph edge so the staging view is built before anything that depends on it. Refusing to compile on unknown refs turns typo-level mistakes into CI failures instead of 3 a.m. BigQuery errors.

Modelling the Dependency Graph

Dataform graphs have three node types worth distinguishing. Declared sources register tables owned by other systems, such as a replicated operational database, without Dataform managing their contents. Models are the views, tables, and incremental tables you own. Assertions are test queries attached to models. The compile step validates that every ref resolves, that no cycle exists, and that the invocation scope, such as a tag filter, is consistent with the graph.

-- definitions/sources/raw_orders.sqlx
config {
  type: "declaration",
  database: "ops-replica",
  schema: "public",
  name: "orders",
  deleted: false
}

Declaring sources pays off during migrations: when the operational feed moves from one project to another, the change lands in one declaration file instead of rippling through dozens of models that hardcoded project.dataset.table strings. Graph shape is also a reviewable artefact: compilation outputs the resolved DAG, so a pull request that adds an edge from a mart directly to a source shows up plainly in the graph diff, even when the SQL itself looks innocuous. Teams that print the graph into CI artifacts find structural regressions early, and the same artefact doubles as documentation for the on-call engineer staring at a failed invocation at odd hours.

Assertions as Executable Contracts

Assertions compile to queries whose rows represent violations. An assertion passes when its query returns zero rows and fails otherwise, which inverts the usual test mental model: you write the conditions that indicate broken data, not the conditions that indicate healthy data.

-- definitions/tests/assert_orders_usable.sqlx
config {
  type: "assertion",
  dataset: "staging",
  tags: ["daily", "orders"],
  description: "Orders must have ids, positive amounts, and valid timestamps"
}

SELECT
  order_id,
  amount,
  order_ts
FROM {{ ref("stg_orders") }}
WHERE order_id IS NULL
   OR amount IS NULL
   OR amount <= 0
   OR order_ts IS NULL

Split assertions into focused files rather than one mega-check, so a failure names the rule that broke. Tag them with the layer they protect so a workflow invocation can run only the staging assertions on a fast feedback loop while the nightly run executes everything.

Incremental Models and Merge Keys

Full rebuilds are simple but do not scale past the largest table you are willing to reprocess nightly. Incremental models append or merge only new data, gated by a condition that is usually a timestamp comparison. The unique key determines merge semantics: matching keys update, new keys insert.

-- definitions/marts/orders_daily.sqlx
config {
  type: "incremental",
  schema: "marts",
  uniqueKey: ["order_date"],
  incrementalStrategy: "merge",
  tags: ["daily", "finance"]
}

SELECT
  DATE(order_ts) AS order_date,
  COUNT(*) AS order_count,
  SUM(amount) AS revenue
FROM {{ ref("stg_orders") }}
WHERE DATE(order_ts) >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
{% if var("full_refresh") %}
  -- Full rebuild window forced by the invoking workflow.
  AND TRUE
{% else %}
  AND DATE(order_ts) >= DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY)
{% endif %}
GROUP BY 1

The full-refresh escape hatch matters operationally: after a backfill or a schema change, a scheduled run must be able to rebuild the whole table without editing the model. Pass full_refresh as a workflow variable and the same SQLX covers both paths.

Scheduling and Selective Runs

Dataform exposes scheduling through workflow configurations attached to a git commitish, usually a release ref that pins production to reviewed commits. Each workflow config carries a cron expression, a default compilation target, and optional tags or included dependencies that narrow the run. Cloud Composer can drive the same graph with the Dataform provider operators when the warehouse run must sit inside a larger orchestration with sensors and SLAs.

python
from google.cloud import dataform_v1beta1

client = dataform_v1beta1.DataformClient()
repo = "projects/my-project/locations/us-central1/repositories/warehouse"

invocation = client.create_workflow_invocation(
    request={
        "parent": f"{repo}/workspaces/main",
        "workflow_invocation": {
            "workflow_config": "daily_marts",
            "invocation_config": {
                "included_tags": ["daily"],
                "transitive_dependencies_included": True,
            },
        },
    }
)
print(invocation.name)

Transitive dependency inclusion is the difference between running only tagged nodes and running everything those nodes read. Omit it and a changed staging view will not be rebuilt before the mart that depends on it, which produces stale-but-successful runs that are hard to detect.

Debugging Compilations and Invocations

Most failed Dataform runs fall into four buckets. A compile error usually means a broken ref, a syntax error in a config block, or JavaScript templating that throws for one environment. An assertion failure means the data changed; read the returned rows before changing the assertion, because the assertion is usually right. An execution timeout points at a model whose query plan regressed, often after upstream data skew appeared. A stale workflow config points at a commitish that was never updated when the release moved.

Local iteration runs through the CLI, which executes the same compiler as the service: dataform compile validates the graph, dataform run executes against a configured warehouse connection, and the compiler errors name file and line. Keeping compilation in CI on every pull request prevents most of the breakage that would otherwise surface during the nightly window. When an invocation does fail at runtime, start with the compilation result attached to it, because the compiled SQL is what BigQuery actually rejected, and the diff between compiled SQL for the last green run and the failing one usually names the offending model change in a single glance.

Failure modeWhere it surfacesFirst response
Broken ref or cyclecompile stepfix the graph edge, rerun compile
Data quality regressionassertion queryinspect violating rows before touching SQL
Plan regressionexecution timeoutcheck upstream partitions and skew
Stale code in prodsilent stalenessverify release commitish and config target

Dataform versus dbt

Feature-wise the overlap is large: layered models, tests, documentation, incremental strategies, and a CLI. The meaningful differences for a GCP shop are operational rather than syntactic. Dataform is a managed service with git integration in the console, native BigQuery job semantics, and first-class releases; dbt gives you a wider adapter ecosystem and a larger community, at the cost of hosting your own orchestration and CI glue. Teams already standardised on Airflow often run dbt through it; teams that want the warehouse lifecycle owned by GCP usually pick Dataform and keep Composer for cross-service orchestration.

Common Mistakes

Hardcoding project.dataset.table in models

Fix: Use ref and declare so renames and environment promotion change one declaration, not every SQL string.

Disabling transitive dependencies on scheduled runs

Fix: Include them so changed upstream models rebuild before dependent marts, or accept silent staleness after backfills.

Writing assertions that return healthy rows

Fix: Assertions pass on zero rows; invert your predicate so the query returns only violations.

Best Practices

  • Keep sources declared and models layered so the graph enforces ownership boundaries
  • Tag assertions alongside models and wire tags into workflow configs for targeted feedback
  • Pin production to a release ref and promote through releases rather than running main directly

Key Takeaways

  • Compilation resolves ref into fully qualified relations and fails the build on missing models or cycles
  • Assertions are queries that pass by returning zero rows, which turns data rules into executable tests
  • Incremental models need a unique key and a full-refresh escape hatch for backfills
  • Selective runs with tags plus transitive dependencies keep nightly workflows fast without going stale

Interview Questions

Interview Questions

Q1: How does Dataform resolve dependencies?

The ref function creates a graph edge and compiles into the target relation name; the compiler fails on unresolvable refs and cycles, so the graph is validated before any BigQuery job runs.

Q2: What happens when an assertion fails during a workflow?

The assertion query returns violating rows, the invocation marks that node failed, and dependent models are skipped or the workflow halts depending on configuration, preventing bad data from propagating.

Q3: How do you rebuild one model and everything it depends on?

Invoke the workflow with that model included and transitive dependencies enabled, or run it locally with the CLI; tags give the same control when several models share a rebuild reason.

Q4: When would you prefer Dataform over raw scheduled SQL?

When you need dependency-aware execution, tests as gates, environment promotion through releases, and reviewable git history; raw SQL scripts none of those, and each one is custom tooling you would have to build.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement