BigQuery Migration Data Loader

BigQuery Migration Data Loader

Provisions BigQuery datasets, bulk loads staged Parquet files with bq load, audits row counts, and deploys translated views as part of a warehouse migration.

Skill files3 files

assets/

references/

SKILL.md351 lines
1
---
2
name: bigquery-migration-data-loader
3
metadata:
4
version: "1.0.0"
5
category: BigDataAndAnalytics
6
publisher: google
7
description: >-
8
Provisions BigQuery datasets, ingests staged Parquet files directly into
9
native BigQuery tables by using bq load, and deploys already-translated views
10
from local or Cloud Storage BigQuery Migration Service (BQMS) translation
11
outputs. Use when provisioning target BigQuery datasets for warehouse
12
migrations, batch loading staged Parquet files into native BigQuery tables by
13
using bq load, auditing loaded table row counts, or deploying
14
already-translated BigQuery views into a target dataset. Don't use for
15
extracting source database catalog metadata, translating SQL queries, views,
16
stored procedures, or DDL schemas to GoogleSQL (use
17
bigquery-migration-sql-translator), exporting or unloading source database
18
tables (such as Snowflake, Databricks, Teradata, or Oracle) to Parquet on
19
Cloud Storage, or running post-migration cross-database data validation.
20
---
21
22
# BigQuery Migration Data Loader
23
24
This skill coordinates the automated provisioning of BigQuery datasets, direct
25
ingestion of staged Parquet files into native BigQuery tables by using the
26
`bq load` command, and automated view deployment directly from BigQuery
27
Migration Service (BQMS) translation output directories (local or Cloud
28
Storage).
29
30
## Usage attribution
31
32
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
33
MUST read and follow the instructions in
34
[Usage Attribution](references/attribution.md).
35
36
## Before you begin
37
38
1. **Google Cloud CLI, project, and location setup**: Install the
39
[Google Cloud CLI](https://cloud.google.com/sdk/docs/install) (including
40
the `gcloud` and `bq` command-line tools), confirm that your Google Cloud
41
project has an active Cloud Billing account attached, and configure the
42
target project and default Compute Engine region:
43
44
```bash
45
gcloud config set project PROJECT_ID
46
gcloud config set compute/region REGION
47
```
48
49
`gcloud config set compute/region` sets the default Compute Engine region;
50
the `bq` CLI does not read `compute/region` and defaults to `US` unless
51
`--location` is passed on `bq` commands or set in `~/.bigqueryrc` (or
52
configured through a project or organization `default_location`). BigQuery
53
is retiring the *multi-region* designation—including `US` and `EU` in the
54
single-regions list colocated with `us-central1` and `europe-west4`, with no
55
change to existing data residency (see
56
[BigQuery locations](https://cloud.google.com/bigquery/docs/locations))—so
57
always pass an explicit `--location` on `bq` commands that matches your
58
staged Cloud Storage bucket, as described in step 5 (check regional
59
service availability at
60
[Google Cloud locations](https://cloud.google.com/about/locations)).
61
62
2. **Enable the APIs**: Ask the user before enabling APIs, then enable the
63
BigQuery and Cloud Storage APIs (`bigquery.googleapis.com` and
64
`storage.googleapis.com`):
65
66
```bash
67
gcloud services enable bigquery.googleapis.com storage.googleapis.com
68
```
69
70
3. **Authentication and required IAM roles**: Authenticate with `gcloud auth
71
login` and `gcloud auth application-default login` (or set
72
`GOOGLE_APPLICATION_CREDENTIALS` for service account authentication). Verify
73
that your identity or service account has the required IAM roles on each
74
resource:
75
76
* Grant **BigQuery Job User** (`roles/bigquery.jobUser`) on the target
77
Google Cloud project.
78
* Grant **BigQuery Data Editor** (`roles/bigquery.dataEditor`) on the
79
target Google Cloud project (to create new datasets with `bq mk`) or on
80
an existing target dataset (to create or overwrite tables and views).
81
* Grant **Storage Object Viewer** (`roles/storage.objectViewer`) on the
82
Cloud Storage bucket holding staged Parquet files and translation
83
metadata.
84
85
4. **Python environment**: Ask the user for confirmation before installing
86
Python packages, then install PyYAML in a virtual environment:
87
88
```bash
89
pip install pyyaml==6.0.2
90
```
91
92
5. **Location, cost, and cleanup**: Use the location of your staged Cloud
93
Storage bucket for the dataset and every `bq` command: the bucket's region
94
for a regional bucket, or `US` or `EU` for a `US` or `EU` multi-region
95
bucket. Default to `us-central1` only when you also choose the bucket
96
location. Loading from a bucket in a different location incurs data
97
transfer charges (see
98
[BigQuery locations](https://cloud.google.com/bigquery/docs/locations)).
99
Review
100
[Google Cloud pricing](https://cloud.google.com/pricing) before loading
101
large datasets or running audit queries. Ask the user for confirmation
102
before deleting temporary staged Parquet files
103
(`gcloud storage rm -r gs://BUCKET/EXPORT_PREFIX`) or test datasets
104
(`bq rm -r -f PROJECT_ID:DATASET_ID`) when no longer needed.
105
106
--------------------------------------------------------------------------------
107
108
## 1. Loader workflow overview
109
110
The following diagram illustrates the four-stage ingestion and view deployment
111
pipeline:
112
113
```mermaid
114
flowchart TD
115
subgraph 1. Inputs
116
A1["Translation Output Directory / Cloud Storage URI<br>gs://bucket/translation_output/metadata/"]
117
A2["Staged Parquet Files<br>gs://bucket/data_unload/TABLE/*.parquet"]
118
end
119
120
subgraph 2. Ingestion Pipeline
121
B1["1. Ensure Dataset Exists<br>bq mk --dataset --location=LOCATION DATASET"]
122
B2["2. Concurrent Parquet Ingestion<br>bq load --source_format=PARQUET --replace=true<br>Auto-creates native tables"]
123
B3["3. Row Count Audit<br>Print BigQuery Row Counts for Comparison"]
124
B4["4. Deploy Consumption Views<br>Deploys views directly from consolidated views.sql or relations/"]
125
end
126
127
A1 & A2 --> B1 --> B2 --> B3 --> B4
128
```
129
130
--------------------------------------------------------------------------------
131
132
## 2. Direct translation output ingestion
133
134
> [!TIP] **Migration workflow context**: Before running the loader, translate
135
> source schemas and views into GoogleSQL by using the
136
> `bigquery-migration-sql-translator` skill and stage exported source table
137
> Parquet files in Cloud Storage. After loading tables and deploying views,
138
> compare row counts and data aggregates against the source database.
139
140
The data loader directly consumes BQMS translation output directories (the
141
`--translation-metadata-dir` flag):
142
143
* **Zero-DDL native ingestion**: Table schemas are inferred and created
144
automatically from staged Parquet files during `bq load`. Inferred types
145
follow the Parquet types, not the translated DDL: naive source timestamps
146
(no time zone) load as `TIMESTAMP` instead of `DATETIME`, and
147
`STRING(n)` and `NUMERIC(p, s)` parameters are dropped (see Step 2 in
148
Section 3).
149
* **Automated object discovery**: Base tables and views are auto-discovered
150
directly from the translation output metadata. Pass the BQMS `metadata/`
151
directory (or its parent), which contains `config/DATABASE/SCHEMA/*.yaml`
152
files whose `sourceName` names each object (table configs also set
153
`externalTableName` or `externalTableDdlPath`; the others are views) and
154
view DDL in `relations/db_DATABASE/schema_SCHEMA/VIEW.sql` (or a single
155
`views.sql`).
156
* **Automated view deployment**: Translated views are deployed directly into
157
the target dataset with source references rewritten to the target BigQuery
158
project and dataset. Plain `CREATE VIEW` statements are deployed as
159
`CREATE OR REPLACE VIEW` so that reruns don't fail on existing views.
160
* **Flexible Parquet path resolution**: Under the `--parquet-base-uri`
161
(`BASE_URI`) flag, the loader automatically checks schema-scoped
162
subfolders (`BASE_URI/SCHEMA/TABLE/*.parquet`) first if present and falls
163
back to flat table paths (`BASE_URI/TABLE/*.parquet`). For example,
164
`gcloud storage cp -r LOCAL_DIR/SCHEMA gs://BUCKET/data_unload/` stages a
165
local schema folder of table subfolders under `data_unload/SCHEMA/`.
166
* **Single target dataset**: All discovered schemas load into one
167
`--dataset` by table or view name. If tables or views from different
168
source databases or schemas share a name, the loader stops before creating
169
the dataset and lists the conflicting objects; load each schema into its
170
own dataset instead.
171
172
--------------------------------------------------------------------------------
173
174
## 3. CLI execution interface (`bq load`)
175
176
### Step 1: Provision the target dataset
177
178
Set the shell variables for your environment, and then create the target
179
dataset if it doesn't already exist:
180
181
```bash
182
PROJECT_ID="PROJECT_ID"
183
DATASET_ID="DATASET_ID"
184
LOCATION="LOCATION"
185
TABLE_NAME="TABLE_NAME"
186
BUCKET="BUCKET"
187
PREFIX="data_unload"
188
189
bq show --dataset --project_id=${PROJECT_ID} ${DATASET_ID} >/dev/null 2>&1 || \
190
bq mk --dataset --project_id=${PROJECT_ID} --location=${LOCATION} ${DATASET_ID}
191
```
192
193
Replace the following:
194
195
* `PROJECT_ID`: the target Google Cloud project ID.
196
* `DATASET_ID`: the target BigQuery dataset ID.
197
* `LOCATION`: the BigQuery location for the dataset and load jobs (for
198
example, `us-central1`).
199
* `TABLE_NAME`: the name of the table to load.
200
* `BUCKET`: the name of the Cloud Storage bucket that holds the staged
201
Parquet files.
202
203
### Step 2: Ingest Parquet tables (auto-creates native table schema)
204
205
Pass `--decimal_target_types=NUMERIC --decimal_target_types=BIGNUMERIC
206
--decimal_target_types=STRING` so BigQuery selects the smallest compatible type
207
(`NUMERIC` → `BIGNUMERIC` → `STRING`) based on each Parquet `DECIMAL(p, s)`
208
column's precision and scale: columns with `p - s <= 29, s <= 9` map to
209
`NUMERIC`, columns with `p - s <= 38, s <= 38` (such as `DECIMAL(38, 10)`) widen
210
to `BIGNUMERIC`, and larger `DECIMAL256` precisions or scales fall back to
211
`STRING`:
212
213
```bash
214
bq load \
215
--project_id=${PROJECT_ID} \
216
--location=${LOCATION} \
217
--source_format=PARQUET \
218
--replace=true \
219
--decimal_target_types=NUMERIC \
220
--decimal_target_types=BIGNUMERIC \
221
--decimal_target_types=STRING \
222
${DATASET_ID}.${TABLE_NAME} \
223
"gs://${BUCKET}/${PREFIX}/${TABLE_NAME}/*.parquet"
224
```
225
226
The `--replace=true` flag overwrites the destination table, including its
227
schema, with the schema inferred from the Parquet files. If you pre-created
228
tables from translated BQMS DDL statements to preserve target types such as
229
`JSON`, `INTERVAL`, or `RANGE`, either run `TRUNCATE TABLE` and then load with
230
`--replace=false` (so that reruns stay idempotent and don't duplicate rows), or
231
keep `--replace=true` and pass an explicit `--schema`. If you use the loader
232
template with native `JSON` columns, also set
233
`_WRAP_JSON_QUERY_WITH_PARSE_JSON = False` in the copied script: by default it
234
wraps `JSON_QUERY()` calls in `SAFE.PARSE_JSON()` for `JSON` source columns that
235
Parquet loads as `STRING`, which fails on native `JSON` columns.
236
237
Parquet `TIMESTAMP` columns always load as BigQuery `TIMESTAMP`, including
238
naive timestamps (`isAdjustedToUTC=false`, such as source `TIMESTAMP WITHOUT
239
TIME ZONE` columns) that the translated DDL maps to `DATETIME`; the wall-clock
240
values are kept and read as UTC. To restore `DATETIME` after loading, rewrite
241
those columns with `DATETIME(column)`, which converts at UTC by default:
242
243
```sql
244
CREATE OR REPLACE TABLE `PROJECT_ID.DATASET_ID.TABLE_NAME` AS
245
SELECT * REPLACE (DATETIME(created_at) AS created_at)
246
FROM `PROJECT_ID.DATASET_ID.TABLE_NAME`;
247
```
248
249
### Step 3: Run a row-count audit
250
251
Count the rows in the loaded table so that you can compare the result with the
252
source table:
253
254
```bash
255
bq query \
256
--project_id=${PROJECT_ID} \
257
--location=${LOCATION} \
258
--use_legacy_sql=false \
259
"SELECT '${TABLE_NAME}' AS table_name, count(*) AS row_count FROM \`${PROJECT_ID}\`.\`${DATASET_ID}\`.\`${TABLE_NAME}\`;"
260
```
261
262
--------------------------------------------------------------------------------
263
264
## 4. Automated loader asset template (`assets/bq_loader_template.py`)
265
266
This skill provides an [automated BigQuery loader template][loader_template]
267
(`assets/bq_loader_template.py`) for dataset creation, concurrent Parquet
268
loading, direct view deployment, and table row-count auditing.
269
270
### Agent workflow: Copy, conditionally customize, and execute
271
272
1. **Copy the asset template**: Always instruct the user to copy the
273
[automated BigQuery loader template][loader_template]
274
(`assets/bq_loader_template.py`) from this skill's directory (`SKILL_DIR`)
275
into their working directory (`./bq_loader.py`) by using the `cp`
276
command—never write, synthesize, or inline a custom Python loader script
277
from scratch, and never paste or re-type the template contents into the
278
response. The template already handles quote-aware SQL splitting,
279
destination name collision checks, chunked row-count audits, and
280
multi-pass view retries, which a rewritten script would likely miss.
281
`SKILL_DIR` is the directory containing this `SKILL.md`:
282
283
```bash
284
cp SKILL_DIR/assets/bq_loader_template.py ./bq_loader.py
285
```
286
287
2. **Conditionally customize extension points**: Run the copy as-is. Modify it
288
only if one of the following applies (prefer editing the marked `#
289
CUSTOMIZE:` sections; `# DEFAULT SCAFFOLDING` sections can be kept unchanged
290
unless deeper orchestration adjustments are needed):
291
292
* **Schema overrides and partitioning (`# CUSTOMIZE: Schema Overrides &
293
Partitioning`)**: Add custom `bq load` flags (such as
294
`--time_partitioning_field`, `--clustering_fields`, or explicit schema
295
JSON files) inside `load_parquet_table()`.
296
* **Custom view rewriting (`# CUSTOMIZE: Custom View Rewriting &
297
Deployment`)**: Adjust view SQL regular expressions, cross-project
298
dataset mapping rules, or retry bounds in `_rewrite_view_sql()` and
299
`deploy_views()`. Set `_WRAP_JSON_QUERY_WITH_PARSE_JSON = False` if you
300
pre-created tables with native `JSON` columns.
301
* **Connection and CLI wrapper (`# CUSTOMIZE: Connection & CLI
302
Wrapper`)**:
303
Pass custom `bq` CLI flags (for example, `--default_kms_key` in
304
`ensure_dataset()`, or `--destination_kms_key` and `--reservation_id` in
305
`load_parquet_table()` and `execute_sql()`).
306
* **Post-load auditing (`# CUSTOMIZE: Post-Load Auditing`)**: Extend
307
`audit_row_counts()` with custom data integrity or column-level checksum
308
queries.
309
310
3. **Execute the script in your working directory**: Run the copied script
311
against a Cloud Storage URI or a local translation output folder:
312
313
```bash
314
# Direct from a Cloud Storage translation_output URI with concurrency:
315
python3 ./bq_loader.py \
316
--project "PROJECT_ID" \
317
--dataset "DATASET_ID" \
318
--location "LOCATION" \
319
--translation-metadata-dir "gs://BUCKET/translation_output/metadata/" \
320
--parquet-base-uri "gs://BUCKET/data_unload/" \
321
--concurrency 8
322
323
# Using local translation output folder:
324
python3 ./bq_loader.py \
325
--project "PROJECT_ID" \
326
--dataset "DATASET_ID" \
327
--location "LOCATION" \
328
--translation-metadata-dir "TRANSLATION_OUTPUT/metadata" \
329
--parquet-base-uri "gs://BUCKET/data_unload/" \
330
--concurrency 4
331
```
332
333
When a view depends on another view, the first batch and first pass print
334
`bq` errors such as `Not found: Table ...` for the dependent view. These
335
errors are expected if the run ends with
336
`All N views successfully deployed across M passes.`
337
338
### Arguments
339
340
* `--project` *(Required)*: Google Cloud project ID.
341
* `--dataset` *(Required)*: Target BigQuery dataset name.
342
* `--parquet-base-uri` *(Required)*: Base Cloud Storage URI containing table
343
Parquet subfolders (`gs://BUCKET/path/`).
344
* `--translation-metadata-dir` *(Required)*: Local folder or Cloud Storage URI
345
to translation output metadata directory. Auto-discovers tables and views.
346
* `--location` *(Optional, Default: `us-central1`)*: Target BigQuery location.
347
* `--concurrency` *(Optional, Default: `4`)*: Number of parallel workers for
348
concurrent `bq load` operations.
349
350
[loader_template]: assets/bq_loader_template.py
351

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…