BigQuery
Connection
Section titled “Connection”Non-secret settings in workflow_settings.yaml (committed):
warehouse: bigquerydefaultProject: my-gcp-project # GCP project IDdefaultLocation: US # BigQuery regiondefaultDataset: analytics # default dataset for actionssqlanvilCoreVersion: 1.39.0 # pin the release you installed — `sqlanvil init` writes thisAuth lives in .df-credentials.json (gitignored). For BigQuery you typically only need the project
and location — credentials resolve via Application Default Credentials
(gcloud auth application-default login locally, or an attached service account in CI):
{ "projectId": "my-gcp-project", "location": "US" }The two locations should normally match. If they differ, defaultLocation wins: run and
validate send BigQuery jobs and create new datasets there, and run prints a warning (since
1.36.2; earlier releases used the credentials file’s location).
Both locations are optional (since 1.38.0; init and init-creds used to require one). With
neither set, BigQuery infers each job’s location from the tables it reads, and a new dataset is
created in the location of the data read by the first action writing to it (US if that action
reads no tables), since 1.40.0; earlier releases created it in US. A script that runs
SET @@dataset_id still needs a location, because BigQuery does not infer it from that
statement; run warns when an action does this with no location set.
run creates a missing dataset when the first action that writes to it runs, not up front
(since 1.40.0). Tables, views, incremental tables, assertions and imports create their target
dataset. An operation creates it only when it declares hasOutput: true; otherwise add
CREATE SCHEMA IF NOT EXISTS to the operation itself. Exports never create one. Dry runs never
create datasets but still check each query in full, and a disabled action never causes one to
be created.
To use an explicit service account instead of ADC, add its key JSON as a credentials field.
To run as a service account without holding its key, add impersonateServiceAccount (since
1.36): the CLI impersonates it using your ADC identity (or the credentials key) as the source,
which needs roles/iam.serviceAccountTokenCreator on that account. sqlanvil init-creds asks for
it as an optional last step and runs the connection test as the impersonated account:
{ "projectId": "my-gcp-project", "location": "US", "impersonateServiceAccount": "etl@my-gcp-project.iam.gserviceaccount.com" }For keyless setups, provide a short-lived OAuth2 accessToken instead of a key — SQLAnvil
authenticates BigQuery with it directly (precedence: accessToken → impersonateServiceAccount → credentials key → ADC). This
suits callers that already run inside GCP and can mint a token by impersonating a service account
(e.g. SQLAnvil Cloud’s runner), so no key is ever written. Tokens are short-lived (≈1h):
{ "projectId": "my-gcp-project", "location": "US", "accessToken": "ya29...." }Running in production
Section titled “Running in production”If you’re coming from Dataform, its workflow configurations let each scheduled workflow run as a service account or an authenticated account. The same shapes map directly onto SQLAnvil’s auth modes — usually with no key ever written:
| Where it runs | How it authenticates |
|---|---|
| Your machine | ADC from gcloud auth application-default login — the secretless { projectId, location } credentials file is all you need (Dataform-local parity). |
| GCP compute (Cloud Run, GCE, Cloud Build, Composer…) | The attached service account is ADC — the identical secretless file works unchanged. This is the closest analog of a Dataform service-account workflow. |
| External CI (GitHub Actions…) | Keyless via Workload Identity Federation: the workflow mints a short-lived token (e.g. google-github-actions/auth) and passes it as accessToken. No stored key. |
| Anywhere, with a key | A service-account key in the credentials field — supported, but prefer the keyless rows above. |
Per-workflow splits — different projects, datasets, or identities for dev/test/prod — are
named environments: each environment can override
defaultDatabase (the GCP project), add a schemaSuffix, and point at its own credentials
file, selected at run time with --environment <name>.
Partitioning and clustering
Section titled “Partitioning and clustering”Use partitionBy and clusterBy in the action config block:
-- definitions/orders.sqlxconfig { type: "table", partitionBy: "DATE(created_at)", clusterBy: ["customer_id", "region"], partitionExpirationDays: 90}
SELECT order_id, customer_id, region, created_atFROM ${ref("raw_orders")}Incremental tables
Section titled “Incremental tables”SQLAnvil generates a BigQuery MERGE statement for incremental tables:
-- definitions/events_incremental.sqlxconfig { type: "incremental", uniqueKey: ["event_id"], partitionBy: "DATE(event_timestamp)"}
SELECT event_id, event_timestamp, user_id, event_nameFROM ${ref("raw_events")}${when(incremental(), `WHERE event_timestamp > (SELECT MAX(event_timestamp) FROM ${self()})`)}insert_overwrite (1.29+)
Section titled “insert_overwrite (1.29+)”When a run recomputes a date range rather than matching individual rows, a MERGE on a
uniqueKey is the wrong instrument: it needs a key, and it leaves behind any row the recomputed
range no longer produces. incrementalStrategy: "insert_overwrite" replaces every partition
the incremental output touches instead — rows that disappear from a reprocessed day disappear from
the table.
config { type: "incremental", incrementalStrategy: "insert_overwrite", bigquery: { partitionBy: "event_date", // Optional: narrow what the replacement is allowed to touch. incrementalPredicates: ["T.event_date >= '2026-01-01'"] }}
SELECT event_date, user_id, count(*) AS eventsFROM ${ref("raw_events")}${when(incremental(), `WHERE event_date >= current_date() - 3`)}GROUP BY 1, 2partitionBy is required — without a partition column there is nothing to scope the replacement to,
and SQLAnvil fails the compile rather than truncate the table. No uniqueKey is needed. In
incrementalPredicates, T is the destination and S the staged rows.
BigQuery only. On Postgres, Supabase or MySQL the strategy is a compile error naming that
reason — it is not silently downgraded to a merge, because that would be a run that succeeds and
writes different rows than you asked for. Use the default merge with a uniqueKey there, or delete
the range you are replacing in a pre_operations block.
Schema changes (onSchemaChange)
Section titled “Schema changes (onSchemaChange)”onSchemaChange decides what an incremental run does when the query’s columns no longer match the
table’s:
| Value | Behaviour |
|---|---|
IGNORE (default) | No comparison. The write uses the columns the table already has. |
FAIL | Fails the run, naming the added and removed columns. |
EXTEND | Adds new columns to the table; fails if a column was removed. |
SYNCHRONIZE | Adds new columns and drops removed ones, but never a uniqueKey column. |
config { type: "incremental", uniqueKey: ["event_id"], onSchemaChange: "EXTEND"}FAIL, EXTEND and SYNCHRONIZE work from 1.32.8; before that, every run that used them
failed.
From 1.39.0 the whole append runs inside one BigQuery script: the schema change, then the insert or merge built from the columns as they are after it, so the run that adds a column fills it and the run that drops one succeeds. Pre- and post-operations run in the same script. From upstream Dataform #2320.
From 1.41.0 that script is a plain block, with no stored procedure created in your dataset, and
it stages the incremental query before any ALTER TABLE: a query that fails at run time stops the
run with the table’s columns and rows untouched. Added and dropped column names are quoted, so
reserved words and hyphenated names work, and SYNCHRONIZE refuses to drop a unique-key column
whatever case or backticks the key is written with. From upstream
#2503,
#2511 and
#2498.
BigQuery only. On Postgres, Supabase and MySQL, onSchemaChange compiles but has no effect:
an incremental run writes only the columns the table already has.
Governance controls
Section titled “Governance controls”preserveGovernanceControls: true keeps BigQuery column governance controls (e.g. data policies)
attached when SQLAnvil recreates a table. Set it per-table, or as a default in
workflow_settings.yaml. BigQuery only.
Since 1.32.7 it also applies to type: "incremental" tables, where a --full-refresh
recreates the table and is exactly when those controls would otherwise be lost.
Labels
Section titled “Labels”Attach BigQuery labels to any action for cost tracking:
config { type: "table", labels: { team: "analytics", env: "production" }}SELECT ...Materialized views
Section titled “Materialized views”config { type: "view", materialized: true, partitionBy: "DATE(created_at)"}SELECT ...BigQuery reservations
Section titled “BigQuery reservations”To run actions on a specific BigQuery reservation (slot commitment):
defaultReservation: projects/my-project/locations/US/reservations/my-reservationOr per-action in YAML:
actions:- table: filename: heavy_model.sql reservation: projects/my-project/locations/US/reservations/heavyAdditional BigQuery options
Section titled “Additional BigQuery options”Pass arbitrary BigQuery table options via additionalOptions:
config { type: "table", additionalOptions: { kms_key_name: "projects/my-proj/locations/us/keyRings/my-ring/cryptoKeys/my-key" }}SELECT ...Assertions
Section titled “Assertions”SQLAnvil generates assertion views in BigQuery under your defaultDataset. A failing assertion (one that returns rows) is reported as an error:
config { type: "assertion"}SELECT * FROM ${ref("orders")} WHERE order_total < 0