bruin-data/ingestr/bigquery-destination
Claude Code and agent skill by bruin-data/ingestr
- community
Checking that the SKILL.md file is still in the repository.
How the ingestr BigQuery destination works — the staging→swap write path, load methods (load_job/storage_write), where dedup happens, copy-job vs CTAS swap selection, partition/cluster change handling (rename-aside), and merge partition pruning. Use when changing anything in pkg/destination/bigquery/ or BigQuery-affecting behavior in the replace/merge strategies (pkg/strategy/replace.go, pkg/strategy/merge.go). If your change alters behavior described here, update this file in the same change.
Install
npx vskill@latest install bruin-data/ingestr/bigquery-destinationSKILL.md
The same SKILL.md was published earlier as bruin-data/ingestr/bigquery-destination.
BigQuery Destination — Implementation
How ingestr writes data to BigQuery, including how partition/cluster changes are handled.
Maintenance: this file documents current behavior. If your change alters anything described here, update the relevant section in the same PR.
1. Write Path
Replace flows through a staging table:
- The staging table is created first with the configured partition/clustering.
- Data is loaded into staging.
- Replace swaps staging into the destination.
2. Loading Data into Staging (load methods)
- `load_job` (default): a BigQuery load job.
- `storage_write`: the BigQuery Storage Write API.
- A transient
Not found: Datasetimmediately after dataset creation is retryable, but BigQuery'swas not found in locationvariant is permanent and fails immediately.
Selected via the destination URI: bigquery://project/dataset?load_method=storage_write. Default is load_job.
3. Preparing Tables (PrepareTable)
- Before inspecting or creating a table,
PrepareTableensures its dataset exists. The location it creates a dataset in is the effective location (effectiveLocation): the URI's configuredlocationif set, otherwise the location resolved once from the target table's dataset (resolveLocation, cached inresolvedLocation). So with no `location` configured, a newly created_bruin_staginginherits the target table's location instead of the hardcodedUSdefault, keeping staging and target in the same location so the cross-location swap failure never arises.resolveLocationruns at the top ofPrepareTableoffopts.TargetTable(replace sets it on the staging prepare, since replace prepares only the staging table) oropts.Table(other strategies prepare the target first, which resolves it); the resolved value flows througheffectiveLocation()into every dataset create and every load/copy/query job'sLocation. If a dataset already exists and its live BigQuery location differs from the effective location, preparation fails with an actionable, non-retryabledatasetLocationMismatchError. When no location resolves (none configured and the target dataset does not exist yet), the effective location falls back todefaultDatasetLocation(US) for this check too, so a pre-existing_bruin_stagingin a non-US region still fails fast rather than loading and dying at swap time on a cross-location job. Projects that write in multiple locations need a separate staging dataset per location, selected with--staging-dataset. - Tables are created through the BigQuery API (
BuildTableMetadata->FieldSchema,TimePartitioning{Field, Type}orRangePartitioning,Clustering{Fields}), not SQL DDL. See section 9 for howpartition_bymaps to these. - Staging table: prepared with
DropFirst = trueand the configuredPartitionBy/ClusterBy. After synchronous dataset existence/location validation,DropFirstis implemented as an optimistic async TRUNCATE: fireTRUNCATE TABLEwithout checking table existence first (the remaining flow runs in a goroutine, overlapping with source reading); if the table doesn't exist, fall back to a fresh CREATE. So an existing staging table is truncated and reused — unless its columns no longer fit the requested schema (type kind,Repeated, or a narrower length/precision, pervalidateBigQuerySchemaCompatibility), in which case it is dropped and recreated soDropFirstalways yields the prepared schema. - Destination table: created only if it does not already exist; if it exists, schema evolution runs instead (
addMissingColumns, plus REQUIRED→NULLABLE column relaxation for load jobs). - Primary key constraint:
BuildTableMetadataadds an informational (NOT ENFORCED)PRIMARY KEYconstraint when primary keys are present. BigQuery never enforces uniqueness with it — it is only a query-optimizer hint; ingestr's own dedup guarantees uniqueness. Whether the destination ends up carrying the constraint depends on the swap path: the copy job (and the merge/appendPrepareTablepath) inherit it from staging (pk present); CTAS does not declare one (pk absent). BigQuery caps the constraint at 16 columns — with more PKs the constraint is skipped with a warning (merge still works; the MERGE SQL keys on the in-memory PK list, not the constraint). - Default PK clustering (
defaultClusteringFromPrimaryKeys): when nocluster_byis configured, ingestr clusters the table by up to 4 clusterable primary-key columns (skipping repeated fields and non-clusterable types: FLOAT, BYTES, TIME, JSON) so PK-joined MERGEs can prune clustered blocks instead of scanning the whole table. Applied both at table creation (BuildTableMetadata) and at swap time (effectiveClusterBy). - CDC mode: non-PK columns are made nullable in staging and keyed merge targets because CDC DELETE events carry only key values. Existing REQUIRED non-key target fields are relaxed before merge, including with
storage_write, so delete-only tombstones can be stored. - Sized string columns: a
STRING(n)/BYTES(n)bound (from a sourcevarchar(n)or a--columnsoverride) rides onschema.Column.MaxLength.BuildBigQuerySchemawrites it toFieldSchema.MaxLengthon create, and `GetTableSchema` reads it back — the read-back must preserve it, otherwise an unchanged sized column looks unbounded to schema evolution and a subsequent incremental run derives an unbounded prepared schema that no longer matches the bounded table. When the target already exists,validateBigQuerySchemaCompatibilityfail-fasts on an incompatible existing column (a bounded column asked to become unbounded, a bound narrower than required, or insufficient NUMERIC precision/scale) rather than silently truncating. Widening a bounded string in place is not auto-applied — a wider requirement is rejected, notALTERed (the one exception is the CDC_cdc_lsnstate column, which is explicitly widened to unbounded). - Array read-back:
GetTableSchemamaps aREPEATEDfield toTypeArraywithArrayTypeset from the element type. Without the element type, every typed array looked changed on the next run and evolution triedALTER ... SET DATA TYPE ARRAY<JSON>, which BigQuery rejects. Array elements are still created without precision/scale/length, soARRAY<NUMERIC>reads back as (38,9). - Differing column type kind (e.g. existing
INTEGER, desiredFLOAT): handled by schema evolution, not by the compat check, becausePrepareTableruns with the final schema but before the strategy callsjob.ApplyEvolution— the physical column is still the old type when the check runs, so rejecting would kill the veryALTERthat resolves it. ThedeferTypeChangesargument toreconcileExistingTablegates this:trueon the "table already existed" path (a plan exists, defer to it);falseon the concurrent-create-winner path, where evolution planning saw the table absent, so no plan exists and the mismatch is rejected — the run fails and a retry re-plans against the now-existing table. Deferring there would let the write hit an incompatible physical column and truncate silently via the merge cast. ARepeated(scalar↔array) mismatch is not a widening evolution can perform and is always rejected.
4. Deduplication (where it happens)
Two places dedup by primary key, both using QUALIFY ROW_NUMBER():
- In the MERGE statement's `USING` clause (
buildMergeSQLWithPartitionPruning). Used by: - the merge write strategy (upsert into the existing target), and
- the replace strategy's dedup path:
deduplicateStagingrunsMergeTableto collapse a PK-free raw staging table into a fresh, deduplicated "normalised" staging table (created in the target's dataset), then drops the raw staging. - In the CTAS swap select (
buildBigQueryDedupSelect). This only runs when primary keys are present at swap time, which for BigQuery is the fast path (source guarantees unique PKs), so it operates on already-unique data.
So the swap reads either the normalised staging (dedup already done) or the raw staging (no dedup needed).
The guaranteed-unique fast path is source-declared. Connectors only declare auto-detected, database-enforced primary keys unique; user-supplied keys, custom-query keys, and informational constraints remain untrusted and continue through deduplication.
Keyed CDC batch full refreshes with --cdc-delete-behavior=hard always use the normalised staging path, even when source keys are guaranteed unique. Its merge honors CDCHardDelete, so a delete arriving after the snapshot removes that key before the swap. Raw and normalised staging are prepared in CDC mode to admit key-only delete events; the normalised table and swap schema omit staging-only CDC columns. Soft-delete and non-CDC replacement retain the unique-key fast path.
5. Swap: Staging -> Destination (replace strategy, SwapTable)
Two swap mechanisms:
- copy job (
swapTableWithCopyJob):CreateDisposition = CreateIfNeeded,WriteDisposition = WriteTruncate. Free (no query billing). If the target does not exist it is created, inheriting staging's schema and partition. Cannot dedup and cannot read the streaming buffer. - CTAS:
CREATE OR REPLACE TABLE target [PARTITION BY ...] [CLUSTER BY ...] AS SELECT ... FROM staging. Billed (scans staging). Reads the streaming buffer. Can dedup (buildBigQueryDedupSelectemits aQUALIFYwhen PKs are present at swap) — but in practice that only fires on the fast path, where the data is already unique, so it's a no-op; when CTAS reads a normalised staging the PKs have been nilled and the select is a bareSELECT *. TheCLUSTER BYuses the effective clustering (configuredcluster_by, or the default PK clustering).
Before either path, SwapTable ensures the target dataset exists (replace only PrepareTables the staging side; CREATE OR REPLACE and copy jobs do not auto-create datasets). After a successful swap, the staging table is deleted (best-effort, 30s timeout).
Both startLoadJobWithRetry and startCopyJobWithRetry cap ambiguous-start retries at loadJobStartMaxAttempts (10), so a persistent NotFound/duplicate (e.g. a missing dataset) can't retry forever. On exhaustion each adopts an already-submitted job of the same ID if one exists, else fails.
Branch:
The branch keys on primary keys being empty at swap time, not on the source lacking a primary key. In the dedup path, replace.go collapses duplicates into the normalised staging (via MergeTable) and then NILS the primary keys, so "no PKs at swap" is a consequence of dedup, not of a missing source PK. That is why the copy job can read a normalised staging table.
Swap selection (replace strategy):
- Source has PKs, not guaranteed-unique -> dedup runs: raw -> normalised staging via MERGE, then PKs nilled.
load_jobuses the copy job,storage_writeuses CTAS. Both read the normalised (already-deduped) staging. - No PKs -> no dedup: raw staging.
load_jobuses the copy job,storage_writeuses CTAS. - PKs guaranteed-unique (fast path) -> no dedup, PKs kept: CTAS (its QUALIFY dedup is a no-op since the data is already unique). Reads the raw staging.
storage_writealways uses CTAS (a copy job can't read the streaming buffer).
So the copy job reads a normalised staging only in the "source has PKs + needs dedup + load_job" case; CTAS on load_job happens only in the fast-path (guaranteed-unique) case.
6. Partition / Cluster Change (rename-aside)
BigQuery cannot change a table's partitioning in place:
CREATE OR REPLACErejects a table with a different partitioning spec.- A copy job cannot repartition an existing table.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/bigquery-destination/SKILL.md
Popularity
- Repository stars
- 4,039
- Repository forks
- 168
- 7-day trend score
- 0
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/bruin-data/ingestr/bigquery-destination)