Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-migration-metadata-extractor@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin bigquery-migration-metadata-extractor v1.0.0 follows the Agent Plugins spec.
gh skills-hub install bigquery-migration-metadata-extractor Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/bigquery-migration-metadata-extractor/ Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-migration-metadata-extractor for Copilot to auto-discover it.
Skill Files (6)
SKILL.md 29.5 KB
---
name: bigquery-migration-metadata-extractor
metadata:
version: "1.0.0"
category: BigDataAndAnalytics
publisher: google
description: >-
Extracts database catalog metadata and query logs from data warehouses by
running the DWH migration extractor locally or on a temporary Google Cloud VM
through the BigQuery Migration Cloud Extractor (credentials held in Secret
Manager), and inspects extracted `.zip` archives to report object and volume
statistics. Use when extracting database metadata or query logs from
Snowflake, Redshift, Teradata, Oracle, PostgreSQL, SQL Server, Hive, etc.,
deciding between local and cloud (Cloud Extractor) extraction, or inspecting
extracted dwh-migration-*.zip archives to print post-extraction statistics.
Don't use for SQL dialect translation (use bigquery-migration-sql-translator),
exporting table data to Parquet or CSV files (such as Snowflake `COPY INTO`
unloads) or loading it into BigQuery (use the BigQuery Data Transfer Service
or bigquery-basics), or validating migrated data.
---
# BigQuery Migration Metadata Extraction
Extraction runs the DWH migration extractor (`dwh-migration-dumper`) through two
gcloud commands to collect catalog DDL and query history—not table row data. If
the user wants to migrate table rows (such as Snowflake `COPY INTO` unloads),
ask whether they prefer the [BigQuery Data Transfer Service][bq_dts] (including
the [Snowflake connector][snowflake_dts]) or exporting to Cloud Storage and
loading with `bq load`. Both extract commands are in the **alpha** release
track:
Command | Use for
:--------------------------------------------- | :------
`gcloud alpha bq migration metadata extract` | Catalog metadata (metadata connectors)
`gcloud alpha bq migration query-logs extract` | Query history (`*-logs` connectors)
Both take the same arguments. gcloud flags come first; the extractor's own flags
come after `--` and are passed to the extractor unchanged:
```text
gcloud alpha bq migration {metadata|query-logs} extract \
--connector=CONNECTOR --output=gs://BUCKET/PATH/ \
[--run-mode=local|cloud] [cloud flags] \
-- [EXTRACTOR FLAGS] [PASSWORD]
```
* `--connector` and `--output` are required gcloud flags. `--output` is a
Cloud Storage path (`gs://...`); local mode also accepts a local file or
directory path. This skill uses Cloud Storage in both run modes.
* `--run-mode=local` (the default) runs the extractor on this machine.
`--run-mode=cloud` runs it on a temporary Compute Engine VM (the **BigQuery
Migration Cloud Extractor**).
* Database flags (`--host`, `--port`, `--user`, `--database`, `--schema`,
`--warehouse`, `--role`, `--driver`, `--assessment`, `--query-log-*`, ...)
go after `--`. Putting them before `--` is an error.
* How the password is passed depends on the run mode (Section 4): an extractor
response file (`@FILE`) in local mode, and `--password` read from a file in
cloud mode. Never type a literal password.
> [!IMPORTANT]
> The commands are in the alpha track. If gcloud reports an invalid choice or
> unknown command, ask the user before updating the Google Cloud CLI, then
> retry. Update it with `gcloud components update`, or, if gcloud was installed
> with a system package manager such as `apt` or `yum` (which disables the
> component manager), upgrade the `google-cloud-cli` package with that package
> manager.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Before you begin
1. **Google Cloud CLI, authentication, project, region, and zone**: Ensure the
[Google Cloud CLI][gcloud_install] is installed, verify that the Google
Cloud project has an active Cloud Billing account, authenticate with user
and Application Default Credentials, and configure the target project, a
default region such as `us-central1` (check regional service availability at
[Google Cloud locations][cloud_locations]), and a zone in that region. Cloud
mode takes the VM's zone from `--zone`, then `compute/zone`, then
`us-central1-a`; it does not read `compute/region`:
```bash
gcloud auth login
gcloud auth application-default login
gcloud config set project {project_id}
gcloud config set compute/region {region}
gcloud config set compute/zone {zone}
```
2. **Output bucket**: This skill writes the ZIP archives to a Cloud Storage
bucket (`--output`) that the project owns and that is not public, in both
run modes. In both modes the command checks the bucket before it starts
the extractor, so the caller needs `storage.buckets.list` on the bucket's
project and `storage.buckets.getIamPolicy` on the bucket unless public
access prevention is enforced on it. In local mode the Application Default
Credentials also need to create objects in the bucket.
3. **Run-mode prerequisites** (ask the user before installing software or
enabling APIs):
* **Local mode (`--run-mode=local`)**: Java 11 or later (JRE 11+) on
`PATH`, the `bqms` gcloud component, vendor JDBC driver JARs
(`--driver`) when required, and local network access to the database;
see the [local extraction guide](references/local_extraction.md).
Without a terminal the extract command cannot prompt to install
`bqms` and fails, so once the user agrees, install it first with
`gcloud components install bqms --quiet` (for a gcloud installed with
`apt` or `yum`, install the `google-cloud-cli-bqms` package instead).
* **Cloud mode (`--run-mode=cloud`)**:
* **APIs**: Compute Engine (`compute.googleapis.com`), Secret Manager
(`secretmanager.googleapis.com`), Cloud Storage
(`storage.googleapis.com`), and Cloud Logging
(`logging.googleapis.com`).
* **Network and subnet**: A VPC `--network` and `--subnet` (default
`default`) with routing to the database, and the VM's egress IP
range allowlisted by the database. The VM also needs internet
access to download the extractor and reach Google APIs: keep the
default external IP, or with `--no-address` add Cloud NAT in the
VM's region. A Cloud VPN or Cloud Interconnect route to the
database does not replace it.
* **IAM permissions**: The caller needs roles to create the VM and
the secret, for example Compute Admin (`roles/compute.admin`) and
Secret Manager Admin (`roles/secretmanager.admin`), plus the
bucket permissions in item 2. With a prepared
`--gce-service-account`, the caller also needs Service Account User
(`roles/iam.serviceAccountUser`) on that account, and the account
itself needs the roles listed in the
[cloud extraction guide](references/cloud_extraction.md).
* **Default service account**: Without `--gce-service-account`, every
run creates or reuses
`bqms-cloud-extractor@{project_id}.iam.gserviceaccount.com` and
grants it nine project roles, including `roles/editor`,
`roles/compute.admin`, and `roles/cloudkms.cryptoKeyDecrypter`.
This needs Service Account Admin (`roles/iam.serviceAccountAdmin`)
and Project IAM Admin (`roles/resourcemanager.projectIamAdmin`).
Without a terminal, gcloud accepts its own "create it?" prompt, so
get the user's explicit approval before you omit
`--gce-service-account`; see the
[cloud extraction guide](references/cloud_extraction.md).
4. **Cost and cleanup**: Review
[Google Cloud Pricing](https://cloud.google.com/pricing) for Compute Engine,
Secret Manager, and Cloud Storage. After a cloud run, delete the run's
Secret Manager secret (Section 5).
## 1. Choose the Run Mode
| `--run-mode=local` (default) | `--run-mode=cloud` (Cloud Extractor)
:----------------------- | :------------------------------------------------------- | :-----------------------------------
Where the extractor runs | This machine (needs a Java runtime) | Temporary Compute Engine VM
Network path to the DB | This machine's network (VPN, on-prem, bastion) | The VM's VPC; the DB must accept connections from it
JDBC drivers | Any, including vendor JARs passed with `--driver` | Only drivers bundled with the extractor; the VM has no vendor JARs and cannot read a local `--driver` path
Credentials | `@FILE` response file read by the local extractor | `--password` (read from a file) stored with the other extractor arguments in a Secret Manager secret that the VM reads
Failed extractor tasks | Partial ZIP still lands in `--output` | No ZIP is uploaded; the run fails
Read next | [local extraction guide](references/local_extraction.md) | [cloud extraction guide](references/cloud_extraction.md)
Pick **local** when any of these is true:
* The connector needs a JDBC driver that the cloud VM does not have:
`teradata`, `teradata-logs`, `teradata14-logs`, `oracle`, `oracle-logs`,
`oracle-stats`, `sqlserver`, `mysql`, `netezza`, `vertica`, `vertica-logs`.
Locally, the `bqms` launcher downloads the Oracle, SQL Server, and MySQL
drivers itself (the local extractor ships without JDBC drivers, so the
launcher also downloads the Snowflake, Redshift, PostgreSQL, and Greenplum
drivers); Teradata, Netezza, and Vertica need `--driver` (Section 3).
* The database is only reachable from the user's network (on-prem, VPN,
private endpoint with no route from Google Cloud).
* The user cannot create Compute Engine VMs, service accounts, or secrets in
the project.
* `--host` is `localhost`, `127.0.0.1`, `::1`, or a private address with no
route from a Google Cloud VPC. Never use `--run-mode=cloud` for these; the
VM cannot reach them (on the VM, `127.0.0.1` is the VM itself, even if the
user says the address is routed). Ask for a routable address, or, if the
user already accepted a fallback, run locally with the same `--output` and
drop the cloud-only flags.
Pick **cloud** when the database is reachable from Google Cloud (Snowflake,
Redshift, BigQuery, cloud-hosted PostgreSQL/Greenplum, Hive metastore) and the
user wants nothing installed locally.
Tell the user which run mode you chose and why, for example that cloud mode
cannot load vendor JDBC drivers or reach a database that only the user's network
can reach.
## 2. Connectors and Commands
Each connector extracts **either** catalog metadata **or** query logs, so it
belongs to exactly one command. Run both commands to get both.
Source | `metadata extract` connector | `query-logs extract` connector
:-------------------- | :---------------------------------------------------------------------------------------------------- | :-----------------------------
Snowflake | `snowflake` (or `snowflake-account-usage-metadata`, `snowflake-information-schema-metadata`) | `snowflake-logs` (or `snowflake-account-usage-logs`, `snowflake-information-schema-logs`)
Amazon Redshift | `redshift` | `redshift-raw-logs` (or `redshift-logs`, `redshift-serverless-logs`)
Teradata | `teradata` | `teradata-logs` (version 15+), `teradata14-logs`
Oracle | `oracle` (DDL), `oracle-stats` (workload statistics for assessment; window set by `--query-log-days`) | `oracle-logs`
Google BigQuery | `bigquery` | `bigquery-logs`
Greenplum | `greenplum` | `greenplum-logs`
Vertica | `vertica` | `vertica-logs`
PostgreSQL | `postgresql` | none
SQL Server / Azure | `sqlserver` | none
MySQL | `mysql` | none
Netezza | `netezza` | none
Apache Hive metastore | `hiveql` | none
> [!TIP]
> Catalog metadata is fast (minutes) and is all that SQL translation,
> schema creation, Parquet export, and static lineage need. Query logs take
> longer and are only needed for workload assessment or lineage of queries that
> are not stored as views (for example dbt or Airflow `INSERT ... SELECT` jobs).
> Always bound log extraction with `--query-log-start`/`--query-log-end` or
> `--query-log-days` (after `--`).
## 3. Flags
gcloud flags (before `--`):
Flag | Run mode | Meaning
:-------------------------------------------- | :--------- | :------
`--connector` | both | Required. Must match the command (Section 2).
`--output` | both | Required. `gs://BUCKET/PATH/` (or a `.zip` object path). Local mode also accepts a local file or directory path.
`--run-mode` | both | `local` (default) or `cloud`.
`--expected-owner` | both | Project that must own the `--output` bucket (defaults to the current project).
`--endpoint-mode` | both | Standard gcloud regional endpoint selection; leave unset unless the user asks.
`--project` | both | Standard gcloud project flag.
`--zone`, `--secret`, `--network`, and others | cloud only | See the [cloud extraction guide](references/cloud_extraction.md).
Extractor flags (after `--`):
Flag | Meaning
:--------------------------------------------------------- | :------
`--host`, `--port`, `--url` | Server address, or a full JDBC URL that overrides host and port.
`--user`, `@FILE` | User, and a response file holding the password (Section 4).
`--database`, `--schema` | Comma-separated lists to limit what is extracted. `postgresql` extracts only the first `--database` and ignores `--schema`; run it once per database, each with its own `--output`.
`--warehouse`, `--role` | Snowflake session settings (set per session; never change user defaults).
`--assessment` | Extra data for BigQuery Migration Assessment (omit `--database` and `--schema` when passing `--assessment` to `snowflake`, which rejects combining them). Only changes the output of `teradata`, `teradata-logs`, `redshift`, `redshift-raw-logs`, `snowflake`, `snowflake-logs`, `hiveql`, and `greenplum-logs`; other connectors ignore it.
`--query-log-start`, `--query-log-end`, `--query-log-days` | Query log window for `*-logs` connectors.
`--driver` | Vendor JDBC driver JAR(s) (required for `teradata*`, `vertica*`, and `netezza`; optional override when the local `bqms` launcher downloads the driver). Local mode only.
## 4. Credentials
Never type a literal password on the command line, and never ask the user to
paste it into the chat. Ask the user to run the password-file command below in
their own terminal, with `DB_PASSWORD` set there (for example with
`read -rs DB_PASSWORD && export DB_PASSWORD` in `bash` or `zsh`), or to create
the file another way, and to give you only its path. The commands stop with an
error instead of writing an empty password when `DB_PASSWORD` is unset. Which
mechanism to use depends on the run mode.
**Local mode: `@FILE` response file.** The local extractor reads `@FILE`
arguments as YAML response files and turns each key into a flag, so a file with
`password: ...` supplies `--password` without putting it on the command line.
Write it so only the user can read it, with the value single-quoted (any `'`
doubled) so special characters survive. This form works in `bash`, `zsh`, and
`sh` and assumes a single-line password:
```bash
: "${DB_PASSWORD:?DB_PASSWORD is not set}" && umask 077 && printf "password: '%s'\n" "$(printf '%s' "$DB_PASSWORD" | sed "s/'/''/g")" > ./extractor-secret.yaml
```
Pass `@./extractor-secret.yaml` after `--` (for a file outside the current
directory use an absolute path such as `@$HOME/path/file.yaml`; `@~/...` is not
expanded).
**Cloud mode: `--password` read from a file.** The CLI stores the extractor
arguments in Secret Manager exactly as given, and the VM runs the extractor with
them. The VM has none of your local files, so an `@FILE` argument fails there.
Put the password in a file only the user can read and pass it with command
substitution after `--`:
```bash
: "${DB_PASSWORD:?DB_PASSWORD is not set}" && umask 077 && printf '%s' "${DB_PASSWORD}" > ./db_password
```
```text
-- ... --password="$(cat ./db_password)"
```
The value then lives in the run's Secret Manager secret (delete it after the
run, Section 5) and is visible in this machine's process list while gcloud runs,
so use a machine only the user can access.
Delete the password file when done if you created it; leave a file the user
supplied in place.
## 5. Quick Start
Local (Teradata on-prem with the vendor driver):
```bash
gcloud alpha bq migration metadata extract \
--connector=teradata \
--output="gs://{bucket}/teradata_metadata/" \
-- \
--host="{teradata_host}" \
--user="{db_user}" \
--driver="{path_to}/terajdbc4.jar" \
--assessment \
@./extractor-secret.yaml
```
Cloud (Snowflake through the Cloud Extractor):
```bash
gcloud alpha bq migration metadata extract \
--connector=snowflake \
--output="gs://{bucket}/snowflake_metadata/{run_label}/" \
--run-mode=cloud \
--project="{project_id}" \
--zone="{zone}" \
--secret="bqms-extractor-creds-{run_label}" \
-- \
--host="{account_identifier}.snowflakecomputing.com" \
--user="{db_user}" \
--database="{db_name}" \
--warehouse="{db_warehouse}" \
--role="{db_role}" \
--password="$(cat ./db_password)"
```
`--secret` is optional. Without it the CLI creates
`bqms-extractor-creds-run-EPOCH_SECONDS`, prints its name, and labels it
`goog-bqms-extractor-run-id`. If you pass `--secret`, use a new `{run_label}`
for every run: for a secret that already exists the CLI only adds a version,
and deleting that secret later would also delete its earlier versions.
Give every cloud run an `--output` prefix that holds no `.zip` yet, such as a
new `{run_label}` folder. gcloud reports success as soon as it finds any
non-empty `.zip` under `--output`, without checking when it was written. An
older archive there (from an earlier metadata, query-log, or local run) ends
the command at once with `Extraction complete` while the new VM is still
starting, and deleting the secret then breaks the real run. If the user names a
prefix, use it as given after checking that `gcloud storage ls
"gs://{bucket}/{path}/"` lists no `.zip`; otherwise propose a new sub-prefix.
Every answer that runs or recommends an extraction must include these steps, in
order, with their commands:
1. Check the exit code and task summary (Section 6, step 1).
2. Verify the output with the statistics template (Section 6, step 2): `cp
<SKILL_DIR>/assets/extraction_stats_template.py ./extraction_stats.py &&
python3 ./extraction_stats.py --input "gs://{bucket}/{path}/"`.
3. After a cloud run, delete the run's Secret Manager secret once steps 1 and 2
are done (or right away if the run failed), and say why: it still holds the
database password. Delete the `--secret` name if you passed one: `gcloud
secrets delete bqms-extractor-creds-{run_label} --project={project_id}
--quiet`. Otherwise delete the auto-named
`bqms-extractor-creds-run-EPOCH_SECONDS` secret the command printed, or find
it with `gcloud secrets list
--filter="labels.goog-bqms-extractor-run-id:*"`. Only delete secrets created
for this run; if the user had you reuse an existing secret, record its
newest version before the run and destroy only a version this run added.
See the cleanup section of the
[cloud extraction guide](references/cloud_extraction.md).
4. Delete `extractor-secret.yaml` or `db_password` if you created it; leave a
file the user supplied in place.
## 6. Check the Result
1. **Exit code and task summary.** The extractor exits 1 when any required task
fails. What that means depends on the run mode:
* **Local:** gcloud reports `BigQuery Migration Extractor failed with exit
code 1`, but the extractor has already written the ZIP to `--output`,
with a `*.exception.txt` entry for each failure. A ZIP present after
this error is a partial success, not a reason to rerun.
* **Cloud:** the VM uploads the ZIP only when the extractor exits 0, so
`Extraction complete` means success only if `--output` held no `.zip`
before the run (Section 5). If any required task fails, nothing is
uploaded and gcloud reports `Extraction finished, but no non-empty
artifact was found`. Always tell the user both next steps: read the
VM's logs to see why the extractor failed, and then either fix the
cause and rerun, or rerun with `--run-mode=local`, which keeps the
partial ZIP. gcloud prints a `gcloud logging read
'resource.type="gce_instance" AND resource.labels.instance_id="..."'`
command only when it finds error entries; otherwise query the logs by
the VM name from the `Instance Link:` line (see Monitoring in the
[cloud extraction guide](references/cloud_extraction.md)). Also delete
the run's secret (Section 5).
For a local partial ZIP, read the `N TASKS SUCCEEDED / N TASKS FAILED`
summary and the exception entries (`unzip -l {archive}.zip
'*.exception.txt'` lists the failed tasks; each file is long, so read just
the error with `unzip -p {archive}.zip '{task}.exception.txt' | grep -m 3 -E
'^\s*message:'`). A failure is harmless when a version-specific fallback of
the same task succeeded; the fallback has a version suffix, for example
`functions.csv.exception.txt` next to a populated `functions-11.csv` on
PostgreSQL 11 and later.
2. **Archive integrity and statistics.** Copy the
[extraction statistics template][extraction_stats_template]
(`<SKILL_DIR>/assets/extraction_stats_template.py`, where `<SKILL_DIR>` is
the directory that contains this `SKILL.md`) into the working directory and
run it on the ZIP, its folder, or the GCS prefix:
```bash
cp <SKILL_DIR>/assets/extraction_stats_template.py ./extraction_stats.py
python3 ./extraction_stats.py --input "gs://{bucket}/snowflake_metadata/"
```
If the `gs://` form fails, copy the ZIP locally with `gcloud storage cp` and
run the script on the local file.
It rejects incomplete archives (22-byte placeholders) and reports the
extractor telemetry status, counts of databases, schemas, base tables,
views, and columns, total base table row counts and byte sizes, per-schema
and per-table breakdowns, and the column data type distribution. See the
[statistics report specification](references/extraction_stats_report.md)
for the full report metrics and the `# CUSTOMIZE:` extension points (for
example, editing `_EXCLUDED_SYSTEM_SCHEMAS` or `_should_include_schema()` to
drop a `STAGING_TMP` schema).
> [!NOTE]
> The script computes object, row, and byte counts from the Snowflake, Redshift
> (`svv_*`), and Teradata (`dbc.*V`) catalog layouts, and table, view, and
> top-level column counts from the BigQuery `tables.jsonl` (rows and sizes show
> as `N/A` there because that connector does not record them). It reads the run
> status from `dumper-telemetry.jsonl` when the archive has one. For other
> layouts (for example PostgreSQL, Oracle, or the Hive `tables.jsonl`) it still
> validates the archive and reports the connector and host, but object counts
> are zero and the run status can show `UNKNOWN`. On PostgreSQL 11 and later it
> shows `FAILURE` because of the harmless `functions.csv` and `aggregates.csv`
> fallbacks (Section 6, step 1). Then use the task summary printed by the
> extract command for the run status, and count objects from the connector's
> own files (Section 7).
## 7. Output Archives
Unless `--output` names a `.zip` object, the extractor names the ZIP
`dwh-migration-{connector}-metadata.zip` for `metadata extract` connectors and
`dwh-migration-{connector}.zip` for `query-logs extract` connectors, whose names
already end in `-logs`: `snowflake` writes
`dwh-migration-snowflake-metadata.zip` and `snowflake-logs` writes
`dwh-migration-snowflake-logs.zip`. A few names differ (`oracle-stats` writes
`dwh-migration-oracle-stats.zip`; `hiveql`, and query logs extracted with
`--assessment`, add a `-YYYYMMDDTHHMMSS` timestamp), so list `--output` to find
the archive. Every archive contains `compilerworks-metadata.yaml` (extractor
version and arguments) plus connector-specific CSVs:
```text
dwh-migration-snowflake-metadata.zip
├── databases-au.csv # Databases and owners
├── schemata-au.csv # Schemas
├── tables-au.csv # Tables, row counts, byte sizes
├── columns-au.csv # Columns, ordinal positions, types, nullability
├── views-au.csv # View DDL
├── functions-au.csv # User-defined and external functions
├── external_tables.csv # External stage tables
├── snowflake.yaml # Assessment flag and warehouse count
├── compilerworks-metadata.yaml # Extractor version and flags
└── dumper-telemetry.jsonl # Task timings
dwh-migration-snowflake-logs.zip
├── query_history_2026-08-05T000000Z.csv # One file per rotation window
├── ...
└── compilerworks-metadata.yaml
dwh-migration-postgresql-metadata.zip
├── database.csv # Databases on the server
├── is_columns_private.csv # Columns of user tables and views
├── pg_views_private.csv # User view DDL
├── functions-11.csv # Functions on search_path (11+; drop pg_catalog)
├── aggregates-11.csv, types.csv, casts.csv
├── is_columns_generic.csv, pg_views_generic.csv # System catalog objects
├── pg_user.csv # Roles and privileges (passwords masked)
├── *.csv.exception.txt # One per failed task
└── compilerworks-{metadata.yaml,arguments.txt,version.txt,format.txt}
```
In PostgreSQL archives the `*_private.csv` files hold user objects and the
`*_generic.csv` files hold system objects. `is_columns_private.csv` includes
view columns; subtract the views in `pg_views_private.csv` to count base tables.
`functions-11.csv`, `aggregates-11.csv`, and `types.csv` list only objects
visible on the session `search_path` (`"$user", public` by default), so other
schemas' functions and types are missing. To include them, replace `--host`,
`--port`, and `--database` with
`--url="jdbc:postgresql://{host}:{port}/{db_name}?currentSchema={schema1},{schema2},public"`.
Archives never contain the database password: to confirm, check that
`compilerworks-arguments.txt` and `compilerworks-metadata.yaml` have no
`password` entry (scanning for the password value is unreliable when it is a
common word), but they do contain object DDL and role lists, and
`dumper-telemetry.jsonl` is copied from
`~/.cache/DWH-Dumper/all-dumper-telemetry.jsonl`, so it can hold connectors,
hosts, and errors from earlier extractor runs on the same machine. Treat them
as sensitive and keep them in a private bucket.
## 8. Downstream BigQuery Workflows
Each cloud run writes to its own `--output` prefix (Section 5). To hand the
archives over together, copy the finished ZIPs into one shared prefix, for
example `gcloud storage cp "gs://{bucket}/{run_prefix}/*.zip"
"gs://{bucket}/assessment/"`, and never use that shared prefix as a cloud
`--output`. Then:
1. **BigQuery Migration Assessment**: direct the user to **BigQuery >
Migration > Assessment** in the Google Cloud Console and give it the GCS
prefix that holds the metadata (extracted with `--assessment`) and logs.
2. **Batch SQL translation**: attach the metadata ZIP as schema context in
**BigQuery > Migration > SQL translation**, or through the BigQuery
Migration API / BQMS MCP tools (see `bigquery-migration-sql-translator`).
3. **Table data transfer (out of scope)**: this skill extracts catalog metadata
and query logs only. If the user asks to export or load table rows (such as
Snowflake `COPY INTO` unloads), ask whether they want to use the
[BigQuery Data Transfer Service][bq_dts] (including the
[Snowflake transfer connector][snowflake_dts]) or export to Parquet/CSV in
Cloud Storage and load with `bq load`.
[bq_dts]: https://docs.cloud.google.com/bigquery/docs/dts-introduction.md.txt
[cloud_locations]: https://cloud.google.com/about/locations
[extraction_stats_template]: assets/extraction_stats_template.py
[gcloud_install]: https://cloud.google.com/sdk/docs/install
[snowflake_dts]: https://docs.cloud.google.com/bigquery/docs/migration/snowflake-transfer.md.txt
extraction_stats_template.py 49.6 KB
#!/usr/bin/env python3
r"""Template Script for BigQuery Migration Metadata Extraction Statistics.
This asset template script inspects metadata and query-log ZIP archives
produced by `gcloud alpha bq migration {metadata,query-logs} extract` (such as
`dwh-migration-snowflake-metadata.zip` and `dwh-migration-snowflake-logs.zip`),
whether it ran locally or in the cloud, from either a local path or a Google
Cloud Storage (`gs://`) URI. It validates that the archive is not an incomplete
22-byte GCS NIO ZipFS placeholder, parses the extracted catalog files and
extractor telemetry across Snowflake, Redshift, Teradata, ANSI SQL, and
BigQuery dumps, and prints a structured summary of what was extracted.
Usage Pattern:
Copy `assets/extraction_stats_template.py` from this skill's directory
(`<SKILL_DIR>`, the directory containing `SKILL.md`) into your working
directory (e.g., `./extraction_stats.py`). Run the copy as-is for
standard post-extraction verification and reporting, and prioritize modifying
the marked `# CUSTOMIZE:` extension points if your workflow requires custom
schema/table filtering, custom complex data type rules, custom validation
thresholds, or custom output formatting. Sections marked
`# DEFAULT SCAFFOLDING` can be kept unchanged unless deeper orchestration
adjustments are needed.
Dependencies:
Uses the Python 3.9+ standard library only (no third-party pip packages
required). Requires `gcloud` CLI when inspecting `gs://` URIs directly.
Usage Examples:
# Copy the template from this skill's directory to your working directory:
cp <SKILL_DIR>/assets/extraction_stats_template.py ./extraction_stats.py
# 1. Inspect a GCS extraction output directory or ZIP URI directly:
python3 ./extraction_stats.py \
--input gs://my-bucket/snowflake_metadata/
# 2. Inspect a local extracted metadata ZIP archive and export JSON/Markdown:
python3 ./extraction_stats.py \
--input ./dwh-migration-snowflake-metadata.zip \
--output-json ./extraction_stats.json \
--output-markdown ./extraction_stats.md
"""
from __future__ import annotations
import argparse
import collections
import csv
import datetime
import io
import json
import os
import re
import subprocess
import sys
from typing import Any
import zipfile
# Increase CSV field limit to safely parse multi-line view DDLs and query logs.
csv.field_size_limit(10 * 1024 * 1024)
# ==============================================================================
# 1. Extension Points: Filtering & Classification Rules (CUSTOMIZE)
# ==============================================================================
# CUSTOMIZE: Custom Schema & Table Filtering
_EXCLUDED_SYSTEM_SCHEMAS: set[str] = {
"INFORMATION_SCHEMA",
"PG_CATALOG",
"PG_INTERNAL",
"DBC",
"SYSLIB",
"SYSUDTLIB",
}
def _should_include_schema(schema_name: str) -> bool:
"""Determines whether a source schema should be included in catalog stats.
Override this function or update `_EXCLUDED_SYSTEM_SCHEMAS` if you want to
exclude system, staging, or scratch schemas (such as INFORMATION_SCHEMA,
PG_CATALOG, DBC, or STAGING_TMP) from object counts.
Args:
schema_name: Source schema name from catalog CSVs.
Returns:
True if the schema should be included in the statistics report.
"""
excluded = {s.strip().upper() for s in _EXCLUDED_SYSTEM_SCHEMAS}
return schema_name.strip().upper() not in excluded
# CUSTOMIZE: Complex Data Type Classification
def _classify_special_data_types(
data_type_counts: dict[str, int],
) -> dict[str, int]:
"""Identifies source column types requiring special migration attention.
Flags semi-structured, high-precision numeric, and temporal types that need
explicit casting or transformation during downstream Parquet export and
BigQuery SQL translation.
Args:
data_type_counts: Mapping of uppercase source DataType to column count.
Returns:
Subset mapping of flagged data types to their column counts.
"""
special_keywords = (
"VARIANT",
"ARRAY",
"OBJECT",
"SUPER",
"GEOGRAPHY",
"GEOMETRY",
"NUMBER",
"DECIMAL",
"NUMERIC",
"TIMESTAMP",
)
flagged: dict[str, int] = {}
for dtype, count in data_type_counts.items():
if any(kw in dtype.upper() for kw in special_keywords):
flagged[dtype] = count
return flagged
# CUSTOMIZE: Custom Telemetry & Archive Validation Thresholds
_MIN_VALID_ZIP_BYTES = 22
# ==============================================================================
# 2. Storage & Archive Discovery Helpers (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Local and GCS ZIP discovery and reading utilities.
def format_bytes(num_bytes: int) -> str:
"""Formats a byte count into a human-readable string."""
if num_bytes < 1024:
return f"{num_bytes:,} B"
if num_bytes < 1024 * 1024:
return f"{num_bytes:,} B ({num_bytes / 1024:.2f} KB)"
if num_bytes < 1024 * 1024 * 1024:
return f"{num_bytes:,} B ({num_bytes / (1024 * 1024):.2f} MB)"
return f"{num_bytes:,} B ({num_bytes / (1024 * 1024 * 1024):.2f} GB)"
def discover_zip_sources(input_path_or_uri: str) -> list[str]:
"""Resolves a local path or GCS URI into one or more ZIP archive paths/URIs.
Ignores temporary GCS NIO ZipFS staging files (`zipfstmp*.tmp`).
Args:
input_path_or_uri: Local file/directory path or `gs://` file/prefix URI.
Returns:
Sorted list of local paths or `gs://` URIs ending in `.zip`.
Raises:
FileNotFoundError: If no matching ZIP archives exist at the given path/URI.
"""
if input_path_or_uri.startswith("gs://"):
if input_path_or_uri.lower().endswith(".zip"):
return [input_path_or_uri]
prefix = input_path_or_uri.rstrip("/") + "/*.zip"
cmd = ["gcloud", "storage", "ls", prefix]
res = subprocess.run(cmd, capture_output=True, text=True, check=False)
if res.returncode != 0:
raise FileNotFoundError(
f"No .zip archives found under GCS URI '{input_path_or_uri}': "
f"{res.stderr.strip()}"
)
uris = [
line.strip()
for line in res.stdout.splitlines()
if line.strip().endswith(".zip")
and "zipfstmp" not in os.path.basename(line.strip())
]
if not uris:
raise FileNotFoundError(
f"No finalized .zip archives found under '{input_path_or_uri}'."
)
return sorted(uris)
if not os.path.exists(input_path_or_uri):
raise FileNotFoundError(f"Input path not found: '{input_path_or_uri}'")
if os.path.isfile(input_path_or_uri):
return [input_path_or_uri]
found: list[str] = []
for entry in sorted(os.listdir(input_path_or_uri)):
if entry.endswith(".zip") and not entry.startswith("zipfstmp"):
found.append(os.path.join(input_path_or_uri, entry))
if not found:
raise FileNotFoundError(
f"No .zip archives found in directory: '{input_path_or_uri}'"
)
return found
def read_zip_bytes(path_or_uri: str) -> bytes:
"""Reads raw bytes of a ZIP archive from a local path or GCS URI."""
if path_or_uri.startswith("gs://"):
cmd = ["gcloud", "storage", "cat", path_or_uri]
res = subprocess.run(cmd, capture_output=True, check=False)
if res.returncode != 0:
err = res.stderr.decode("utf-8", errors="replace").strip()
raise RuntimeError(f"Failed to read GCS archive '{path_or_uri}': {err}")
return res.stdout
with open(path_or_uri, "rb") as f:
return f.read()
# ==============================================================================
# 3. CSV & Telemetry Parsing Engine (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Escape-aware CSV reader and multi-dialect catalog parser.
def _find_zip_entry(zf: zipfile.ZipFile, candidates: list[str]) -> str | None:
"""Finds the first matching entry in a ZipFile (exact or basename match)."""
entries = [info.filename for info in zf.infolist() if not info.is_dir()]
entry_set = set(entries)
for cand in candidates:
if cand in entry_set:
return cand
lower_map = {os.path.basename(e).lower(): e for e in entries}
for cand in candidates:
match = lower_map.get(cand.lower())
if match:
return match
return None
def _read_csv_from_zip(
zf: zipfile.ZipFile, candidates: list[str]
) -> list[dict[str, str]]:
r"""Reads the first matching CSV file from a ZipFile using escapechar='\\'.
The extractor escapes embedded quotes inside multi-line view DDLs with
backslashes (`\"`). Setting `escapechar='\\'` prevents misparsing multi-line
SQL definitions into extra rows.
Args:
zf: Open `zipfile.ZipFile` instance.
candidates: Ordered list of candidate entry filenames (e.g.
`['tables-au.csv', 'tables.csv']`).
Returns:
List of row dictionaries parsed via `csv.DictReader`.
"""
target = _find_zip_entry(zf, candidates)
if not target:
return []
raw_text = zf.read(target).decode("utf-8-sig", errors="replace")
reader = csv.DictReader(io.StringIO(raw_text), escapechar="\\")
return [dict(row) for row in reader]
def _count_csv_rows_in_zip(zf: zipfile.ZipFile, entry_name: str) -> int:
r"""Counts the data rows of a CSV entry without loading it into memory.
Streams the entry with the same `escapechar='\\'` parsing as
`_read_csv_from_zip()` and, like `csv.DictReader`, skips blank rows and does
not count the header row.
Args:
zf: Open `zipfile.ZipFile` instance.
entry_name: Exact entry name inside the archive.
Returns:
Number of data rows (0 for an empty file or a header-only file).
"""
with zf.open(entry_name) as raw:
text = io.TextIOWrapper(
raw, encoding="utf-8-sig", errors="replace", newline=""
)
non_blank_rows = sum(1 for row in csv.reader(text, escapechar="\\") if row)
return max(non_blank_rows - 1, 0)
def _get_field(row: dict[str, str], *keys: str) -> str:
"""Case-insensitive dictionary lookup returning a stripped string."""
for k in keys:
val = row.get(k)
if val is not None and str(val).strip():
return str(val).strip()
lower_row = {
str(rk).strip().lower(): str(rv).strip()
for rk, rv in row.items()
if rk is not None and rv is not None
}
for k in keys:
val = lower_row.get(k.lower())
if val:
return val
return ""
def _read_bigquery_tables_jsonl(
zf: zipfile.ZipFile,
) -> tuple[
bool, list[dict[str, str]], list[dict[str, str]], list[dict[str, str]]
]:
"""Reads a `bigquery` connector `tables.jsonl` as table and column rows.
The `bigquery` connector writes one JSON object per table (project, dataset,
table, tableType, a nested schema, and `viewQuery` for views) instead of
catalog CSVs. Each object is converted into the row shape used for the CSV
catalogs so that the same counting logic applies:
* `TABLE` becomes a base table; `VIEW` and `MATERIALIZED_VIEW` become views,
with `viewQuery` as their DDL.
* `EXTERNAL` tables are returned as external table rows. Like external tables
in the CSV catalogs, they and their columns are not counted as base tables.
* Other types (such as `SNAPSHOT` table snapshots) are kept in the table rows
so that their columns are excluded, but are not counted as tables or views.
Only top-level fields count as columns; nested `RECORD` subfields do not. The
connector records no row counts or sizes.
Args:
zf: Open `zipfile.ZipFile` instance.
Returns:
Tuple of (found, table rows, column rows, external table rows). `found` is
True when the archive has a `tables.jsonl` entry, even an empty one; the
lists are empty without one.
"""
target = _find_zip_entry(zf, ["tables.jsonl"])
if not target:
return False, [], [], []
table_rows: list[dict[str, str]] = []
col_rows: list[dict[str, str]] = []
ext_rows: list[dict[str, str]] = []
raw_text = zf.read(target).decode("utf-8-sig", errors="replace")
for line in raw_text.splitlines():
line = line.strip()
if not line:
continue
try:
record = json.loads(line)
except json.JSONDecodeError:
continue
if not isinstance(record, dict):
continue
project = str(record.get("project") or "")
dataset = str(record.get("dataset") or "")
table = str(record.get("table") or "")
if not dataset or not table:
continue
table_type = str(record.get("tableType") or "TABLE").upper()
table_rows.append({
"TableCatalog": project,
"TableSchema": dataset,
"TableName": table,
"TableType": "BASE TABLE" if table_type == "TABLE" else table_type,
"ViewDefinition": str(record.get("viewQuery") or ""),
})
if table_type == "EXTERNAL":
ext_rows.append({
"TableCatalog": project,
"SchemaName": dataset,
"TableName": table,
})
fields = record.get("schema")
if not isinstance(fields, list):
continue
for field in fields:
if not isinstance(field, dict):
continue
dtype = str(field.get("type") or "UNKNOWN").upper()
if str(field.get("mode") or "").upper() == "REPEATED":
dtype = f"ARRAY<{dtype}>"
col_rows.append({
"TableCatalog": project,
"TableSchema": dataset,
"TableName": table,
"ColumnName": str(field.get("name") or ""),
"DataType": dtype,
})
return True, table_rows, col_rows, ext_rows
_MIN_DATETIME = datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)
def _parse_client_time(value: str) -> datetime.datetime | None:
"""Parses a telemetry `dumperRunStartClientTime` into an aware datetime.
The extractor writes ISO-8601 timestamps with a `Z` or `+HH:MM` offset (and
possibly a `[Region/City]` zone ID) and a variable number of fractional
digits, which `datetime.fromisoformat()` only accepts from Python 3.11 on.
Args:
value: Raw timestamp string.
Returns:
Timezone-aware datetime (UTC if the value has no offset), or None if the
value cannot be parsed.
"""
text = re.sub(r"\[[^\]]*\]$", "", value.strip())
if text[-1:] in ("Z", "z"):
text = text[:-1] + "+00:00"
parts = re.match(
r"^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2})(:\d{2})?(?:[.,](\d+))?(.*)$", text
)
if not parts:
return None
fraction = (parts.group(3) or "").ljust(6, "0")[:6]
text = f"{parts.group(1)}{parts.group(2) or ':00'}.{fraction}{parts.group(4)}"
try:
parsed = datetime.datetime.fromisoformat(text)
except ValueError:
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=datetime.timezone.utc)
return parsed
def _select_archive_run(
records: list[dict[str, Any]], archive_connector: str
) -> list[dict[str, Any]]:
"""Returns the telemetry records of the run that produced this archive.
The extractor keeps one telemetry file per machine, adds every run to it (not
always in time order), and copies the whole file into each archive. Only the
run that wrote this archive may contribute fields such as host, warehouse, or
user. A record with a start time opens a run; records without one continue
the run opened before them, and records before the first start time are used
only if no run has a start time. Runs whose connector matches
`compilerworks-arguments.txt` are preferred, and among them the run with the
latest start time (compared as timezone-aware datetimes) wins.
Args:
records: Parsed `dumper-telemetry.jsonl` records, in file order.
archive_connector: Connector named in `compilerworks-arguments.txt`, or "".
Returns:
Records of the selected run, in file order (empty if there are none).
"""
runs: dict[str, list[dict[str, Any]]] = {}
current_start = ""
for record in records:
start = str(record.get("dumperRunStartClientTime") or "")
if start:
current_start = start
runs.setdefault(current_start, []).append(record)
candidates = {k: v for k, v in runs.items() if k} or runs
def _run_connector(run: list[dict[str, Any]]) -> str:
for record in run:
payloads = record.get("payload")
if isinstance(payloads, list) and payloads:
first = payloads[0] if isinstance(payloads[0], dict) else {}
summary = first.get("argumentSummary")
if isinstance(summary, dict) and summary.get("connector"):
return str(summary["connector"]).strip().lower()
return ""
wanted = archive_connector.strip().lower()
if wanted:
matching = {
k: v for k, v in candidates.items() if _run_connector(v) == wanted
}
candidates = matching or candidates
if not candidates:
return []
def _run_order(start: str) -> tuple[bool, datetime.datetime, str]:
parsed = _parse_client_time(start) if start else None
return (parsed is not None, parsed or _MIN_DATETIME, start)
return candidates[max(candidates, key=_run_order)]
def _parse_dumper_telemetry(zf: zipfile.ZipFile) -> dict[str, Any]:
"""Extracts connector, host, status, and task counts from telemetry files."""
telemetry: dict[str, Any] = {
"format": "",
"overall_status": "UNKNOWN",
"connector": "",
"host": "",
"warehouse": "",
"user": "",
"databases_arg": [],
"dumper_version": "",
"run_start_time": "",
"run_duration_minutes": 0,
"tasks_succeeded": 0,
"tasks_skipped": 0,
"tasks_failed": 0,
"warehouse_count": None,
}
fmt_entry = _find_zip_entry(zf, ["compilerworks-format.txt"])
if fmt_entry:
telemetry["format"] = (
zf.read(fmt_entry).decode("utf-8", errors="replace").strip()
)
sf_entry = _find_zip_entry(zf, ["snowflake.yaml"])
if sf_entry:
sf_yaml = zf.read(sf_entry).decode("utf-8", errors="replace")
match = re.search(r"warehouse_count:\s*(\d+)", sf_yaml)
if match:
telemetry["warehouse_count"] = int(match.group(1))
# compilerworks-arguments.txt holds the arguments of the run that wrote this
# archive; its connector also picks that run out of the shared telemetry.
archive_args: dict[str, str] = {}
args_entry = _find_zip_entry(zf, ["compilerworks-arguments.txt"])
if args_entry:
args_txt = zf.read(args_entry).decode("utf-8", errors="replace")
for arg_name in ("connector", "host", "warehouse"):
arg_match = re.search(rf"\b{arg_name}=([^,\s}}]+)", args_txt)
if arg_match and arg_match.group(1) != "null":
archive_args[arg_name] = arg_match.group(1)
tel_entry = _find_zip_entry(zf, ["dumper-telemetry.jsonl"])
if tel_entry:
raw_lines = (
zf.read(tel_entry).decode("utf-8", errors="replace").splitlines()
)
records: list[dict[str, Any]] = []
for line in raw_lines:
line = line.strip()
if not line:
continue
try:
parsed = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
records.append(parsed)
records = _select_archive_run(records, archive_args.get("connector", ""))
for record in records:
if record.get("dumperRunStartClientTime"):
telemetry["run_start_time"] = record["dumperRunStartClientTime"]
meta = record.get("dumperMetadata", {})
if isinstance(meta, dict) and meta.get("version"):
telemetry["dumper_version"] = meta["version"]
payloads = record.get("payload", [])
if isinstance(payloads, list) and payloads:
first = payloads[0] if isinstance(payloads[0], dict) else {}
if first.get("overallStatus"):
telemetry["overall_status"] = first["overallStatus"]
if first.get("runDurationInMinutes") is not None:
telemetry["run_duration_minutes"] = first["runDurationInMinutes"]
task_summary = first.get("taskExecutionSummary")
if isinstance(task_summary, list) and task_summary:
telemetry["tasks_succeeded"] = 0
telemetry["tasks_skipped"] = 0
telemetry["tasks_failed"] = 0
for task_stat in task_summary:
if not isinstance(task_stat, dict):
continue
status = str(task_stat.get("status", "")).upper()
count = int(task_stat.get("count", 0) or 0)
if status == "SUCCEEDED":
telemetry["tasks_succeeded"] += count
elif status == "SKIPPED":
telemetry["tasks_skipped"] += count
elif status == "FAILED":
telemetry["tasks_failed"] += count
args_summary = first.get("argumentSummary", {})
if isinstance(args_summary, dict):
if args_summary.get("connector"):
telemetry["connector"] = args_summary["connector"]
if args_summary.get("host"):
telemetry["host"] = args_summary["host"]
if args_summary.get("warehouse"):
telemetry["warehouse"] = args_summary["warehouse"]
if args_summary.get("user"):
telemetry["user"] = args_summary["user"]
dbs = args_summary.get("database", [])
if isinstance(dbs, list) and dbs:
telemetry["databases_arg"] = [str(d) for d in dbs]
for arg_name, arg_value in archive_args.items():
if not telemetry[arg_name]:
telemetry[arg_name] = arg_value
return telemetry
def _safe_int(val: str | None) -> int:
"""Parses an integer string safely, returning 0 on empty or invalid input."""
if not val:
return 0
try:
return int(float(val.strip()))
except (ValueError, TypeError):
return 0
def analyze_zip_archive(path_or_uri: str, zip_bytes: bytes) -> dict[str, Any]:
"""Analyzes a Cloud Extractor ZIP payload and returns structured statistics.
Supports Snowflake, Redshift, Teradata, ANSI SQL, and BigQuery catalog dumps
as well as query history log archives.
Args:
path_or_uri: Source path or GCS URI of the archive.
zip_bytes: Raw bytes of the `.zip` file.
Returns:
Dictionary containing archive validation status, telemetry metadata, object
counts, row/byte volume totals, per-schema breakdown, base table details,
view inventory, data type distribution, and query log statistics.
"""
size_bytes = len(zip_bytes)
is_zipfs_placeholder = size_bytes <= _MIN_VALID_ZIP_BYTES
stats: dict[str, Any] = {
"archive_path": path_or_uri,
"archive_name": os.path.basename(path_or_uri.rstrip("/")),
"size_bytes": size_bytes,
"size_formatted": format_bytes(size_bytes),
"is_valid_archive": False,
"is_zipfs_placeholder": is_zipfs_placeholder,
"validation_message": "",
"archive_type": "UNKNOWN",
"telemetry": {},
"files_in_archive": [],
"databases": [],
"schemas": [],
"counts": {
"databases": 0,
"schemas": 0,
"active_schemas": 0,
"base_tables": 0,
"views": 0,
"columns": 0,
"base_table_columns": 0,
"view_columns": 0,
"functions": 0,
"external_tables": 0,
"query_log_files": 0,
"query_log_entries": 0,
},
"volume": {
"total_base_rows": 0,
"total_base_bytes": 0,
"total_base_bytes_formatted": "0 B",
"available": True,
},
"schema_breakdown": [],
"base_tables": [],
"views": [],
"data_type_distribution": {},
"special_data_types": {},
}
if is_zipfs_placeholder:
stats["validation_message"] = (
f"INCOMPLETE ARCHIVE ({size_bytes} bytes <= {_MIN_VALID_ZIP_BYTES} B): "
"Detected GCS NIO ZipFS empty placeholder header. The GCE extraction "
"VM may still be running or terminated before flushing ZIP chunks."
)
return stats
try:
zf_ctx = zipfile.ZipFile(io.BytesIO(zip_bytes), "r")
except zipfile.BadZipFile as e:
stats["validation_message"] = f"CORRUPT ZIP ARCHIVE: {e}"
return stats
with zf_ctx as zf:
namelist = sorted(
info.filename for info in zf.infolist() if not info.is_dir()
)
stats["files_in_archive"] = namelist
stats["is_valid_archive"] = True
stats["validation_message"] = (
f"VALID ({format_bytes(size_bytes)}, {len(namelist)} files)"
)
telemetry = _parse_dumper_telemetry(zf)
stats["telemetry"] = telemetry
# Parse catalog CSVs across Snowflake, Redshift, Teradata, and ANSI SQL
db_candidates = [
"databases-au.csv",
"databases.csv",
"database.csv",
"dbc.DatabasesV.csv",
]
db_entry = _find_zip_entry(zf, db_candidates)
db_rows = _read_csv_from_zip(zf, db_candidates)
schema_rows = _read_csv_from_zip(
zf,
["schemata-au.csv", "schemata.csv"],
) + _read_csv_from_zip(zf, ["svv_external_schemas.csv"])
table_rows = _read_csv_from_zip(
zf,
[
"tables-au.csv",
"tables.csv",
"svv_tables.csv",
"dbc.TablesV.csv",
],
)
rs_table_info_rows = _read_csv_from_zip(zf, ["svv_table_info.csv"])
td_table_size_rows = _read_csv_from_zip(zf, ["dbc.TableSizeV.csv"])
view_rows = _read_csv_from_zip(zf, ["views-au.csv", "views.csv"])
col_rows = _read_csv_from_zip(
zf,
[
"columns-au.csv",
"columns.csv",
"svv_columns.csv",
"dbc.ColumnsV.csv",
"dbc.Columns.csv",
],
)
func_rows = _read_csv_from_zip(
zf,
[
"functions-au.csv",
"functions.csv",
"function_info.csv",
"dbc.FunctionsV.csv",
],
)
ext_rows = _read_csv_from_zip(
zf, ["external_tables.csv", "svv_external_tables.csv"]
)
# The bigquery connector writes tables.jsonl instead of catalog CSVs and
# records no row counts or sizes, even when tables.jsonl is empty. Other
# connectors (such as hiveql) write a tables.jsonl with a different layout,
# so read it only when the archive names the bigquery connector (or names
# no connector or format at all).
archive_source = (
str(telemetry.get("connector") or "").strip().lower()
or str(telemetry.get("format") or "").strip().lower()
)
is_bigquery_archive = not archive_source or archive_source.startswith(
"bigquery"
)
bq_found = False
bq_table_rows: list[dict[str, str]] = []
if is_bigquery_archive and not table_rows and not col_rows:
bq_found, bq_table_rows, bq_col_rows, bq_ext_rows = (
_read_bigquery_tables_jsonl(zf)
)
if bq_found:
table_rows = bq_table_rows
col_rows = bq_col_rows
ext_rows = ext_rows + bq_ext_rows
has_volume_stats = not bq_found
# Build lookup maps for Redshift svv_table_info and Teradata dbc.TableSizeV
rs_info_map: dict[tuple[str, str, str], dict[str, Any]] = {}
for info_r in rs_table_info_rows:
r_db = _get_field(info_r, "database", "table_catalog")
r_sch = _get_field(info_r, "schema", "table_schema")
r_tbl = _get_field(info_r, "table", "table_name")
if not r_tbl:
continue
size_mb = _safe_int(_get_field(info_r, "size"))
info_entry = {
"catalog": r_db,
"schema": r_sch,
"table": r_tbl,
"row_count": _safe_int(
_get_field(info_r, "tbl_rows", "estimated_visible_rows")
),
"bytes": size_mb * 1024 * 1024,
"clustering_key": _get_field(info_r, "sortkey1"),
}
rs_info_map[(r_db.upper(), r_sch.upper(), r_tbl.upper())] = info_entry
rs_info_map.setdefault(("", r_sch.upper(), r_tbl.upper()), info_entry)
# If svv_tables.csv is absent in a Redshift dump, synthesize table_rows
if not table_rows and rs_table_info_rows:
for info_r in rs_table_info_rows:
table_rows.append({
"TableCatalog": _get_field(info_r, "database"),
"TableSchema": _get_field(info_r, "schema"),
"TableName": _get_field(info_r, "table"),
"TableType": "BASE TABLE",
})
td_size_map: collections.Counter[tuple[str, str]] = collections.Counter()
for sz_r in td_table_size_rows:
t_sch = _get_field(sz_r, "DataBaseName", "DatabaseName", "TableSchema")
t_tbl = _get_field(sz_r, "TableName")
perm_bytes = _safe_int(_get_field(sz_r, "CurrentPerm", "Bytes"))
if t_sch and t_tbl:
td_size_map[(t_sch.upper(), t_tbl.upper())] += perm_bytes
# Parse query log CSVs if present
log_prefixes = ("query_history", "querytext", "ddltext", "dwhassessment_")
query_log_files = [
fn
for fn in namelist
if os.path.basename(fn).lower().startswith(log_prefixes)
and fn.lower().endswith(".csv")
]
query_log_entries = sum(
_count_csv_rows_in_zip(zf, qfn) for qfn in query_log_files
)
if query_log_files and not table_rows and not col_rows:
stats["archive_type"] = "QUERY_LOGS"
else:
stats["archive_type"] = "CATALOG_METADATA"
# Databases
db_names_set: set[str] = set()
# The Redshift, PostgreSQL, and Greenplum connectors write database.csv
# with the database name in a `Name` column, including the template0 and
# template1 template databases. Read `Name` only from that file so that
# other dialects' database CSVs can't match it.
is_pg_database_csv = (
bool(db_entry) and os.path.basename(db_entry).lower() == "database.csv"
)
db_name_keys: tuple[str, ...] = (
"DatabaseName",
"DataBaseName",
"database_name",
"datname",
)
if is_pg_database_csv:
db_name_keys += ("Name",)
for r in db_rows:
dname = _get_field(r, *db_name_keys)
if not dname or not _should_include_schema(dname):
continue
if is_pg_database_csv and dname.lower() in ("template0", "template1"):
continue
db_names_set.add(dname)
for info_v in rs_info_map.values():
if info_v["catalog"]:
db_names_set.add(info_v["catalog"])
for bq_row in bq_table_rows:
if bq_row["TableCatalog"]:
db_names_set.add(bq_row["TableCatalog"])
if not db_names_set and telemetry.get("databases_arg"):
db_names_set.update(telemetry["databases_arg"])
db_names = sorted(db_names_set)
stats["databases"] = db_names
# Schemas (normalized case-insensitively via per_schema)
per_schema: dict[str, dict[str, Any]] = {}
def _ensure_schema_entry(schema_name: str) -> dict[str, Any]:
key = schema_name.upper()
if key not in per_schema:
per_schema[key] = {
"schema": schema_name,
"base_tables": 0,
"views": 0,
"rows": 0,
"bytes": 0,
"bytes_formatted": "0 B",
}
return per_schema[key]
for r in schema_rows:
sname = _get_field(
r, "SchemaName", "schema_name", "schemaname", "DatabaseName"
)
if sname and _should_include_schema(sname):
_ensure_schema_entry(sname)
# Identify skipped non-table/non-view relations (e.g. Teradata macros/UDFs
# or EXTERNAL/TEMPORARY/EVENT TABLE rows) so their columns are excluded from
# column totals without colliding across catalogs.
skipped_relations: set[tuple[str, str, str]] = set()
skipped_relations_no_cat: set[tuple[str, str]] = set()
included_relations: set[tuple[str, str, str]] = set()
included_relations_no_cat: set[tuple[str, str]] = set()
for t in table_rows:
t_cat = _get_field(t, "TableCatalog", "table_catalog")
t_schema = _get_field(
t, "TableSchema", "table_schema", "DataBaseName", "DatabaseName"
)
t_name = _get_field(t, "TableName", "table_name")
t_type = _get_field(t, "TableType", "table_type").upper()
t_kind = _get_field(t, "TableKind", "table_kind").upper()
if not t_name or not t_schema:
continue
is_skipped = False
if t_kind and not t_type and t_kind not in ("T", "O", "V"):
is_skipped = True
elif any(k in t_type for k in ("EXTERNAL", "TEMPORARY", "EVENT")):
is_skipped = True
elif t_type and "VIEW" not in t_type and "TABLE" not in t_type:
is_skipped = True
if is_skipped:
skipped_relations.add((t_cat.upper(), t_schema.upper(), t_name.upper()))
skipped_relations_no_cat.add((t_schema.upper(), t_name.upper()))
else:
included_relations.add(
(t_cat.upper(), t_schema.upper(), t_name.upper())
)
included_relations_no_cat.add((t_schema.upper(), t_name.upper()))
# Columns per (catalog, schema, table) & DataType distribution
col_count_by_table: collections.Counter[tuple[str, str, str]] = (
collections.Counter()
)
col_count_by_table_no_cat: collections.Counter[tuple[str, str]] = (
collections.Counter()
)
dtype_counter: collections.Counter[str] = collections.Counter()
filtered_col_count = 0
for c in col_rows:
c_cat = _get_field(c, "TableCatalog", "table_catalog")
c_schema = _get_field(
c, "TableSchema", "table_schema", "DatabaseName", "DataBaseName"
)
c_table = _get_field(c, "TableName", "table_name")
if not c_schema or not _should_include_schema(c_schema):
continue
c_key3 = (c_cat.upper(), c_schema.upper(), c_table.upper())
c_key2 = (c_schema.upper(), c_table.upper())
if c_key3 in skipped_relations or (
c_key3 not in included_relations
and c_key2 in skipped_relations_no_cat
and (not c_cat or c_key2 not in included_relations_no_cat)
):
continue
filtered_col_count += 1
if c_table:
col_count_by_table[c_key3] += 1
col_count_by_table_no_cat[c_key2] += 1
dtype = _get_field(c, "DataType", "data_type", "ColumnType") or "UNKNOWN"
if dtype:
dtype_counter[dtype.upper()] += 1
def _get_col_count(cat: str, schema: str, name: str) -> int:
exact = col_count_by_table.get(
(cat.upper(), schema.upper(), name.upper())
)
if exact is not None:
return exact
if not cat:
return col_count_by_table_no_cat.get((schema.upper(), name.upper()), 0)
return col_count_by_table.get(("", schema.upper(), name.upper()), 0)
# Tables & Views breakdown
base_tables: list[dict[str, Any]] = []
views_from_tables_csv: dict[tuple[str, str, str], dict[str, Any]] = {}
td_extra_functions = 0
for t in table_rows:
t_cat = _get_field(t, "TableCatalog", "table_catalog")
t_schema = _get_field(
t, "TableSchema", "table_schema", "DataBaseName", "DatabaseName"
)
t_name = _get_field(t, "TableName", "table_name")
t_type = _get_field(t, "TableType", "table_type").upper()
t_kind = _get_field(t, "TableKind", "table_kind").upper()
if not t_name or not t_schema or not _should_include_schema(t_schema):
continue
# Teradata TableKind classification ('T'/'O' = Table, 'V' = View)
if t_kind and not t_type:
if t_kind in ("T", "O"):
t_type = "BASE TABLE"
elif t_kind == "V":
t_type = "VIEW"
elif t_kind in ("F", "U", "P", "E", "M"):
td_extra_functions += 1
continue
else:
continue
if any(k in t_type for k in ("EXTERNAL", "TEMPORARY", "EVENT")):
continue
if t_type and "VIEW" not in t_type and "TABLE" not in t_type:
continue
s_entry = _ensure_schema_entry(t_schema)
key3 = (t_cat.upper(), t_schema.upper(), t_name.upper())
key2 = (t_schema.upper(), t_name.upper())
if "VIEW" in t_type:
req_ddl = _get_field(t, "ViewDefinition", "RequestText")
views_from_tables_csv[key3] = {
"catalog": t_cat,
"schema": t_schema,
"view": t_name,
"full_name": f"{t_schema}.{t_name}",
"column_count": _get_col_count(t_cat, t_schema, t_name),
"has_ddl": bool(req_ddl),
}
else:
rs_meta = rs_info_map.get(key3) or rs_info_map.get(
("", t_schema.upper(), t_name.upper()), {}
)
row_cnt = _safe_int(_get_field(t, "RowCount", "row_count"))
if not row_cnt and rs_meta:
row_cnt = rs_meta.get("row_count", 0)
byte_cnt = _safe_int(_get_field(t, "Bytes", "bytes"))
if not byte_cnt and rs_meta:
byte_cnt = rs_meta.get("bytes", 0)
if not byte_cnt and key2 in td_size_map:
byte_cnt = td_size_map[key2]
cluster_key = _get_field(t, "ClusteringKey", "clustering_key")
if not cluster_key and rs_meta:
cluster_key = rs_meta.get("clustering_key", "")
col_cnt = _get_col_count(t_cat, t_schema, t_name)
base_tables.append({
"catalog": t_cat or rs_meta.get("catalog", ""),
"schema": t_schema,
"table": t_name,
"full_name": f"{t_schema}.{t_name}",
"row_count": row_cnt,
"bytes": byte_cnt,
"bytes_formatted": format_bytes(byte_cnt),
"column_count": col_cnt,
"clustering_key": cluster_key,
})
s_entry["base_tables"] += 1
s_entry["rows"] += row_cnt
s_entry["bytes"] += byte_cnt
# Views from views-au.csv merged with VIEW rows from tables CSV
views_list: list[dict[str, Any]] = []
seen_views: set[tuple[str, str, str]] = set()
seen_views_no_cat: set[tuple[str, str]] = set()
for v in view_rows:
v_cat = _get_field(v, "TableCatalog", "table_catalog")
v_schema = _get_field(v, "TableSchema", "table_schema")
v_name = _get_field(v, "TableName", "table_name")
v_ddl = _get_field(v, "ViewDefinition", "view_definition")
if not v_name or not v_schema or not _should_include_schema(v_schema):
continue
key3 = (v_cat.upper(), v_schema.upper(), v_name.upper())
if key3 in seen_views:
continue
seen_views.add(key3)
seen_views_no_cat.add((v_schema.upper(), v_name.upper()))
s_entry = _ensure_schema_entry(v_schema)
s_entry["views"] += 1
views_list.append({
"catalog": v_cat,
"schema": v_schema,
"view": v_name,
"full_name": f"{v_schema}.{v_name}",
"column_count": _get_col_count(v_cat, v_schema, v_name),
"has_ddl": bool(v_ddl),
})
# Include any views from tables CSV that were not in views-au.csv
for key3, v_entry in sorted(views_from_tables_csv.items()):
cat_u, sch_u, name_u = key3
already_seen = (
key3 in seen_views
or ("", sch_u, name_u) in seen_views
or (not cat_u and (sch_u, name_u) in seen_views_no_cat)
)
if not already_seen:
seen_views.add(key3)
seen_views_no_cat.add((sch_u, name_u))
s_entry = _ensure_schema_entry(v_entry["schema"])
s_entry["views"] += 1
views_list.append(v_entry)
# Sort base tables by row_count descending, then bytes descending, then name
base_tables.sort(
key=lambda x: (-x["row_count"], -x["bytes"], x["full_name"])
)
views_list.sort(key=lambda x: x["full_name"])
for s_entry in per_schema.values():
s_entry["bytes_formatted"] = format_bytes(s_entry["bytes"])
schema_breakdown = sorted(
per_schema.values(),
key=lambda s: (
-(s["base_tables"] + s["views"]),
-s["rows"],
s["schema"],
),
)
active_schemas = [
s for s in schema_breakdown if s["base_tables"] > 0 or s["views"] > 0
]
total_rows = sum(t["row_count"] for t in base_tables)
total_bytes = sum(t["bytes"] for t in base_tables)
base_table_cols = sum(t["column_count"] for t in base_tables)
view_cols = sum(v["column_count"] for v in views_list)
views_with_ddl = sum(1 for v in views_list if v.get("has_ddl"))
filtered_funcs = [
fn_r
for fn_r in func_rows
if _should_include_schema(
_get_field(
fn_r,
"FunctionSchema",
"function_schema",
"SchemaName",
"DatabaseName",
"Schema",
)
)
]
filtered_exts = [
ex_r
for ex_r in ext_rows
if _should_include_schema(
_get_field(ex_r, "SchemaName", "schemaname", "table_schema")
)
]
sorted_dtypes = dict(
sorted(dtype_counter.items(), key=lambda kv: (-kv[1], kv[0]))
)
special_dtypes = _classify_special_data_types(sorted_dtypes)
normalized_schemas = sorted(s["schema"] for s in per_schema.values())
stats["schemas"] = normalized_schemas
stats["counts"] = {
"databases": len(db_names),
"schemas": len(normalized_schemas),
"active_schemas": len(active_schemas),
"base_tables": len(base_tables),
"views": len(views_list),
"views_with_ddl": views_with_ddl,
"columns": filtered_col_count,
"base_table_columns": base_table_cols,
"view_columns": view_cols,
"functions": len(filtered_funcs) + td_extra_functions,
"external_tables": len(filtered_exts),
"query_log_files": len(query_log_files),
"query_log_entries": query_log_entries,
}
stats["volume"] = {
"total_base_rows": total_rows,
"total_base_bytes": total_bytes,
"total_base_bytes_formatted": format_bytes(total_bytes),
"available": has_volume_stats,
}
stats["schema_breakdown"] = schema_breakdown
stats["base_tables"] = base_tables
stats["views"] = views_list
stats["data_type_distribution"] = sorted_dtypes
stats["special_data_types"] = special_dtypes
return stats
# ==============================================================================
# 4. Report Formatting & Output Channels (CUSTOMIZE)
# ==============================================================================
# CUSTOMIZE: Report Formatting & Output Channels
def format_stats_report(
archive_stats_list: list[dict[str, Any]], top_tables: int = 25
) -> str:
"""Formats extracted archive statistics into a Markdown/console report.
Customize this function to alter table columns, add downstream migration
cost/complexity estimates, or adjust summary sections.
Args:
archive_stats_list: List of archive statistic dicts from
`analyze_zip_archive()`.
top_tables: Maximum number of base tables to list in the detailed table.
Returns:
Formatted multi-line Markdown report string.
"""
lines: list[str] = []
lines.append("=" * 80)
lines.append(" BIGQUERY MIGRATION CLOUD EXTRACTOR - EXTRACTION REPORT")
lines.append("=" * 80)
for idx, st in enumerate(archive_stats_list, start=1):
if idx > 1:
lines.append("\n" + "-" * 80)
lines.append(f"\n### Archive {idx}: `{st['archive_name']}`")
lines.append(f"- **Archive Path / URI**: `{st['archive_path']}`")
lines.append(f"- **Archive Validation**: {st['validation_message']}")
if not st["is_valid_archive"]:
continue
tel = st.get("telemetry", {})
connector = tel.get("connector") or tel.get("format") or "unknown"
host = tel.get("host") or "N/A"
warehouse = tel.get("warehouse") or "N/A"
wh_cnt = tel.get("warehouse_count")
wh_suffix = f" (total warehouses in account: {wh_cnt})" if wh_cnt else ""
status = tel.get("overall_status") or "SUCCESS"
dumper_ver = tel.get("dumper_version") or "N/A"
start_time = tel.get("run_start_time") or "N/A"
lines.append(f"- **Archive Type**: `{st['archive_type']}`")
lines.append(
f"- **Extractor Run Status**: `{status}` "
f"(Tasks: {tel.get('tasks_succeeded', 0)} succeeded, "
f"{tel.get('tasks_skipped', 0)} skipped, "
f"{tel.get('tasks_failed', 0)} failed | Version: {dumper_ver})"
)
lines.append(f"- **Source Connector & Host**: `{connector}` (`{host}`)")
lines.append(f"- **Compute Warehouse**: `{warehouse}`{wh_suffix}")
lines.append(f"- **Extraction Timestamp**: `{start_time}`")
cnt = st["counts"]
vol = st["volume"]
db_str = ", ".join(f"`{d}`" for d in st["databases"]) or "None"
schema_str = ", ".join(f"`{s}`" for s in st["schemas"]) or "None"
base_cols = cnt.get("base_table_columns", 0)
view_cols = cnt.get("view_columns", 0)
col_detail = (
f"{base_cols:,} in base tables, {view_cols:,} in views; "
f"{len(st['data_type_distribution'])} distinct data types"
)
views_total = cnt["views"]
views_ddl = cnt.get("views_with_ddl", views_total)
views_val = (
f"{views_ddl} (of {views_total} total)"
if views_ddl != views_total
else f"{views_ddl}"
)
lines.append("\n#### 1. Crucial Extracted Object Summary")
lines.append("| Metric | Count / Value | Details |")
lines.append("| :--- | :--- | :--- |")
lines.append(f"| **Databases** | {cnt['databases']} | {db_str} |")
lines.append(
f"| **Schemas** | {cnt['schemas']} "
f"({cnt['active_schemas']} with objects) | {schema_str} |"
)
has_volume = vol.get("available", True)
if has_volume:
base_detail = (
f"Total Rows: **{vol['total_base_rows']:,}** "
f"({vol['total_base_bytes_formatted']})"
)
else:
base_detail = "Rows and sizes are not recorded by this connector"
lines.append(f"| **Base Tables** | {cnt['base_tables']} | {base_detail} |")
lines.append(
f"| **Views (with DDL)** | {views_val} | "
"Ready for BQMS SQL translation |"
)
lines.append(f"| **Total Columns** | {cnt['columns']:,} | {col_detail} |")
lines.append(
f"| **Functions / Procedures** | {cnt['functions']} | "
"UDFs and stored procedures |"
)
lines.append(
f"| **External Tables** | {cnt['external_tables']} | "
"External stage tables |"
)
if cnt["query_log_files"] > 0:
lines.append(
f"| **Query History Logs** | {cnt['query_log_entries']:,} queries | "
f"Across {cnt['query_log_files']} log partition file(s) |"
)
if st["schema_breakdown"]:
lines.append("\n#### 2. Per-Schema Object Breakdown")
lines.append(
"| Schema | Base Tables | Views | Total Base Rows | Total Base Size |"
)
lines.append("| :--- | ---: | ---: | ---: | ---: |")
for sb in st["schema_breakdown"]:
sb_rows = f"{sb['rows']:,}" if has_volume else "N/A"
sb_size = sb["bytes_formatted"] if has_volume else "N/A"
lines.append(
f"| `{sb['schema']}` | {sb['base_tables']} | {sb['views']} | "
f"{sb_rows} | {sb_size} |"
)
if st["base_tables"]:
shown = st["base_tables"][:top_tables]
lines.append(
"\n#### 3. Base Tables Inventory "
f"(Showing {len(shown)} of {len(st['base_tables'])})"
)
lines.append(
"| # | Schema.Table | Rows | Size | Columns | Clustering Key |"
)
lines.append("| ---: | :--- | ---: | ---: | ---: | :--- |")
for i, tb in enumerate(shown, start=1):
ckey = f"`{tb['clustering_key']}`" if tb["clustering_key"] else "-"
tb_rows = f"{tb['row_count']:,}" if has_volume else "N/A"
tb_size = tb["bytes_formatted"] if has_volume else "N/A"
lines.append(
f"| {i} | `{tb['full_name']}` | {tb_rows} | "
f"{tb_size} | {tb['column_count']} | {ckey} |"
)
if st["views"]:
lines.append(f"\n#### 4. Extracted Views Inventory ({len(st['views'])})")
view_names = [f"`{v['full_name']}`" for v in st["views"]]
lines.append(", ".join(view_names[:40]))
if len(view_names) > 40:
lines.append(f"... and {len(view_names) - 40} more view(s).")
if st["data_type_distribution"]:
lines.append("\n#### 5. Column Data Type Distribution")
dtype_items = [
f"`{dt}`: {c:,}" for dt, c in st["data_type_distribution"].items()
]
lines.append("- **All Data Types**: " + ", ".join(dtype_items))
if st["special_data_types"]:
spec_items = [
f"`{dt}` ({c:,})" for dt, c in st["special_data_types"].items()
]
lines.append(
"- **Types Flagged for Type-Safe Parquet Cast / Translation**: "
+ ", ".join(spec_items)
)
lines.append("\n" + "=" * 80)
return "\n".join(lines)
# ==============================================================================
# 5. CLI Entrypoint & Orchestration (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Command-line parsing and exit-code management.
def main(argv: list[str] | None = None) -> int:
"""Main CLI entrypoint for inspecting Cloud Extractor ZIP archives."""
parser = argparse.ArgumentParser(
description=(
"Inspects BigQuery Migration Cloud Extractor ZIP archives and "
"prints crucial catalog and volume statistics."
)
)
parser.add_argument(
"--input",
required=True,
help=(
"Path to a local .zip archive, local directory containing .zip "
"archives, or a GCS URI (e.g. gs://bucket/snowflake_metadata/)."
),
)
parser.add_argument(
"--top-tables",
type=int,
default=25,
help="Maximum number of base tables to print in detail (default: 25).",
)
parser.add_argument(
"--output-json",
default="",
help="Optional path to write structured JSON statistics.",
)
parser.add_argument(
"--output-markdown",
default="",
help="Optional path to write the formatted Markdown summary report.",
)
args = parser.parse_args(argv)
zip_sources = discover_zip_sources(args.input)
all_stats: list[dict[str, Any]] = []
has_invalid = False
for src in zip_sources:
raw_bytes = read_zip_bytes(src)
st = analyze_zip_archive(src, raw_bytes)
if not st["is_valid_archive"]:
has_invalid = True
all_stats.append(st)
report_text = format_stats_report(all_stats, top_tables=args.top_tables)
print(report_text)
if args.output_json:
with open(args.output_json, "w", encoding="utf-8") as jf:
json.dump({"archives": all_stats}, jf, indent=2)
print(f"\n[INFO] Wrote JSON extraction statistics to: {args.output_json}")
if args.output_markdown:
with open(args.output_markdown, "w", encoding="utf-8") as mf:
mf.write(report_text + "\n")
print(f"[INFO] Wrote Markdown extraction report to: {args.output_markdown}")
return 1 if has_invalid else 0
if __name__ == "__main__":
sys.exit(main())
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-migration-metadata-extractor)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:bigquery-migration-metadata-extractor)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```text
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:bigquery-migration-metadata-extractor)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
cloud_extraction.md 19.5 KB
# Cloud Extraction (Cloud Extractor)
`--run-mode=cloud` runs the extractor on a temporary Compute Engine VM, the
**BigQuery Migration Cloud Extractor**. Nothing is installed locally. The
extractor arguments, including the password, reach the VM through a Secret
Manager secret.
## Contents
- [How It Works](#how-it-works): Lines 19-64
- [Prerequisites](#prerequisites): Lines 65-155
- [Cloud Flags](#cloud-flags): Lines 156-173
- [Credentials](#credentials): Lines 174-191
- [Recipes](#recipes): Lines 192-296
- [Monitoring](#monitoring): Lines 297-329
- [Cleanup](#cleanup): Lines 330-386
- [Troubleshooting](#troubleshooting): Lines 387-401
## How It Works
```mermaid
sequenceDiagram
autonumber
participant CLI as gcloud (user terminal)
participant SM as Secret Manager
participant VM as Cloud Extractor VM
participant DB as Source database
participant GCS as Cloud Storage bucket
CLI->>GCS: Verify the --output bucket (owner, not public)
CLI->>SM: Add the extractor arguments, as given, as a version of the secret
CLI->>VM: Create VM (service account, connector, secret, output in metadata)
VM->>SM: Read the extractor arguments with its service account
VM->>DB: Run dwh-migration-dumper --connector ... (ZIP on the VM's disk)
VM->>GCS: Only if the extractor exits 0, copy the ZIP to --output
VM->>VM: Delete itself, whether or not the extractor succeeded
CLI->>GCS: Poll until a non-empty ZIP appears or the VM is gone
```
The command waits (typically 10 to 20 minutes) and prints `Artifact Path:
gs://... (N bytes)` when the ZIP arrives. If the VM finishes without uploading
one, the command fails with `Extraction finished, but no non-empty artifact was
found`. It also prints a `gcloud logging read` command for the VM's errors, but
only when it finds error entries; otherwise query the logs by VM name (see
[Monitoring](#monitoring)).
> [!WARNING]
> The command takes the first non-empty `.zip` under `--output` as the result,
> without checking when it was written, and looks for it before it checks the
> VM. Give every run an `--output` prefix with no `.zip` in it, such as
> `gs://{bucket}/snowflake_metadata/{run_label}/`. With an older archive there,
> the command prints `Extraction complete` for that archive right away while
> the new VM is still starting, and deleting the secret then breaks the real
> run.
> [!IMPORTANT]
> Cloud mode has no partial results. The VM uploads the ZIP only
> when the extractor exits 0, and the extractor exits 1 if any required task
> fails, even one with a harmless fallback. When a source is known to fail some
> tasks (for example older-catalog queries on a newer PostgreSQL), run it
> locally instead; local mode keeps the partial ZIP. To see why a cloud run
> uploaded nothing, read the VM's logs: run the `gcloud logging read` command
> it printed, or query by VM name (see [Monitoring](#monitoring)).
## Prerequisites
1. **A project ID** (not the numeric project number), passed with `--project`
or set with `gcloud config set project`.
2. **A zone** (optional). `--zone` falls back to the `compute/zone` property,
then to `us-central1-a`. All regional resources (the subnet, the
startup-script bucket, and the secret's replica) use the zone's region.
3. **APIs**. Enable them up front, or when the command reports a disabled API:
```bash
gcloud services enable compute.googleapis.com secretmanager.googleapis.com \
storage.googleapis.com logging.googleapis.com --project="{project_id}"
```
4. **A destination bucket** that is not public and is owned by the current
project, or by the project passed with `--expected-owner`:
```bash
gcloud storage buckets create "gs://{bucket}" --project="{project_id}" \
--location="{region}" --uniform-bucket-level-access
```
5. **Permissions for the caller**:
* To create the VM and the secret, for example Compute Admin
(`roles/compute.admin`) and Secret Manager Admin
(`roles/secretmanager.admin`).
* To verify the `--output` bucket: `storage.buckets.list` on the owner
project (for example `roles/storage.bucketViewer`), plus
`storage.buckets.getIamPolicy` on the bucket (`roles/storage.admin`)
unless public access prevention is enforced on it.
* With a prepared `--gce-service-account`: Service Account User
(`roles/iam.serviceAccountUser`) on that account. The account itself
needs, at minimum: Secret Manager Secret Accessor
(`roles/secretmanager.secretAccessor`) on the project, or with an IAM
condition on the `bqms-extractor-creds-` secret name prefix, to read
the extractor arguments (each run's secret is new and is created just
before the VM starts, so it cannot be granted on the secret in
advance); permission to create objects in the `--output`
bucket (for example `roles/storage.objectUser` on the bucket); Logs
Writer (`roles/logging.logWriter`), so the `gcloud logging read`
command shows the VM's output; and Compute Instance Admin (v1)
(`roles/compute.instanceAdmin.v1`), so the VM can delete itself (if it
cannot, delete it as in [Cleanup](#cleanup)). For `bigquery` and
`bigquery-logs`, the extractor on the VM authenticates as this
account, so it also needs BigQuery Metadata Viewer
(`roles/bigquery.metadataViewer`) on the source projects, plus
`bigquery.jobs.listAll` (for example BigQuery Resource Viewer,
`roles/bigquery.resourceViewer`) for `bigquery-logs`.
* Without `--gce-service-account`: Service Account Admin
(`roles/iam.serviceAccountAdmin`) and Project IAM Admin
(`roles/resourcemanager.projectIamAdmin`). Every such run creates or
reuses `bqms-cloud-extractor@{project_id}.iam.gserviceaccount.com`,
grants the caller (or `--service-account-user`)
`roles/iam.serviceAccountUser` on it, and grants it these nine project
roles: `roles/editor`, `roles/compute.admin`,
`roles/storage.objectAdmin`, `roles/secretmanager.secretAccessor`,
`roles/cloudkms.cryptoKeyDecrypter`, `roles/logging.logWriter`,
`roles/logging.viewer`, `roles/errorreporting.writer`, and
`roles/monitoring.metricWriter`.
The command asks before it creates the default account, but without a
terminal gcloud takes the default answer (yes), and `--quiet` does the
same. Show the user these roles and get explicit approval before you omit
`--gce-service-account`; otherwise ask for a prepared service account.
6. **A network path from the VM to the database.** The VM runs on the `default`
network and subnet with an external IP unless you pass `--network`,
`--subnet`, or `--no-address`. The database must accept connections from the
VM (add its egress range to the database allowlist or network policy). To
reach a database over Cloud VPN or Cloud Interconnect, pass the
`--network` and `--subnet` that have that connectivity. The VM also needs
internet egress: its startup script is downloaded from Cloud Storage, it
downloads the extractor release from `github.com`, and it reads Secret
Manager, writes to Cloud Storage and Cloud Logging, and deletes itself
through the Compute Engine API. Keep the external IP, or with
`--no-address` make sure Cloud NAT serves the subnet; a route to the
database alone is not enough. Without egress the VM never runs the
extractor or deletes itself and the command keeps polling: check
`get-serial-port-output` (see [Monitoring](#monitoring)), then delete the
VM.
`localhost`, `127.0.0.1`, and private addresses outside the VPC are never
reachable. If the user gives one, do not use `--run-mode=cloud`: ask for an
address the VM can reach, or run locally.
7. **A connector with a bundled driver**: `snowflake*`, `redshift*`,
`bigquery*`, `postgresql`, `greenplum*`, or `hiveql`. The VM has no vendor
JDBC drivers and cannot read a local `--driver` path, so Teradata, Oracle,
SQL Server, MySQL, Netezza, and Vertica must run locally; see the
[local extraction guide](local_extraction.md).
## Cloud Flags
These gcloud flags are only accepted with `--run-mode=cloud`; the command
rejects them in local mode.
Flag | Meaning
:------------------------- | :------
`--zone` | VM zone. Defaults to the `compute/zone` property, then `us-central1-a`.
`--secret` | Secret Manager secret that passes the extractor arguments to the VM, as a name or `projects/{project_id}/secrets/{name}`. Optional: without it the command creates `bqms-extractor-creds-run-EPOCH_SECONDS` and prints its name. A secret the command creates is labeled `goog-bqms-extractor-run-id=run-EPOCH_SECONDS`; for an existing secret it adds a new version.
`--gce-instance` | VM name (default `cloud-extractor-EPOCH_SECONDS`).
`--gce-service-account` | VM service account (default `bqms-cloud-extractor@{project_id}.iam.gserviceaccount.com`).
`--service-account-user` | User to grant `roles/iam.serviceAccountUser` on the VM service account.
`--network`, `--subnet` | VPC network and subnet for the VM (default `default`).
`--no-address` | Give the VM no external IP. It then needs Cloud NAT for internet and Google API access (see [Prerequisites](#prerequisites)); a VPN or Interconnect route alone is not enough.
Everything after `--` is stored in the secret exactly as given and passed to the
extractor on the VM.
## Credentials
The VM has none of your local files, so an extractor `@FILE` response file, or a
`--driver` path, fails there. Pass the password as `--password` after `--`, read
from a file only the user can read so it is never typed. Ask the user to
create the file in their own terminal (with `DB_PASSWORD` set there) and share
only its path; never ask for the password in the chat. The command stops
instead of writing an empty file when `DB_PASSWORD` is unset:
```bash
: "${DB_PASSWORD:?DB_PASSWORD is not set}" && umask 077 && printf '%s' "${DB_PASSWORD}" > ./db_password
```
and end the extractor arguments with `--password="$(cat ./db_password)"`. The
value is stored in the run's secret (delete it after the run; see
[Cleanup](#cleanup)) and is visible in this machine's process list while gcloud
runs. Use the user's existing password file in place if they have one.
## Recipes
Pick a new run label for every run, for example the date and time, for the
secret name and the `--output` folder, so each run starts from an empty prefix
(see [How It Works](#how-it-works)). Naming the secret yourself makes cleanup
unambiguous; leaving `--secret` out also works (see [Cleanup](#cleanup)). Do
not point `--secret` at a secret that already exists: the command only adds a
version to it, and the cleanup below would delete its earlier versions too.
### Snowflake catalog metadata
```bash
gcloud alpha bq migration metadata extract \
--connector=snowflake \
--output="gs://{bucket}/snowflake_metadata/{run_label}/" \
--run-mode=cloud \
--project="{project_id}" \
--zone="{zone}" \
--secret="bqms-extractor-creds-{run_label}" \
-- \
--host="{account_identifier}.snowflakecomputing.com" \
--user="{db_user}" \
--database="{db_name}" \
--warehouse="{db_warehouse}" \
--role="{db_role}" \
--password="$(cat ./db_password)"
```
For Migration Assessment, pass `--assessment` and omit `--database` and
`--schema`. Then check the result and delete the secret, which still holds the
password:
`gcloud secrets delete bqms-extractor-creds-{run_label} --project={project_id}
--quiet`.
### Snowflake query logs
```bash
gcloud alpha bq migration query-logs extract \
--connector=snowflake-logs \
--output="gs://{bucket}/snowflake_logs/{run_label}/" \
--run-mode=cloud \
--project="{project_id}" \
--zone="{zone}" \
--secret="bqms-extractor-creds-{run_label}" \
-- \
--host="{account_identifier}.snowflakecomputing.com" \
--user="{db_user}" \
--warehouse="{db_warehouse}" \
--role="{db_role}" \
--query-log-start="2026-09-01" \
--query-log-end="2026-10-01" \
--password="$(cat ./db_password)"
```
Then check the result and delete the secret, which still holds the password:
`gcloud secrets delete bqms-extractor-creds-{run_label} --project={project_id}
--quiet`.
### Amazon Redshift metadata
```bash
gcloud alpha bq migration metadata extract \
--connector=redshift \
--output="gs://{bucket}/redshift_metadata/{run_label}/" \
--run-mode=cloud \
--project="{project_id}" \
--zone="{zone}" \
--secret="bqms-extractor-creds-{run_label}" \
-- \
--host="{cluster_name}.{xyz}.{region}.redshift.amazonaws.com" \
--port=5439 \
--database="{db_name}" \
--user="{db_user}" \
--password="$(cat ./db_password)"
```
Then check the result and delete the secret, which still holds the password:
`gcloud secrets delete bqms-extractor-creds-{run_label} --project={project_id}
--quiet`.
### Database reachable only through an existing VPC
```bash
gcloud alpha bq migration metadata extract \
--connector=postgresql \
--output="gs://{bucket}/postgres_metadata/{run_label}/" \
--run-mode=cloud \
--project="{project_id}" \
--zone="{zone}" \
--secret="bqms-extractor-creds-{run_label}" \
--network="{vpc}" \
--subnet="{subnet}" \
--no-address \
-- \
--host="{private_ip}" \
--port=5432 \
--database="{db_name}" \
--user="{db_user}" \
--password="$(cat ./db_password)"
```
Then check the result and delete the secret, which still holds the password:
`gcloud secrets delete bqms-extractor-creds-{run_label} --project={project_id}
--quiet`.
## Monitoring
The command prints an `Instance Link:` to the VM in the Google Cloud Console and
polls until the ZIP appears or the VM is gone. Pass `--quiet` to read-only
`gcloud` commands so a disabled API fails fast instead of prompting to enable
it. To watch the extractor while it runs:
```bash
gcloud compute instances describe "{instance_name}" --zone="{zone}" \
--project="{project_id}" --format="value(id,status)" --quiet
gcloud compute instances get-serial-port-output "{instance_name}" \
--zone="{zone}" --project="{project_id}" | tail -n 40
gcloud logging read \
'resource.type="gce_instance" AND resource.labels.instance_id="{instance_id}"' \
--project="{project_id}" --limit=200 --format="value(jsonPayload.message,textPayload)"
```
After the VM deletes itself, `describe` no longer returns its ID, and the
extract command prints a `gcloud logging read` command only when it finds error
entries. Query the logs by the VM name from the `Instance Link:` line instead:
```bash
gcloud logging read \
'resource.type="gce_instance" AND labels."compute.googleapis.com/resource_name"="{instance_name}"' \
--project="{project_id}" --limit=200 --format="value(jsonPayload.message,textPayload)"
```
The VM writes the ZIP to its own disk and copies it to `--output` only at the
end, so nothing appears in the bucket while the extractor runs. `describe`
returning "not found" after the run means the VM has deleted itself.
## Cleanup
The run's secret **stays** after the run and still contains the database
password. It is written before the VM starts and before any database connection,
so delete it after **every** run, including failed, aborted, or interrupted
ones: right after the result checks in SKILL.md Section 6, or as soon as a
failed run has stopped.
If you passed `--secret` with a name new to this run:
```bash
gcloud secrets delete "bqms-extractor-creds-{run_label}" \
--project="{project_id}" --quiet
```
If you did not, use the name the command printed (`Creating secret ...`), or
find the secrets the command created by their label:
```bash
gcloud secrets list --project="{project_id}" --quiet \
--filter="labels.goog-bqms-extractor-run-id:*" \
--format="value(name,labels)"
```
Delete only secrets created for the run. If the user had you pass an existing
secret, do not delete it. Before the extract command, record its newest
version:
```bash
gcloud secrets versions list "{secret}" --project="{project_id}" --quiet \
--sort-by="~createTime" --limit=1 --format="value(name.basename())"
```
After the run, run the same command again. The run added a version only if
the command printed `Adding version to secret` and the newest version number is
now higher than the one you recorded; if it is unchanged (for example because
the run failed at the bucket check or service account setup), the run added
nothing, so destroy nothing. Otherwise, with the user's confirmation of that
exact version, destroy only it:
```bash
gcloud secrets versions destroy "{version}" --secret="{secret}" \
--project="{project_id}" --quiet
```
The VM deletes itself when the extractor finishes, whether or not it succeeded.
If it is still listed long after the run, delete it too:
```bash
gcloud compute instances list --project="{project_id}" --quiet \
--filter="labels.goog-bqms-extractor-run-id:*"
gcloud compute instances delete "{instance_name}" --zone="{zone}" \
--project="{project_id}" --quiet
```
Delete `db_password` if you created it; leave a file the user supplied in place.
## Troubleshooting
Symptom | Cause and fix
:----------------------------------------------------------- | :------------
`Invalid choice: 'migration'` or unknown command | Use the alpha track (`gcloud alpha bq migration ...`). If that still fails, ask the user, then update the Google Cloud CLI (`gcloud components update`, or upgrade the `google-cloud-cli` package with `apt` or `yum` if gcloud was installed that way).
`unrecognized arguments: --host=...` | Database flags go after `--`.
`Connector '...' is a query-logs connector` (or the reverse) | Use `query-logs extract` for `*-logs` connectors and `metadata extract` for the rest.
`Extraction finished, but no non-empty artifact was found` | The extractor on the VM exited non-zero (any failed required task, a bad credential, an unreachable host, or an `@FILE`/`--driver` path that only exists locally), so the VM uploaded nothing. Read the VM's logs (the printed `gcloud logging read` command, or the query by VM name in [Monitoring](#monitoring)) to see why, fix it, and rerun, or run locally to keep a partial ZIP.
`Extraction complete` right away, for an older ZIP | `--output` already held a `.zip`, so the command reported it while the new VM was still running. Wait until the VM is gone (`describe` returns "not found"), check the prefix for the new archive, then delete the secret. Use an empty prefix next time.
The command keeps polling and the VM stays `RUNNING` | The VM cannot reach the internet or Google APIs (for example `--no-address` without Cloud NAT). Check `get-serial-port-output`, delete the VM, fix egress, and rerun.
`FileNotFoundException` for a `.yaml` file in the VM logs | An `@FILE` response file was passed in cloud mode. Pass `--password="$(cat ./db_password)"` instead (see [Credentials](#credentials)).
`Permission denied` reading the secret on the VM | The service account lacks `roles/secretmanager.secretAccessor`, or IAM has not propagated yet (wait a minute and rerun).
`gcloud` calls fail with a numeric project | Use the project ID, not the project number.
Connection timeouts in the VM logs | The database does not accept connections from the VM. Allowlist the VM's egress, or run in a VPC with connectivity (`--network`, `--subnet`).
Vendor-driver connector fails in cloud mode | The VM has no vendor JDBC drivers. Run it with `--run-mode=local`.
extraction_stats_report.md 9.7 KB
# Post-Extraction Verification & Statistics Reporting Specification
After an extraction completes (or whenever inspecting an extracted metadata or
query-log archive), run the extraction statistics script based on
`assets/extraction_stats_template.py` and print the crucial extraction summary
metrics to the user.
## Contents
- [1. Prerequisites and dependencies][s1]: Lines 15-29
- [2. Agent workflow and extension points][s2]: Lines 30-73
- [3. Crucial Extracted Data to Present to the User][s3]: Lines 74-127
- [4. Example Extraction Report][s4]: Lines 128-183
## 1. Prerequisites and dependencies
The script uses only the Python 3.9+ standard library (no third-party `pip`
packages required) and requires the Google Cloud SDK when reading archives
directly from `gs://` URIs:
```bash
# Authenticate Google Cloud SDK for gs:// URIs:
gcloud auth login && gcloud auth application-default login
```
* **Google Cloud CLI (`gcloud`)**: Ensure the
[Google Cloud CLI][gcloud_install] is installed and authenticated when
inspecting extracted `.zip` archives on Cloud Storage (`gs://`).
## 2. Agent workflow and extension points
1. **Copy the Asset Template**: Copy `assets/extraction_stats_template.py` from
the skill directory (`<SKILL_DIR>`, the directory that contains `SKILL.md`)
into your working directory:
```bash
cp <SKILL_DIR>/assets/extraction_stats_template.py ./extraction_stats.py
```
2. **Conditionally Customize Extension Points**: Run the copy as-is, or modify
the marked `# CUSTOMIZE:` sections when needed (`# DEFAULT SCAFFOLDING`
sections can be kept unchanged):
* **Custom Schema & Table Filtering (`# CUSTOMIZE: Custom Schema & Table
Filtering`)**: Update `_EXCLUDED_SYSTEM_SCHEMAS` or
`_should_include_schema()` if you need to exclude specific staging,
scratch, or system schemas (e.g., `STAGING_TMP`) from migration totals.
* **Complex Data Type Classification (`# CUSTOMIZE: Complex Data Type
Classification`)**: Update `_classify_special_data_types()` to flag
additional custom data types that require special casting during
downstream Parquet export or BigQuery SQL translation.
* **Custom Telemetry & Archive Validation Thresholds (`# CUSTOMIZE: Custom
Telemetry & Archive Validation Thresholds`)**: Adjust
`_MIN_VALID_ZIP_BYTES` or telemetry validation logic in
`analyze_zip_archive()`.
* **Report Formatting & Output Channels (`# CUSTOMIZE: Report Formatting &
Output Channels`)**: Customize `format_stats_report()` to alter table
columns or add custom summary sections.
3. **Execute the Script After Extraction**:
```bash
# 1. Inspect a GCS extraction output directory or ZIP URI directly:
python3 ./extraction_stats.py \
--input "gs://{bucket}/snowflake_metadata/"
# 2. Inspect a local metadata ZIP and write JSON + Markdown reports:
python3 ./extraction_stats.py \
--input ./dwh-migration-snowflake-metadata.zip \
--output-json ./extraction_stats.json \
--output-markdown ./extraction_stats.md
```
## 3. Crucial Extracted Data to Present to the User
After running `./extraction_stats.py`, present the following extraction metrics:
1. **Archive Health & Run Telemetry**:
* Archive name, byte size (confirming `> 22` bytes so it is not an
incomplete GCS NIO ZipFS placeholder), and file count.
* Extractor `overallStatus` (`SUCCESS`), task execution counts
(`SUCCEEDED` / `SKIPPED` / `FAILED`), source `connector`, `host`, and
compute `warehouse` from the run that wrote the archive. The
`dumper-telemetry.jsonl` file accumulates every run made on the same
machine, so the script picks the latest run (by start time, with
offsets applied) whose connector matches
`compilerworks-arguments.txt`.
2. **Catalog Object Inventory Counts**:
* **Databases**: Count and names (e.g., `SALES_DB`).
* **Schemas**: Total schemas discovered vs. active schemas containing
objects (e.g., `RAW_POS`, `RAW_CUSTOMER`, `HARMONIZED`, `ANALYTICS`).
* **Base Tables**: Count of physical tables (`TableType = BASE TABLE`).
* **Views (with DDL)**: Count of extracted view definitions from
`views-au.csv` ready for BQMS SQL translation.
* **Columns, Functions & External Tables**: Total columns across all
relations broken down into base-table columns (`base_table_columns`) and
view columns (`view_columns`), plus counts of UDFs/stored procedures
(`functions-au.csv`, `function_info.csv`, `dbc.FunctionsV.csv`) and
external stage tables (`external_tables.csv`,
`svv_external_tables.csv`).
* **Query History Logs** *(for `snowflake-logs` / query log archives)*:
Number of query log partitions (`query_history*.csv`, `querytext*.csv`,
`dwhassessment_*.csv`) and total historical queries extracted.
3. **Total Data Volume & Per-Schema / Per-Table Breakdown**:
* Aggregate **Total Base Table Rows** (e.g., `3,600` rows) and **Total
Base Table Bytes** (e.g., `227,840 B (222.50 KB)`).
* Per-schema breakdown table (`Schema`, `Base Tables`, `Views`, `Rows`,
`Size`) and the Base Tables inventory (`Schema.Table`, `Rows`, `Size`,
`Columns`, `Clustering Key`).
* For `bigquery` connector archives, the script reads `tables.jsonl`,
counts top-level columns only, and shows `N/A` for rows and sizes
because that connector does not record them (even when `tables.jsonl`
is empty). `VIEW` and `MATERIALIZED_VIEW` entries count as views, with
`viewQuery` as their DDL; `EXTERNAL` entries count as external tables;
other types such as `SNAPSHOT` are not counted as tables or views.
The script reads `tables.jsonl` only when the archive's connector (or
`compilerworks-format.txt`) is `bigquery`, or when the archive names
neither; `hiveql` archives also contain a `tables.jsonl`, in a
different layout, which the script does not parse.
4. **Extracted Views & Column Data Type Distribution**:
* List of extracted view names (`Schema.View`) and column data type counts
(`TEXT`, `NUMBER`, `DATE`, `TIMESTAMP_NTZ`, `ARRAY`, `VARIANT`, etc.),
highlighting special types (`NUMBER`, `TIMESTAMP_NTZ`, `ARRAY`,
`VARIANT`, `SUPER`) that require type-safe casting during downstream
Parquet export and SQL translation
(`bigquery-migration-sql-translator`).
## 4. Example Extraction Report (Sample Snowflake Database)
```text
================================================================================
BIGQUERY MIGRATION CLOUD EXTRACTOR - EXTRACTION REPORT
================================================================================
### Archive 1: `dwh-migration-snowflake-metadata.zip`
- **Archive Path / URI**: `gs://example-bucket/snowflake_metadata/dwh-migration-snowflake-metadata.zip`
- **Archive Validation**: VALID (10,559 B (10.31 KB), 13 files)
- **Archive Type**: `CATALOG_METADATA`
- **Extractor Run Status**: `SUCCESS` (Tasks: 12 succeeded, 6 skipped, 0 failed | Version: v1.7.0)
- **Source Connector & Host**: `snowflake` (`myorg-myaccount.snowflakecomputing.com`)
- **Compute Warehouse**: `MIGRATION_WH` (total warehouses in account: 4)
- **Extraction Timestamp**: `2026-08-11T00:54:12.805787467Z`
#### 1. Crucial Extracted Object Summary
| Metric | Count / Value | Details |
| :--- | :--- | :--- |
| **Databases** | 1 | `SALES_DB` |
| **Schemas** | 5 (4 with objects) | `ANALYTICS`, `HARMONIZED`, `PUBLIC`, `RAW_CUSTOMER`, `RAW_POS` |
| **Base Tables** | 8 | Total Rows: **3,600** (227,840 B (222.50 KB)) |
| **Views (with DDL)** | 7 | Ready for BQMS SQL translation |
| **Total Columns** | 214 | 86 in base tables, 128 in views; 8 distinct data types |
| **Functions / Procedures** | 0 | UDFs and stored procedures |
| **External Tables** | 0 | External stage tables |
#### 2. Per-Schema Object Breakdown
| Schema | Base Tables | Views | Total Base Rows | Total Base Size |
| :--- | ---: | ---: | ---: | ---: |
| `RAW_POS` | 8 | 0 | 3,600 | 227,840 B (222.50 KB) |
| `ANALYTICS` | 0 | 3 | 0 | 0 B |
| `HARMONIZED` | 0 | 3 | 0 | 0 B |
| `RAW_CUSTOMER` | 0 | 1 | 0 | 0 B |
| `PUBLIC` | 0 | 0 | 0 | 0 B |
#### 3. Base Tables Inventory (Showing 8 of 8)
| # | Schema.Table | Rows | Size | Columns | Clustering Key |
| ---: | :--- | ---: | ---: | ---: | :--- |
| 1 | `RAW_POS.COUNTRY` | 800 | 17,920 B (17.50 KB) | 7 | - |
| 2 | `RAW_POS.FRANCHISE` | 700 | 32,256 B (31.50 KB) | 7 | - |
| 3 | `RAW_POS.LOCATION` | 600 | 29,696 B (29.00 KB) | 7 | - |
| 4 | `RAW_POS.MENU` | 500 | 41,472 B (40.50 KB) | 11 | - |
| 5 | `RAW_POS.TRUCK` | 400 | 32,768 B (32.00 KB) | 14 | - |
| 6 | `RAW_POS.ORDER_HEADER` | 300 | 26,624 B (26.00 KB) | 16 | - |
| 7 | `RAW_POS.ORDER_DETAIL` | 200 | 12,288 B (12.00 KB) | 9 | - |
| 8 | `RAW_POS.CUSTOMER_LOYALTY` | 100 | 34,816 B (34.00 KB) | 15 | - |
#### 4. Extracted Views Inventory (7)
`ANALYTICS.CUSTOMER_LOYALTY_METRICS_V`, `ANALYTICS.MENU_V`, `ANALYTICS.ORDERS_V`, `HARMONIZED.CUSTOMER_LOYALTY_METRICS_V`, `HARMONIZED.MENU_V`, `HARMONIZED.ORDERS_V`, `RAW_CUSTOMER.CUSTOMER_LOYALTY`
#### 5. Column Data Type Distribution
- **All Data Types**: `TEXT`: 125, `NUMBER`: 74, `DATE`: 6, `TIMESTAMP_NTZ`: 3, `ARRAY`: 2, `TIME`: 2, `FLOAT`: 1, `VARIANT`: 1
- **Types Flagged for Type-Safe Parquet Cast / Translation**: `NUMBER` (74), `TIMESTAMP_NTZ` (3), `ARRAY` (2), `VARIANT` (1)
================================================================================
```
[gcloud_install]: https://cloud.google.com/sdk/docs/install
[s1]: #1-prerequisites-and-dependencies
[s2]: #2-agent-workflow-and-extension-points
[s3]: #3-crucial-extracted-data-to-present-to-the-user
[s4]: #4-example-extraction-report-sample-snowflake-database
local_extraction.md 8.9 KB
# Local Extraction
`--run-mode=local` is the default: the command runs the DWH migration extractor
on this machine, connects to the database over this machine's network, and
writes the ZIP to `--output`. The recipes use a Cloud Storage path; local mode
also accepts a local file or directory path. It is the only mode that supports
vendor-licensed JDBC drivers.
## Contents
- [Prerequisites](#prerequisites): Lines 15-54
- [Recipes](#recipes): Lines 55-180
- [Troubleshooting](#troubleshooting): Lines 181-193
## Prerequisites
1. **Java 11 or later** on `PATH`; the extractor is a JVM program and the
command refuses older Java versions. Set `JAVA_OPTS` to pass extra JVM
options (for example `-Xmx4g`). Ask the user before installing Java.
2. **The `bqms` gcloud component**, which contains the extractor. Ask the user
before installing it. The extract command offers to install it, but
without a terminal that prompt fails, so after the user agrees run `gcloud
components install bqms --quiet` before the extraction. If gcloud was
installed with `apt` or `yum`, install the `google-cloud-cli-bqms` package
with that package manager instead.
3. **Network access** from this machine to the database host and port. Test it
first (for example `nc -vz {host} {port}`).
4. **JDBC drivers**: the local extractor ships without JDBC drivers, and the
`bqms` launcher downloads the drivers for `snowflake*`, `redshift*`,
`postgresql`, `greenplum*`, `oracle*`, `sqlserver`, and `mysql` when you
omit `--driver` (behind a proxy, set `HTTPS_PROXY`). For `teradata*`,
`netezza`, and `vertica*`, download the vendor JAR and pass it after `--`
with `--driver=/path/a.jar[,/path/b.jar]`.
5. **A read-only database user** that can read the system catalog (and the
query history views for `*-logs` connectors).
6. **Application Default Credentials** for writing to a `gs://` `--output`.
Check with `gcloud auth application-default print-access-token
>/dev/null`; if it fails, run `gcloud auth application-default login`.
Check that the bucket exists with `gcloud storage buckets describe
gs://{bucket}`. The command itself checks that the bucket is owned by the
current project (or `--expected-owner`) and is not public before it starts
the extractor. That check needs `storage.buckets.list` on the owner
project (for example `roles/storage.bucketViewer`), plus
`storage.buckets.getIamPolicy` on the bucket (`roles/storage.admin`) unless
public access prevention is enforced on it; object-level access alone is
not enough.
7. **The password response file** from SKILL.md Section 4
(`./extractor-secret.yaml`), or the user's existing one in place.
8. **A scratch working directory**: every run writes a `progress.log.TIMESTAMP`
file to the current directory, so run the command from a scratch folder.
Delete `./extractor-secret.yaml` after the run if you created it for the
extraction; leave a file the user supplied in place.
## Recipes
All recipes use `metadata extract` except the query logs ones, which use
`query-logs extract`. gcloud flags come before `--`; database flags after.
### Snowflake catalog metadata
```bash
gcloud alpha bq migration metadata extract \
--connector=snowflake \
--output="gs://{bucket}/snowflake_metadata/" \
-- \
--host="{account_identifier}.snowflakecomputing.com" \
--user="{db_user}" \
--database="{db_name}" \
--warehouse="{db_warehouse}" \
--role="{db_role}" \
@./extractor-secret.yaml
```
Pass `--warehouse` and `--role`; they apply to the extractor's session only. Do
not run `ALTER USER ... SET DEFAULT_WAREHOUSE` on shared accounts. For
Migration Assessment, pass `--assessment` and omit `--database` and `--schema`
(the `snowflake` connector rejects combining `--assessment` with `--database` or
`--schema`).
### Snowflake query logs
```bash
gcloud alpha bq migration query-logs extract \
--connector=snowflake-logs \
--output="gs://{bucket}/snowflake_logs/" \
-- \
--host="{account_identifier}.snowflakecomputing.com" \
--user="{db_user}" \
--warehouse="{db_warehouse}" \
--role="{db_role}" \
--query-log-start="2026-09-01" \
--query-log-end="2026-10-01" \
@./extractor-secret.yaml
```
`--query-log-start` is inclusive and `--query-log-end` is exclusive. Use
`--query-log-days=N` for the most recent N days instead.
### Teradata metadata for Migration Assessment
```bash
gcloud alpha bq migration metadata extract \
--connector=teradata \
--output="gs://{bucket}/teradata_metadata/" \
-- \
--host="{teradata_host}" \
--user="{db_user}" \
--driver="{path_to}/terajdbc4.jar" \
--assessment \
@./extractor-secret.yaml
```
For query logs use `query-logs extract` with `--connector=teradata-logs`
(Teradata 15 and later) or `teradata14-logs`, the same `--driver`, and a query
log window.
### Oracle metadata
```bash
gcloud alpha bq migration metadata extract \
--connector=oracle \
--output="gs://{bucket}/oracle_metadata/" \
-- \
--host="{oracle_host}" \
--port=1521 \
--oracle-service="{service_name}" \
--user="{db_user}" \
@./extractor-secret.yaml
```
Use `--oracle-sid` instead of `--oracle-service` for SID-based connections. The
`bqms` launcher downloads the Oracle driver; add
`--driver="{path_to}/ojdbc8.jar"` only to use a specific JAR.
### Amazon Redshift metadata
```bash
gcloud alpha bq migration metadata extract \
--connector=redshift \
--output="gs://{bucket}/redshift_metadata/" \
-- \
--host="{cluster_name}.{xyz}.{region}.redshift.amazonaws.com" \
--port=5439 \
--database="{db_name}" \
--user="{db_user}" \
@./extractor-secret.yaml
```
For query logs use `query-logs extract` with `--connector=redshift-raw-logs` and
a query log window.
### PostgreSQL metadata
PostgreSQL has no query logs connector, and `--assessment` does not change its
output.
```bash
gcloud alpha bq migration metadata extract \
--connector=postgresql \
--output="gs://{bucket}/postgres_metadata/" \
-- \
--host="{postgres_host}" \
--port=5432 \
--database="{db_name}" \
--user="{db_user}" \
@./extractor-secret.yaml
```
The connector extracts only the first `--database` and ignores `--schema`, so
run it once per database, each with its own `--output`. `functions-11.csv`,
`aggregates-11.csv`, and `types.csv` list only objects visible on the session
`search_path` (`"$user", public` by default), so functions and types in other
schemas are missing. To include them, replace `--host`, `--port`, and
`--database` with a JDBC URL that sets `currentSchema`:
```text
--url="jdbc:postgresql://{postgres_host}:5432/{db_name}?currentSchema={schema1},{schema2},public" \
```
## Troubleshooting
Symptom | Cause and fix
:------------------------------------------------------------------------------ | :------------
`Invalid choice: 'migration'` or unknown command | Use the alpha track (`gcloud alpha bq migration ...`). If that still fails, ask the user, then update the Google Cloud CLI (`gcloud components update`, or upgrade the `google-cloud-cli` package with `apt` or `yum` if gcloud was installed that way).
`unrecognized arguments: --host=...` | Database flags go after `--`.
`Connector '...' is a query-logs connector` (or `is a metadata connector`) | Use `query-logs extract` for `*-logs` connectors and `metadata extract` for the rest.
`BigQuery Migration Extractor failed with exit code 1`, ZIP exists | Some required tasks failed; the ZIP still holds everything that succeeded plus `*.exception.txt` entries. List them with `unzip -l archive.zip '*.exception.txt'`. A failure is harmless when a version-suffixed fallback (for example `functions-11.csv`) succeeded.
`JDBC driver encountered communication error` / connection refused or timed out | The host or port is unreachable from this machine. Check VPN, firewall, and allowlists; test with `nc -vz`.
`ClassNotFoundException` or "driver required" | A Teradata, Netezza, or Vertica connector is missing `--driver` (after `--`), or the `bqms` launcher printed a warning that it could not download the driver (behind a proxy, set `HTTPS_PROXY`); pass `--driver`.
Authentication errors | Check the user, the response file (`password: '...'`, single-quoted), and connector-specific settings such as Snowflake `--role`.
Empty or missing query logs | The window is outside the source's retention, or the user lacks access to the query history views.
`gs://` output is 22 bytes while the extractor is running | The extractor streams the ZIP to Cloud Storage and writes a 22-byte placeholder first. Wait for the command to exit before reading it.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE