bruin-data/ingestr/bigquery-destination

Claude Code and agent skill by bruin-data/ingestr

Trust tier 2
  • community
LLM review pending
Source check pending

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-destination

SKILL.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:

source -> staging table -> destination 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: Dataset immediately after dataset creation is retryable, but BigQuery's was not found in location variant 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, PrepareTable ensures its dataset exists. The location it creates a dataset in is the effective location (effectiveLocation): the URI's configured location if set, otherwise the location resolved once from the target table's dataset (resolveLocation, cached in resolvedLocation). So with no `location` configured, a newly created _bruin_staging inherits the target table's location instead of the hardcoded US default, keeping staging and target in the same location so the cross-location swap failure never arises. resolveLocation runs at the top of PrepareTable off opts.TargetTable (replace sets it on the staging prepare, since replace prepares only the staging table) or opts.Table (other strategies prepare the target first, which resolves it); the resolved value flows through effectiveLocation() into every dataset create and every load/copy/query job's Location. If a dataset already exists and its live BigQuery location differs from the effective location, preparation fails with an actionable, non-retryable datasetLocationMismatchError. When no location resolves (none configured and the target dataset does not exist yet), the effective location falls back to defaultDatasetLocation (US) for this check too, so a pre-existing _bruin_staging in 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} or RangePartitioning, Clustering{Fields}), not SQL DDL. See section 9 for how partition_by maps to these.
  • Staging table: prepared with DropFirst = true and the configured PartitionBy / ClusterBy. After synchronous dataset existence/location validation, DropFirst is implemented as an optimistic async TRUNCATE: fire TRUNCATE TABLE without 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, per validateBigQuerySchemaCompatibility), in which case it is dropped and recreated so DropFirst always 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: BuildTableMetadata adds an informational (NOT ENFORCED) PRIMARY KEY constraint 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/append PrepareTable path) 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 no cluster_by is 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 source varchar(n) or a --columns override) rides on schema.Column.MaxLength. BuildBigQuerySchema writes it to FieldSchema.MaxLength on 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, validateBigQuerySchemaCompatibility fail-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, not ALTERed (the one exception is the CDC _cdc_lsn state column, which is explicitly widened to unbounded).
  • Array read-back: GetTableSchema maps a REPEATED field to TypeArray with ArrayType set from the element type. Without the element type, every typed array looked changed on the next run and evolution tried ALTER ... SET DATA TYPE ARRAY<JSON>, which BigQuery rejects. Array elements are still created without precision/scale/length, so ARRAY<NUMERIC> reads back as (38,9).
  • Differing column type kind (e.g. existing INTEGER, desired FLOAT): handled by schema evolution, not by the compat check, because PrepareTable runs with the final schema but before the strategy calls job.ApplyEvolution — the physical column is still the old type when the check runs, so rejecting would kill the very ALTER that resolves it. The deferTypeChanges argument to reconcileExistingTable gates this: true on the "table already existed" path (a plan exists, defer to it); false on 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. A Repeated (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: deduplicateStaging runs MergeTable to 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 (buildBigQueryDedupSelect emits a QUALIFY when 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 bare SELECT *. The CLUSTER BY uses the effective clustering (configured cluster_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:

if load method == load_job AND no primary keys at swap:
copy job
else:
CTAS (needed for dedup, or for storage_write's streaming buffer)

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_job uses the copy job, storage_write uses CTAS. Both read the normalised (already-deduped) staging.
  • No PKs -> no dedup: raw staging. load_job uses the copy job, storage_write uses 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_write always 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 REPLACE rejects 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

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
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/bruin-data/ingestr/bigquery-destination/badge)](https://verified-skill.com/skills/bruin-data/ingestr/bigquery-destination)

Something wrong with this skill or its page? Tell us.