Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-migration-data-exporter@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin bigquery-migration-data-exporter v1.0.0 follows the Agent Plugins spec.
gh skills-hub install bigquery-migration-data-exporter Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/bigquery-migration-data-exporter/ Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-migration-data-exporter for Copilot to auto-discover it.
Skill Files (12)
SKILL.md 25.5 KB
---
name: bigquery-migration-data-exporter
metadata:
version: "1.0.0"
category: BigDataAndAnalytics
publisher: google
description: >-
Generates type-safe, schema-aligned database data export SQL files (.sql) for
Snowflake, Databricks, Teradata, Oracle, and PostgreSQL directly from
BigQuery Migration Service (BQMS) translation_output/metadata
configs, exporting into target file formats (such as Parquet). Use when
generating source database export SQL scripts for BigQuery ingestion without
connecting to the source database. Don't use for executing SQL against source
databases or streaming/staging exported files, extracting source database
catalog metadata, translating SQL queries or DDL schemas (use
bigquery-migration-sql-translator), loading staged Parquet files into
BigQuery, or running post-migration data validation.
---
# BigQuery Migration Data Exporter
This skill coordinates the generation of type-aware data export SQL scripts
(`.sql` files) for source data warehouses (such as Snowflake, Databricks,
Teradata, Oracle, and PostgreSQL) into target file formats (such as
**BigQuery-aligned Parquet files**), guided by dialect and format specifications
in the **`references/`** directory.
All templates in this skill are **pure SQL generators with zero JDBC or database
connector dependencies**.
> [!TIP]
> Point directly to the BigQuery Migration Service (BQMS)
> **`translation_output/metadata`** directory (local path or Cloud Storage URI).
> It automatically discovers all physical tables and target BigQuery logical
> types from `metadata/config/*.yaml`.
## 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 & Project Setup**: When reading translation outputs or
metadata archives from `gs://` Cloud Storage URIs, ensure the
[Google Cloud CLI](https://cloud.google.com/sdk/docs/install) is
installed, verify that your Google Cloud project has an active Cloud Billing
account attached, and configure the target project:
```bash
gcloud config set project {project_id}
```
2. **Enable the API**: When reading metadata from Cloud Storage (`gs://`), ask
the user before enabling APIs, then enable the Cloud Storage API
(`storage.googleapis.com`):
```bash
gcloud services enable storage.googleapis.com
```
3. **Authentication & Required Identity and Access Management (IAM) Roles**:
Authenticate with `gcloud auth login` and `gcloud auth application-default
login` (or set `GOOGLE_APPLICATION_CREDENTIALS` for service account
authentication). Verify that your identity or service account has
`roles/storage.objectViewer` (Storage Object Viewer) on any Cloud Storage
bucket holding input metadata. Creating a staging bucket requires
`roles/storage.admin` (Storage Admin) on the Google Cloud project, and
deleting staged files requires `roles/storage.objectAdmin` (Storage Object
Admin) on the staging bucket.
4. **Python Environment**: The generator templates require Python 3.9 or
later. Ask the user for confirmation before installing Python packages,
then install PyYAML in a virtual environment (generator templates have
zero JDBC or database connector dependencies):
```bash
pip install pyyaml==6.0.2
```
5. **Region, Cost & Cleanup**: Ask the user for confirmation before creating
a new Cloud Storage bucket for staging exported Parquet files (`gcloud
storage buckets create gs://{bucket} --location={region}`), and default to
`us-central1` unless your target BigQuery dataset uses another region
(co-locate buckets with your dataset; see
[Google Cloud locations](https://cloud.google.com/about/locations)). Review
[Google Cloud Pricing](https://cloud.google.com/pricing) before staging
large exports. After BigQuery ingestion, temporary staged Parquet prefixes
can be removed with `gcloud storage rm -r gs://{bucket}/{export_prefix}`.
This deletion is permanent: run it only after the user explicitly confirms
the exact URI, and never with an empty `{export_prefix}` (which would delete
every object in the bucket).
6. **Snowflake Storage Integration**: To unload Snowflake tables directly to a
private Cloud Storage bucket (`--stage-path 'gcs://...'`), Snowflake
requires a [storage integration][snowflake_gcs_integration] that grants its
service account access to the bucket. Ask the user for the integration name
and pass it with the `--storage-integration` flag, which adds a
`STORAGE_INTEGRATION` clause to each generated `COPY INTO` statement.
Unloads to a Snowflake stage (for example, `@~/bqms_export/` or a named
external stage) don't need this flag.
--------------------------------------------------------------------------------
## 1. Direct Consumption of Translation Output Metadata
`bigquery-migration-data-exporter` consumes the native BigQuery Migration
Service (BQMS) metadata translation output:
`translation_output/metadata/config/<database>/<schema>/<table_name>.yaml`
Each configuration file specifies:
1. `sourceName`: Fully qualified source table name.
2. `columns`: Source data types, precision, scale, and BigQuery target types.
3. Table versus view: A config with neither `externalTableName` nor
`externalTableDdlPath` describes a view, which is recreated as a SQL view
and isn't exported. The Databricks generator also honors an explicit
`TableType` field when present.
--------------------------------------------------------------------------------
## 2. Format-Guided Type-Safe Export Fundamentals
A plain unguided `COPY INTO @stage FROM table` or `SELECT *` often fails during
BigQuery ingestion (`bq load`) due to serializer discrepancies (for example,
`VARIANT` JSON encoding, `CHAR(n)` fixed-width space padding, unbounded
Teradata/Oracle/PostgreSQL `NUMBER`/`NUMERIC` scale truncation, PostgreSQL
`MONEY` locale currency formatting, Oracle `DATE` time-of-day components, or
timestamp nanosecond ticks).
To ensure zero type drift and clean BigQuery ingestion, apply type-aware
projections guided by the target format and dialect specifications in the
**`references/`** directory. While Parquet is the standard and recommended
format for BigQuery batch ingestion due to columnar compression and strict
typing, the export structure adapts based on target format requirements.
For Parquet data exports, the core rules are summarized below; the mapping
references listed after them hold the full per-dialect type matrices:
1. **Session Parameters (Snowflake)**:
```sql
ALTER SESSION SET TIME_OUTPUT_FORMAT = 'HH24:MI:SS.FF6';
ALTER SESSION SET TIMESTAMP_NTZ_OUTPUT_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF6';
ALTER SESSION SET TIMESTAMP_TZ_OUTPUT_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF6 TZHTZM';
```
2. **Semi-Structured / JSON (`VARIANT`, `OBJECT`, `STRUCT`, `MAP`, `ARRAY`,
`JSON`, `JSONB`, `XMLTYPE`, `XML`, `UUID`, `INET`)**:
* Snowflake: `TO_VARCHAR(col) AS col`.
* Databricks / Spark SQL: `TO_JSON(col) AS col` for `MAP` (and for
`STRUCT`/`ARRAY` when targeting `JSON` or `STRING`; native passthrough
`col` when targeting `RECORD`/`ARRAY`); `CAST(col AS STRING) AS col` for
`VARIANT`/`JSON`/`INTERVAL`.
* Teradata: `CAST(col AS CLOB) AS col`.
* Oracle: `JSON_SERIALIZE(col RETURNING CLOB) AS col` for 21c+ native
`JSON`, and `XMLSERIALIZE(CONTENT col AS CLOB) AS col` for `XMLTYPE`.
* PostgreSQL: `CAST(col AS TEXT) AS col` for `JSON`, `JSONB`, `XML`,
`UUID`, `INET`, `CIDR`, `MACADDR`, `INTERVAL`, `BIT`, and `ARRAY`.
3. **Decimals, Numbers, Integers & Floats**:
* `NUMBER(p, s)` / `DECIMAL(p, s)` / `NUMERIC(p, s)` with `s > 0` →
`CAST(col AS DECIMAL(p, s)) AS col` (or `CAST(col AS NUMBER(p, s)) AS
col` in Oracle, or `CAST(col AS NUMERIC(p, s)) AS col` in PostgreSQL).
* Unbounded or unconstrained `NUMBER` / `NUMBER(*)` / `NUMERIC` /
`DECIMAL` → `CAST(col AS DECIMAL(38, 9)) AS col` in Snowflake and
Teradata, `CAST(col AS NUMBER(38, 9)) AS col` in Oracle, or `CAST(col AS
NUMERIC(38, 9)) AS col` in PostgreSQL (supports `<= 29` integer digits
and `9` fractional digits by default; override scale in Teradata,
Oracle, and PostgreSQL by using `--unbounded-number-scale`); PostgreSQL
`MONEY` → `CAST(col AS NUMERIC(38, 2)) AS col`.
* `TINYINT` / `BYTEINT` / `SMALLINT` / `INT` / `INTEGER` / `BIGINT` /
`SERIAL` → `CAST(col AS BIGINT) AS col`. In Oracle, `SMALLINT` →
`CAST(col AS NUMBER(19, 0)) AS col` and the ANSI `NUMBER(38)` aliases
`INT` / `INTEGER` → `CAST(col AS NUMBER(38, 0)) AS col`. Scale-0
decimals with a `TargetType` of `INT64` project as 64-bit integers;
the mapping references list which `NUMBER(p, 0)` / `DECIMAL(p, 0)`
precisions become 64-bit integers by default.
* Databricks / Snowflake `FLOAT` / `REAL` → `CAST(col AS DOUBLE) AS col`;
PostgreSQL `REAL` / `DOUBLE PRECISION` → `CAST(col AS DOUBLE PRECISION)
AS col`; Oracle `BINARY_FLOAT` / `BINARY_DOUBLE` / `FLOAT(p)` →
`CAST(col AS BINARY_DOUBLE) AS col` (widens to 64-bit IEEE-754
`FLOAT64`).
4. **Temporal (`DATE`, `TIME`, `TIMESTAMP`, `TIMESTAMP_NTZ`, `TIMESTAMP WITH
TIME ZONE`)**:
* Snowflake: `CAST(col AS TIMESTAMP_NTZ(6)) AS col` and
`CAST(CONVERT_TIMEZONE('UTC', col) AS TIMESTAMP_NTZ(6)) AS col`.
* Databricks / Spark SQL: `CAST(col AS TIMESTAMP) AS col` when targeting
`TIMESTAMP`, or leave `TIMESTAMP_NTZ` uncast when targeting BigQuery
`DATETIME`. `TIMESTAMP_NTZ` to `TIMESTAMP` casts (and back) use the
session time zone, so run the scripts in a UTC session (see the
[Databricks reference][databricks_map]).
* Teradata: `CAST(col AS TIMESTAMP(6)) AS col`, `CAST((col AT TIME ZONE
'GMT') AS TIMESTAMP(6)) AS col`, and `CAST((col AT TIME ZONE 'GMT') AS
TIME(6)) AS col`.
* Oracle: `CAST(col AS TIMESTAMP(6)) AS col` for `DATE` and
`TIMESTAMP(p)` (or `TRUNC(col) AS col` when `DATE` explicitly targets
BigQuery `DATE`), `CAST(SYS_EXTRACT_UTC(col) AS TIMESTAMP(6)) AS col`
for `TIMESTAMP WITH TIME ZONE`, and `CAST(SYS_EXTRACT_UTC(CAST(col AS
TIMESTAMP WITH TIME ZONE)) AS TIMESTAMP(6)) AS col` for `TIMESTAMP WITH
LOCAL TIME ZONE` (UTC, whatever the session time zone).
* PostgreSQL: `CAST(col AS TIME(6)) AS col` for `TIME` and `TIMETZ`,
`CAST(col AS TIMESTAMP(6) WITHOUT TIME ZONE) AS col` for `TIMESTAMP
[WITHOUT TIME ZONE]`, and `CAST(col AS TIMESTAMP(6) WITH TIME ZONE) AS
col` for `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`.
5. **Fixed-Width Character Padding (`CHAR(n)` / `NCHAR(n)` / `BPCHAR` /
`GRAPHIC(n)`)**: `TRIM(TRAILING FROM col) AS col` (Teradata) or `RTRIM(col)
AS col` (Oracle and PostgreSQL) to strip fixed-width trailing pad spaces.
6. **Explicit Target Types**: A BigQuery `TargetType` from the BQMS config
(for example a schema override to `INT64`, `NUMERIC`, `DATE`, or
`TIMESTAMP`) wins over the source-type defaults above so the Parquet
column matches the BigQuery DDL. Cross-type overrides that a template
doesn't convert keep the default projection: `STRING`, `JSON`, and
`BYTES` in Oracle and Teradata (text columns stay text, binary columns
stay bytes, and numeric or datetime columns keep their type); `BOOL` in
Teradata and Oracle; `TIME` in Oracle and Databricks; `DATE` on Oracle
columns other than `DATE` / `TIMESTAMP`; and targets other than numeric
or `STRING` on Databricks `DECIMAL` columns. If `bq load` reports a type
mismatch, edit the template's `# CUSTOMIZE: Custom Type Projections`
hook.
> [!IMPORTANT]
> Always consult the **`references/`** directory
> (**[Snowflake Parquet mapping reference][snowflake_map]**,
> **[Databricks and Spark SQL Parquet mapping reference][databricks_map]**,
> **[Teradata Parquet mapping reference][teradata_map]**,
> **[Oracle Parquet mapping reference][oracle_map]**, and
> **[PostgreSQL Parquet mapping reference][postgres_map]**) to
> verify type conversions, formatting options, and dialect-specific export
> syntax.
--------------------------------------------------------------------------------
## 3. Asset Templates & Agent Workflow
This skill provides pure-Python SQL generator asset templates in `assets/` (with
no JDBC or warehouse driver dependencies):
* [Snowflake export SQL generator template][snowflake_exporter_template]
(`assets/export_snowflake_tables_template.py`)
* [Databricks export SQL generator template][databricks_exporter_template]
(`assets/export_databricks_tables_template.py`)
* [Teradata export SQL generator template][teradata_exporter_template]
(`assets/export_teradata_tables_template.py`)
* [Oracle export SQL generator template][oracle_exporter_template]
(`assets/export_oracle_tables_template.py`)
* [PostgreSQL export SQL generator template][postgres_exporter_template]
(`assets/export_postgres_tables_template.py`)
### Agent Workflow: Copy, Conditionally Customize, and Generate SQL
1. **Copy the Asset Template**: Copy `assets/<template_name>_template.py` from
this skill's directory (`<SKILL_DIR>`) into your working directory (copy the
file; do not paste or re-type the template contents into the response).
`<SKILL_DIR>` is the directory containing this `SKILL.md`:
```bash
# For Snowflake:
cp <SKILL_DIR>/assets/export_snowflake_tables_template.py ./export_snowflake_tables.py
# For Databricks:
cp <SKILL_DIR>/assets/export_databricks_tables_template.py ./export_databricks_tables.py
# For Teradata:
cp <SKILL_DIR>/assets/export_teradata_tables_template.py ./export_teradata_tables.py
# For Oracle:
cp <SKILL_DIR>/assets/export_oracle_tables_template.py ./export_oracle_tables.py
# For PostgreSQL:
cp <SKILL_DIR>/assets/export_postgres_tables_template.py ./export_postgres_tables.py
```
2. **Conditionally Customize Extension Points**: Run the copy as-is. Modify it
only if one of the following applies (prefer editing the marked `#
CUSTOMIZE:` sections; `# DEFAULT SCAFFOLDING` sections can be kept unchanged
unless deeper orchestration adjustments are needed):
* **Custom Type Projections (`# CUSTOMIZE: Custom Type Projections`)**:
Adjust `format_column_cast()` in `export_snowflake_tables.py`,
`export_databricks_tables.py`, `export_teradata_tables.py`,
`export_oracle_tables.py`, or `export_postgres_tables.py` for
non-standard data types, custom precision bounds, or special
JSON/geography serialization formats.
* **Stage & Storage Configuration (`# CUSTOMIZE: Stage & Storage
Configuration`)**: Customize `COPY INTO` file format options
(`MAX_FILE_SIZE`, compression codecs, or encryption flags) in
`_build_copy_into_query()` or Spark SQL `INSERT OVERWRITE DIRECTORY`
options in `_build_insert_overwrite_query()`. Pass Snowflake storage
integration names with the `--storage-integration` flag instead of
editing the template.
* **Table & Row Filtering (`# CUSTOMIZE: Table & Row Filtering` / `#
CUSTOMIZE: Row Filters`)**: Add custom `WHERE` clauses, partition
predicates, or custom schema/table inclusion/exclusion filters in
`_filter_tables_to_export()`, `_build_select_query()`, or
`load_tables_from_metadata_path()`.
3. **Generate the Export SQL Files**: Run the copied script with `python3`
(`python3 ./export_snowflake_tables.py`,
`python3 ./export_databricks_tables.py`,
`python3 ./export_teradata_tables.py`, `python3 ./export_oracle_tables.py`,
or `python3 ./export_postgres_tables.py`) to output a unified `.sql` script
(`--output-sql`) and/or per-table `*_export.sql` scripts (`--output-dir`).
4. **Check the Output**: Confirm the script exited with status `0`, report
any `WARNING:` lines from stderr (such as skipped duplicate tables), and
check that the number of `-- Unload Table:` markers (or `*_export.sql`
files) matches the tables you expect to export.
--------------------------------------------------------------------------------
### A. Snowflake Export SQL Generator (`./export_snowflake_tables.py`)
#### 1. Generate Unified Export SQL Script (`--output-sql`)
Unloading directly to Cloud Storage (`gcs://`) requires a Snowflake storage
integration (see [Before you begin](#before-you-begin)):
```bash
python3 ./export_snowflake_tables.py \
--translation-metadata-dir gs://my-bucket/translation_output/metadata/ \
--stage-path 'gcs://my-bucket/data_unload/' \
--storage-integration my_gcs_integration \
--output-sql export_snowflake_to_parquet.sql
```
#### 2. Generate Per-Table Export SQL Files (`--output-dir`)
```bash
python3 ./export_snowflake_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--stage-path '@~/bqms_export/' \
--output-dir ./export_sql
```
When the tables span more than one Snowflake database (tables whose metadata
omits the database count as `--default-database`), the generator
prefixes each unload subpath, `-- Unload Table:` label, and per-table file name
with the database (for example, `@~/bqms_export/<DB>/<SCHEMA>/<TABLE>/`) so that
identically named `<SCHEMA>.<TABLE>` pairs don't overwrite each other.
Snowflake resolves unquoted identifiers to uppercase, so names that aren't
uppercase are double-quoted to keep their exact case. Pass `--default-database`
and `--default-schema` exactly as the catalog stores them (usually uppercase,
such as `ANALYTICS`).
### B. Databricks Export SQL Generator (`./export_databricks_tables.py`)
Generates catalog-agnostic 2-part `<schema>.<table>` Spark SQL `INSERT OVERWRITE
DIRECTORY ... USING PARQUET` (or standalone `SELECT` by using `--export-mode
select`) scripts (`.sql`) with explicit type-safe projections for all discovered
Delta / Spark tables. Leave `--catalog` unset so the generated `.sql` files work
across both Unity Catalog and `hive_metastore` (activated by using `USE CATALOG`
on the target Spark or Databricks session at execution time), or pass `--catalog
<CATALOG>` for explicit 3-part table qualification. `--catalog` also exports
only the tables of that catalog when the metadata names catalogs (3-part YAML
`sourceName` values or the extractor `metadata.zip`); the generator exits with
an error that lists the available catalogs when it matches none of them:
```bash
python3 ./export_databricks_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--stage-path '/tmp/databricks_export' \
--output-sql export_databricks_to_parquet.sql \
--output-dir ./export_sql
```
### C. Teradata Export SQL Generator (`./export_teradata_tables.py`)
Generates explicit-cast Teradata `SELECT` scripts (`.sql`) with `-- Unload
Table: <DB>.<TABLE> -> Parquet` and `-- Required Columns:` markers consumed by
downstream Python Parquet streaming scripts (for example, by using `teradatasql`
and `pyarrow`). Use `--default-database <DB>` as a fallback qualifier when
metadata omits `TableSchema` (defaults to `$TERADATA_DATABASE`), `--database
<DB>` (repeatable) as an allow-list filter to export only specific databases
(the generator exits with an error when it leaves no tables),
`--unbounded-number-scale <S>` to adjust the fractional scale for unbounded
`NUMBER` / `NUMBER(*)` columns (default `9`), and `--keep-char-padding` if
fixed-width `CHAR(n)` trailing spaces must be preserved instead of trimmed:
```bash
# 1. Generate per-table Teradata export SQL files from BQMS translation output:
python3 ./export_teradata_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--default-database my_db \
--output-dir ./export_sql
# 2. Generate a unified export SQL script from a Teradata extractor metadata.zip:
python3 ./export_teradata_tables.py \
--metadata-zip gs://my-bucket/teradata_metadata/dwh-migration-teradata-metadata.zip \
--database my_db \
--output-sql teradata_export.sql
```
### D. Oracle Export SQL Generator (`./export_oracle_tables.py`)
Generates explicit-cast Oracle `SELECT` scripts (`.sql`) with `-- Unload Table:
<SCHEMA>.<TABLE> -> Parquet` and `-- Required Columns:` markers consumed by
downstream Python Parquet streaming scripts (for example, by using
`python-oracledb` and `pyarrow`). Use `--default-schema <SCHEMA>` as a fallback
qualifier when metadata omits `TableSchema` (defaults to `$ORACLE_SCHEMA`),
`--schema <SCHEMA>` (repeatable) as an allow-list filter to export only specific
schemas, `--unbounded-number-scale <S>` to adjust the fractional scale for
unconstrained `NUMBER` columns (default `9`), and `--keep-char-padding` if
fixed-width `CHAR(n)` / `NCHAR(n)` trailing spaces must be preserved instead of
trimmed. Identifiers that aren't uppercase are double-quoted to keep their exact
case, so pass `--default-schema` exactly as the catalog stores it (usually
uppercase, such as `HR`):
```bash
# 1. Generate per-table Oracle export SQL files from BQMS translation output:
python3 ./export_oracle_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--default-schema MY_SCHEMA \
--output-dir ./export_sql
# 2. Generate a unified export SQL script from an Oracle extractor metadata.zip:
python3 ./export_oracle_tables.py \
--metadata-zip gs://my-bucket/oracle_metadata/dwh-migration-oracle-metadata.zip \
--schema MY_SCHEMA \
--output-sql oracle_export.sql
```
### E. PostgreSQL Export SQL Generator (`./export_postgres_tables.py`)
Generates explicit-cast PostgreSQL `SELECT` scripts (`.sql`) with `-- Unload
Table: <SCHEMA>.<TABLE> -> Parquet` and `-- Required Columns:` markers consumed
by downstream Python Parquet streaming scripts (for example, by using `psycopg2`
and `pyarrow`). Use `--default-schema <SCHEMA>` as a fallback qualifier when
metadata omits `TableSchema` (defaults to `$PG_SCHEMA`), `--schema <SCHEMA>`
(repeatable) as an allow-list filter to export only specific schemas,
`--database <DB>` (repeatable) to keep only one database's tables when the
metadata spans several PostgreSQL databases (the generator exits with an error
when `--schema` / `--database` leave no tables),
`--unbounded-number-scale <S>` to adjust the fractional scale for unconstrained
`NUMERIC` columns (default `9`), and `--keep-char-padding` if fixed-width
`CHAR(n)` / `BPCHAR` trailing spaces must be preserved instead of trimmed.
Identifiers that aren't lowercase are double-quoted to keep their exact case,
so pass `--default-schema` exactly as the catalog stores it (usually lowercase,
such as `public`). BQMS YAML configs record PostgreSQL `NUMERIC` columns as a
`NUMERIC(18, 0)` placeholder, so pass the extractor `--metadata-zip` together
with `--translation-metadata-dir` (example 3) to restore exact `NUMERIC(p, s)`
and `NOT NULL` details:
```bash
# 1. Generate per-table PostgreSQL export SQL files from BQMS translation output:
python3 ./export_postgres_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--default-schema public \
--output-dir ./export_sql
# 2. Generate a unified export SQL script from a PostgreSQL extractor metadata.zip:
python3 ./export_postgres_tables.py \
--metadata-zip gs://my-bucket/postgres_metadata/postgresql-metadata.zip \
--schema public \
--output-sql postgres_export.sql
# 3. Combine BQMS translation output with the extractor metadata.zip:
python3 ./export_postgres_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--metadata-zip gs://my-bucket/postgres_metadata/postgresql-metadata.zip \
--default-schema public \
--output-dir ./export_sql
```
--------------------------------------------------------------------------------
## 4. Generated SQL Pattern
### Snowflake COPY INTO Pattern
```sql
ALTER SESSION SET TIME_OUTPUT_FORMAT = 'HH24:MI:SS.FF6';
ALTER SESSION SET TIMESTAMP_NTZ_OUTPUT_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF6';
ALTER SESSION SET TIMESTAMP_TZ_OUTPUT_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF6 TZHTZM';
COPY INTO 'gcs://my-bucket/data_unload/RAW_POS/MENU/'
FROM (
SELECT
CAST(MENU_ID AS BIGINT) AS MENU_ID,
CAST(COST_OF_GOODS_USD AS DECIMAL(38, 4)) AS COST_OF_GOODS_USD,
TO_VARCHAR(MENU_ITEM_HEALTH_METRICS_OBJ) AS MENU_ITEM_HEALTH_METRICS_OBJ
FROM MY_DB.RAW_POS.MENU
)
STORAGE_INTEGRATION = my_gcs_integration
FILE_FORMAT = (
TYPE = PARQUET
COMPRESSION = SNAPPY
)
HEADER = TRUE
OVERWRITE = TRUE
MAX_FILE_SIZE = 104857600;
```
### Databricks, Teradata, Oracle, and PostgreSQL Patterns
Section 4 of the [Databricks][databricks_map], [Teradata][teradata_map],
[Oracle][oracle_map], and [PostgreSQL][postgres_map] mapping references shows
the complete generated script: Spark SQL `INSERT OVERWRITE DIRECTORY ... USING
PARQUET SELECT ...` for Databricks, and explicit-cast `SELECT ...` statements
(`LOCKING ROW FOR ACCESS SELECT ...` in Teradata) with `-- Unload Table:` and
`-- Required Columns:` markers for the others.
[snowflake_exporter_template]: assets/export_snowflake_tables_template.py
[databricks_exporter_template]: assets/export_databricks_tables_template.py
[teradata_exporter_template]: assets/export_teradata_tables_template.py
[oracle_exporter_template]: assets/export_oracle_tables_template.py
[postgres_exporter_template]: assets/export_postgres_tables_template.py
[snowflake_map]: references/snowflake_parquet_mapping.md
[databricks_map]: references/databricks_parquet_mapping.md
[teradata_map]: references/teradata_parquet_mapping.md
[oracle_map]: references/oracle_parquet_mapping.md
[postgres_map]: references/postgres_parquet_mapping.md
[snowflake_gcs_integration]: https://docs.snowflake.com/en/user-guide/data-load-gcs-config
export_databricks_tables_template.py 39.8 KB
#!/usr/bin/env python3
r"""Template Script for Generating Databricks/Spark SQL Parquet Export SQL.
This asset template script provides a reference implementation for generating
type-safe Databricks / Spark SQL Parquet export scripts (.sql) from BQMS
translation_output/metadata configs, schema DDLs, or metadata archives. It
supports both:
1. `insert_overwrite` mode (`INSERT OVERWRITE DIRECTORY ... USING PARQUET
OPTIONS ('compression' = 'snappy') SELECT ...`) for cloud storage URIs,
Unity Catalog Volumes, or Spark Thrift Servers.
2. `select` mode (explicit-cast `SELECT ... FROM ...;` with `-- Unload Table:`
markers) for streaming Arrow/Parquet directly from Databricks SQL
Warehouses via `databricks-sql-connector`.
Note: Downstream Databricks SQL Warehouse execution scripts can run EITHER
format (extracting the inner `SELECT` and streaming Arrow/Parquet batches when
an `INSERT OVERWRITE DIRECTORY` targets a local filesystem path).
Usage Pattern:
Copy `assets/export_databricks_tables_template.py` from this skill's directory
(`<SKILL_DIR>`, the directory containing `SKILL.md`) into your
working directory (e.g., `./export_databricks_tables.py`). Run the copy as-is
for standard export SQL generation, and prioritize modifying the marked
`# CUSTOMIZE:` extension points if your environment requires custom type
projections, stage options, or table filtering. Sections marked
`# DEFAULT SCAFFOLDING` can be kept unchanged unless deeper orchestration
adjustments are needed.
Dependencies:
pip install pyyaml==6.0.2
Usage Examples:
cp <SKILL_DIR>/assets/export_databricks_tables_template.py \
./export_databricks_tables.py
# 1. Generate a unified Databricks Parquet export SQL file:
python3 ./export_databricks_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--stage-path '/tmp/databricks_export' \
--output-sql databricks_export.sql
# 2. Generate per-table Databricks Parquet export SQL files in a directory:
python3 ./export_databricks_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--stage-path '/tmp/databricks_export' \
--output-dir ./export_sql
"""
from __future__ import annotations
import argparse
import csv
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from typing import Any
import zipfile
import yaml
# ==============================================================================
# 1. File & Metadata Discovery Helpers (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Deterministic file reading and metadata discovery.
_SQL_TABLE_REGEX = re.compile(
r"CREATE\s+(?:OR\s+REPLACE\s+)?TABLE\s+"
r"(?:IF\s+NOT\s+EXISTS\s+)?([^\s\(\;]+)",
re.IGNORECASE,
)
_VALID_IDENT_REGEX = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_PARAM_TYPE_REGEX = re.compile(
r"^(?P<base>[A-Za-z0-9_]+)\s*\(\s*(?P<p>\d+)(?:\s*,\s*(?P<s>\d+))?\s*\)$"
)
def read_file_or_gcs(path_or_uri: str) -> bytes:
"""Reads content from a local file path or a Cloud Storage URI.
Args:
path_or_uri: Local file path or Cloud Storage URI (starts with 'gs://').
Returns:
The raw file content as bytes.
Raises:
FileNotFoundError: If the local file does not exist.
RuntimeError: If gcloud storage fails to read from Cloud Storage.
"""
if path_or_uri.startswith("gs://"):
cmd = ["gcloud", "storage", "cat", path_or_uri]
try:
return subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
raise RuntimeError(
f"Failed to read from Cloud Storage '{path_or_uri}': {e}"
) from e
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot read '{path_or_uri}': the gcloud CLI was not found. Install"
" the Google Cloud CLI, or download the file and pass a local path."
) from e
else:
if not os.path.exists(path_or_uri):
raise FileNotFoundError(f"Local file not found: '{path_or_uri}'")
with open(path_or_uri, "rb") as f:
return f.read()
def _run_gcloud_copy(cmd: list[str], uri: str) -> None:
"""Runs a `gcloud storage cp` command, surfacing its stderr on failure."""
try:
subprocess.run(cmd, capture_output=True, check=True)
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot copy '{uri}': the gcloud CLI was not found. Install the"
" Google Cloud CLI, or copy the files locally and pass a local path."
) from e
except subprocess.CalledProcessError as e:
stderr = (e.stderr or b"").decode("utf-8", errors="replace").strip()
raise RuntimeError(
f"Failed to copy from Cloud Storage '{uri}' (exit code"
f" {e.returncode}): {stderr or e}"
) from e
# DEFAULT SCAFFOLDING: Metadata directory resolution and YAML/SQL parsers.
def _resolve_metadata_dir(path_or_uri: str) -> tuple[str, str | None]:
"""Downloads Cloud Storage metadata if needed; returns (dir, temp_dir)."""
if path_or_uri.startswith("gs://"):
temp_dir = tempfile.mkdtemp(prefix="bqms_db_meta_")
if path_or_uri.endswith((".zip", ".yaml", ".yml")):
local_file = os.path.join(temp_dir, os.path.basename(path_or_uri))
with open(local_file, "wb") as f:
f.write(read_file_or_gcs(path_or_uri))
return temp_dir, temp_dir
cmd = [
"gcloud",
"storage",
"cp",
"-r",
path_or_uri.rstrip("/") + "/*",
temp_dir,
]
_run_gcloud_copy(cmd, path_or_uri)
return temp_dir, temp_dir
if not os.path.exists(path_or_uri):
# Only a missing `.../metadata` leaf falls back to its parent (for
# example `translated_output/metadata` when the sibling layout is
# used); any other missing path is a typo, not a directory to scan.
trimmed = path_or_uri.rstrip("/")
parent = os.path.dirname(trimmed)
if (
os.path.basename(trimmed).lower() == "metadata"
and parent
and os.path.isdir(parent)
):
return parent, None
raise FileNotFoundError(f"Metadata path not found: '{path_or_uri}'")
return path_or_uri, None
def _find_config_dir(dir_to_scan: str) -> str:
"""Identifies the config directory containing table YAMLs."""
config_dir = os.path.join(dir_to_scan, "metadata", "config")
if not os.path.isdir(config_dir) and os.path.isdir(
os.path.join(dir_to_scan, "config")
):
return os.path.join(dir_to_scan, "config")
elif not os.path.isdir(config_dir):
return dir_to_scan
return config_dir
# Placeholder catalog names that BQMS or Spark emit for the session catalog.
_PLACEHOLDER_CATALOGS = frozenset(("__default_database__", "spark_catalog"))
def _real_catalog(name: str) -> str:
"""Returns the catalog name, or '' for a session-catalog placeholder."""
name = name.strip()
return "" if name.lower() in _PLACEHOLDER_CATALOGS else name
def _warn_duplicate_table(name: str, source: str) -> None:
"""Warns that a schema.table already discovered was skipped."""
# Generated SQL is 2-part (catalog-agnostic) unless --catalog is set, so a
# same-named table from another catalog can't be exported alongside.
print(
f"WARNING: Skipping duplicate table {name} in {source};"
" pass --catalog to choose which catalog to export.",
file=sys.stderr,
)
_VIEW_TABLE_TYPES = frozenset(
("VIEW", "VIRTUAL_VIEW", "MATERIALIZED_VIEW", "METRIC_VIEW")
)
def _parse_yaml_file(
fpath: str,
seen: set[tuple[str, str]],
discovered: list[dict[str, Any]],
catalog: str | None = None,
) -> None:
"""Parses a single BQMS config YAML file.
Args:
fpath: Path to the YAML file.
seen: Lower-cased (schema, table) keys already discovered.
discovered: List that new table entries are appended to.
catalog: Optional --catalog filter. Tables whose 3-part sourceName names a
different (non-placeholder) catalog are skipped.
"""
try:
with open(fpath, "r", encoding="utf-8") as yf:
cfg = yaml.safe_load(yf)
except (yaml.YAMLError, OSError):
return
if not isinstance(cfg, dict):
return
table_type = (
str(cfg.get("TableType") or cfg.get("tableType") or "").strip().upper()
)
is_view = table_type in _VIEW_TABLE_TYPES or not bool(
cfg.get("externalTableName") or cfg.get("externalTableDdlPath")
)
if is_view:
return
src_name = cfg.get("sourceName", "")
parts = src_name.split(".") if src_name else []
if len(parts) >= 2:
schema = parts[-2]
table = parts[-1]
else:
schema = "default"
table = parts[0] if parts else os.path.basename(fpath).rsplit(".", 1)[0]
src_catalog = _real_catalog(parts[-3]) if len(parts) >= 3 else ""
if catalog and src_catalog and src_catalog.lower() != catalog.lower():
return
cols: list[dict[str, str]] = []
for col in cfg.get("columns") or []:
if not isinstance(col, dict):
continue
col_name = str(col.get("sourceName") or "")
# `sourceType: null` / `targetType: null` load as None; treat them as empty
# instead of the literal string "None".
src_type = col.get("sourceType") or {}
tgt_type = col.get("targetType") or {}
# `genericName: null` or a missing genericName falls back to the source
# `name`, so the column still gets a type-specific cast.
gen_name = (
str(src_type.get("genericName") or src_type.get("name") or "STRING")
if isinstance(src_type, dict)
else str(src_type)
)
precision = (
str(src_type.get("precision", ""))
if isinstance(src_type, dict) and src_type.get("precision") is not None
else ""
)
scale = (
str(src_type.get("scale", ""))
if isinstance(src_type, dict) and src_type.get("scale") is not None
else ""
)
tgt_name = (
str(tgt_type.get("name") or "")
if isinstance(tgt_type, dict)
else str(tgt_type)
)
if col_name:
cols.append({
"ColumnName": col_name,
"DataType": gen_name,
"NumericPrecision": precision,
"NumericScale": scale,
"TargetType": tgt_name,
})
key = (schema.lower(), table.lower())
if key in seen:
_warn_duplicate_table(src_name or table, fpath)
return
seen.add(key)
discovered.append({"schema": schema, "table": table, "columns": cols})
def _yaml_catalogs(config_dir: str) -> set[str]:
"""Returns the catalogs named by 3-part sourceName values of table YAMLs."""
catalogs: set[str] = set()
paths: list[str] = []
if os.path.isfile(config_dir) and config_dir.endswith((".yaml", ".yml")):
paths.append(config_dir)
elif os.path.isdir(config_dir):
for root, _, files in os.walk(config_dir):
paths.extend(
os.path.join(root, f) for f in files if f.endswith((".yaml", ".yml"))
)
for path in paths:
try:
with open(path, "r", encoding="utf-8") as yf:
cfg = yaml.safe_load(yf)
except (yaml.YAMLError, OSError, UnicodeDecodeError):
continue
if not isinstance(cfg, dict):
continue
if not (cfg.get("externalTableName") or cfg.get("externalTableDdlPath")):
continue
parts = str(cfg.get("sourceName") or "").split(".")
if len(parts) >= 3 and _real_catalog(parts[-3]):
catalogs.add(_real_catalog(parts[-3]))
return catalogs
def _parse_tables_from_yaml_configs(
config_dir: str, catalog: str | None = None
) -> list[dict[str, Any]]:
"""Parses table configurations from YAML metadata files."""
discovered: list[dict[str, Any]] = []
seen: set[tuple[str, str]] = set()
if os.path.isfile(config_dir) and (
config_dir.endswith(".yaml") or config_dir.endswith(".yml")
):
_parse_yaml_file(config_dir, seen, discovered, catalog=catalog)
return discovered
if not os.path.isdir(config_dir):
return discovered
for root, dirs, files in os.walk(config_dir):
dirs.sort() # Deterministic order, so the first catalog wins.
for f in sorted(files):
if f.endswith(".yaml") or f.endswith(".yml"):
_parse_yaml_file(
os.path.join(root, f), seen, discovered, catalog=catalog
)
return discovered
def _extract_tables_from_sql_text(
sql_text: str,
seen: set[tuple[str, str]],
discovered: list[dict[str, Any]],
) -> None:
"""Extracts schema and table pairs from SQL CREATE TABLE statements."""
for match in _SQL_TABLE_REGEX.finditer(sql_text):
raw_target = match.group(1).strip()
parts = [p.strip().strip("`").strip('"') for p in raw_target.split(".")]
schema = parts[-2] if len(parts) >= 2 else "default"
table = parts[-1] if len(parts) >= 2 else parts[0]
key = (schema.lower(), table.lower())
if key not in seen:
seen.add(key)
discovered.append({"schema": schema, "table": table, "columns": []})
def _zip_view_keys(
zf: zipfile.ZipFile, by_base: dict[str, str]
) -> set[tuple[str, str, str]]:
"""Returns lower-cased (catalog, schema, table) keys of views in a zip.
The Databricks extractor records TableType in tables.csv (and lists views in
views.csv); columns.csv has rows for both tables and views.
Args:
zf: The open metadata zip archive.
by_base: The archive's entry names keyed by lower-cased basename.
Returns:
The set of view keys, with session-catalog placeholders as ''.
"""
keys: set[tuple[str, str, str]] = set()
for entry in ("tables.csv", "views.csv"):
if entry not in by_base:
continue
text = zf.read(by_base[entry]).decode("utf-8-sig", errors="replace")
for row in csv.DictReader(io.StringIO(text)):
table_type = (row.get("TableType") or "").strip().upper()
if entry == "tables.csv" and table_type not in _VIEW_TABLE_TYPES:
continue
keys.add((
_real_catalog(row.get("TableCatalog") or "").lower(),
(row.get("TableSchema") or "default").strip().lower(),
(row.get("TableName") or "").strip().lower(),
))
return keys
def _extract_tables_from_zip(
zf: zipfile.ZipFile,
seen: set[tuple[str, str]],
discovered: list[dict[str, Any]],
catalog: str | None = None,
skipped_catalogs: set[str] | None = None,
) -> None:
"""Extracts tables and columns from a metadata zip archive.
Args:
zf: The open metadata zip archive.
seen: Lower-cased (schema, table) keys already discovered.
discovered: List that new table entries are appended to.
catalog: Optional --catalog filter.
skipped_catalogs: Collects the catalogs of rows that --catalog skipped.
"""
skipped: set[str] = set()
names = zf.namelist()
by_base = {os.path.basename(n).lower(): n for n in names}
initial_count = len(discovered)
zip_name = zf.filename or "metadata zip"
if "columns.csv" in by_base:
text = zf.read(by_base["columns.csv"]).decode("utf-8-sig", errors="replace")
reader = csv.DictReader(io.StringIO(text))
cols_by_key: dict[tuple[str, str, str], list[dict[str, str]]] = {}
orig_names: dict[tuple[str, str, str], tuple[str, str]] = {}
view_keys = _zip_view_keys(zf, by_base)
for row in reader:
table_type = (row.get("TableType") or "").strip().upper()
if table_type in _VIEW_TABLE_TYPES:
continue
row_cat = _real_catalog(row.get("TableCatalog") or "")
if catalog and row_cat and row_cat.lower() != catalog.lower():
skipped.add(row_cat)
continue
schema = (row.get("TableSchema") or "default").strip()
table = (row.get("TableName") or "").strip()
col_name = (row.get("ColumnName") or "").strip()
if not (table and col_name):
continue
cat_key = (row_cat.lower(), schema.lower(), table.lower())
if cat_key in view_keys:
continue
orig_names.setdefault(cat_key, (schema, table))
cols_by_key.setdefault(cat_key, []).append({
"ColumnName": col_name,
"DataType": (
(
row.get("FullDataType") or row.get("DataType") or "STRING"
).strip()
),
"NumericPrecision": (row.get("NumericPrecision") or "").strip(),
"NumericScale": (row.get("NumericScale") or "").strip(),
"TargetType": "",
})
for cat_key, cols in cols_by_key.items():
key = cat_key[1:]
s_orig, t_orig = orig_names[cat_key]
if key in seen:
_warn_duplicate_table(f"{s_orig}.{t_orig}", f"{zip_name}/columns.csv")
continue
seen.add(key)
discovered.append({"schema": s_orig, "table": t_orig, "columns": cols})
if len(discovered) > initial_count:
if skipped_catalogs is not None:
skipped_catalogs.update(skipped)
return
if "tables.jsonl" in by_base:
text = zf.read(by_base["tables.jsonl"]).decode(
"utf-8-sig", errors="replace"
)
for line in text.splitlines():
if not line.strip():
continue
try:
obj = json.loads(line)
except ValueError:
continue
if str(obj.get("type", "")).strip().upper() in _VIEW_TABLE_TYPES:
continue
obj_cat = _real_catalog(str(obj.get("catalogName") or ""))
if catalog and obj_cat and obj_cat.lower() != catalog.lower():
skipped.add(obj_cat)
continue
schema = str(obj.get("schemaName") or "default").strip()
table = str(obj.get("name") or "").strip()
if not table:
continue
cols: list[dict[str, str]] = []
for f_entry in (obj.get("fields") or []) + (
obj.get("partitionKeys") or []
):
if isinstance(f_entry, dict) and f_entry.get("name"):
cols.append({
"ColumnName": str(f_entry["name"]),
"DataType": str(f_entry.get("type") or "STRING"),
"NumericPrecision": "",
"NumericScale": "",
"TargetType": "",
})
key = (schema.lower(), table.lower())
if key in seen:
_warn_duplicate_table(f"{schema}.{table}", f"{zip_name}/tables.jsonl")
continue
seen.add(key)
discovered.append({"schema": schema, "table": table, "columns": cols})
if len(discovered) > initial_count:
if skipped_catalogs is not None:
skipped_catalogs.update(skipped)
return
if skipped:
# The zip names catalogs, so don't fall back to unfiltered DDL parsing.
if skipped_catalogs is not None:
skipped_catalogs.update(skipped)
return
for zname in sorted(names):
if zname.endswith(".sql") and "view" not in zname.lower():
sql_text = zf.read(zname).decode("utf-8", errors="replace")
_extract_tables_from_sql_text(sql_text, seen, discovered)
def _parse_tables_from_sql_or_zip(
dir_to_scan: str,
catalog: str | None = None,
skipped_catalogs: set[str] | None = None,
) -> list[dict[str, Any]]:
"""Fallback table discovery from DDL SQL files or metadata zip archives."""
discovered: list[dict[str, Any]] = []
seen: set[tuple[str, str]] = set()
if os.path.isfile(dir_to_scan):
if dir_to_scan.endswith(".sql"):
with open(dir_to_scan, "r", encoding="utf-8") as sf:
_extract_tables_from_sql_text(sf.read(), seen, discovered)
elif dir_to_scan.endswith(".zip"):
with zipfile.ZipFile(dir_to_scan, "r") as zf:
_extract_tables_from_zip(
zf, seen, discovered, catalog, skipped_catalogs
)
return discovered
if not os.path.isdir(dir_to_scan):
return discovered
sql_paths: list[str] = []
for root, dirs, files in os.walk(dir_to_scan):
dirs.sort() # Deterministic order, so the first catalog wins.
for f in sorted(files):
fpath = os.path.join(root, f)
if f.endswith(".zip"):
try:
with zipfile.ZipFile(fpath, "r") as zf:
_extract_tables_from_zip(
zf, seen, discovered, catalog, skipped_catalogs
)
except (zipfile.BadZipFile, OSError):
pass
elif f.endswith(".sql") and "view" not in f.lower():
sql_paths.append(fpath)
# Loose DDL has no catalog, so skip it once a zip row was filtered out by
# --catalog.
if skipped_catalogs:
return discovered
for fpath in sql_paths:
try:
with open(fpath, "r", encoding="utf-8") as sf:
sql_text = sf.read()
except OSError:
continue
_extract_tables_from_sql_text(sql_text, seen, discovered)
return discovered
# CUSTOMIZE: Table & Row Filtering — Edit load_tables_from_metadata_path() to
# add custom schema/table inclusion or exclusion filters.
def load_tables_from_metadata_path(
path_or_uri: str,
catalog: str | None = None,
) -> list[dict[str, Any]]:
"""Discovers tables to export from translation metadata, DDL, or zip archive.
Inspects BQMS translated YAML configuration files first, falling back to
sibling `metadata/` or parsing table DDLs from SQL files or zip archives.
Args:
path_or_uri: Local path or Cloud Storage URI to metadata directory, config
dir, or DDLs.
catalog: Optional catalog filter when reading multi-catalog metadata zips.
Returns:
A list of dictionaries each containing 'schema' and 'table' keys (and
optional 'columns').
"""
dir_to_scan, temp_dir = _resolve_metadata_dir(path_or_uri)
skipped_catalogs: set[str] = set()
try:
config_dir = _find_config_dir(dir_to_scan)
discovered_tables = _parse_tables_from_yaml_configs(
config_dir, catalog=catalog
)
if catalog and not discovered_tables:
yaml_catalogs = _yaml_catalogs(config_dir)
if yaml_catalogs:
# Don't fall back to unfiltered DDL parsing when YAML configs exist
# but none of them is in the requested catalog.
raise ValueError(
f"--catalog {catalog} matches none of the BQMS YAML configs;"
f" available catalogs: {', '.join(sorted(yaml_catalogs))}."
)
# A gs:// download lives under the shared temp root, so never scan its
# parent's metadata/ directory.
if not discovered_tables and os.path.isdir(dir_to_scan) and not temp_dir:
parent_dir = os.path.dirname(os.path.abspath(dir_to_scan))
sibling_meta_dir = os.path.join(parent_dir, "metadata")
if os.path.isdir(sibling_meta_dir) and os.path.abspath(
sibling_meta_dir
) != os.path.abspath(dir_to_scan):
discovered_tables = _parse_tables_from_sql_or_zip(
sibling_meta_dir, catalog, skipped_catalogs
)
if not discovered_tables:
discovered_tables = _parse_tables_from_sql_or_zip(
dir_to_scan, catalog, skipped_catalogs
)
if catalog and not discovered_tables and skipped_catalogs:
raise ValueError(
f"--catalog {catalog} matches no tables in the metadata zip;"
f" available catalogs: {', '.join(sorted(skipped_catalogs))}."
)
return [
{"schema": str(t["schema"]), "table": str(t["table"])}
if not t.get("columns")
else t
for t in discovered_tables
]
finally:
if temp_dir:
shutil.rmtree(temp_dir, ignore_errors=True)
# ==============================================================================
# 2. Type-Safe Spark SQL Generation Logic
# ==============================================================================
# Spark SQL keywords reserved in ANSI mode plus the NULL/TRUE/FALSE literals.
# Backticks are always valid, so quoting these is safe in default mode too.
_SPARK_RESERVED = frozenset((
"ALL",
"AND",
"ANTI",
"ANY",
"AS",
"AUTHORIZATION",
"BETWEEN",
"BOTH",
"BY",
"CASE",
"CAST",
"CHECK",
"COLLATE",
"COLUMN",
"CONSTRAINT",
"CREATE",
"CROSS",
"CURRENT_DATE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_USER",
"DELETE",
"DISTINCT",
"ELSE",
"END",
"ESCAPE",
"EXCEPT",
"EXISTS",
"FALSE",
"FETCH",
"FILTER",
"FOR",
"FOREIGN",
"FROM",
"FULL",
"GRANT",
"GROUP",
"HAVING",
"IN",
"INNER",
"INSERT",
"INTERSECT",
"INTERVAL",
"INTO",
"IS",
"JOIN",
"LATERAL",
"LEADING",
"LEFT",
"LIKE",
"MINUS",
"NATURAL",
"NOT",
"NULL",
"OF",
"OFFSET",
"ON",
"ONLY",
"OR",
"ORDER",
"OUTER",
"OVERLAPS",
"PRIMARY",
"REFERENCES",
"RIGHT",
"SELECT",
"SEMI",
"SESSION_USER",
"SOME",
"TABLE",
"THEN",
"TIME",
"TO",
"TRAILING",
"TRUE",
"UNION",
"UNIQUE",
"UNKNOWN",
"UPDATE",
"USER",
"USING",
"VALUES",
"WHEN",
"WHERE",
"WINDOW",
"WITH",
))
# BigQuery integer target type names (INT64 and its aliases).
_INT_TARGET_TYPES = frozenset(
("INT64", "INT", "INTEGER", "BIGINT", "SMALLINT", "TINYINT", "BYTEINT")
)
# Spark SQL decimal and character source type names.
_DECIMAL_SOURCE_TYPES = frozenset(
("DECIMAL", "DEC", "NUMERIC", "NUMBER", "BIGNUMERIC")
)
_STRING_SOURCE_TYPES = frozenset(("STRING", "VARCHAR", "CHAR"))
_INT_SOURCE_TYPES = frozenset((
"BIGINT",
"LONG",
"INT",
"INTEGER",
"SMALLINT",
"SHORT",
"TINYINT",
"BYTE",
"BYTEINT",
))
# Comment lines written at the top of the unified script and of every per-table
# file. They stay comments (not `SET TIME ZONE 'UTC';`) because the SQL
# warehouse connector runs exactly one statement per call.
_SESSION_TIME_ZONE_NOTE = (
"-- NOTE: TIMESTAMP_NTZ <-> TIMESTAMP casts use the session time zone. Run",
"-- in a UTC session (SQL warehouse TIMEZONE or spark.sql.session.timeZone",
"-- set to UTC, or SET TIME ZONE 'UTC' first in a beeline session).",
)
# DEFAULT SCAFFOLDING: Spark SQL identifier quoting helper.
def quote_ident(ident: str) -> str:
"""Quotes an identifier with backticks if needed for Spark SQL.
Names that start with a digit, contain special characters, or match a
reserved word or literal (such as `select` or `null`) are backtick-quoted.
Args:
ident: The raw SQL identifier string.
Returns:
The properly quoted or unquoted identifier.
"""
if not ident:
return ""
if len(ident) >= 2 and ident.startswith("`") and ident.endswith("`"):
# Already quoted: re-escape any bare inner backticks.
inner = ident[1:-1].replace("``", "`").replace("`", "``")
return f"`{inner}`"
if (
ident[0].isdigit()
or not _VALID_IDENT_REGEX.match(ident)
or ident.upper() in _SPARK_RESERVED
):
escaped = ident.replace("`", "``")
return f"`{escaped}`"
return ident
# CUSTOMIZE: Custom Type Projections — Edit format_column_cast() to add custom
# Spark SQL column projections (e.g. TO_JSON for STRUCT/MAP/ARRAY, DECIMAL
# precision bounds, or timestamp formatting).
def format_column_cast(
col: dict[str, str], target_bq_type: str | None = None
) -> str:
"""Generates a type-safe Spark SQL projection expression for export."""
col_raw = str(col.get("ColumnName") or "").strip()
col_name = quote_ident(col_raw)
raw_data_type = str(col.get("DataType") or "").upper().strip()
precision_str = str(col.get("NumericPrecision") or "").strip()
scale_str = str(col.get("NumericScale") or "").strip()
precision = int(precision_str) if precision_str.isdigit() else None
scale = int(scale_str) if scale_str.isdigit() else None
param_match = _PARAM_TYPE_REGEX.match(raw_data_type)
if param_match:
data_type = param_match.group("base")
if precision is None:
precision = int(param_match.group("p"))
if scale is None:
if param_match.group("s") is not None:
scale = int(param_match.group("s"))
elif data_type in ("DECIMAL", "DEC", "NUMERIC", "NUMBER"):
scale = 0
else:
data_type = re.split(r"[<(\s]", raw_data_type, maxsplit=1)[0].strip()
target = (target_bq_type or str(col.get("TargetType") or "")).upper().strip()
if data_type == "MAP":
return f"TO_JSON({col_name}) AS {col_name}"
if data_type in ("STRUCT", "ARRAY") and (
target.startswith("JSON") or target == "STRING"
):
return f"TO_JSON({col_name}) AS {col_name}"
if target.startswith("JSON") or data_type in ("VARIANT", "OBJECT", "JSON"):
return f"CAST({col_name} AS STRING) AS {col_name}"
if data_type.startswith("INTERVAL"):
return f"CAST({col_name} AS STRING) AS {col_name}"
# Explicit BigQuery target types (for example schema overrides) win over the
# source-type defaults below. DECIMAL sources are handled in their own branch,
# and same-family targets (a STRING column with a STRING target, or a
# timestamp column with a TIMESTAMP / DATETIME target) keep the defaults.
target_base = re.split(r"[(<]", target, maxsplit=1)[0].strip()
is_timestamp = data_type.startswith("TIMESTAMP") or data_type == "DATETIME"
if target_base and data_type not in _DECIMAL_SOURCE_TYPES:
if target_base in _INT_TARGET_TYPES:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if target_base in ("FLOAT64", "FLOAT", "DOUBLE"):
return f"CAST({col_name} AS DOUBLE) AS {col_name}"
if target_base in ("BOOL", "BOOLEAN"):
return f"CAST({col_name} AS BOOLEAN) AS {col_name}"
if target_base == "DATE":
return f"CAST({col_name} AS DATE) AS {col_name}"
if target_base == "BYTES":
return f"CAST({col_name} AS BINARY) AS {col_name}"
if target_base in ("NUMERIC", "BIGNUMERIC", "DECIMAL"):
# Parquet DECIMAL for a fixed-point BigQuery column; integers keep
# scale 0. NUMERIC (alias DECIMAL) holds at most 29 integer digits.
if data_type in _INT_SOURCE_TYPES:
p_val = 38 if target_base == "BIGNUMERIC" else 29
return f"CAST({col_name} AS DECIMAL({p_val}, 0)) AS {col_name}"
return f"CAST({col_name} AS DECIMAL(38, 9)) AS {col_name}"
if target_base == "STRING" and data_type not in _STRING_SOURCE_TYPES:
return f"CAST({col_name} AS STRING) AS {col_name}"
if target_base == "TIMESTAMP" and not is_timestamp:
return f"CAST({col_name} AS TIMESTAMP) AS {col_name}"
if target_base == "DATETIME" and not is_timestamp:
return f"CAST({col_name} AS TIMESTAMP_NTZ) AS {col_name}"
if data_type in _DECIMAL_SOURCE_TYPES:
# An explicit BigQuery target type wins over the implicit BIGINT shortcut.
if target.startswith(("FLOAT", "DOUBLE")):
return f"CAST({col_name} AS DOUBLE) AS {col_name}"
if target.startswith("STRING"):
return f"CAST({col_name} AS STRING) AS {col_name}"
if target in _INT_TARGET_TYPES:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if (
scale == 0
and precision is not None
and precision <= 18
and not target.startswith(("NUMERIC", "BIGNUMERIC", "DECIMAL"))
):
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if scale is None:
return f"{col_name}"
# Spark DECIMAL(p, s) requires 1 <= p <= 38 and 0 <= s <= p.
p_val = min(max(precision, 1), 38) if precision is not None else 38
s_val = min(scale, p_val)
return f"CAST({col_name} AS DECIMAL({p_val}, {s_val})) AS {col_name}"
if data_type in _INT_SOURCE_TYPES:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if data_type in ("DOUBLE", "FLOAT", "REAL"):
return f"CAST({col_name} AS DOUBLE) AS {col_name}"
if data_type in ("TIMESTAMP_NTZ", "DATETIME"):
if target == "DATETIME":
return f"{col_name}"
return f"CAST({col_name} AS TIMESTAMP) AS {col_name}"
if data_type.startswith("TIMESTAMP"):
if target == "DATETIME":
return f"CAST({col_name} AS TIMESTAMP_NTZ) AS {col_name}"
return f"CAST({col_name} AS TIMESTAMP) AS {col_name}"
if data_type == "DATE":
return f"CAST({col_name} AS DATE) AS {col_name}"
if data_type in ("BOOLEAN", "BOOL"):
return f"CAST({col_name} AS BOOLEAN) AS {col_name}"
if data_type in ("BINARY", "VARBINARY", "BYTES"):
return f"CAST({col_name} AS BINARY) AS {col_name}"
return f"{col_name}"
def _sanitize_comment_token(value: str) -> str:
"""Replaces control characters so SQL line comments stay single-line."""
return re.sub(r"[\x00-\x1f\x7f]+", " ", str(value)).strip()
# CUSTOMIZE: Stage & Storage Configuration — Edit
# _build_insert_overwrite_query() to customize the Spark SQL INSERT OVERWRITE
# DIRECTORY options (compression codec, WHERE filter predicates, or partition
# options).
def _build_insert_overwrite_query(
schema: str,
table_name: str,
columns: list[dict[str, str]] | None = None,
stage_path: str = "/tmp/databricks_export",
include_schema_subpath: bool = False,
catalog: str | None = None,
export_mode: str = "insert_overwrite",
) -> str:
"""Builds the Spark SQL export statement for a table."""
clean_stage = stage_path.strip().strip("'").rstrip("/")
if include_schema_subpath and schema:
target_dir = f"{clean_stage}/{schema}/{table_name}"
else:
target_dir = f"{clean_stage}/{table_name}"
escaped_target_dir = target_dir.replace("'", "''")
if catalog:
qualified_src = (
f"{quote_ident(catalog)}.{quote_ident(schema)}."
f"{quote_ident(table_name)}"
)
else:
qualified_src = f"{quote_ident(schema)}.{quote_ident(table_name)}"
if columns:
projections = ",\n ".join(format_column_cast(c) for c in columns)
select_clause = f"SELECT\n {projections}\nFROM {qualified_src}"
else:
select_clause = f"SELECT * FROM {qualified_src}"
if export_mode.lower() == "select":
return (
f"-- Target Directory: {_sanitize_comment_token(target_dir)}\n"
f"{select_clause};"
)
return (
f"INSERT OVERWRITE DIRECTORY '{escaped_target_dir}'\n"
"USING PARQUET\n"
"OPTIONS ('compression' = 'snappy')\n"
f"{select_clause};"
)
# DEFAULT SCAFFOLDING: Primary Databricks SQL script generator.
def generate_export_sql(
metadata_path_or_uri: str,
stage_path: str = "/tmp/databricks_export",
catalog: str | None = None,
export_mode: str = "insert_overwrite",
) -> str:
"""Generates the Databricks / Spark SQL Parquet export script (.sql).
Args:
metadata_path_or_uri: Path or Cloud Storage URI to translation metadata,
config dir, or DDLs.
stage_path: Destination directory path inside the Spark/Databricks
environment (default: '/tmp/databricks_export').
catalog: Optional Unity Catalog name to prefix 3-part table references.
export_mode: 'insert_overwrite' (default) or 'select'.
Returns:
A complete, formatted Spark SQL script string ready for execution.
"""
tables = load_tables_from_metadata_path(metadata_path_or_uri, catalog=catalog)
generator_name = (
os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] else ""
) or "export_databricks_tables_template.py"
table_name_counts: dict[str, int] = {}
for item in tables:
t_lower = str(item.get("table") or "").lower()
if t_lower:
table_name_counts[t_lower] = table_name_counts.get(t_lower, 0) + 1
colliding_tables = {t for t, count in table_name_counts.items() if count > 1}
colliding_schemas = {
str(item.get("schema") or "default").lower()
for item in tables
if str(item.get("table") or "").lower() in colliding_tables
}
sql_lines = [
"-- " + "=" * 77,
"-- Databricks / Spark SQL to Parquet Type-Safe Data Export Script",
f"-- Generated by bigquery-migration-data-exporter / {generator_name}",
*_SESSION_TIME_ZONE_NOTE,
"-- " + "=" * 77,
"",
]
divider = "-- " + "-" * 77
for item in tables:
schema = str(item.get("schema") or "default")
table_name = str(item.get("table") or "")
if not table_name:
continue
cols = item.get("columns") or []
t_lower = table_name.lower()
has_collision = t_lower in colliding_tables or t_lower in colliding_schemas
stmt = _build_insert_overwrite_query(
schema=schema,
table_name=table_name,
columns=cols,
stage_path=stage_path,
include_schema_subpath=has_collision,
catalog=catalog,
export_mode=export_mode,
)
table_label = _sanitize_comment_token(f"{schema}.{table_name}")
sql_lines.append(
f"{divider}\n-- Unload Table: {table_label} ->"
f" Parquet\n{divider}\n{stmt}\n"
)
return "\n".join(sql_lines)
def _sanitize_sql_filename(label: str, used_filenames: set[str]) -> str:
"""Builds a safe, collision-free per-table SQL filename."""
unquoted = label.replace('"', "").replace("`", "").strip()
safe_parts = [
re.sub(r"[^A-Za-z0-9_-]+", "_", p.strip()).strip("_") or "table"
for p in unquoted.split(".")
if p.strip()
]
stem = "_".join(safe_parts) if safe_parts else "table"
filename = f"{stem}_export.sql"
if filename.lower() in used_filenames and len(safe_parts) > 1:
filename = f"{'__'.join(safe_parts)}_export.sql"
idx = 2
base_stem = filename[: -len("_export.sql")]
while filename.lower() in used_filenames:
filename = f"{base_stem}_{idx}_export.sql"
idx += 1
used_filenames.add(filename.lower())
return filename
def _write_table_sql_files(sql: str, output_dir: str) -> list[str]:
"""Splits unified Spark SQL script and writes per-table SQL files."""
os.makedirs(output_dir, exist_ok=True)
divider = "-- " + "-" * 77
stmts = sql.split(f"{divider}\n-- Unload Table: ")
written_paths: list[str] = []
used_filenames: set[str] = set()
for chunk in stmts[1:]:
table_label = chunk.split(" -> Parquet")[0].strip()
filename = _sanitize_sql_filename(table_label, used_filenames)
table_sql = (
"\n".join(_SESSION_TIME_ZONE_NOTE)
+ f"\n{divider}\n-- Unload Table: {chunk}"
)
tbl_path = os.path.join(output_dir, filename)
with open(tbl_path, "w", encoding="utf-8") as f:
f.write(table_sql)
written_paths.append(tbl_path)
print(f"Generated table export SQL: {tbl_path}")
return written_paths
# ==============================================================================
# 3. CLI Router (DEFAULT SCAFFOLDING CLI ROUTER)
# ==============================================================================
# DEFAULT SCAFFOLDING: CLI argument parser and SQL file writer entrypoint.
def _parse_args(args: list[str] | None = None) -> argparse.Namespace:
"""Builds and parses CLI arguments for Databricks export SQL generation."""
parser = argparse.ArgumentParser(
description=(
"Databricks / Spark SQL Parquet Export SQL Generator (outputs .sql"
" scripts)."
)
)
parser.add_argument(
"--translation-metadata-dir",
"--translation-output",
"--metadata-dir",
"--config-dir",
dest="metadata_path",
required=True,
help=(
"Path or Cloud Storage URI to translation_output/metadata, config"
" directory, or DDL metadata"
),
)
parser.add_argument(
"--stage-path",
"--export-dir",
dest="stage_path",
default="/tmp/databricks_export",
help=(
"Target directory path for Spark SQL INSERT OVERWRITE DIRECTORY"
" (default: '/tmp/databricks_export')"
),
)
parser.add_argument(
"--catalog",
default=None,
help=(
"Optional Unity Catalog name for 3-part table qualification (leave"
" unset for catalog-agnostic 2-part schema.table SQL)"
),
)
parser.add_argument(
"--export-mode",
choices=["insert_overwrite", "select"],
default="insert_overwrite",
help=(
"SQL generation mode: 'insert_overwrite' (default, emits INSERT"
" OVERWRITE DIRECTORY ... USING PARQUET SELECT ...) or 'select'"
" (emits standalone SELECT ... statements)"
),
)
parser.add_argument(
"--output-sql",
help="File path to write the unified Databricks export SQL script",
)
parser.add_argument(
"--output-dir",
help="Directory to write individual per-table *_export.sql files",
)
return parser.parse_args(args)
def main() -> None:
"""CLI entrypoint for the Databricks Parquet export SQL generator."""
args = _parse_args()
try:
sql = generate_export_sql(
metadata_path_or_uri=args.metadata_path,
stage_path=args.stage_path,
catalog=args.catalog,
export_mode=args.export_mode,
)
except ValueError as e:
sys.exit(f"ERROR: {e}")
if args.output_sql:
out_dir = os.path.dirname(os.path.abspath(args.output_sql))
if out_dir:
os.makedirs(out_dir, exist_ok=True)
with open(args.output_sql, "w", encoding="utf-8") as f:
f.write(sql)
print(f"Generated unified Databricks export script: {args.output_sql}")
if args.output_dir:
_write_table_sql_files(sql, args.output_dir)
if not args.output_sql and not args.output_dir:
print(sql)
if __name__ == "__main__":
main()
export_oracle_tables_template.py 41.9 KB
#!/usr/bin/env python3
r"""Template Script for Generating Type-Safe Oracle Export SQL Files.
This asset template script provides a reference implementation for generating
type-safe Oracle SELECT export scripts (.sql) directly from BQMS
translation_output/metadata configs or an Oracle extractor metadata.zip
(DBA.Tables.csv / ALL.Tables.csv and DBA.TabColumns.csv / ALL.TabColumns.csv).
It has zero JDBC or database connector dependencies.
Oracle has no native SQL statement that unloads arbitrary relational tables to
Parquet on local disk or Cloud Storage (DBMS_CLOUD.EXPORT_DATA is
Autonomous Database-only). The export therefore happens in two steps:
1. This script emits one explicit-cast SELECT per table. The casts pin every
column to an Oracle SQL type whose `python-oracledb` cursor metadata and
Parquet representation BigQuery loads without drift (NUMBER(1..19,0) ->
NUMBER(19,0) -> INT64, NUMBER(p,s) -> DECIMAL128 -> NUMERIC/BIGNUMERIC,
FLOAT/BINARY_FLOAT/BINARY_DOUBLE -> BINARY_DOUBLE -> FLOAT64,
DATE -> TIMESTAMP(6) -> DATETIME, TIMESTAMP -> TIMESTAMP(6),
TIMESTAMP WITH [LOCAL] TIME ZONE -> UTC TIMESTAMP(6), CHAR/NCHAR padding
trimmed via RTRIM).
2. A downstream Python execution script runs each SELECT via the
`python-oracledb` driver, derives the Arrow schema from
`cursor.description`, and writes Snappy Parquet files under
./data_unload/[<SCHEMA>/]<TABLE>/.
Usage Pattern:
Copy `assets/export_oracle_tables_template.py` from this skill's directory
(`<SKILL_DIR>`, the directory containing `SKILL.md`) into your
working directory (e.g., `./export_oracle_tables.py`). Run the copy as-is
for standard export SQL generation, and prioritize modifying the marked
`# CUSTOMIZE:` extension points if your environment requires custom type
projections, row filters, or schema/table filtering. Sections marked
`# DEFAULT SCAFFOLDING` can be kept unchanged unless deeper orchestration
adjustments are needed.
Dependencies:
pip install pyyaml==6.0.2
Usage Examples:
# Copy the template from this skill's directory to your working directory:
cp <SKILL_DIR>/assets/export_oracle_tables_template.py \
./export_oracle_tables.py
# 1. Generate per-table Oracle export SQL files from BQMS output:
python3 ./export_oracle_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--default-schema MY_SCHEMA \
--output-dir ./export_sql
# 2. Generate a unified export SQL file straight from the extractor zip:
python3 ./export_oracle_tables.py \
--metadata-zip gs://my-bucket/dwh-migration-oracle-metadata.zip \
--schema MY_SCHEMA \
--output-sql oracle_export.sql
"""
from __future__ import annotations
import argparse
import csv
import io
import logging
import os
import re
import subprocess
import sys
import tempfile
import zipfile
import yaml
# ==============================================================================
# 1. File & Metadata Loading Functions (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Deterministic metadata loading and archive parsing.
def read_file_or_gcs(path_or_uri: str) -> bytes:
"""Reads content from a local file path or a Cloud Storage URI.
Args:
path_or_uri: Local file path or Cloud Storage URI (starts with 'gs://').
Returns:
The content of the file as bytes.
Raises:
FileNotFoundError: If the local file does not exist.
RuntimeError: If gcloud storage fails to read from Cloud Storage.
"""
if path_or_uri.startswith("gs://"):
cmd = ["gcloud", "storage", "cat", path_or_uri]
try:
return subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
raise RuntimeError(
f"Failed to read from Cloud Storage '{path_or_uri}': {e}"
) from e
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot read '{path_or_uri}': the gcloud CLI was not found. Install"
" the Google Cloud CLI, or download the file and pass a local path."
) from e
if not os.path.exists(path_or_uri):
raise FileNotFoundError(f"Local file not found: '{path_or_uri}'")
with open(path_or_uri, "rb") as f:
return f.read()
def _run_gcloud_copy(cmd: list[str], uri: str) -> None:
"""Runs a `gcloud storage cp` command, surfacing its stderr on failure."""
try:
subprocess.run(cmd, capture_output=True, check=True)
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot copy '{uri}': the gcloud CLI was not found. Install the"
" Google Cloud CLI, or copy the files locally and pass a local path."
) from e
except subprocess.CalledProcessError as e:
stderr = (e.stderr or b"").decode("utf-8", errors="replace").strip()
raise RuntimeError(
f"Failed to copy from Cloud Storage '{uri}' (exit code"
f" {e.returncode}): {stderr or e}"
) from e
def _strip(value: str | None) -> str:
"""Trims whitespace around Oracle data dictionary CSV fields."""
return (value or "").strip()
def load_metadata_from_zip(
zip_bytes: bytes,
) -> dict[str, list[dict[str, str]]]:
"""Extracts table and column metadata from an Oracle extractor metadata.zip.
Reads DBA.Tables.csv / ALL.Tables.csv and DBA.TabColumns.csv /
ALL.TabColumns.csv (falls back to the generic tables.csv / columns.csv layout)
and normalizes rows to the shared TableCatalog/TableSchema/TableName/
ColumnName/DataType record shape. Note that DBA.TabColumns.csv in Oracle
extractor archives contains columns for both base tables and views; pairing
with DBA.Tables.csv ensures only physical base tables are exported.
Args:
zip_bytes: Raw bytes of the metadata zip archive.
Returns:
A dictionary containing 'tables' and 'columns' lists of records.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as z:
names = z.namelist()
by_base = {os.path.basename(n).lower(): n for n in names}
def _rows(candidates: list[str]) -> tuple[str | None, list[dict[str, str]]]:
for c in candidates:
member = by_base.get(c.lower())
if member:
with z.open(member) as fh:
return c, list(
csv.DictReader(io.TextIOWrapper(fh, encoding="utf-8-sig"))
)
return None, []
tables_fn, table_rows = _rows(
["DBA.Tables.csv", "ALL.Tables.csv", "tables.csv"]
)
columns_fn, column_rows = _rows(
["DBA.TabColumns.csv", "ALL.TabColumns.csv", "columns.csv"]
)
if tables_fn in ("DBA.Tables.csv", "ALL.Tables.csv"):
for r in table_rows:
tbl_name = _strip(r.get("TABLE_NAME") or r.get("TableName"))
dropped = _strip(r.get("DROPPED")).upper() == "YES"
secondary = _strip(r.get("SECONDARY")).upper() == "Y"
nested = _strip(r.get("NESTED")).upper() == "YES"
is_recyclebin = tbl_name.startswith("BIN$")
is_base = not (dropped or secondary or nested or is_recyclebin)
result["tables"].append({
"TableCatalog": "",
"TableSchema": _strip(r.get("OWNER") or r.get("TableSchema")),
"TableName": tbl_name,
"TableType": "BASE TABLE" if is_base else "SECONDARY",
})
else:
result["tables"] = [
{k: _strip(v) for k, v in r.items() if k is not None}
for r in table_rows
]
if columns_fn in ("DBA.TabColumns.csv", "ALL.TabColumns.csv"):
for r in column_rows:
nullable = _strip(r.get("NULLABLE") or r.get("Nullable")).upper() or "Y"
result["columns"].append({
"TableCatalog": "",
"TableSchema": _strip(r.get("OWNER") or r.get("TableSchema")),
"TableName": _strip(r.get("TABLE_NAME") or r.get("TableName")),
"ColumnName": _strip(r.get("COLUMN_NAME") or r.get("ColumnName")),
"OrdinalPosition": _strip(
r.get("COLUMN_ID") or r.get("OrdinalPosition")
),
"DataType": _strip(r.get("DATA_TYPE") or r.get("DataType")).upper(),
"ColumnLength": _strip(
r.get("CHAR_LENGTH")
or r.get("DATA_LENGTH")
or r.get("ColumnLength")
),
"NumericPrecision": _strip(
r.get("DATA_PRECISION") or r.get("NumericPrecision")
),
"NumericScale": _strip(r.get("DATA_SCALE") or r.get("NumericScale")),
"Nullable": nullable,
"ExplicitNotNull": "Y" if nullable == "N" else "N",
})
else:
for r in column_rows:
col_dict = {k: _strip(v) for k, v in r.items() if k is not None}
if "ExplicitNotNull" not in col_dict:
nullable = (
_strip(col_dict.get("Nullable") or col_dict.get("NULLABLE")).upper()
or "Y"
)
col_dict["ExplicitNotNull"] = "Y" if nullable == "N" else "N"
result["columns"].append(col_dict)
return result
def load_metadata_from_config_dir(
config_dir: str,
) -> dict[str, list[dict[str, str]]]:
"""Loads table/column metadata from BQMS metadata/config/*.yaml files.
Args:
config_dir: Local path to the BQMS metadata config directory.
Returns:
A dictionary containing 'tables' and 'columns' metadata parsed from YAMLs.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
if not os.path.isdir(config_dir):
return result
# (schema, table) -> database of the config already loaded for it.
loaded_from: dict[tuple[str, str], str] = {}
for root, dirs, files in os.walk(config_dir):
dirs.sort() # Deterministic order, so the first database wins.
for f in sorted(files):
if not (f.endswith(".yaml") or f.endswith(".yml")):
continue
try:
with open(os.path.join(root, f), "r", encoding="utf-8") as yf:
cfg = yaml.safe_load(yf)
except (yaml.YAMLError, OSError):
continue
if not isinstance(cfg, dict):
continue
src_name = cfg.get("sourceName", "")
parts = src_name.split(".") if src_name else []
# Oracle names in BQMS are __DEFAULT_DATABASE__.SCHEMA.TABLE or
# SCHEMA.TABLE.
schema = parts[-2] if len(parts) >= 2 else ""
table = parts[-1] if parts else f.rsplit(".", 1)[0]
database = parts[0] if len(parts) >= 3 else ""
# Views are recreated, not exported; skip them before they claim the
# SCHEMA.TABLE slot of a table in another database.
if not (cfg.get("externalTableName") or cfg.get("externalTableDdlPath")):
continue
# One Oracle connection can't read the same SCHEMA.TABLE from two
# databases, and merging both configs would mix their columns.
prior = loaded_from.setdefault((schema, table), database)
if prior != database:
print(
f"WARNING: Skipping {src_name}: {schema}.{table} was already"
f" loaded from database '{prior}'.",
file=sys.stderr,
)
continue
result["tables"].append({
"TableCatalog": "",
"TableSchema": schema,
"TableName": table,
"TableType": "BASE TABLE",
})
for idx, col in enumerate(cfg.get("columns") or [], start=1):
if not isinstance(col, dict):
continue
src_type = col.get("sourceType") or {}
src = (
src_type
if isinstance(src_type, dict)
else {"genericName": src_type}
)
raw_code = str(src.get("name") or "").strip().upper()
generic_name = str(src.get("genericName") or "").strip().upper()
# Prefer raw Oracle type name ('DATE', 'NUMBER', 'TIMESTAMP(6)', etc.)
# because BQMS sets genericName='DATETIME' for Oracle DATE.
data_type = raw_code or generic_name
tgt_type = col.get("targetType") or {}
tgt = tgt_type if isinstance(tgt_type, dict) else {"name": tgt_type}
tgt_name = str(tgt.get("name") or "").strip().upper()
col_entry = {
"TableCatalog": "",
"TableSchema": schema,
"TableName": table,
"ColumnName": col.get("sourceName", ""),
"OrdinalPosition": str(idx),
"DataType": data_type,
"NumericPrecision": str(src.get("precision", "")),
"NumericScale": str(src.get("scale", "")),
"Nullable": "N" if col.get("notNull") else "Y",
"ExplicitNotNull": "Y" if col.get("notNull") else "N",
}
# Persist every BQMS target type so format_column_cast() honors
# INT64 / NUMERIC / BIGNUMERIC / FLOAT64 / DATE / DATETIME overrides.
if tgt_name:
col_entry["TargetType"] = tgt_name
result["columns"].append(col_entry)
return result
def _find_config_dir(dir_path: str) -> str | None:
"""Locates the directory containing BQMS table YAML configurations."""
for candidate in (
os.path.join(dir_path, "metadata", "config"),
os.path.join(dir_path, "config"),
):
if os.path.isdir(candidate):
return candidate
for _, _, files in os.walk(dir_path):
if any(f.endswith((".yaml", ".yml")) for f in files):
return dir_path
return None
def load_metadata_from_dir(dir_path: str) -> dict[str, list[dict[str, str]]]:
"""Discovers metadata in a directory (BQMS YAML configs or embedded zip)."""
config_dir = _find_config_dir(dir_path)
if config_dir:
res = load_metadata_from_config_dir(config_dir)
if res["tables"] and res["columns"]:
return res
for root, _, files in os.walk(dir_path):
for f in files:
if f.endswith(".zip") and "metadata" in f:
with open(os.path.join(root, f), "rb") as zf:
return load_metadata_from_zip(zf.read())
return {"tables": [], "columns": []}
def _resolve_and_load_metadata(
path_or_uri: str | None,
) -> dict[str, list[dict[str, str]]]:
"""Resolves local or Cloud Storage metadata path/zip and loads metadata."""
if not path_or_uri:
return {"tables": [], "columns": []}
if path_or_uri.startswith("gs://"):
if path_or_uri.endswith(".zip"):
return load_metadata_from_zip(read_file_or_gcs(path_or_uri))
with tempfile.TemporaryDirectory(prefix="bqms_meta_") as temp_dir:
cmd = [
"gcloud",
"storage",
"cp",
"-r",
path_or_uri.rstrip("/") + "/*",
temp_dir,
]
_run_gcloud_copy(cmd, path_or_uri)
return load_metadata_from_dir(temp_dir)
if os.path.isdir(path_or_uri):
return load_metadata_from_dir(path_or_uri)
return load_metadata_from_zip(read_file_or_gcs(path_or_uri))
def _ordinal(col: dict[str, str]) -> int:
pos = str(col.get("OrdinalPosition", ""))
return int(pos) if pos.isdigit() else 999999
def _group_and_sort_columns(
columns: list[dict[str, str]],
) -> tuple[
dict[tuple[str, str], list[dict[str, str]]],
dict[str, list[dict[str, str]]],
]:
"""Groups columns by (schema, table) and table name, sorted by ordinal."""
by_schema_table: dict[tuple[str, str], list[dict[str, str]]] = {}
by_table: dict[str, list[dict[str, str]]] = {}
for col in columns:
key = (
_strip(col.get("TableSchema")),
_strip(col.get("TableName")),
)
by_schema_table.setdefault(key, []).append(col)
for (_, tbl), cols in by_schema_table.items():
cols.sort(key=_ordinal)
by_table.setdefault(tbl, cols)
return by_schema_table, by_table
def _lookup_table_columns(
by_schema_table: dict[tuple[str, str], list[dict[str, str]]],
raw_schema: str,
schema: str,
tbl: str,
) -> list[dict[str, str]]:
"""Finds a table's columns without borrowing them from another schema.
Tries the metadata schema, then the --default-schema fallback, then columns
recorded without a schema. A table without any schema only matches a
same-named table when exactly one candidate exists; otherwise it gets no
column projections and falls back to SELECT *.
Args:
by_schema_table: Column metadata keyed by (schema, table name).
raw_schema: The schema recorded in the metadata for this table.
schema: The effective schema after applying --default-schema.
tbl: The table name.
Returns:
The table's column metadata, or an empty list when no unambiguous match
exists.
"""
for key in ((raw_schema, tbl), (schema, tbl), ("", tbl)):
cols = by_schema_table.get(key)
if cols:
return cols
if not schema:
matches = [c for (_, t), c in by_schema_table.items() if t == tbl and c]
if len(matches) == 1:
return matches[0]
return []
# CUSTOMIZE: Table & Row Filtering — Edit _filter_tables_to_export() to add
# custom schema/table inclusion or exclusion rules.
def _filter_tables_to_export(
raw_tables: list[dict[str, str]],
columns_by_table: dict[str, list[dict[str, str]]],
schemas: set[str] | None = None,
columns_by_schema_table: (
dict[tuple[str, str], list[dict[str, str]]] | None
) = None,
default_schema: str = "",
) -> list[dict[str, str]]:
"""Filters tables to export: drops views/system objects, applies filters.
The schema allow-list and duplicate check use the effective schema
(TableSchema, else default_schema), so schema-less entries match
--schema and don't duplicate qualified entries for the same table.
Args:
raw_tables: Table rows from the metadata (may be empty).
columns_by_table: Column metadata keyed by table name.
schemas: Optional upper-cased schema allow-list.
columns_by_schema_table: Column metadata keyed by (schema, table name), used
when raw_tables is empty.
default_schema: Fallback schema for entries without a TableSchema.
Returns:
The table entries to export, without duplicates.
"""
out: list[dict[str, str]] = []
seen: set[tuple[str, str]] = set()
default_schema = _strip(default_schema)
if raw_tables:
for t in raw_tables:
tbl = _strip(t.get("TableName"))
schema = _strip(t.get("TableSchema")) or default_schema
tbl_type = _strip(t.get("TableType")).upper()
if tbl_type and tbl_type not in ("BASE TABLE", "TABLE"):
continue
if schemas and schema.upper() not in schemas:
continue
if (schema, tbl) in seen:
continue
seen.add((schema, tbl))
out.append(t)
out.sort(
key=lambda t: (
_strip(t.get("TableSchema")) or default_schema,
_strip(t.get("TableName")),
)
)
elif columns_by_schema_table:
for raw_schema, tbl in sorted(columns_by_schema_table):
schema = raw_schema or default_schema
if schemas and schema.upper() not in schemas:
continue
if (schema, tbl) not in seen:
seen.add((schema, tbl))
out.append({"TableSchema": raw_schema, "TableName": tbl})
else:
for tbl in sorted(columns_by_table):
cols = columns_by_table[tbl]
raw_schema = _strip(cols[0].get("TableSchema")) if cols else ""
schema = raw_schema or default_schema
if schemas and schema.upper() not in schemas:
continue
if (schema, tbl) not in seen:
seen.add((schema, tbl))
entry = {"TableName": tbl}
if raw_schema:
entry["TableSchema"] = raw_schema
out.append(entry)
return out
# ==============================================================================
# 2. Type-Safe SQL Generation Logic
# ==============================================================================
_VALID_IDENT_REGEX = re.compile(r"^[A-Z][A-Z0-9_$#]*$")
# A subset of Oracle reserved words that commonly appear as column or table
# names in migrated schemas. Anything matching is double-quoted.
_ORACLE_RESERVED = frozenset((
"ACCESS",
"ADD",
"ALL",
"ALTER",
"AND",
"ANY",
"AS",
"ASC",
"AUDIT",
"BETWEEN",
"BY",
"CHAR",
"CHECK",
"CLUSTER",
"COLUMN",
"COMMENT",
"COMPRESS",
"CONNECT",
"CREATE",
"CURRENT",
"DATE",
"DECIMAL",
"DEFAULT",
"DELETE",
"DESC",
"DISTINCT",
"DROP",
"ELSE",
"EXCLUSIVE",
"EXISTS",
"FILE",
"FLOAT",
"FOR",
"FROM",
"GRANT",
"GROUP",
"HAVING",
"IDENTIFIED",
"IMMEDIATE",
"IN",
"INCREMENT",
"INDEX",
"INITIAL",
"INSERT",
"INTEGER",
"INTERSECT",
"INTO",
"IS",
"LEVEL",
"LIKE",
"LOCK",
"LONG",
"MAXEXTENTS",
"MINUS",
"MLSLABEL",
"MODE",
"MODIFY",
"NOAUDIT",
"NOCOMPRESS",
"NOT",
"NOWAIT",
"NULL",
"NUMBER",
"OF",
"OFFLINE",
"ON",
"ONLINE",
"OPTION",
"OR",
"ORDER",
"PCTFREE",
"PRIOR",
"PUBLIC",
"RAW",
"RENAME",
"RESOURCE",
"REVOKE",
"ROW",
"ROWID",
"ROWNUM",
"ROWS",
"SELECT",
"SESSION",
"SET",
"SHARE",
"SIZE",
"SMALLINT",
"START",
"SUCCESSFUL",
"SYNONYM",
"SYSDATE",
"TABLE",
"THEN",
"TO",
"TRIGGER",
"UID",
"UNION",
"UNIQUE",
"UPDATE",
"USER",
"VALIDATE",
"VALUES",
"VARCHAR",
"VARCHAR2",
"VIEW",
"WHENEVER",
"WHERE",
"WITH",
))
# Oracle INTEGER / INT are ANSI aliases for NUMBER(38) (scale 0), so they keep
# 38 integer digits instead of narrowing to NUMBER(19, 0).
_ANSI_INTEGER_TYPES = frozenset(("INTEGER", "INT"))
_INT_TYPES = frozenset((
"SMALLINT",
"BIGINT",
"TINYINT",
"BYTEINT",
"INT64",
"PLS_INTEGER",
"BINARY_INTEGER",
))
_NUMBER_TYPES = frozenset(("NUMBER", "DECIMAL", "NUMERIC", "DEC", "BIGNUMERIC"))
_FLOAT_TYPES = frozenset((
"FLOAT",
"REAL",
"DOUBLE PRECISION",
"DOUBLE",
"BINARY_FLOAT",
"BINARY_DOUBLE",
"FLOAT64",
))
_DATE_TYPES = frozenset(("DATE",))
_TIMESTAMP_TYPES = frozenset((
"TIMESTAMP",
"DATETIME",
))
_TIMESTAMP_LTZ_TYPES = frozenset((
"TIMESTAMP WITH LOCAL TIME ZONE",
"TIMESTAMPLTZ",
))
_TIMESTAMP_TZ_TYPES = frozenset((
"TIMESTAMP WITH TIME ZONE",
"TIMESTAMPTZ",
))
_CHAR_TYPES = frozenset(("CHAR", "NCHAR", "CHARACTER"))
_VARCHAR_TYPES = frozenset((
"VARCHAR2",
"NVARCHAR2",
"VARCHAR",
"NVARCHAR",
"STRING",
"CLOB",
"NCLOB",
"LONG",
))
_BYTE_TYPES = frozenset((
"RAW",
"LONG RAW",
"BLOB",
"BFILE",
"BINARY",
"VARBINARY",
"BYTES",
))
_ROWID_TYPES = frozenset(("ROWID", "UROWID"))
_XML_TYPES = frozenset(("XMLTYPE", "SYS.XMLTYPE", "XML"))
_JSON_TYPES = frozenset(("JSON",))
# DEFAULT SCAFFOLDING: Identifier quoting helper.
def quote_ident(ident: str) -> str:
"""Double-quotes an Oracle identifier when it is not a plain name.
Args:
ident: The raw SQL identifier string.
Returns:
The properly quoted or unquoted identifier.
"""
if not ident:
return ""
if len(ident) >= 2 and ident.startswith('"') and ident.endswith('"'):
# Already quoted: re-escape any bare inner double quotes.
inner = ident[1:-1].replace('""', '"').replace('"', '""')
return f'"{inner}"'
if not _VALID_IDENT_REGEX.match(ident) or ident.upper() in _ORACLE_RESERVED:
escaped = ident.replace('"', '""')
return f'"{escaped}"'
return ident
_PARAM_TYPE_REGEX = re.compile(
r"^(?P<base>[A-Z0-9_ ]+?)\s*\(\s*(?P<p>-?\d+|\*)"
r"(?:\s*,\s*(?P<s>-?\d+))?(?:\s+(?:BYTE|CHAR))?\s*\)\s*(?P<rest>.*)$"
)
_INTERVAL_YM_REGEX = re.compile(
r"^INTERVAL\s+YEAR(?:\s*\(\d+\))?\s+TO\s+MONTH$"
)
_INTERVAL_DS_REGEX = re.compile(
r"^INTERVAL\s+DAY(?:\s*\(\d+\))?\s+TO\s+SECOND(?:\s*\(\d+\))?$"
)
def _to_int(value: str | None) -> int | None:
value = str(value or "").strip()
return int(value) if value.lstrip("-").isdigit() else None
def _normalize_data_type(
raw_type: str, precision: int | None, scale: int | None
) -> tuple[str, int | None, int | None]:
"""Normalizes an Oracle DATA_TYPE string into (base_type, p, s)."""
dt = " ".join(raw_type.upper().split())
if (
_INTERVAL_YM_REGEX.match(dt)
or _INTERVAL_DS_REGEX.match(dt)
or dt.startswith("INTERVAL ")
):
return "INTERVAL", precision, scale
m = _PARAM_TYPE_REGEX.match(dt)
if m:
base = f"{m.group('base').strip()} {m.group('rest').strip()}".strip()
if precision is None and m.group("p") != "*":
precision = _to_int(m.group("p"))
if scale is None and m.group("s") is not None:
scale = _to_int(m.group("s"))
# In Oracle, NUMBER(p) with a single argument means NUMBER(p, 0).
if base in _NUMBER_TYPES and m.group("p") != "*" and scale is None:
scale = 0
return base, precision, scale
return dt, precision, scale
def _ltz_to_utc(col_name: str) -> str:
"""Projects TIMESTAMP WITH LOCAL TIME ZONE as UTC TIMESTAMP(6).
LOCAL TIME ZONE values render in the session time zone, so the explicit
TIMESTAMP WITH TIME ZONE cast plus SYS_EXTRACT_UTC keeps the export
independent of the session's TIME_ZONE setting.
Args:
col_name: The quoted column name.
Returns:
The SQL projection expression.
"""
return (
f"CAST(SYS_EXTRACT_UTC(CAST({col_name} AS TIMESTAMP WITH TIME ZONE))"
f" AS TIMESTAMP(6)) AS {col_name}"
)
# CUSTOMIZE: Custom Type Projections -- Edit format_column_cast() to change
# how an Oracle type is projected before Parquet serialization (e.g. keep CHAR
# padding, project DATE as TRUNC(col) for a BigQuery DATE, or widen NUMBER
# precision).
def format_column_cast(
col: dict[str, str],
target_bq_type: str | None = None,
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Generates a type-safe Oracle projection expression for Parquet export.
The executor derives the Parquet schema from `cursor.description`, so the
SQL projection here determines both the PyArrow type and the BigQuery column
type created by `bq load --source_format=PARQUET`:
NUMBER(1..19, 0) / SMALLINT -> CAST AS NUMBER(19, 0) -> INT64
NUMBER(20..38, 0) / INTEGER / INT -> CAST AS NUMBER(p, 0) -> BIGNUMERIC
NUMBER(p, s > 0) -> CAST AS NUMBER(p, s) -> NUMERIC
NUMBER(p, s < 0) -> CAST AS NUMBER(p+|s|,0) -> NUMERIC
NUMBER (unconstrained) -> CAST AS NUMBER(38, 9) -> BIGNUMERIC
FLOAT / REAL / BINARY_FLOAT/DOUBLE -> CAST AS BINARY_DOUBLE -> FLOAT64
DATE -> CAST AS TIMESTAMP(6) -> DATETIME
TIMESTAMP(n) -> CAST AS TIMESTAMP(6) -> TIMESTAMP
TIMESTAMP(n) WITH [LOCAL] TIME ZONE -> SYS_EXTRACT_UTC TS(6) -> TIMESTAMP
CHAR(n) / NCHAR(n) -> RTRIM(col) -> STRING
VARCHAR2 / NVARCHAR2 / CLOB / NCLOB -> col -> STRING
RAW / BLOB / BFILE -> col -> BYTES
ROWID / UROWID -> ROWIDTOCHAR / VARCHAR2 -> STRING
INTERVAL YEAR/DAY -> TRIM(CAST AS VARCHAR2) -> STRING
XMLTYPE -> XMLSERIALIZE AS CLOB -> STRING
JSON -> JSON_SERIALIZE AS CLOB -> STRING
Args:
col: Column metadata dict containing ColumnName, DataType, etc.
target_bq_type: Optional BigQuery target type override.
rtrim_char: Strip CHAR(n)/NCHAR(n) trailing pad spaces (BigQuery STRING has
no fixed-width semantics, so padded values would mismatch in validation).
unbounded_number_scale: Fractional scale for unconstrained NUMBER /
NUMBER(*) columns (default 9, supporting up to 29 integer digits).
Returns:
A SQL projection expression, e.g. 'CAST(SS_ITEM_SK AS NUMBER(19, 0)) AS
SS_ITEM_SK'.
"""
col_name = quote_ident(_strip(col.get("ColumnName")))
data_type, precision, scale = _normalize_data_type(
str(col.get("DataType") or ""),
_to_int(col.get("NumericPrecision")),
_to_int(col.get("NumericScale")),
)
if scale is None and (
data_type in _ANSI_INTEGER_TYPES or data_type in _INT_TYPES
):
scale = 0 # INTEGER / INT are NUMBER(38) aliases.
explicit_target = (
(target_bq_type or col.get("TargetType") or "").upper().strip()
)
explicit_base = (
re.split(r"[(<]", explicit_target, maxsplit=1)[0].strip()
if explicit_target
else ""
)
if 0 <= unbounded_number_scale <= 38:
default_unb_scale = unbounded_number_scale
else:
logging.warning(
"Out-of-range unbounded_number_scale=%d (expected 0..38); falling back"
" to 9.",
unbounded_number_scale,
)
default_unb_scale = 9
# Honor explicit target_bq_type overrides first. Other cross-type targets
# (STRING, JSON, BYTES, BOOL, TIME, and DATE on columns other than DATE /
# TIMESTAMP) keep the default projection below.
if explicit_base:
if explicit_base in (
"INT64",
"INTEGER",
"BIGINT",
"SMALLINT",
"TINYINT",
"BYTEINT",
):
return f"CAST({col_name} AS NUMBER(19, 0)) AS {col_name}"
if explicit_base in ("FLOAT64", "FLOAT", "DOUBLE"):
return f"CAST({col_name} AS BINARY_DOUBLE) AS {col_name}"
if explicit_base == "DATE" and (
data_type in _DATE_TYPES or data_type in _TIMESTAMP_TYPES
):
return f"TRUNC({col_name}) AS {col_name}"
if explicit_base in ("DATETIME", "TIMESTAMP"):
if data_type in _TIMESTAMP_TZ_TYPES:
return (
f"CAST(SYS_EXTRACT_UTC({col_name}) AS TIMESTAMP(6)) AS {col_name}"
)
if data_type in _TIMESTAMP_LTZ_TYPES:
return _ltz_to_utc(col_name)
return f"CAST({col_name} AS TIMESTAMP(6)) AS {col_name}"
if explicit_base in ("NUMERIC", "DECIMAL"):
if scale is not None and scale > 0:
s_val = min(scale, 38)
p_val = min(max(precision or 29, s_val, 1), 38)
return f"CAST({col_name} AS NUMBER({p_val}, {s_val})) AS {col_name}"
if scale is not None and scale <= 0:
p_val = min(max((precision or 29) + abs(scale), 29), 38)
return f"CAST({col_name} AS NUMBER({p_val}, 0)) AS {col_name}"
return (
f"CAST({col_name} AS NUMBER(38, {default_unb_scale})) AS {col_name}"
)
if explicit_base == "BIGNUMERIC":
if scale is not None and scale > 0:
s_val = min(scale, 38)
p_val = min(max(precision or 38, s_val, 1), 38)
return f"CAST({col_name} AS NUMBER({p_val}, {s_val})) AS {col_name}"
if scale is not None and scale <= 0:
return f"CAST({col_name} AS NUMBER(38, 0)) AS {col_name}"
return (
f"CAST({col_name} AS NUMBER(38, {default_unb_scale})) AS {col_name}"
)
if data_type in _ANSI_INTEGER_TYPES:
return f"CAST({col_name} AS NUMBER(38, 0)) AS {col_name}"
if data_type in _INT_TYPES:
return f"CAST({col_name} AS NUMBER(19, 0)) AS {col_name}"
if data_type in _NUMBER_TYPES:
# Unconstrained NUMBER has precision=None, scale=None in DBA.TabColumns.csv
# and precision=38, scale=None in BQMS metadata/config/*.yaml.
if scale is None:
return (
f"CAST({col_name} AS NUMBER(38, {default_unb_scale})) AS {col_name}"
)
if scale < 0:
eff_p = min((precision or 38) + abs(scale), 38)
if eff_p <= 19:
return f"CAST({col_name} AS NUMBER(19, 0)) AS {col_name}"
return f"CAST({col_name} AS NUMBER({eff_p}, 0)) AS {col_name}"
if scale == 0:
if precision is not None and 1 <= precision <= 19:
return f"CAST({col_name} AS NUMBER(19, 0)) AS {col_name}"
p_val = min(max(precision or 38, 20), 38)
return f"CAST({col_name} AS NUMBER({p_val}, 0)) AS {col_name}"
# scale > 0
s_val = min(scale, 38)
p_val = min(max(precision or 38, s_val, 1), 38)
return f"CAST({col_name} AS NUMBER({p_val}, {s_val})) AS {col_name}"
if data_type in _FLOAT_TYPES:
return f"CAST({col_name} AS BINARY_DOUBLE) AS {col_name}"
if data_type in _DATE_TYPES:
return f"CAST({col_name} AS TIMESTAMP(6)) AS {col_name}"
if data_type in _TIMESTAMP_TYPES:
return f"CAST({col_name} AS TIMESTAMP(6)) AS {col_name}"
if data_type in _TIMESTAMP_TZ_TYPES:
return f"CAST(SYS_EXTRACT_UTC({col_name}) AS TIMESTAMP(6)) AS {col_name}"
if data_type in _TIMESTAMP_LTZ_TYPES:
return _ltz_to_utc(col_name)
if data_type in _CHAR_TYPES:
if rtrim_char:
return f"RTRIM({col_name}) AS {col_name}"
return f"{col_name} AS {col_name}"
if data_type in _VARCHAR_TYPES or data_type in _BYTE_TYPES:
return f"{col_name} AS {col_name}"
if data_type == "ROWID":
return f"ROWIDTOCHAR({col_name}) AS {col_name}"
if data_type in _ROWID_TYPES:
return f"CAST({col_name} AS VARCHAR2(256)) AS {col_name}"
if data_type == "INTERVAL":
return f"TRIM(CAST({col_name} AS VARCHAR2(100))) AS {col_name}"
if data_type in _XML_TYPES:
return f"XMLSERIALIZE(CONTENT {col_name} AS CLOB) AS {col_name}"
if data_type in _JSON_TYPES:
return f"JSON_SERIALIZE({col_name} RETURNING CLOB) AS {col_name}"
# SDO_GEOMETRY, ANYDATA, user-defined object types, etc.
return f"CAST({col_name} AS VARCHAR2(4000)) AS {col_name}"
# DEFAULT SCAFFOLDING: Table name qualification helper.
def _build_qualified_table_name(
table_meta: dict[str, str], default_schema: str = ""
) -> str:
"""Builds a quoted SCHEMA.TABLE name."""
tbl = _strip(table_meta.get("TableName"))
schema = _strip(table_meta.get("TableSchema")) or _strip(default_schema)
return (
f"{quote_ident(schema)}.{quote_ident(tbl)}"
if schema
else quote_ident(tbl)
)
# CUSTOMIZE: Row Filters -- Edit _build_select_query() to add WHERE
# predicates (e.g. incremental extraction windows or partition filters).
def _build_select_query(
table_meta: dict[str, str],
columns: list[dict[str, str]],
default_schema: str = "",
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Builds the explicit-cast SELECT statement for a single Oracle table.
Args:
table_meta: Table metadata dictionary with TableSchema and TableName.
columns: Ordered list of column metadata dictionaries for the table.
default_schema: Fallback schema/owner name when TableSchema is empty.
rtrim_char: Whether to RTRIM fixed-width CHAR(n)/NCHAR(n) columns.
unbounded_number_scale: Fractional scale for unconstrained NUMBER columns.
Returns:
A complete Oracle SELECT statement ending with a semicolon.
"""
qualified = _build_qualified_table_name(table_meta, default_schema)
if columns:
body = ",\n".join(
" "
+ format_column_cast(
c,
rtrim_char=rtrim_char,
unbounded_number_scale=unbounded_number_scale,
)
for c in columns
)
else:
body = " *"
return f"SELECT\n{body}\nFROM {qualified};"
def _is_not_null(col: dict[str, str]) -> bool:
"""Returns True when a column is marked non-nullable in YAML or zip CSV."""
if "ExplicitNotNull" in col:
return str(col.get("ExplicitNotNull", "N")).strip().upper() == "Y"
return str(col.get("Nullable", "Y")).strip().upper() == "N"
def _sanitize_comment_token(val: str) -> str:
"""Replaces control chars (CR, LF, NUL) so SQL comments stay single-line."""
return re.sub(r"[\r\n\x00]+", " ", str(val)).strip()
# DEFAULT SCAFFOLDING: Primary SQL script generator and orchestration.
def generate_export_sql(
metadata_path_or_uri: str | None = None,
default_schema: str | None = None,
schemas: list[str] | None = None,
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Generates the unified Oracle export SQL script.
Each table section is introduced by a divider and a
`-- Unload Table: <SCHEMA>.<TABLE> -> Parquet` marker that the executor uses
to name the ./data_unload/[<SCHEMA>/]<TABLE>/ output directory.
Args:
metadata_path_or_uri: Path or Cloud Storage URI to translation metadata dir
or zip.
default_schema: Fallback schema/owner when metadata omits it.
schemas: Optional schema allow-list (case-insensitive).
rtrim_char: Strip CHAR(n)/NCHAR(n) trailing pad spaces.
unbounded_number_scale: Fractional scale for unconstrained NUMBER columns.
Returns:
A complete Oracle SQL script string.
"""
metadata = _resolve_and_load_metadata(metadata_path_or_uri)
by_schema_table, by_table = _group_and_sort_columns(
metadata.get("columns", [])
)
schema_filter = {s.upper() for s in schemas} if schemas else None
tables = _filter_tables_to_export(
metadata.get("tables", []),
by_table,
schema_filter,
columns_by_schema_table=by_schema_table,
default_schema=default_schema or "",
)
if not tables and schema_filter:
available = sorted({
_strip(t.get("TableSchema")) or _strip(default_schema)
for t in metadata.get("tables", []) or metadata.get("columns", [])
})
print(
"WARNING: No tables match the --schema filter. Available schemas:"
f" {', '.join(s for s in available if s) or '(none)'}.",
file=sys.stderr,
)
generator_name = (
os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] else ""
) or "export_oracle_tables_template.py"
lines = [
"-- " + "=" * 77,
"-- Oracle to Parquet Type-Safe Data Export Script",
f"-- Generated by bigquery-migration-data-exporter / {generator_name}",
"-- Execute via python-oracledb and stream results to Snappy Parquet",
"-- " + "=" * 77,
"",
]
divider = "-- " + "-" * 77
for t in tables:
tbl = _strip(t.get("TableName"))
raw_schema = _strip(t.get("TableSchema"))
schema = raw_schema or _strip(default_schema)
cols = _lookup_table_columns(by_schema_table, raw_schema, schema, tbl)
stmt = _build_select_query(
t,
cols,
default_schema or "",
rtrim_char=rtrim_char,
unbounded_number_scale=unbounded_number_scale,
)
label = _sanitize_comment_token(f"{schema}.{tbl}" if schema else tbl)
lines.append(f"{divider}\n-- Unload Table: {label} -> Parquet\n{divider}")
required = [
_sanitize_comment_token(_strip(c.get("ColumnName")))
for c in cols
if _is_not_null(c) and _strip(c.get("ColumnName"))
]
if required:
lines.append(f"-- Required Columns: {','.join(required)}")
lines.append(stmt + "\n")
return "\n".join(lines)
# ==============================================================================
# 3. CLI Main Router (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: CLI argument parser and SQL file writer entrypoint.
def _parse_args(args: list[str] | None = None) -> argparse.Namespace:
"""Builds and parses CLI arguments for Oracle export SQL generation."""
parser = argparse.ArgumentParser(
description="Oracle Parquet Export SQL Generator (outputs .sql)."
)
parser.add_argument(
"--translation-metadata-dir",
"--translation-output",
"--metadata-dir",
"--config-dir",
"--metadata-zip",
dest="metadata_path",
required=True,
help=(
"Path or Cloud Storage URI to translation_output/metadata directory,"
" config directory, or Oracle extractor metadata.zip"
),
)
parser.add_argument(
"--output-sql", help="File path to write the unified export SQL script"
)
parser.add_argument(
"--output-dir",
help="Directory to write individual per-table *_export.sql files",
)
parser.add_argument(
"--default-schema",
"--default-database",
dest="default_schema",
default=os.environ.get("ORACLE_SCHEMA", ""),
help="Fallback source schema/owner name when omitted in metadata",
)
parser.add_argument(
"--schema",
"--database",
action="append",
dest="schemas",
help=(
"Only export tables in this schema/owner (repeatable); --database"
" is an alias for the owner, not the Oracle service or PDB"
),
)
parser.add_argument(
"--keep-char-padding",
action="store_true",
help="Do not RTRIM CHAR(n)/NCHAR(n) columns",
)
parser.add_argument(
"--unbounded-number-scale",
type=int,
default=9,
help=(
"Decimal scale (0..38) for unconstrained NUMBER / NUMBER(*) columns"
" (default: 9, supporting up to 29 integer digits)"
),
)
parsed = parser.parse_args(args)
if not 0 <= parsed.unbounded_number_scale <= 38:
parser.error("--unbounded-number-scale must be between 0 and 38.")
return parsed
def _sanitize_sql_filename(label: str, used_filenames: set[str]) -> str:
"""Builds a safe, collision-free per-table SQL filename."""
unquoted = label.replace('"', "").strip()
safe_parts = [
re.sub(r"[^A-Za-z0-9_-]+", "_", p.strip()).strip("_") or "table"
for p in unquoted.split(".")
if p.strip()
]
stem = "_".join(safe_parts) if safe_parts else "table"
filename = f"{stem}_export.sql"
if filename.upper() in used_filenames and len(safe_parts) > 1:
filename = f"{'__'.join(safe_parts)}_export.sql"
idx = 2
base_stem = filename[: -len("_export.sql")]
while filename.upper() in used_filenames:
filename = f"{base_stem}_{idx}_export.sql"
idx += 1
used_filenames.add(filename.upper())
return filename
def _write_table_sql_files(sql: str, output_dir: str) -> list[str]:
"""Splits the unified SQL script and writes individual table SQL files."""
os.makedirs(output_dir, exist_ok=True)
divider = "-- " + "-" * 77
chunks = sql.split(f"{divider}\n-- Unload Table: ")
written: list[str] = []
used_filenames: set[str] = set()
for chunk in chunks[1:]:
label = chunk.split(" -> Parquet")[0].strip()
filename = _sanitize_sql_filename(label, used_filenames)
path = os.path.join(output_dir, filename)
with open(path, "w", encoding="utf-8") as f:
f.write(f"{divider}\n-- Unload Table: {chunk}")
written.append(path)
print(f"Generated table export SQL: {path}")
return written
def main() -> None:
"""CLI entrypoint for the Oracle Parquet export SQL generator."""
args = _parse_args()
sql = generate_export_sql(
metadata_path_or_uri=args.metadata_path,
default_schema=args.default_schema,
schemas=args.schemas,
rtrim_char=not args.keep_char_padding,
unbounded_number_scale=args.unbounded_number_scale,
)
if args.schemas and "-- Unload Table:" not in sql:
sys.exit("ERROR: No tables to export; check --schema.")
if args.output_sql:
out_dir = os.path.dirname(os.path.abspath(args.output_sql))
os.makedirs(out_dir, exist_ok=True)
with open(args.output_sql, "w", encoding="utf-8") as f:
f.write(sql)
print(f"Generated unified export SQL: {args.output_sql}")
if args.output_dir:
_write_table_sql_files(sql, args.output_dir)
if not args.output_sql and not args.output_dir:
print(sql)
if __name__ == "__main__":
main()
export_postgres_tables_template.py 54.5 KB
#!/usr/bin/env python3
r"""Template Script for Generating Type-Safe PostgreSQL Export SQL Files.
This asset template script provides a reference implementation for generating
type-safe PostgreSQL SELECT export scripts (.sql) directly from BQMS
translation_output/metadata configs or a PostgreSQL extractor metadata.zip
(is_columns_private.csv and pg_views_private.csv, or generic tables.csv and
columns.csv). It has zero JDBC or database connector dependencies.
PostgreSQL COPY ... TO cannot write Parquet directly to Cloud Storage
and requires superuser privileges for server-side file output. The export
therefore happens in two steps:
1. This script emits one explicit-cast SELECT per table. The casts pin every
column to a PostgreSQL SQL type whose `psycopg2` cursor metadata and
Parquet representation BigQuery loads without drift (SMALLINT/INTEGER/
BIGINT -> BIGINT -> INT64, NUMERIC(p,s) -> DECIMAL128 -> NUMERIC/
BIGNUMERIC, MONEY -> NUMERIC(38,2) -> BIGNUMERIC, REAL/DOUBLE PRECISION ->
DOUBLE PRECISION -> FLOAT64, DATE -> DATE, TIME/TIMETZ -> TIME(6) -> TIME,
TIMESTAMP -> TIMESTAMP(6) WITHOUT TIME ZONE -> DATETIME, TIMESTAMPTZ ->
TIMESTAMP(6) WITH TIME ZONE -> TIMESTAMP, CHAR/BPCHAR padding trimmed via
RTRIM, and JSON/JSONB/XML/UUID/INET/CIDR/MACADDR/INTERVAL -> TEXT).
2. A downstream Python execution script runs each SELECT via the `psycopg2`
driver, derives the Arrow schema from `cursor.description`, and writes
Snappy Parquet files under ./data_unload/[<SCHEMA>/]<TABLE>/.
Usage Pattern:
Copy `assets/export_postgres_tables_template.py` from this skill's directory
(`<SKILL_DIR>`, the directory containing `SKILL.md`) into your
working directory (e.g., `./export_postgres_tables.py`). Run the copy as-is
for standard export SQL generation, and prioritize modifying the marked
`# CUSTOMIZE:` extension points if your environment requires custom type
projections, row filters, or schema/table filtering. Sections marked
`# DEFAULT SCAFFOLDING` can be kept unchanged unless deeper orchestration
adjustments are needed.
Dependencies:
pip install pyyaml==6.0.2
Usage Examples:
# Copy the template from this skill's directory to your working directory:
cp <SKILL_DIR>/assets/export_postgres_tables_template.py \
./export_postgres_tables.py
# 1. Generate per-table PostgreSQL export SQL files from BQMS output:
python3 ./export_postgres_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--default-schema public \
--output-dir ./export_sql
# 2. Generate a unified export SQL file straight from the extractor zip:
python3 ./export_postgres_tables.py \
--metadata-zip gs://my-bucket/postgresql-metadata.zip \
--schema public \
--output-sql postgres_export.sql
"""
from __future__ import annotations
import argparse
import csv
import io
import logging
import os
import re
import subprocess
import sys
import tempfile
import zipfile
import yaml
# ==============================================================================
# 1. File & Metadata Loading Functions (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Deterministic metadata loading and archive parsing.
_SYSTEM_SCHEMAS = frozenset((
"pg_catalog",
"pg_internal",
"information_schema",
"pg_toast",
))
def read_file_or_gcs(path_or_uri: str) -> bytes:
"""Reads content from a local file path or a Cloud Storage URI.
Args:
path_or_uri: Local file path or Cloud Storage URI (starts with 'gs://').
Returns:
The content of the file as bytes.
Raises:
FileNotFoundError: If the local file does not exist.
RuntimeError: If gcloud storage fails to read from Cloud Storage.
"""
if path_or_uri.startswith("gs://"):
cmd = ["gcloud", "storage", "cat", path_or_uri]
try:
return subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
raise RuntimeError(
f"Failed to read from Cloud Storage '{path_or_uri}': {e}"
) from e
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot read '{path_or_uri}': the gcloud CLI was not found. Install"
" the Google Cloud CLI, or download the file and pass a local path."
) from e
if not os.path.exists(path_or_uri):
raise FileNotFoundError(f"Local file not found: '{path_or_uri}'")
with open(path_or_uri, "rb") as f:
return f.read()
def _run_gcloud_copy(cmd: list[str], uri: str) -> None:
"""Runs a `gcloud storage cp` command, surfacing its stderr on failure."""
try:
subprocess.run(cmd, capture_output=True, check=True)
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot copy '{uri}': the gcloud CLI was not found. Install the"
" Google Cloud CLI, or copy the files locally and pass a local path."
) from e
except subprocess.CalledProcessError as e:
stderr = (e.stderr or b"").decode("utf-8", errors="replace").strip()
raise RuntimeError(
f"Failed to copy from Cloud Storage '{uri}' (exit code"
f" {e.returncode}): {stderr or e}"
) from e
def _strip(value: str | None) -> str:
"""Trims whitespace around PostgreSQL catalog CSV fields."""
return (value or "").strip()
def _decode_pg_scale(scale: int | None) -> int | None:
"""Decodes PostgreSQL 15+ negative NUMERIC scale from information_schema.
In PostgreSQL 15+, information_schema._pg_numeric_scale masks
((typmod - 4) & 0x7ff) without sign extension, so negative scales such as
NUMERIC(10, -2) are reported as 2046 (2048 - 2).
Args:
scale: Raw numeric scale integer or None.
Returns:
Signed numeric scale integer or None.
"""
if scale is not None and 1024 <= scale < 2048:
return scale - 2048
return scale
def _decode_pg_scale_str(scale_str: str) -> str:
"""Decodes a numeric scale string if it encodes a PG 15+ negative scale."""
s = _strip(scale_str)
if s.lstrip("-").isdigit():
val = _decode_pg_scale(int(s))
return str(val) if val is not None else ""
return s
def load_metadata_from_zip(
zip_bytes: bytes,
) -> dict[str, list[dict[str, str]]]:
"""Extracts table and column metadata from a PostgreSQL metadata.zip.
Reads is_columns_private.csv and pg_views_private.csv (falls back to generic
tables.csv and columns.csv) and normalizes rows to the shared TableCatalog/
TableSchema/TableName/ColumnName/DataType record shape. Pairing
is_columns_private.csv with pg_views_private.csv ensures views and system
catalogs are excluded so only physical user base tables are exported.
Args:
zip_bytes: Raw bytes of the metadata zip archive.
Returns:
A dictionary containing 'tables' and 'columns' lists of records.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as z:
names = z.namelist()
by_base = {os.path.basename(n).lower(): n for n in names}
def _rows(candidates: list[str]) -> tuple[str | None, list[dict[str, str]]]:
for c in candidates:
member = by_base.get(c.lower())
if member:
with z.open(member) as fh:
return c, list(
csv.DictReader(io.TextIOWrapper(fh, encoding="utf-8-sig"))
)
return None, []
tables_fn, table_rows = _rows(["tables.csv"])
views_fn, view_rows = _rows(["pg_views_private.csv", "views.csv"])
columns_fn, column_rows = _rows(["is_columns_private.csv", "columns.csv"])
view_keys: set[tuple[str, str, str]] = set()
if views_fn:
for r in view_rows:
v_cat = _strip(r.get("table_catalog") or r.get("TableCatalog"))
v_schema = _strip(
r.get("schemaname") or r.get("table_schema") or r.get("TableSchema")
)
v_name = _strip(
r.get("viewname") or r.get("table_name") or r.get("TableName")
)
if v_name:
# Exact case: PostgreSQL keeps quoted identifiers case-sensitive, so
# a view "Report" must not hide a base table report.
view_keys.add((v_cat, v_schema, v_name))
if tables_fn == "tables.csv" and table_rows:
for r in table_rows:
t_dict = {k: _strip(v) for k, v in r.items() if k is not None}
t_schema = _strip(t_dict.get("TableSchema") or t_dict.get("table_schema"))
t_name = _strip(t_dict.get("TableName") or t_dict.get("table_name"))
t_cat = _strip(t_dict.get("TableCatalog") or t_dict.get("table_catalog"))
t_type = _strip(
t_dict.get("TableType") or t_dict.get("table_type") or "BASE TABLE"
).upper()
# tables.csv rows carry their own TableType, so only a view in the
# same database reclassifies them.
if (t_cat, t_schema, t_name) in view_keys:
t_type = "VIEW"
result["tables"].append({
"TableCatalog": t_cat,
"TableSchema": t_schema,
"TableName": t_name,
"TableType": t_type,
})
seen_tables: set[tuple[str, str, str]] = set()
if columns_fn:
for r in column_rows:
schema = _strip(r.get("table_schema") or r.get("TableSchema"))
if schema.lower() in _SYSTEM_SCHEMAS:
continue
tbl_name = _strip(r.get("table_name") or r.get("TableName"))
catalog = _strip(r.get("table_catalog") or r.get("TableCatalog"))
is_nullable = (
_strip(
r.get("is_nullable") or r.get("Nullable") or r.get("NULLABLE")
).upper()
or "YES"
)
not_null = is_nullable in ("NO", "N", "FALSE")
raw_dt = _strip(r.get("data_type") or r.get("DataType")).upper()
udt_name = _strip(r.get("udt_name")).upper()
if raw_dt == "USER-DEFINED" and udt_name:
data_type = udt_name
else:
data_type = raw_dt
radix = _strip(r.get("numeric_precision_radix"))
if radix == "10" or data_type in ("NUMERIC", "DECIMAL", "DEC", "NUMBER"):
num_prec = _strip(
r.get("numeric_precision") or r.get("NumericPrecision")
)
num_scale = _decode_pg_scale_str(
_strip(r.get("numeric_scale") or r.get("NumericScale"))
)
else:
num_prec = ""
num_scale = ""
result["columns"].append({
"TableCatalog": catalog,
"TableSchema": schema,
"TableName": tbl_name,
"ColumnName": _strip(r.get("column_name") or r.get("ColumnName")),
"OrdinalPosition": _strip(
r.get("ordinal_position") or r.get("OrdinalPosition")
),
"DataType": data_type,
"ColumnLength": _strip(
r.get("character_maximum_length") or r.get("ColumnLength")
),
"NumericPrecision": num_prec,
"NumericScale": num_scale,
"Nullable": "N" if not_null else "Y",
"ExplicitNotNull": "Y" if not_null else "N",
})
if not table_rows and (catalog, schema, tbl_name) not in seen_tables:
seen_tables.add((catalog, schema, tbl_name))
# pg_views_private.csv has no database column, so its views match
# the same schema.table in any database.
is_view = any(
(cat, schema, tbl_name) in view_keys for cat in (catalog, "")
)
result["tables"].append({
"TableCatalog": catalog,
"TableSchema": schema,
"TableName": tbl_name,
"TableType": "VIEW" if is_view else "BASE TABLE",
})
return result
def load_metadata_from_config_dir(
config_dir: str,
) -> dict[str, list[dict[str, str]]]:
"""Loads table/column metadata from BQMS metadata/config/*.yaml files.
Args:
config_dir: Local path to the BQMS metadata config directory.
Returns:
A dictionary containing 'tables' and 'columns' metadata parsed from YAMLs.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
if not os.path.isdir(config_dir):
return result
for root, dirs, files in os.walk(config_dir):
dirs.sort() # Deterministic order, so the first database wins.
for f in sorted(files):
if not (f.endswith(".yaml") or f.endswith(".yml")):
continue
try:
with open(os.path.join(root, f), "r", encoding="utf-8") as yf:
cfg = yaml.safe_load(yf)
except (yaml.YAMLError, OSError):
continue
if not isinstance(cfg, dict):
continue
src_name = cfg.get("sourceName", "")
parts = src_name.split(".") if src_name else []
# PostgreSQL names in BQMS are __DEFAULT_DATABASE__.schema.table or
# db.schema.table or schema.table.
schema = parts[-2] if len(parts) >= 2 else ""
table = parts[-1] if parts else f.rsplit(".", 1)[0]
catalog = (
parts[0]
if len(parts) >= 3 and parts[0] != "__DEFAULT_DATABASE__"
else ""
)
# Views are recreated, not exported; skipping them here keeps a view
# from shadowing a same-named table in another database.
if not (cfg.get("externalTableName") or cfg.get("externalTableDdlPath")):
continue
result["tables"].append({
"TableCatalog": catalog,
"TableSchema": schema,
"TableName": table,
"TableType": "BASE TABLE",
})
for idx, col in enumerate(cfg.get("columns") or [], start=1):
if not isinstance(col, dict):
continue
src_type = col.get("sourceType") or {}
src = (
src_type
if isinstance(src_type, dict)
else {"genericName": src_type}
)
raw_code = str(src.get("name") or "").strip().upper()
generic_name = str(src.get("genericName") or "").strip().upper()
# Prefer raw PostgreSQL type name ('timestamp without time zone',
# 'time with time zone', 'money', 'bytea', 'uuid', 'inet', etc.).
data_type = raw_code or generic_name
raw_prec = src.get("precision")
raw_scale = src.get("scale")
# For MONEY, BQMS sets sourceType: {name: 'money', precision: 2}.
if data_type == "MONEY":
num_prec = ""
num_scale = ""
else:
num_prec = str(raw_prec) if raw_prec is not None else ""
num_scale = (
_decode_pg_scale_str(str(raw_scale))
if raw_scale is not None
else ""
)
col_entry = {
"TableCatalog": catalog,
"TableSchema": schema,
"TableName": table,
"ColumnName": col.get("sourceName", ""),
"OrdinalPosition": str(idx),
"DataType": data_type,
"NumericPrecision": num_prec,
"NumericScale": num_scale,
"Nullable": "N" if col.get("notNull") else "Y",
"ExplicitNotNull": "Y" if col.get("notNull") else "N",
}
# Persist the BQMS target type so format_column_cast() honors INT64 /
# NUMERIC / BIGNUMERIC / FLOAT64 / DATETIME / TIMESTAMP overrides.
tgt_type = col.get("targetType") or {}
tgt_name = (
(
str(tgt_type.get("name") or "")
if isinstance(tgt_type, dict)
else str(tgt_type)
)
.strip()
.upper()
)
if tgt_name:
col_entry["TargetType"] = tgt_name
result["columns"].append(col_entry)
return result
def _enrich_yaml_columns_from_zip(
yaml_meta: dict[str, list[dict[str, str]]],
zip_meta: dict[str, list[dict[str, str]]],
) -> None:
"""Enriches BQMS YAML column metadata with extractor zip catalog details.
BQMS translate_metadata for PostgreSQL emits a generic placeholder
(precision=18, scale=0) for NUMERIC columns and omits notNull in
metadata/config/*.yaml. When an extractor metadata.zip is present alongside
the config directory, this function restores the exact precision, scale, and
NOT NULL constraints from is_columns_private.csv.
Args:
yaml_meta: Metadata dictionary loaded from BQMS YAML config files.
zip_meta: Metadata dictionary loaded from extractor metadata.zip.
"""
# Match (database, schema, table, column) with exact identifier case first
# (PostgreSQL keeps quoted names like "Report" distinct from report); fall
# back to a case-insensitive match in a compatible database (same name, or
# either one empty) only when it is unambiguous.
def _cat(row: dict[str, str]) -> str:
return _strip(row.get("TableCatalog")).lower()
def _key(row: dict[str, str]) -> tuple[str, str, str]:
return (
_strip(row.get("TableSchema")),
_strip(row.get("TableName")),
_strip(row.get("ColumnName")),
)
zip_cols: dict[tuple[str, str, str, str], dict[str, str]] = {}
zip_cols_lower: dict[tuple[str, ...], list[dict[str, str]]] = {}
for zc in zip_meta.get("columns", []):
zip_cols[(_cat(zc),) + _key(zc)] = zc
lower_key = tuple(k.lower() for k in _key(zc))
zip_cols_lower.setdefault(lower_key, []).append(zc)
for yc in yaml_meta.get("columns", []):
y_cat = _cat(yc)
zc = zip_cols.get((y_cat,) + _key(yc))
if not zc:
candidates = [
c
for c in zip_cols_lower.get(tuple(k.lower() for k in _key(yc)), [])
if not y_cat or not _cat(c) or _cat(c) == y_cat
]
zc = candidates[0] if len(candidates) == 1 else None
if not zc:
continue
if zc.get("ExplicitNotNull") == "Y":
yc["ExplicitNotNull"] = "Y"
yc["Nullable"] = "N"
if (
yc.get("DataType") in ("NUMERIC", "DECIMAL", "DEC", "NUMBER")
and yc.get("NumericPrecision") == "18"
and yc.get("NumericScale") == "0"
):
yc["NumericPrecision"] = zc.get("NumericPrecision", "")
yc["NumericScale"] = zc.get("NumericScale", "")
# BQMS may map the (18, 0) placeholder to INT64; drop that target when
# the restored type has a fractional part or more than 18 digits, so
# the NUMERIC(p, s) projection keeps the decimals.
prec = yc["NumericPrecision"]
fits_int64 = (
yc["NumericScale"] == "0" and prec.isdigit() and 1 <= int(prec) <= 18
)
if yc.get("TargetType") == "INT64" and not fits_int64:
yc.pop("TargetType", None)
def _find_config_dir(dir_path: str) -> str | None:
"""Locates the directory containing BQMS table YAML configurations."""
for candidate in (
os.path.join(dir_path, "metadata", "config"),
os.path.join(dir_path, "config"),
):
if os.path.isdir(candidate):
return candidate
for _, _, files in os.walk(dir_path):
if any(f.endswith((".yaml", ".yml")) for f in files):
return dir_path
return None
def _find_nearby_metadata_zip(
dir_path: str, search_parents: bool = True
) -> str | None:
"""Searches dir_path and sibling metadata/ directories for a metadata zip.
Args:
dir_path: Directory holding the BQMS YAML configs.
search_parents: Also search metadata/ next to dir_path and its parent. Set
to False for temporary download directories.
Returns:
The path to the first metadata zip found, or None.
"""
abs_dir = os.path.abspath(dir_path)
search_roots = [abs_dir]
if search_parents:
search_roots += [
os.path.join(os.path.dirname(abs_dir), "metadata"),
os.path.join(os.path.dirname(os.path.dirname(abs_dir)), "metadata"),
]
for sroot in search_roots:
if not os.path.isdir(sroot):
continue
for root, _, files in os.walk(sroot):
for f in sorted(files):
if f.endswith(".zip") and "metadata" in f.lower():
return os.path.join(root, f)
return None
def load_metadata_from_dir(
dir_path: str,
zip_bytes: bytes | None = None,
search_parents: bool = True,
) -> dict[str, list[dict[str, str]]]:
"""Discovers metadata in a directory (BQMS YAML configs or embedded zip).
Args:
dir_path: Local translation metadata or config directory.
zip_bytes: Optional extractor metadata.zip content (from --metadata-zip)
used to enrich YAML columns. When omitted, a nearby metadata zip is
searched for instead.
search_parents: Allow the nearby-zip search to look in metadata/ directories
next to dir_path and its parent.
Returns:
A dictionary containing 'tables' and 'columns' metadata.
"""
config_dir = _find_config_dir(dir_path)
if config_dir:
res = load_metadata_from_config_dir(config_dir)
if res["tables"] and res["columns"]:
if zip_bytes is not None:
_enrich_yaml_columns_from_zip(res, load_metadata_from_zip(zip_bytes))
return res
zip_path = _find_nearby_metadata_zip(
dir_path, search_parents=search_parents
)
if zip_path:
try:
with open(zip_path, "rb") as zf:
zip_meta = load_metadata_from_zip(zf.read())
_enrich_yaml_columns_from_zip(res, zip_meta)
except (OSError, zipfile.BadZipFile):
pass
return res
if zip_bytes is not None:
return load_metadata_from_zip(zip_bytes)
for root, _, files in os.walk(dir_path):
for f in files:
if f.endswith(".zip") and "metadata" in f:
with open(os.path.join(root, f), "rb") as zf:
return load_metadata_from_zip(zf.read())
return {"tables": [], "columns": []}
def _resolve_and_load_metadata(
path_or_uri: str | None,
metadata_zip_path_or_uri: str | None = None,
) -> dict[str, list[dict[str, str]]]:
"""Resolves local or Cloud Storage metadata path/zip and loads metadata.
Args:
path_or_uri: Translation metadata directory, config directory, or zip.
metadata_zip_path_or_uri: Optional extractor metadata.zip. Used on its own
when path_or_uri is empty, or to enrich YAML configs from path_or_uri.
Returns:
A dictionary containing 'tables' and 'columns' metadata.
"""
zip_bytes = (
read_file_or_gcs(metadata_zip_path_or_uri)
if metadata_zip_path_or_uri
else None
)
if not path_or_uri:
if zip_bytes is not None:
return load_metadata_from_zip(zip_bytes)
return {"tables": [], "columns": []}
if path_or_uri.startswith("gs://"):
if path_or_uri.endswith(".zip"):
return load_metadata_from_zip(read_file_or_gcs(path_or_uri))
with tempfile.TemporaryDirectory(prefix="bqms_meta_") as temp_dir:
cmd = [
"gcloud",
"storage",
"cp",
"-r",
path_or_uri.rstrip("/") + "/*",
temp_dir,
]
_run_gcloud_copy(cmd, path_or_uri)
# The temp dir lives under the shared temp root, so never search its
# parent directories for a metadata zip.
return load_metadata_from_dir(
temp_dir, zip_bytes=zip_bytes, search_parents=False
)
if os.path.isdir(path_or_uri):
return load_metadata_from_dir(path_or_uri, zip_bytes=zip_bytes)
return load_metadata_from_zip(read_file_or_gcs(path_or_uri))
def _ordinal(col: dict[str, str]) -> int:
pos = str(col.get("OrdinalPosition", ""))
return int(pos) if pos.isdigit() else 999999
def _select_databases(
metadata: dict[str, list[dict[str, str]]],
databases: list[str] | None = None,
) -> dict[str, list[dict[str, str]]]:
"""Keeps one database's copy of each schema.table.
A PostgreSQL connection reads one database and the generated SQL is
schema-qualified, so same-named tables from several databases in one BQMS
config directory (db1.public.orders and db2.public.orders) can't share a
script. Tables from databases outside `databases` are dropped (tables without
a database qualifier are kept). When a schema.table still appears under more
than one database, the first one is kept and a warning names the others.
Args:
metadata: Metadata dictionary with 'tables' and 'columns' lists.
databases: Optional database allow-list (case-insensitive).
Returns:
The metadata dictionary restricted to one database per schema.table.
"""
wanted = {d.lower() for d in databases} if databases else None
def _key(row: dict[str, str]) -> tuple[str, str]:
return (_strip(row.get("TableSchema")), _strip(row.get("TableName")))
def _wanted(cat: str) -> bool:
return not wanted or not cat or cat.lower() in wanted
rows = metadata.get("tables", [])
if wanted:
# An exact --database match wins over a table without a database.
rows = sorted(
rows, key=lambda t: _strip(t.get("TableCatalog")).lower() not in wanted
)
chosen: dict[tuple[str, str], str] = {}
duplicated: set[tuple[str, str]] = set()
tables: list[dict[str, str]] = []
for t in rows:
cat = _strip(t.get("TableCatalog"))
if not _wanted(cat):
continue
key = _key(t)
if key in chosen and chosen[key].lower() != cat.lower():
print(
f"WARNING: Skipping {cat}.{key[0]}.{key[1]}: {key[0]}.{key[1]} was"
f" already loaded from database '{chosen[key]}'; pass --database to"
" choose which database to export.",
file=sys.stderr,
)
duplicated.add(key)
continue
chosen.setdefault(key, cat)
tables.append(t)
def _same_db(c: dict[str, str]) -> bool:
chosen_cat = chosen.get(_key(c), "").lower()
col_cat = _strip(c.get("TableCatalog")).lower()
if chosen_cat == col_cat:
return True
# A database-less table or column matches any database, unless the
# schema.table has copies in several databases.
return _key(c) not in duplicated and not (chosen_cat and col_cat)
columns = [
c
for c in metadata.get("columns", [])
if _wanted(_strip(c.get("TableCatalog"))) and _same_db(c)
]
return {"tables": tables, "columns": columns}
def _group_and_sort_columns(
columns: list[dict[str, str]],
) -> tuple[
dict[tuple[str, str], list[dict[str, str]]],
dict[str, list[dict[str, str]]],
]:
"""Groups columns by (schema, table) and table name, sorted by ordinal."""
by_schema_table: dict[tuple[str, str], list[dict[str, str]]] = {}
by_table: dict[str, list[dict[str, str]]] = {}
for col in columns:
key = (
_strip(col.get("TableSchema")),
_strip(col.get("TableName")),
)
by_schema_table.setdefault(key, []).append(col)
for (_, tbl), cols in by_schema_table.items():
cols.sort(key=_ordinal)
by_table.setdefault(tbl, cols)
return by_schema_table, by_table
def _lookup_table_columns(
by_schema_table: dict[tuple[str, str], list[dict[str, str]]],
raw_schema: str,
schema: str,
tbl: str,
) -> list[dict[str, str]]:
"""Finds a table's columns without borrowing them from another schema.
Tries the metadata schema, then the --default-schema fallback, then columns
recorded without a schema. A table without any schema only matches a
same-named table when exactly one candidate exists; otherwise it gets no
column projections and falls back to SELECT *.
Args:
by_schema_table: Column metadata keyed by (schema, table name).
raw_schema: The schema recorded in the metadata for this table.
schema: The effective schema after applying --default-schema.
tbl: The table name.
Returns:
The table's column metadata, or an empty list when no unambiguous match
exists.
"""
for key in ((raw_schema, tbl), (schema, tbl), ("", tbl)):
cols = by_schema_table.get(key)
if cols:
return cols
if not schema:
matches = [c for (_, t), c in by_schema_table.items() if t == tbl and c]
if len(matches) == 1:
return matches[0]
return []
# CUSTOMIZE: Table & Row Filtering — Edit _filter_tables_to_export() to add
# custom schema/table inclusion or exclusion rules.
def _filter_tables_to_export(
raw_tables: list[dict[str, str]],
columns_by_table: dict[str, list[dict[str, str]]],
schemas: set[str] | None = None,
columns_by_schema_table: (
dict[tuple[str, str], list[dict[str, str]]] | None
) = None,
default_schema: str = "",
) -> list[dict[str, str]]:
"""Filters tables to export: drops views/system objects, applies filters.
The schema allow-list and duplicate check use the effective schema
(TableSchema, else default_schema), so schema-less entries match
--schema and don't duplicate qualified entries for the same table.
Args:
raw_tables: Table rows from the metadata (may be empty).
columns_by_table: Column metadata keyed by table name.
schemas: Optional upper-cased schema allow-list.
columns_by_schema_table: Column metadata keyed by (schema, table name), used
when raw_tables is empty.
default_schema: Fallback schema for entries without a TableSchema.
Returns:
The table entries to export, without duplicates.
"""
out: list[dict[str, str]] = []
seen: set[tuple[str, str]] = set()
default_schema = _strip(default_schema)
if raw_tables:
for t in raw_tables:
tbl = _strip(t.get("TableName"))
schema = _strip(t.get("TableSchema")) or default_schema
tbl_type = _strip(t.get("TableType")).upper()
if tbl_type and tbl_type not in ("BASE TABLE", "TABLE"):
continue
if schema.lower() in _SYSTEM_SCHEMAS and (
not schemas or schema.upper() not in schemas
):
continue
if schemas and schema.upper() not in schemas:
continue
if (schema, tbl) in seen:
continue
seen.add((schema, tbl))
out.append(t)
out.sort(
key=lambda t: (
_strip(t.get("TableSchema")) or default_schema,
_strip(t.get("TableName")),
)
)
elif columns_by_schema_table:
for raw_schema, tbl in sorted(columns_by_schema_table):
schema = raw_schema or default_schema
if schema.lower() in _SYSTEM_SCHEMAS and (
not schemas or schema.upper() not in schemas
):
continue
if schemas and schema.upper() not in schemas:
continue
if (schema, tbl) not in seen:
seen.add((schema, tbl))
out.append({"TableSchema": raw_schema, "TableName": tbl})
else:
for tbl in sorted(columns_by_table):
cols = columns_by_table[tbl]
raw_schema = _strip(cols[0].get("TableSchema")) if cols else ""
schema = raw_schema or default_schema
if schema.lower() in _SYSTEM_SCHEMAS and (
not schemas or schema.upper() not in schemas
):
continue
if schemas and schema.upper() not in schemas:
continue
if (schema, tbl) not in seen:
seen.add((schema, tbl))
entry = {"TableName": tbl}
if raw_schema:
entry["TableSchema"] = raw_schema
out.append(entry)
return out
# ==============================================================================
# 2. Type-Safe SQL Generation Logic
# ==============================================================================
# PostgreSQL folds unquoted identifiers to lowercase, so only lowercase names
# stay unquoted; mixed-case or uppercase catalog names are double-quoted to
# keep their exact case.
_VALID_IDENT_REGEX = re.compile(r"^[a-z_][a-z0-9_$]*$")
# PostgreSQL reserved words that commonly appear as column or table names in
# migrated schemas. Anything matching is double-quoted.
_POSTGRES_RESERVED = frozenset((
"ALL",
"ANALYSE",
"ANALYZE",
"AND",
"ANY",
"ARRAY",
"AS",
"ASC",
"ASYMMETRIC",
"AUTHORIZATION",
"BINARY",
"BOTH",
"CASE",
"CAST",
"CHECK",
"COLLATE",
"COLUMN",
"CONCURRENTLY",
"CONSTRAINT",
"CREATE",
"CROSS",
"CURRENT_CATALOG",
"CURRENT_DATE",
"CURRENT_ROLE",
"CURRENT_SCHEMA",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_USER",
"DEFAULT",
"DEFERRABLE",
"DESC",
"DISTINCT",
"DO",
"ELSE",
"END",
"EXCEPT",
"FALSE",
"FETCH",
"FOR",
"FOREIGN",
"FREEZE",
"FROM",
"FULL",
"GRANT",
"GROUP",
"HAVING",
"ILIKE",
"IN",
"INITIALLY",
"INNER",
"INTERSECT",
"INTO",
"IS",
"ISNULL",
"JOIN",
"LATERAL",
"LEADING",
"LEFT",
"LIKE",
"LIMIT",
"LOCALTIME",
"LOCALTIMESTAMP",
"NATURAL",
"NOT",
"NOTNULL",
"NULL",
"OFFSET",
"ON",
"ONLY",
"OR",
"ORDER",
"OUTER",
"OVERLAPS",
"PLACING",
"PRIMARY",
"REFERENCES",
"RETURNING",
"RIGHT",
"SELECT",
"SESSION_USER",
"SIMILAR",
"SOME",
"SYMMETRIC",
"TABLE",
"TABLESAMPLE",
"THEN",
"TO",
"TRAILING",
"TRUE",
"UNION",
"UNIQUE",
"USER",
"USING",
"VARIADIC",
"VERBOSE",
"WHEN",
"WHERE",
"WINDOW",
"WITH",
))
_INT_TYPES = frozenset((
"SMALLINT",
"INT2",
"INTEGER",
"INT",
"INT4",
"BIGINT",
"INT8",
"SERIAL",
"SMALLSERIAL",
"BIGSERIAL",
"SERIAL2",
"SERIAL4",
"SERIAL8",
"TINYINT",
"BYTEINT",
"INT64",
"OID",
))
_NUMBER_TYPES = frozenset(("NUMERIC", "DECIMAL", "DEC", "NUMBER", "BIGNUMERIC"))
_MONEY_TYPES = frozenset(("MONEY",))
_FLOAT_TYPES = frozenset((
"REAL",
"FLOAT4",
"DOUBLE PRECISION",
"FLOAT8",
"FLOAT",
"DOUBLE",
"FLOAT64",
))
_BOOL_TYPES = frozenset(("BOOLEAN", "BOOL"))
_DATE_TYPES = frozenset(("DATE",))
_TIME_TYPES = frozenset(("TIME", "TIME WITHOUT TIME ZONE"))
_TIMETZ_TYPES = frozenset(("TIMETZ", "TIME WITH TIME ZONE"))
_TIMESTAMP_TYPES = frozenset((
"TIMESTAMP",
"TIMESTAMP WITHOUT TIME ZONE",
"DATETIME",
))
_TIMESTAMP_TZ_TYPES = frozenset((
"TIMESTAMPTZ",
"TIMESTAMP WITH TIME ZONE",
))
_CHAR_TYPES = frozenset(("CHAR", "CHARACTER", "BPCHAR", "NCHAR"))
_VARCHAR_TYPES = frozenset((
"VARCHAR",
"CHARACTER VARYING",
"TEXT",
"CITEXT",
"NAME",
"STRING",
"NVARCHAR",
))
_BYTE_TYPES = frozenset(("BYTEA", "BINARY", "VARBINARY", "BYTES"))
_TEXT_CAST_TYPES = frozenset((
"JSON",
"JSONB",
"XML",
"UUID",
"INET",
"CIDR",
"MACADDR",
"MACADDR8",
"INTERVAL",
"BIT",
"BIT VARYING",
"VARBIT",
"TSVECTOR",
"TSQUERY",
"PG_LSN",
"TXID_SNAPSHOT",
"PG_SNAPSHOT",
"POINT",
"LINE",
"LSEG",
"BOX",
"PATH",
"POLYGON",
"CIRCLE",
"INT4RANGE",
"INT8RANGE",
"NUMRANGE",
"TSRANGE",
"TSTZRANGE",
"DATERANGE",
"ARRAY",
"USER-DEFINED",
))
# DEFAULT SCAFFOLDING: Identifier quoting helper.
def quote_ident(ident: str) -> str:
"""Double-quotes a PostgreSQL identifier when it is not a plain name.
Args:
ident: The raw SQL identifier string.
Returns:
The properly quoted or unquoted identifier.
"""
if not ident:
return ""
if len(ident) >= 2 and ident.startswith('"') and ident.endswith('"'):
# Already quoted: re-escape any bare inner double quotes.
inner = ident[1:-1].replace('""', '"').replace('"', '""')
return f'"{inner}"'
if not _VALID_IDENT_REGEX.match(ident) or ident.upper() in _POSTGRES_RESERVED:
escaped = ident.replace('"', '""')
return f'"{escaped}"'
return ident
_PARAM_TYPE_REGEX = re.compile(
r"^(?P<base>[A-Z0-9_ ]+?)\s*\(\s*(?P<p>-?\d+|\*)"
r"(?:\s*,\s*(?P<s>-?\d+))?\s*\)\s*(?P<rest>.*)$"
)
def _to_int(value: str | None) -> int | None:
value = str(value or "").strip()
return int(value) if value.lstrip("-").isdigit() else None
def _normalize_data_type(
raw_type: str, precision: int | None, scale: int | None
) -> tuple[str, int | None, int | None]:
"""Normalizes a PostgreSQL DATA_TYPE string into (base_type, p, s)."""
dt = " ".join(raw_type.upper().split())
scale = _decode_pg_scale(scale)
if dt.startswith("INTERVAL"):
return "INTERVAL", precision, scale
if dt.endswith("[]") or dt.startswith("_"):
return "ARRAY", precision, scale
m = _PARAM_TYPE_REGEX.match(dt)
if m:
base = f"{m.group('base').strip()} {m.group('rest').strip()}".strip()
if precision is None and m.group("p") != "*":
precision = _to_int(m.group("p"))
if scale is None and m.group("s") is not None:
scale = _decode_pg_scale(_to_int(m.group("s")))
# In PostgreSQL SQL, NUMERIC(p) with a single argument means NUMERIC(p, 0).
if base in _NUMBER_TYPES and precision is not None and scale is None:
scale = 0
return base, precision, scale
return dt, precision, scale
# CUSTOMIZE: Custom Type Projections -- Edit format_column_cast() to change
# how a PostgreSQL type is projected before Parquet serialization (e.g. keep
# CHAR padding, widen unconstrained NUMERIC scale, or cast NUMERIC(p,0) to
# BIGINT when targeting INT64).
def format_column_cast(
col: dict[str, str],
target_bq_type: str | None = None,
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Generates a type-safe PostgreSQL projection expression for Parquet export.
The executor derives the Parquet schema from `cursor.description`, so the
SQL projection here determines both the PyArrow type and the BigQuery column
type compatible with `bq load --source_format=PARQUET`:
SMALLINT / INTEGER / BIGINT / SERIAL -> CAST AS BIGINT -> INT64
NUMERIC(p, 0) -> CAST AS NUMERIC(p, 0) -> NUMERIC
NUMERIC(p, s > 0) -> CAST AS NUMERIC(p, s) -> NUMERIC
NUMERIC(p, s < 0) -> CAST AS NUMERIC(p+|s|, 0) -> NUMERIC
NUMERIC (unconstrained) -> CAST AS NUMERIC(38, 9) -> BIGNUMERIC
MONEY -> CAST AS NUMERIC(38, 2) -> BIGNUMERIC
REAL / DOUBLE PRECISION -> CAST AS DOUBLE PRECISION -> FLOAT64
BOOLEAN -> col -> BOOL
DATE -> col -> DATE
TIME / TIMETZ -> CAST AS TIME(6) -> TIME
TIMESTAMP WITHOUT TIME ZONE -> CAST AS TIMESTAMP(6) WITHOUT TZ
TIMESTAMP WITH TIME ZONE -> CAST AS TIMESTAMP(6) WITH TZ
CHAR(n) / CHARACTER(n) / BPCHAR -> RTRIM(col) -> STRING
VARCHAR / TEXT -> col -> STRING
BYTEA -> col -> BYTES
JSON / JSONB / XML / UUID / INET /
CIDR / MACADDR / INTERVAL / BIT -> CAST AS TEXT -> STRING/JSON
Args:
col: Column metadata dict containing ColumnName, DataType, etc.
target_bq_type: Optional BigQuery target type override.
rtrim_char: Strip CHAR(n)/BPCHAR trailing pad spaces (BigQuery STRING has no
fixed-width semantics, so padded values would mismatch in validation).
unbounded_number_scale: Fractional scale for unconstrained NUMERIC columns
(default 9, supporting up to 29 integer digits).
Returns:
A SQL projection expression, e.g. 'CAST(ss_item_sk AS BIGINT) AS
ss_item_sk'.
"""
col_name = quote_ident(_strip(col.get("ColumnName")))
data_type, precision, scale = _normalize_data_type(
str(col.get("DataType") or ""),
_to_int(col.get("NumericPrecision")),
_to_int(col.get("NumericScale")),
)
explicit_target = (
(target_bq_type or col.get("TargetType") or "").upper().strip()
)
explicit_base = (
re.split(r"[(<]", explicit_target, maxsplit=1)[0].strip()
if explicit_target
else ""
)
if 0 <= unbounded_number_scale <= 38:
default_unb_scale = unbounded_number_scale
else:
logging.warning(
"Out-of-range unbounded_number_scale=%d (expected 0..38); falling back"
" to 9.",
unbounded_number_scale,
)
default_unb_scale = 9
# When the BQMS target already matches the source type family, keep the
# default projection below (preserves CHAR(n)/BPCHAR RTRIM for STRING targets
# and keeps YAML output identical to metadata.zip output).
if (
(explicit_base == "DATE" and data_type in _DATE_TYPES)
or (explicit_base in ("BOOL", "BOOLEAN") and data_type in _BOOL_TYPES)
or (
explicit_base == "STRING"
and (data_type in _CHAR_TYPES or data_type in _VARCHAR_TYPES)
)
or (explicit_base == "BYTES" and data_type in _BYTE_TYPES)
):
explicit_base = ""
# Honor explicit target_bq_type overrides first.
if explicit_base:
if explicit_base in (
"INT64",
"INTEGER",
"BIGINT",
"SMALLINT",
"TINYINT",
"BYTEINT",
):
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if explicit_base in ("FLOAT64", "FLOAT", "DOUBLE"):
return f"CAST({col_name} AS DOUBLE PRECISION) AS {col_name}"
if explicit_base in ("BOOL", "BOOLEAN"):
return f"CAST({col_name} AS BOOLEAN) AS {col_name}"
if explicit_base == "DATE":
return f"CAST({col_name} AS DATE) AS {col_name}"
if explicit_base == "TIME":
return f"CAST({col_name} AS TIME(6)) AS {col_name}"
# AT TIME ZONE 'UTC' keeps timestamp <-> timestamptz conversions
# independent of the session TimeZone.
if explicit_base == "DATETIME":
src = (
f"({col_name} AT TIME ZONE 'UTC')"
if data_type in _TIMESTAMP_TZ_TYPES
else col_name
)
return f"CAST({src} AS TIMESTAMP(6) WITHOUT TIME ZONE) AS {col_name}"
if explicit_base == "TIMESTAMP":
src = (
f"(CAST({col_name} AS TIMESTAMP) AT TIME ZONE 'UTC')"
if data_type in _TIMESTAMP_TYPES or data_type in _DATE_TYPES
else col_name
)
return f"CAST({src} AS TIMESTAMP(6) WITH TIME ZONE) AS {col_name}"
if explicit_base in ("STRING", "JSON"):
return f"CAST({col_name} AS TEXT) AS {col_name}"
if explicit_base == "BYTES":
return f"CAST({col_name} AS BYTEA) AS {col_name}"
if explicit_base in ("NUMERIC", "DECIMAL"):
if data_type in _MONEY_TYPES:
return f"CAST({col_name} AS NUMERIC(38, 2)) AS {col_name}"
if scale is not None and scale > 0:
s_val = min(scale, 38)
p_val = min(max(precision or 29, s_val, 1), 38)
return f"CAST({col_name} AS NUMERIC({p_val}, {s_val})) AS {col_name}"
if scale is not None and scale <= 0:
p_val = min(max((precision or 29) + abs(scale), 1), 38)
return f"CAST({col_name} AS NUMERIC({p_val}, 0)) AS {col_name}"
return (
f"CAST({col_name} AS NUMERIC(38, {default_unb_scale})) AS {col_name}"
)
if explicit_base == "BIGNUMERIC":
if data_type in _MONEY_TYPES:
return f"CAST({col_name} AS NUMERIC(38, 2)) AS {col_name}"
if scale is not None and scale > 0:
s_val = min(scale, 38)
p_val = min(max(precision or 38, s_val, 1), 38)
return f"CAST({col_name} AS NUMERIC({p_val}, {s_val})) AS {col_name}"
if scale is not None and scale <= 0:
return f"CAST({col_name} AS NUMERIC(38, 0)) AS {col_name}"
return (
f"CAST({col_name} AS NUMERIC(38, {default_unb_scale})) AS {col_name}"
)
if data_type in _INT_TYPES:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if data_type in _MONEY_TYPES:
return f"CAST({col_name} AS NUMERIC(38, 2)) AS {col_name}"
if data_type in _NUMBER_TYPES:
if scale is None:
return (
f"CAST({col_name} AS NUMERIC(38, {default_unb_scale})) AS {col_name}"
)
if scale < 0:
eff_p = min(max((precision or 29) + abs(scale), 1), 38)
return f"CAST({col_name} AS NUMERIC({eff_p}, 0)) AS {col_name}"
if scale == 0:
p_val = min(max(precision or 29, 1), 38)
return f"CAST({col_name} AS NUMERIC({p_val}, 0)) AS {col_name}"
s_val = min(scale, 38)
p_val = min(max(precision or 38, s_val, 1), 38)
return f"CAST({col_name} AS NUMERIC({p_val}, {s_val})) AS {col_name}"
if data_type in _FLOAT_TYPES:
return f"CAST({col_name} AS DOUBLE PRECISION) AS {col_name}"
if data_type in _BOOL_TYPES or data_type in _DATE_TYPES:
return f"{col_name} AS {col_name}"
if data_type in _TIME_TYPES or data_type in _TIMETZ_TYPES:
return f"CAST({col_name} AS TIME(6)) AS {col_name}"
if data_type in _TIMESTAMP_TYPES:
return f"CAST({col_name} AS TIMESTAMP(6) WITHOUT TIME ZONE) AS {col_name}"
if data_type in _TIMESTAMP_TZ_TYPES:
return f"CAST({col_name} AS TIMESTAMP(6) WITH TIME ZONE) AS {col_name}"
if data_type in _CHAR_TYPES:
if rtrim_char:
return f"RTRIM({col_name}) AS {col_name}"
return f"{col_name} AS {col_name}"
if data_type in _VARCHAR_TYPES or data_type in _BYTE_TYPES:
return f"{col_name} AS {col_name}"
if data_type in _TEXT_CAST_TYPES:
return f"CAST({col_name} AS TEXT) AS {col_name}"
return f"CAST({col_name} AS TEXT) AS {col_name}"
# DEFAULT SCAFFOLDING: Table name qualification helper.
def _build_qualified_table_name(
table_meta: dict[str, str], default_schema: str = ""
) -> str:
"""Builds a quoted schema.table name."""
tbl = _strip(table_meta.get("TableName"))
schema = _strip(table_meta.get("TableSchema")) or _strip(default_schema)
return (
f"{quote_ident(schema)}.{quote_ident(tbl)}"
if schema
else quote_ident(tbl)
)
# CUSTOMIZE: Row Filters -- Edit _build_select_query() to add WHERE
# predicates (e.g. incremental extraction windows or partition filters).
def _build_select_query(
table_meta: dict[str, str],
columns: list[dict[str, str]],
default_schema: str = "",
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Builds the explicit-cast SELECT statement for a single PostgreSQL table.
Args:
table_meta: Table metadata dictionary with TableSchema and TableName.
columns: Ordered list of column metadata dictionaries for the table.
default_schema: Fallback schema name when TableSchema is empty.
rtrim_char: Whether to RTRIM fixed-width CHAR(n)/BPCHAR columns.
unbounded_number_scale: Fractional scale for unconstrained NUMERIC columns.
Returns:
A complete PostgreSQL SELECT statement ending with a semicolon.
"""
qualified = _build_qualified_table_name(table_meta, default_schema)
if columns:
body = ",\n".join(
" "
+ format_column_cast(
c,
rtrim_char=rtrim_char,
unbounded_number_scale=unbounded_number_scale,
)
for c in columns
)
else:
body = " *"
return f"SELECT\n{body}\nFROM {qualified};"
def _is_not_null(col: dict[str, str]) -> bool:
"""Returns True when a column is marked non-nullable in YAML or zip CSV."""
if "ExplicitNotNull" in col:
return str(col.get("ExplicitNotNull", "N")).strip().upper() == "Y"
return str(col.get("Nullable", "Y")).strip().upper() == "N"
def _sanitize_comment_token(val: str) -> str:
"""Replaces control chars (CR, LF, NUL) so SQL comments stay single-line."""
return re.sub(r"[\r\n\x00]+", " ", str(val)).strip()
# DEFAULT SCAFFOLDING: Primary SQL script generator and orchestration.
def generate_export_sql(
metadata_path_or_uri: str | None = None,
default_schema: str | None = None,
schemas: list[str] | None = None,
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
metadata_zip_path_or_uri: str | None = None,
databases: list[str] | None = None,
) -> str:
"""Generates the unified PostgreSQL export SQL script.
Each table section is introduced by a divider and a
`-- Unload Table: <SCHEMA>.<TABLE> -> Parquet` marker that the executor uses
to name the ./data_unload/[<SCHEMA>/]<TABLE>/ output directory.
Args:
metadata_path_or_uri: Path or Cloud Storage URI to translation metadata dir
or zip.
default_schema: Fallback schema when metadata omits it.
schemas: Optional schema allow-list (case-insensitive).
rtrim_char: Strip CHAR(n)/BPCHAR trailing pad spaces.
unbounded_number_scale: Fractional scale for unconstrained NUMERIC columns.
metadata_zip_path_or_uri: Optional path or Cloud Storage URI to an extractor
metadata.zip. Used alone, or alongside metadata_path_or_uri to restore
exact NUMERIC(p, s) and NOT NULL details in BQMS YAML configs.
databases: Optional database allow-list (case-insensitive), matched against
the database part of 3-part metadata names.
Returns:
A complete PostgreSQL SQL script string.
"""
all_metadata = _resolve_and_load_metadata(
metadata_path_or_uri, metadata_zip_path_or_uri
)
metadata = _select_databases(all_metadata, databases)
by_schema_table, by_table = _group_and_sort_columns(
metadata.get("columns", [])
)
schema_filter = {s.upper() for s in schemas} if schemas else None
tables = _filter_tables_to_export(
metadata.get("tables", []),
by_table,
schema_filter,
columns_by_schema_table=by_schema_table,
default_schema=default_schema or "",
)
if not tables and (schema_filter or databases):
rows = all_metadata.get("tables", []) or all_metadata.get("columns", [])
available = sorted(
{_strip(t.get("TableSchema")) or _strip(default_schema) for t in rows}
)
dbs = sorted({_strip(t.get("TableCatalog")) for t in rows} - {""})
print(
"WARNING: No tables match the --schema/--database filters. Available"
f" schemas: {', '.join(s for s in available if s) or '(none)'};"
f" databases: {', '.join(dbs) or '(none)'}.",
file=sys.stderr,
)
generator_name = (
os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] else ""
) or "export_postgres_tables_template.py"
lines = [
"-- " + "=" * 77,
"-- PostgreSQL to Parquet Type-Safe Data Export Script",
f"-- Generated by bigquery-migration-data-exporter / {generator_name}",
"-- Execute via psycopg2 and stream results to Snappy Parquet",
"-- " + "=" * 77,
"",
]
divider = "-- " + "-" * 77
for t in tables:
tbl = _strip(t.get("TableName"))
raw_schema = _strip(t.get("TableSchema"))
schema = raw_schema or _strip(default_schema)
cols = _lookup_table_columns(by_schema_table, raw_schema, schema, tbl)
stmt = _build_select_query(
t,
cols,
default_schema or "",
rtrim_char=rtrim_char,
unbounded_number_scale=unbounded_number_scale,
)
label = _sanitize_comment_token(f"{schema}.{tbl}" if schema else tbl)
lines.append(f"{divider}\n-- Unload Table: {label} -> Parquet\n{divider}")
required = [
_sanitize_comment_token(_strip(c.get("ColumnName")))
for c in cols
if _is_not_null(c) and _strip(c.get("ColumnName"))
]
if required:
lines.append(f"-- Required Columns: {','.join(required)}")
lines.append(stmt + "\n")
return "\n".join(lines)
# ==============================================================================
# 3. CLI Main Router (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: CLI argument parser and SQL file writer entrypoint.
def _parse_args(args: list[str] | None = None) -> argparse.Namespace:
"""Builds and parses CLI arguments for PostgreSQL export SQL generation."""
parser = argparse.ArgumentParser(
description="PostgreSQL Parquet Export SQL Generator (outputs .sql)."
)
parser.add_argument(
"--translation-metadata-dir",
"--translation-output",
"--metadata-dir",
"--config-dir",
dest="metadata_path",
help=(
"Path or Cloud Storage URI to translation_output/metadata directory"
" or config directory"
),
)
parser.add_argument(
"--metadata-zip",
dest="metadata_zip",
help=(
"Path or Cloud Storage URI to a PostgreSQL extractor metadata.zip."
" Use it alone, or with --translation-metadata-dir to restore exact"
" NUMERIC(p, s) and NOT NULL details in the BQMS YAML configs"
),
)
parser.add_argument(
"--output-sql", help="File path to write the unified export SQL script"
)
parser.add_argument(
"--output-dir",
help="Directory to write individual per-table *_export.sql files",
)
parser.add_argument(
"--default-schema",
dest="default_schema",
default=os.environ.get("PG_SCHEMA", ""),
help="Fallback source schema name (exact case) when omitted in metadata",
)
parser.add_argument(
"--schema",
action="append",
dest="schemas",
help="Only export tables in this schema (repeatable)",
)
parser.add_argument(
"--database",
action="append",
dest="databases",
help=(
"Only export tables from this PostgreSQL database (repeatable),"
" matched against the database part of 3-part metadata names;"
" tables without a database qualifier are kept"
),
)
parser.add_argument(
"--keep-char-padding",
action="store_true",
help="Do not RTRIM CHAR(n)/BPCHAR columns",
)
parser.add_argument(
"--unbounded-number-scale",
type=int,
default=9,
help=(
"Decimal scale (0..38) for unconstrained NUMERIC columns"
" (default: 9, supporting up to 29 integer digits)"
),
)
parsed = parser.parse_args(args)
if not parsed.metadata_path and not parsed.metadata_zip:
parser.error(
"one of --translation-metadata-dir or --metadata-zip is required."
)
if not 0 <= parsed.unbounded_number_scale <= 38:
parser.error("--unbounded-number-scale must be between 0 and 38.")
return parsed
def _sanitize_sql_filename(label: str, used_filenames: set[str]) -> str:
"""Builds a safe, collision-free per-table SQL filename."""
unquoted = label.replace('"', "").strip()
safe_parts = [
re.sub(r"[^A-Za-z0-9_-]+", "_", p.strip()).strip("_") or "table"
for p in unquoted.split(".")
if p.strip()
]
stem = "_".join(safe_parts) if safe_parts else "table"
filename = f"{stem}_export.sql"
if filename.upper() in used_filenames and len(safe_parts) > 1:
filename = f"{'__'.join(safe_parts)}_export.sql"
idx = 2
base_stem = filename[: -len("_export.sql")]
while filename.upper() in used_filenames:
filename = f"{base_stem}_{idx}_export.sql"
idx += 1
used_filenames.add(filename.upper())
return filename
def _write_table_sql_files(sql: str, output_dir: str) -> list[str]:
"""Splits the unified SQL script and writes individual table SQL files."""
os.makedirs(output_dir, exist_ok=True)
divider = "-- " + "-" * 77
chunks = sql.split(f"{divider}\n-- Unload Table: ")
written: list[str] = []
used_filenames: set[str] = set()
for chunk in chunks[1:]:
label = chunk.split(" -> Parquet")[0].strip()
filename = _sanitize_sql_filename(label, used_filenames)
path = os.path.join(output_dir, filename)
with open(path, "w", encoding="utf-8") as f:
f.write(f"{divider}\n-- Unload Table: {chunk}")
written.append(path)
print(f"Generated table export SQL: {path}")
return written
def main() -> None:
"""CLI entrypoint for the PostgreSQL Parquet export SQL generator."""
args = _parse_args()
sql = generate_export_sql(
metadata_path_or_uri=args.metadata_path,
default_schema=args.default_schema,
schemas=args.schemas,
rtrim_char=not args.keep_char_padding,
unbounded_number_scale=args.unbounded_number_scale,
metadata_zip_path_or_uri=args.metadata_zip,
databases=args.databases,
)
if (args.schemas or args.databases) and "-- Unload Table:" not in sql:
sys.exit("ERROR: No tables to export; check --schema/--database.")
if args.output_sql:
out_dir = os.path.dirname(os.path.abspath(args.output_sql))
os.makedirs(out_dir, exist_ok=True)
with open(args.output_sql, "w", encoding="utf-8") as f:
f.write(sql)
print(f"Generated unified export SQL: {args.output_sql}")
if args.output_dir:
_write_table_sql_files(sql, args.output_dir)
if not args.output_sql and not args.output_dir:
print(sql)
if __name__ == "__main__":
main()
export_snowflake_tables_template.py 37.2 KB
#!/usr/bin/env python3
r"""Template Script for Generating Type-Safe Snowflake COPY INTO Export SQL Files.
This asset template script provides a reference implementation for generating
type-safe Snowflake SQL export scripts (.sql) directly from BQMS
translation_output/metadata configs or metadata.zip archives. It has zero JDBC
or database connector dependencies.
Usage Pattern:
Copy `assets/export_snowflake_tables_template.py` from this skill's directory
(`<SKILL_DIR>`, the directory containing `SKILL.md`) into your
working directory (for example, `./export_snowflake_tables.py`). Run the copy
as-is for standard export SQL generation, and prioritize modifying the marked
`# CUSTOMIZE:` extension points if your environment requires custom type
projections, stage options, or table filtering. Sections marked
`# DEFAULT SCAFFOLDING` can be kept unchanged unless deeper orchestration
adjustments are needed.
Dependencies:
pip install pyyaml==6.0.2
Usage Examples:
# Copy the template from this skill's directory to your working directory:
cp <SKILL_DIR>/assets/export_snowflake_tables_template.py \
./export_snowflake_tables.py
# 1. Generate a unified Snowflake COPY INTO SQL file that unloads to Cloud
# Storage (Snowflake requires a storage integration for gcs:// URLs):
python3 ./export_snowflake_tables.py \
--translation-metadata-dir gs://my-bucket/translation_output/metadata/ \
--stage-path 'gcs://my-bucket/data_unload/' \
--storage-integration my_gcs_integration \
--output-sql snowflake_export.sql
# 2. Generate per-table Snowflake COPY INTO SQL files in a directory:
python3 ./export_snowflake_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--stage-path '@~/bqms_export/' \
--output-dir ./export_sql
"""
from __future__ import annotations
import argparse
import csv
import io
import os
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
import yaml
# ==============================================================================
# 1. File & Metadata Loading Functions (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Deterministic metadata loading and archive parsing.
def read_file_or_gcs(path_or_uri: str) -> bytes:
"""Reads content from a local file path or a Cloud Storage URI.
Args:
path_or_uri: Local file path or Cloud Storage URI (starts with 'gs://').
Returns:
The content of the file as bytes.
Raises:
FileNotFoundError: If the local file does not exist.
RuntimeError: If gcloud storage fails to read from Cloud Storage.
"""
if path_or_uri.startswith("gs://"):
cmd = ["gcloud", "storage", "cat", path_or_uri]
try:
return subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
raise RuntimeError(
f"Failed to read from Cloud Storage '{path_or_uri}': {e}"
) from e
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot read '{path_or_uri}': the gcloud CLI was not found. Install"
" the Google Cloud CLI, or download the file and pass a local path."
) from e
else:
if not os.path.exists(path_or_uri):
raise FileNotFoundError(f"Local file not found: '{path_or_uri}'")
with open(path_or_uri, "rb") as f:
return f.read()
def _run_gcloud_copy(cmd: list[str], uri: str) -> None:
"""Runs a `gcloud storage cp` command, surfacing its stderr on failure."""
try:
subprocess.run(cmd, capture_output=True, check=True)
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot copy '{uri}': the gcloud CLI was not found. Install the"
" Google Cloud CLI, or copy the files locally and pass a local path."
) from e
except subprocess.CalledProcessError as e:
stderr = (e.stderr or b"").decode("utf-8", errors="replace").strip()
raise RuntimeError(
f"Failed to copy from Cloud Storage '{uri}' (exit code"
f" {e.returncode}): {stderr or e}"
) from e
def load_metadata_from_zip(
zip_bytes: bytes,
) -> dict[str, list[dict[str, str]]]:
"""Extracts table and column metadata from a metadata.zip archive.
Reads tables-au.csv (or tables.csv) and columns-au.csv (or columns.csv)
contained within the zipped metadata payload.
Args:
zip_bytes: Raw bytes of the metadata zip archive.
Returns:
A dictionary containing 'tables' and 'columns' lists of records.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as z:
by_base = {os.path.basename(n).lower(): n for n in z.namelist()}
for key, candidates in (
("tables", ("tables-au.csv", "tables.csv")),
("columns", ("columns-au.csv", "columns.csv")),
):
member = next((by_base[c] for c in candidates if c in by_base), None)
if member:
with z.open(member) as fh:
reader = csv.DictReader(io.TextIOWrapper(fh, encoding="utf-8-sig"))
result[key] = list(reader)
return result
def _str_or_empty(value: object) -> str:
"""Converts a metadata value to a stripped string, mapping None to ''."""
return "" if value is None else str(value).strip()
def load_metadata_from_config_dir(
config_dir: str,
) -> dict[str, list[dict[str, str]]]:
"""Loads table/column metadata from BQMS metadata/config/*.yaml files.
Args:
config_dir: Local path to the BQMS metadata config directory.
Returns:
A dictionary containing 'tables' and 'columns' metadata parsed from YAMLs.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
if not os.path.isdir(config_dir):
return result
for root, _, files in os.walk(config_dir):
for f in sorted(files):
if f.endswith(".yaml") or f.endswith(".yml"):
fpath = os.path.join(root, f)
try:
with open(fpath, "r", encoding="utf-8") as yf:
cfg = yaml.safe_load(yf)
except (yaml.YAMLError, OSError):
continue
if not isinstance(cfg, dict):
continue
src_name = cfg.get("sourceName", "")
parts = src_name.split(".") if src_name else []
db = parts[0] if len(parts) > 2 else ""
# BQMS writes __DEFAULT_DATABASE__ when the source database is unknown;
# leave it empty so --default-database or the session database applies.
if db == "__DEFAULT_DATABASE__":
db = ""
schema = (
parts[1] if len(parts) > 2 else (parts[0] if len(parts) > 1 else "")
)
table = parts[-1] if parts else f.rsplit(".", 1)[0].upper()
is_view = not bool(
cfg.get("externalTableName") or cfg.get("externalTableDdlPath")
)
result["tables"].append({
"TableCatalog": db,
"TableSchema": schema,
"TableName": table,
"TableType": "VIEW" if is_view else "BASE TABLE",
})
for idx, col in enumerate(cfg.get("columns") or [], start=1):
if not isinstance(col, dict):
continue
col_name = col.get("sourceName", "")
# `sourceType: null` / `targetType: null` load as None; treat them
# as empty instead of the literal string "None".
src_type = col.get("sourceType") or {}
tgt_type = col.get("targetType") or {}
src = src_type if isinstance(src_type, dict) else {}
tgt = tgt_type if isinstance(tgt_type, dict) else {}
# Prefer the raw Snowflake type (`name`, such as TIMESTAMP_LTZ or
# VARIANT) over the BQMS genericName (TIMESTAMPTZ or JSON), which
# drops the time zone kind.
gen_name = (
str(src.get("name") or src.get("genericName") or "VARCHAR")
if isinstance(src_type, dict)
else str(src_type)
)
precision = _str_or_empty(src.get("precision"))
scale = _str_or_empty(src.get("scale"))
tgt_name = (
_str_or_empty(tgt.get("name"))
if isinstance(tgt_type, dict)
else str(tgt_type)
)
result["columns"].append({
"TableCatalog": db,
"TableSchema": schema,
"TableName": table,
"ColumnName": col_name,
"OrdinalPosition": str(idx),
"DataType": gen_name,
"NumericPrecision": precision,
"NumericScale": scale,
"TargetType": tgt_name,
})
return result
def _find_config_dir(dir_path: str) -> str | None:
"""Locates the directory containing BQMS table YAML configurations."""
metadata_config = os.path.join(dir_path, "metadata", "config")
if os.path.isdir(metadata_config):
return metadata_config
plain_config = os.path.join(dir_path, "config")
if os.path.isdir(plain_config):
return plain_config
for _, _, files in os.walk(dir_path):
for f in files:
if f.endswith(".yaml") or f.endswith(".yml"):
return dir_path
return None
def load_metadata_from_dir(dir_path: str) -> dict[str, list[dict[str, str]]]:
"""Discovers and extracts metadata from a directory or embedded zip archive.
Scans for BQMS YAML configuration directories ('metadata/config' or 'config')
and falls back to any embedded metadata zip archives if no YAML files are
found.
Args:
dir_path: Local filesystem path to inspect.
Returns:
A dictionary containing 'tables' and 'columns' lists of records.
"""
config_dir = _find_config_dir(dir_path)
if config_dir:
res = load_metadata_from_config_dir(config_dir)
if res["tables"] and res["columns"]:
return res
for root, _, files in os.walk(dir_path):
for f in files:
if f.endswith(".zip") and "metadata" in f:
with open(os.path.join(root, f), "rb") as zf:
return load_metadata_from_zip(zf.read())
return {"tables": [], "columns": []}
def _resolve_and_load_metadata(
path_or_uri: str | None,
) -> dict[str, list[dict[str, str]]]:
"""Resolves local or Cloud Storage metadata and loads metadata dicts."""
if not path_or_uri:
return {"tables": [], "columns": []}
if path_or_uri.startswith("gs://"):
if path_or_uri.endswith(".zip"):
zip_bytes = read_file_or_gcs(path_or_uri)
return load_metadata_from_zip(zip_bytes)
temp_dir = tempfile.mkdtemp(prefix="bqms_meta_")
try:
cmd = [
"gcloud",
"storage",
"cp",
"-r",
path_or_uri.rstrip("/") + "/*",
temp_dir,
]
_run_gcloud_copy(cmd, path_or_uri)
return load_metadata_from_dir(temp_dir)
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
elif os.path.isdir(path_or_uri):
return load_metadata_from_dir(path_or_uri)
else:
zip_bytes = read_file_or_gcs(path_or_uri)
return load_metadata_from_zip(zip_bytes)
def _table_key(meta: dict[str, str]) -> tuple[str, str, str]:
"""Returns the upper-cased (database, schema, table) key for a record."""
return (
_str_or_empty(meta.get("TableCatalog")).upper(),
_str_or_empty(meta.get("TableSchema")).upper(),
_str_or_empty(meta.get("TableName")).upper(),
)
def _group_and_sort_columns(
columns: list[dict[str, str]],
) -> tuple[
dict[tuple[str, str, str], list[dict[str, str]]],
dict[str, list[dict[str, str]]],
]:
"""Groups columns by (database, schema, table) and by table name, sorted."""
columns_by_qualified_table: dict[
tuple[str, str, str], list[dict[str, str]]
] = {}
columns_by_table: dict[str, list[dict[str, str]]] = {}
for col in columns:
columns_by_qualified_table.setdefault(_table_key(col), []).append(col)
for (_, _, tbl), cols in columns_by_qualified_table.items():
cols.sort(
key=lambda x: (
int(x.get("OrdinalPosition", "0"))
if x.get("OrdinalPosition", "").isdigit()
else 9999
)
)
if tbl not in columns_by_table:
columns_by_table[tbl] = cols
return columns_by_qualified_table, columns_by_table
def _lookup_table_columns(
table_key: tuple[str, str, str],
columns_by_qualified_table: dict[
tuple[str, str, str], list[dict[str, str]]
],
resolved_key: tuple[str, str, str] | None = None,
) -> list[dict[str, str]]:
"""Finds a table's columns by (database, schema, table), then looser keys.
Args:
table_key: Upper-cased (database, schema, table) key as written in the table
metadata.
columns_by_qualified_table: Columns grouped by upper-cased key.
resolved_key: Optional key with --default-database / --default-schema filled
in, matching the FROM clause.
Returns:
The matching columns, or an empty list (SELECT *) when no single match.
"""
for key in (table_key, resolved_key):
if key and columns_by_qualified_table.get(key):
return columns_by_qualified_table[key]
db_name, schema_name, tbl_name = resolved_key or table_key
# Fall back to a looser match only when one side omits the database or
# schema name, and only when exactly one table matches. Never borrow columns
# from a same-named table in a different database or schema.
matches = [
cand
for (
col_db,
col_schema,
col_tbl,
), cand in columns_by_qualified_table.items()
if cand
and col_tbl == tbl_name
and (col_schema == schema_name or not col_schema or not schema_name)
and (col_db == db_name or not col_db or not db_name)
]
return matches[0] if len(matches) == 1 else []
# CUSTOMIZE: Table & Row Filtering — Edit _filter_tables_to_export() to add
# custom schema/table inclusion or exclusion rules.
def _resolved_table_key(
meta: dict[str, str],
default_database: str | None = None,
default_schema: str | None = None,
) -> tuple[str, str, str]:
"""Returns the table key with the CLI database and schema defaults applied."""
db_name, schema_name, tbl_name = _table_key(meta)
return (
db_name or _str_or_empty(default_database).upper(),
schema_name or _str_or_empty(default_schema).upper(),
tbl_name,
)
def _filter_tables_to_export(
raw_tables: list[dict[str, str]],
columns_by_table: dict[str, list[dict[str, str]]],
columns_by_qualified_table: (
dict[tuple[str, str, str], list[dict[str, str]]] | None
) = None,
default_database: str | None = None,
default_schema: str | None = None,
) -> list[dict[str, str]]:
"""Drops views and deduplicates tables by (database, schema, table)."""
tables_to_export: list[dict[str, str]] = []
seen_exported_tables: set[tuple[str, str, str]] = set()
if raw_tables:
for t in raw_tables:
table_key = _resolved_table_key(t, default_database, default_schema)
tbl_type = t.get("TableType", "").upper()
if tbl_type and "VIEW" in tbl_type:
continue
if table_key in seen_exported_tables:
continue
seen_exported_tables.add(table_key)
tables_to_export.append(t)
elif columns_by_qualified_table:
# No table list (for example, columns.csv without tables.csv): keep every
# (database, schema, table) group, with the names as written in metadata.
for cols in columns_by_qualified_table.values():
if not cols:
continue
entry = {"TableName": _str_or_empty(cols[0].get("TableName"))}
for field in ("TableCatalog", "TableSchema"):
if _str_or_empty(cols[0].get(field)):
entry[field] = _str_or_empty(cols[0].get(field))
tables_to_export.append(entry)
else:
candidate_tables = list(columns_by_table.keys()) if columns_by_table else []
for tbl_name in candidate_tables:
if ("", "", tbl_name) in seen_exported_tables:
continue
seen_exported_tables.add(("", "", tbl_name))
tables_to_export.append({"TableName": tbl_name})
return tables_to_export
# ==============================================================================
# 2. Type-Safe SQL Generation Logic
# ==============================================================================
_VALID_IDENT_REGEX = re.compile(r"^[A-Z_][A-Z0-9_$]*$")
_PARAM_TYPE_REGEX = re.compile(
r"^(?P<base>[A-Z_]+)\s*\(\s*(?P<p>\d+)(?:\s*,\s*(?P<s>\d+))?\s*\)$"
)
_DATETIME_PREFIXES = ("DATETIME", "TIMESTAMP")
_INT_TYPES = frozenset(
("INT", "INTEGER", "BIGINT", "SMALLINT", "TINYINT", "BYTEINT")
)
_INT_TARGET_TYPES = frozenset(
("INT64", "INT", "INTEGER", "BIGINT", "SMALLINT", "TINYINT", "BYTEINT")
)
_FLOAT_TYPES = frozenset(
("FLOAT", "FLOAT4", "FLOAT8", "DOUBLE", "DOUBLE PRECISION", "REAL")
)
_TIMESTAMP_PREFIXES = (
"TIMESTAMP",
"TIMESTAMP_LTZ",
"TIMESTAMP_TZ",
"TIMESTAMP_NTZ",
"DATETIME",
)
_BOOLEAN_TYPES = frozenset(("BOOLEAN", "BOOL"))
_BINARY_TYPES = frozenset(("BINARY", "VARBINARY", "BYTES"))
_VARIANT_TYPES = frozenset(("VARIANT", "OBJECT", "ARRAY", "JSON"))
# Time zone-aware spellings (including the BQMS genericName TIMESTAMPTZ) that
# are converted to UTC before the TIMESTAMP_NTZ cast.
_TZ_TIMESTAMP_ALIASES = {
"TIMESTAMPTZ": "TIMESTAMP_TZ",
"TIMESTAMP WITH TIME ZONE": "TIMESTAMP_TZ",
"TIMESTAMPLTZ": "TIMESTAMP_LTZ",
"TIMESTAMP WITH LOCAL TIME ZONE": "TIMESTAMP_LTZ",
}
_NUMBER_TYPES = frozenset(("NUMBER", "DECIMAL", "NUMERIC"))
# Snowflake reserved keywords; upper-case identifiers matching these are quoted:
# https://docs.snowflake.com/en/sql-reference/reserved-keywords
_SNOWFLAKE_RESERVED = frozenset((
"ACCOUNT",
"ALL",
"ALTER",
"AND",
"ANY",
"AS",
"BETWEEN",
"BY",
"CASE",
"CAST",
"CHECK",
"COLUMN",
"CONNECT",
"CONNECTION",
"CONSTRAINT",
"CREATE",
"CROSS",
"CURRENT",
"CURRENT_DATE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_USER",
"DATABASE",
"DELETE",
"DISTINCT",
"DROP",
"ELSE",
"EXISTS",
"FALSE",
"FOLLOWING",
"FOR",
"FROM",
"FULL",
"GRANT",
"GROUP",
"GSCLUSTER",
"HAVING",
"ILIKE",
"IN",
"INCREMENT",
"INNER",
"INSERT",
"INTERSECT",
"INTO",
"IS",
"ISSUE",
"JOIN",
"LATERAL",
"LEFT",
"LIKE",
"LOCALTIME",
"LOCALTIMESTAMP",
"MINUS",
"NATURAL",
"NOT",
"NULL",
"OF",
"ON",
"OR",
"ORDER",
"ORGANIZATION",
"QUALIFY",
"REGEXP",
"REVOKE",
"RIGHT",
"RLIKE",
"ROW",
"ROWS",
"SAMPLE",
"SCHEMA",
"SELECT",
"SET",
"SOME",
"START",
"TABLE",
"TABLESAMPLE",
"THEN",
"TO",
"TRIGGER",
"TRUE",
"TRY_CAST",
"UNION",
"UNIQUE",
"UPDATE",
"USING",
"VALUES",
"VIEW",
"WHEN",
"WHENEVER",
"WHERE",
"WINDOW",
"WITH",
))
# DEFAULT SCAFFOLDING: Identifier quoting helper.
def quote_ident(ident: str) -> str:
"""Quotes an identifier with double quotes if needed for Snowflake.
Identifiers starting with digits, containing lowercase or special characters,
or matching reserved words are safely enclosed in double quotes.
Args:
ident: The raw SQL identifier string.
Returns:
The properly quoted or unquoted identifier.
"""
if not ident:
return ""
if len(ident) >= 2 and ident.startswith('"') and ident.endswith('"'):
# Already quoted: re-escape any bare inner double quotes.
inner = ident[1:-1].replace('""', '"').replace('"', '""')
return f'"{inner}"'
if (
ident[0].isdigit()
or not _VALID_IDENT_REGEX.match(ident)
or ident in _SNOWFLAKE_RESERVED
):
escaped = ident.replace('"', '""')
return f'"{escaped}"'
return ident
def _to_int(value: object) -> int | None:
"""Parses a non-negative integer metadata value, preserving integer 0."""
text = _str_or_empty(value)
return int(text) if text.isdigit() else None
def _escape_sql_literal(value: str) -> str:
"""Escapes backslashes and single quotes for a Snowflake string literal."""
return value.replace("\\", "\\\\").replace("'", "''")
def _sanitize_comment_token(value: str) -> str:
"""Replaces control characters so SQL line comments stay single-line."""
return re.sub(r"[\x00-\x1f\x7f]+", " ", str(value)).strip()
# CUSTOMIZE: Custom Type Projections — Edit format_column_cast() to add custom
# data type mappings, precision bounds, or JSON/geography serialization formats.
def format_column_cast(
col: dict[str, str], target_bq_type: str | None = None
) -> str:
"""Generates a type-safe Snowflake projection expression for Parquet export.
Applies explicit type casting (for example, TO_VARCHAR for VARIANT/JSON,
TIMESTAMP_NTZ(6) for timestamps, DECIMAL(p, s) for numerics) to guarantee
zero type drift during downstream BigQuery ingestion.
Args:
col: Column metadata dictionary containing DataType, NumericPrecision, etc.
target_bq_type: Optional target BigQuery type override.
Returns:
A SQL projection expression string, such as 'CAST(ID AS BIGINT) AS ID'.
"""
col_raw = str(col.get("ColumnName") or "").strip()
col_name = quote_ident(col_raw)
raw_data_type = str(col.get("DataType") or "").upper().strip()
precision = _to_int(col.get("NumericPrecision"))
scale = _to_int(col.get("NumericScale"))
param_match = _PARAM_TYPE_REGEX.match(raw_data_type)
if param_match:
data_type = param_match.group("base")
if precision is None:
precision = int(param_match.group("p"))
if scale is None:
if param_match.group("s") is not None:
scale = int(param_match.group("s"))
elif data_type in _NUMBER_TYPES:
scale = 0
else:
data_type = re.split(r"[(\s]", raw_data_type, maxsplit=1)[0].strip()
# TIMESTAMPTZ, TIMESTAMP(9) WITH LOCAL TIME ZONE, etc. keep the
# CONVERT_TIMEZONE('UTC', ...) projection of TIMESTAMP_TZ / TIMESTAMP_LTZ.
tz_key = " ".join(re.sub(r"\(\s*\d+\s*\)", " ", raw_data_type).split())
data_type = _TZ_TIMESTAMP_ALIASES.get(tz_key, data_type)
target = target_bq_type or col.get("TargetType")
if target:
tgt = target.upper().strip()
tgt_base = re.split(r"[(<]", tgt, maxsplit=1)[0].strip()
if any(tgt.startswith(p) for p in _DATETIME_PREFIXES):
if data_type in ("TIMESTAMP_TZ", "TIMESTAMP_LTZ"):
return (
f"CAST(CONVERT_TIMEZONE('UTC', {col_name}) AS TIMESTAMP_NTZ(6))"
f" AS {col_name}"
)
return f"CAST({col_name} AS TIMESTAMP_NTZ(6)) AS {col_name}"
if tgt.startswith("JSON"):
return f"TO_VARCHAR({col_name}) AS {col_name}"
if tgt_base in _INT_TARGET_TYPES:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if tgt.startswith("FLOAT") or tgt.startswith("DOUBLE"):
return f"CAST({col_name} AS DOUBLE) AS {col_name}"
if tgt.startswith("BYTES"):
return f"CAST({col_name} AS BINARY) AS {col_name}"
if (
tgt.startswith("NUMERIC")
or tgt.startswith("BIGNUMERIC")
or tgt.startswith("DECIMAL")
):
# Snowflake DECIMAL(p, s) requires 1 <= p <= 38 and 0 <= s <= p.
if precision is not None:
p_val = min(max(precision, 1), 38)
elif data_type in _INT_TYPES and not tgt.startswith("BIGNUMERIC"):
# BigQuery NUMERIC (alias DECIMAL) holds at most 29 integer digits.
p_val = 29
else:
p_val = 38
if scale is not None:
s_val = min(scale, p_val)
elif data_type in _INT_TYPES:
s_val = 0
else:
s_val = min(9, p_val)
return f"CAST({col_name} AS DECIMAL({p_val}, {s_val})) AS {col_name}"
if tgt.startswith("STRING"):
if data_type in ("TIMESTAMP_TZ", "TIMESTAMP_LTZ"):
# CONVERT_TIMEZONE returns TIMESTAMP_TZ, which uses the session's
# TIMESTAMP_TZ_OUTPUT_FORMAT (FF6) set in the script header.
return f"TO_VARCHAR(CONVERT_TIMEZONE('UTC', {col_name})) AS {col_name}"
return f"TO_VARCHAR({col_name}) AS {col_name}"
if tgt in _BOOLEAN_TYPES:
return f"CAST({col_name} AS BOOLEAN) AS {col_name}"
if tgt in ("DATE", "TIME"):
cast_type = "DATE" if tgt == "DATE" else "TIME(6)"
if data_type in ("TIMESTAMP_TZ", "TIMESTAMP_LTZ"):
return (
f"CAST(CONVERT_TIMEZONE('UTC', {col_name}) AS {cast_type})"
f" AS {col_name}"
)
return f"CAST({col_name} AS {cast_type}) AS {col_name}"
if data_type in _VARIANT_TYPES:
return f"TO_VARCHAR({col_name}) AS {col_name}"
if data_type in _INT_TYPES:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if data_type in _NUMBER_TYPES:
p_val = (
min(precision, 38) if precision is not None and precision > 0 else 38
)
if scale is None:
# Cap the default fractional scale at the precision (DECIMAL(5, 9) is
# invalid in Snowflake).
s_val = min(9, p_val)
return f"CAST({col_name} AS DECIMAL({p_val}, {s_val})) AS {col_name}"
if scale == 0:
if precision is not None and 1 <= precision <= 19:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
return f"CAST({col_name} AS DECIMAL({p_val}, 0)) AS {col_name}"
s_val = min(scale, p_val)
return f"CAST({col_name} AS DECIMAL({p_val}, {s_val})) AS {col_name}"
if data_type in _FLOAT_TYPES:
return f"CAST({col_name} AS DOUBLE) AS {col_name}"
if data_type in ("TIMESTAMP_TZ", "TIMESTAMP_LTZ"):
return (
f"CAST(CONVERT_TIMEZONE('UTC', {col_name}) AS TIMESTAMP_NTZ(6))"
f" AS {col_name}"
)
if any(data_type.startswith(t) for t in _TIMESTAMP_PREFIXES):
return f"CAST({col_name} AS TIMESTAMP_NTZ(6)) AS {col_name}"
if data_type == "TIME":
return f"CAST({col_name} AS TIME(6)) AS {col_name}"
if data_type == "DATE":
return f"CAST({col_name} AS DATE) AS {col_name}"
if data_type in _BOOLEAN_TYPES:
return f"CAST({col_name} AS BOOLEAN) AS {col_name}"
# Keep BINARY/VARBINARY as raw bytes (Parquet BYTE_ARRAY -> BigQuery BYTES);
# a VARCHAR cast would hex-encode values per BINARY_OUTPUT_FORMAT.
if data_type in _BINARY_TYPES:
return f"CAST({col_name} AS BINARY) AS {col_name}"
return f"CAST({col_name} AS VARCHAR) AS {col_name}"
# DEFAULT SCAFFOLDING: Table name qualification helper.
def _build_qualified_table_name(
table_meta: dict[str, str],
default_database: str = "",
default_schema: str = "",
) -> str:
"""Builds a quoted fully-qualified table name (such as MY_DB.MY_SCHEMA.MY_TBL).
Args:
table_meta: Table metadata dictionary containing TableName, TableCatalog,
etc.
default_database: Fallback database name if omitted in table_meta.
default_schema: Fallback schema name if omitted in table_meta.
Returns:
The quoted fully-qualified table identifier string.
"""
tbl_name = table_meta.get("TableName", "")
db_name = table_meta.get("TableCatalog") or default_database or ""
schema_name = table_meta.get("TableSchema") or default_schema or ""
if db_name and schema_name:
return (
f"{quote_ident(db_name)}."
f"{quote_ident(schema_name)}.{quote_ident(tbl_name)}"
)
elif schema_name:
return f"{quote_ident(schema_name)}.{quote_ident(tbl_name)}"
return quote_ident(tbl_name)
# CUSTOMIZE: Stage & Storage Configuration — Edit _build_copy_into_query() to
# customize COPY INTO FILE_FORMAT options (MAX_FILE_SIZE, compression codecs,
# encryption flags) or add WHERE predicates. Pass the storage integration name
# with --storage-integration instead of editing this function.
def _build_copy_into_query(
table_meta: dict[str, str],
columns: list[dict[str, str]],
stage_target: str,
default_database: str = "",
default_schema: str = "",
storage_integration: str | None = None,
) -> str:
"""Builds the COPY INTO Parquet SQL statement for a single table."""
if stage_target.startswith("'gs://"):
stage_target = "'gcs://" + stage_target[len("'gs://") :]
elif stage_target.startswith("gs://"):
stage_target = "gcs://" + stage_target[len("gs://") :]
qualified_src = _build_qualified_table_name(
table_meta, default_database, default_schema
)
if columns:
col_projections = [f" {format_column_cast(c)}" for c in columns]
select_body = ",\n".join(col_projections)
query_from = f"(\n SELECT\n{select_body}\n FROM {qualified_src}\n )"
else:
query_from = qualified_src
integration_clause = (
f"\n STORAGE_INTEGRATION = {storage_integration}"
if storage_integration
else ""
)
return f"""COPY INTO {stage_target}
FROM {query_from}{integration_clause}
FILE_FORMAT = (
TYPE = PARQUET
COMPRESSION = SNAPPY
)
HEADER = TRUE
OVERWRITE = TRUE
MAX_FILE_SIZE = 104857600;"""
# DEFAULT SCAFFOLDING: Primary SQL script generator and orchestration.
def generate_export_sql(
metadata_path_or_uri: str | None = None,
stage_path: str = "",
default_database: str | None = None,
default_schema: str | None = None,
storage_integration: str | None = None,
metadata_zip_path_or_uri: str | None = None,
) -> str:
"""Generates the primary Snowflake COPY INTO Parquet SQL script.
Args:
metadata_path_or_uri: Path or Cloud Storage URI to translation metadata
directory or zip.
stage_path: Destination internal stage or Cloud Storage stage path.
default_database: Optional fallback database name if omitted in metadata.
default_schema: Optional fallback schema name if omitted in metadata.
storage_integration: Optional Snowflake STORAGE_INTEGRATION name for Cloud
Storage/S3.
metadata_zip_path_or_uri: Optional path or Cloud Storage URI to a
metadata.zip archive.
Returns:
A complete, formatted Snowflake SQL script string ready for execution.
"""
path_to_use = metadata_path_or_uri or metadata_zip_path_or_uri
metadata = _resolve_and_load_metadata(path_to_use)
columns_by_qualified_table, columns_by_table = _group_and_sort_columns(
metadata.get("columns", [])
)
tables_to_export = _filter_tables_to_export(
metadata.get("tables", []),
columns_by_table,
columns_by_qualified_table=columns_by_qualified_table,
default_database=default_database,
default_schema=default_schema,
)
generator_name = (
os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] else ""
) or "export_snowflake_tables_template.py"
sql_lines = [
"-- " + "=" * 77,
"-- Snowflake to Parquet Type-Safe Data Export Script",
f"-- Generated by bigquery-migration-data-exporter / {generator_name}",
"-- " + "=" * 77,
"",
"-- Ensure clean Parquet export settings",
"ALTER SESSION SET TIME_OUTPUT_FORMAT = 'HH24:MI:SS.FF6';",
(
"ALTER SESSION SET TIMESTAMP_NTZ_OUTPUT_FORMAT = 'YYYY-MM-DD"
" HH24:MI:SS.FF6';"
),
(
"ALTER SESSION SET TIMESTAMP_TZ_OUTPUT_FORMAT = 'YYYY-MM-DD"
" HH24:MI:SS.FF6 TZHTZM';"
),
"",
]
clean_stage = stage_path.strip().strip("'").rstrip("/")
if clean_stage.startswith("gs://"):
clean_stage = "gcs://" + clean_stage[len("gs://") :]
# Prefix stage subpaths and labels with the database only when the metadata
# spans several databases, so identical SCHEMA.TABLE names in different
# databases do not overwrite each other's unload location. Tables without a
# TableCatalog count as --default-database, matching the FROM clause.
fallback_db = _str_or_empty(default_database)
multi_database = (
len(
{
_str_or_empty(t.get("TableCatalog")).upper()
or fallback_db.upper()
for t in tables_to_export
}
- {""}
)
> 1
)
for t in tables_to_export:
tbl_name = t.get("TableName", "")
db_name = _str_or_empty(t.get("TableCatalog")) or fallback_db
schema_name = t.get("TableSchema") or default_schema or ""
cols = _lookup_table_columns(
_table_key(t),
columns_by_qualified_table,
resolved_key=_resolved_table_key(t, default_database, default_schema),
)
path_parts = [schema_name, tbl_name] if schema_name else [tbl_name]
if multi_database and db_name:
path_parts.insert(0, db_name)
subpath = "/".join(path_parts)
stage_root = clean_stage or "@~/bqms_export"
dest_uri = "'" + _escape_sql_literal(f"{stage_root}/{subpath}/") + "'"
stmt = _build_copy_into_query(
t,
cols,
stage_target=dest_uri,
default_database=default_database or "",
default_schema=default_schema or "",
storage_integration=storage_integration,
)
table_label = ".".join(_sanitize_comment_token(p) for p in path_parts)
divider = "-- " + "-" * 77
sql_lines.append(
f"{divider}\n-- Unload Table: {table_label} ->"
f" Parquet\n{divider}\n{stmt}\n"
)
return "\n".join(sql_lines)
# ==============================================================================
# 3. CLI Main Router (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: CLI argument parser and SQL file writer entrypoint.
def _parse_args(args: list[str] | None = None) -> argparse.Namespace:
"""Builds and parses CLI arguments for Snowflake Parquet export SQL generation."""
parser = argparse.ArgumentParser(
description=(
"Snowflake Parquet Export SQL Generator (outputs .sql scripts)."
)
)
parser.add_argument(
"--translation-metadata-dir",
"--translation-output",
"--metadata-dir",
"--config-dir",
"--metadata-zip",
dest="metadata_path",
required=True,
help=(
"Path or Cloud Storage URI to translation_output/metadata directory,"
" config directory, or metadata.zip archive"
),
)
parser.add_argument(
"--stage-path",
default="",
help=(
"Destination stage or Cloud Storage URI (for example,"
" 'gcs://my-bucket/data_unload/' or '@~/bqms_export/'). Defaults to"
" '@~/bqms_export/'."
),
)
parser.add_argument(
"--output-sql",
help="File path to write the unified export SQL script",
)
parser.add_argument(
"--output-dir",
help="Directory to write individual per-table *_export.sql files",
)
parser.add_argument(
"--default-database",
default=os.environ.get("SNOWFLAKE_DATABASE", ""),
help="Fallback source database name when omitted in metadata",
)
parser.add_argument(
"--default-schema",
default=os.environ.get("SNOWFLAKE_SCHEMA", ""),
help="Fallback source schema name when omitted in metadata",
)
parser.add_argument(
"--storage-integration",
help=(
"Snowflake STORAGE_INTEGRATION name for Cloud Storage/S3. Required"
" when --stage-path is a 'gcs://' (or 'gs://') URL, because"
" Snowflake authorizes direct unloads to private Cloud Storage"
" buckets only through a storage integration."
),
)
return parser.parse_args(args)
def _sanitize_sql_filename(label: str, used_filenames: set[str]) -> str:
"""Builds a safe, collision-free per-table SQL filename."""
unquoted = label.replace('"', "").strip()
safe_parts = [
re.sub(r"[^A-Za-z0-9_-]+", "_", p.strip()).strip("_") or "table"
for p in unquoted.split(".")
if p.strip()
]
stem = "_".join(safe_parts) if safe_parts else "table"
filename = f"{stem}_export.sql"
if filename.upper() in used_filenames and len(safe_parts) > 1:
filename = f"{'__'.join(safe_parts)}_export.sql"
idx = 2
base_stem = filename[: -len("_export.sql")]
while filename.upper() in used_filenames:
filename = f"{base_stem}_{idx}_export.sql"
idx += 1
used_filenames.add(filename.upper())
return filename
def _write_table_sql_files(sql: str, output_dir: str) -> list[str]:
"""Splits the unified SQL script and writes individual table SQL files."""
os.makedirs(output_dir, exist_ok=True)
divider = "-- " + "-" * 77
stmts = sql.split(f"{divider}\n-- Unload Table: ")
session_lines = [
line
for line in stmts[0].splitlines()
if line.strip().upper().startswith("ALTER SESSION")
]
session_header = "\n".join(session_lines) + "\n\n" if session_lines else ""
written_paths: list[str] = []
used_filenames: set[str] = set()
for chunk in stmts[1:]:
table_label = chunk.split(" -> Parquet")[0].strip()
filename = _sanitize_sql_filename(table_label, used_filenames)
table_sql = f"{session_header}{divider}\n-- Unload Table: {chunk}"
tbl_path = os.path.join(output_dir, filename)
with open(tbl_path, "w", encoding="utf-8") as f:
f.write(table_sql)
written_paths.append(tbl_path)
print(f"Generated table export SQL: {tbl_path}")
return written_paths
def main() -> None:
"""CLI entrypoint for the Snowflake Parquet export SQL generator."""
args = _parse_args()
stage_lower = args.stage_path.strip().strip("'").lower()
if (
stage_lower.startswith(("gcs://", "gs://"))
and not args.storage_integration
):
print(
"WARNING: --stage-path is a Cloud Storage URL but"
" --storage-integration is not set. Snowflake requires a"
" STORAGE_INTEGRATION to authorize direct 'gcs://' unloads to"
" private buckets.",
file=sys.stderr,
)
sql = generate_export_sql(
metadata_path_or_uri=args.metadata_path,
stage_path=args.stage_path,
default_database=args.default_database,
default_schema=args.default_schema,
storage_integration=args.storage_integration,
)
if args.output_sql:
out_dir = os.path.dirname(os.path.abspath(args.output_sql))
if out_dir:
os.makedirs(out_dir, exist_ok=True)
with open(args.output_sql, "w", encoding="utf-8") as f:
f.write(sql)
print(f"Generated unified Snowflake export script: {args.output_sql}")
if args.output_dir:
_write_table_sql_files(sql, args.output_dir)
if not args.output_sql and not args.output_dir:
print(sql)
if __name__ == "__main__":
main()
export_teradata_tables_template.py 42.4 KB
#!/usr/bin/env python3
r"""Template Script for Generating Type-Safe Teradata Export SQL Files.
This asset template script provides a reference implementation for generating
type-safe Teradata SELECT export scripts (.sql) directly from BQMS
translation_output/metadata configs or a Teradata extractor metadata.zip
(dbc.TablesV.csv / dbc.ColumnsV.csv). It has zero JDBC or database connector
dependencies.
Teradata has no native "unload to Parquet" statement (WRITE_NOS requires
Teradata 17.0+ with NOS configured, and FastExport emits text/binary files).
The export therefore happens in two steps:
1. This script emits one explicit-cast SELECT per table. The casts pin every
column to a type whose Parquet representation BigQuery loads without drift
(BIGINT -> INT64, DECIMAL(p,s) -> NUMERIC/BIGNUMERIC, TIMESTAMP(6) ->
TIMESTAMP/DATETIME, TIMESTAMP WITH TIME ZONE normalized to UTC, CHAR
padding trimmed).
2. A downstream Python execution script runs each SELECT via the
`teradatasql` driver, derives the Arrow schema from the result-set
metadata, and writes Snappy Parquet files under
./data_unload/[<DB>/]<TABLE>/.
Usage Pattern:
Copy `assets/export_teradata_tables_template.py` from this skill's directory
(`<SKILL_DIR>`, the directory containing `SKILL.md`) into your
working directory (e.g., `./export_teradata_tables.py`). Run the copy as-is
for standard export SQL generation, and prioritize modifying the marked
`# CUSTOMIZE:` extension points if your environment requires custom type
projections, row filters, or table filtering. Sections marked
`# DEFAULT SCAFFOLDING` can be kept unchanged unless deeper orchestration
adjustments are needed.
Dependencies:
pip install pyyaml==6.0.2
Usage Examples:
# Copy the template from this skill's directory to your working directory:
cp <SKILL_DIR>/assets/export_teradata_tables_template.py \
./export_teradata_tables.py
# 1. Generate per-table Teradata export SQL files from BQMS output:
python3 ./export_teradata_tables.py \
--translation-metadata-dir ./translated_output/metadata \
--default-database my_db \
--output-dir ./export_sql
# 2. Generate a unified export SQL file straight from the extractor zip:
python3 ./export_teradata_tables.py \
--metadata-zip gs://my-bucket/metadata/dwh-migration-teradata-metadata.zip \
--database my_db \
--output-sql teradata_export.sql
"""
from __future__ import annotations
import argparse
import csv
import io
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
import yaml
# ==============================================================================
# 1. File & Metadata Loading Functions (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: Deterministic metadata loading and archive parsing.
def read_file_or_gcs(path_or_uri: str) -> bytes:
"""Reads content from a local file path or a Cloud Storage URI.
Args:
path_or_uri: Local file path or Cloud Storage URI (starts with 'gs://').
Returns:
The content of the file as bytes.
Raises:
FileNotFoundError: If the local file does not exist.
RuntimeError: If gcloud storage fails to read from Cloud Storage.
"""
if path_or_uri.startswith("gs://"):
cmd = ["gcloud", "storage", "cat", path_or_uri]
try:
return subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
raise RuntimeError(
f"Failed to read from Cloud Storage '{path_or_uri}': {e}"
) from e
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot read '{path_or_uri}': the gcloud CLI was not found. Install"
" the Google Cloud CLI, or download the file and pass a local path."
) from e
if not os.path.exists(path_or_uri):
raise FileNotFoundError(f"Local file not found: '{path_or_uri}'")
with open(path_or_uri, "rb") as f:
return f.read()
def _run_gcloud_copy(cmd: list[str], uri: str) -> None:
"""Runs a `gcloud storage cp` command, surfacing its stderr on failure."""
try:
subprocess.run(cmd, capture_output=True, check=True)
except FileNotFoundError as e:
raise RuntimeError(
f"Cannot copy '{uri}': the gcloud CLI was not found. Install the"
" Google Cloud CLI, or copy the files locally and pass a local path."
) from e
except subprocess.CalledProcessError as e:
stderr = (e.stderr or b"").decode("utf-8", errors="replace").strip()
raise RuntimeError(
f"Failed to copy from Cloud Storage '{uri}' (exit code"
f" {e.returncode}): {stderr or e}"
) from e
def _strip(value: str | None) -> str:
"""Trims the fixed-width padding Teradata puts on dbc CHAR columns."""
return (value or "").strip()
# Teradata dbc.TablesV.TableKind codes that hold exportable rows.
# T = table, O = table without primary index. Views (V), macros (M),
# procedures (P), join indexes (I), etc. are skipped.
_TERADATA_TABLE_KINDS = frozenset(("T", "O"))
def load_metadata_from_zip(
zip_bytes: bytes,
) -> dict[str, list[dict[str, str]]]:
"""Extracts table and column metadata from a Teradata extractor metadata.zip.
Reads dbc.TablesV.csv and dbc.ColumnsV.csv (falls back to the generic
tables.csv / columns.csv layout) and normalizes rows to the shared
TableCatalog/TableSchema/TableName/ColumnName/DataType record shape. Teradata
has no catalog level, so TableCatalog is empty and the database is stored in
TableSchema.
Args:
zip_bytes: Raw bytes of the metadata zip archive.
Returns:
A dictionary containing 'tables' and 'columns' lists of records.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as z:
names = z.namelist()
by_base = {os.path.basename(n).lower(): n for n in names}
def _rows(candidates: list[str]) -> tuple[str | None, list[dict[str, str]]]:
for c in candidates:
member = by_base.get(c.lower())
if member:
with z.open(member) as fh:
return c, list(
csv.DictReader(io.TextIOWrapper(fh, encoding="utf-8-sig"))
)
return None, []
tables_fn, table_rows = _rows(["dbc.TablesV.csv", "tables.csv"])
columns_fn, column_rows = _rows(["dbc.ColumnsV.csv", "columns.csv"])
if tables_fn == "dbc.TablesV.csv":
for r in table_rows:
kind = _strip(r.get("TableKind")).upper()
result["tables"].append({
"TableCatalog": "",
"TableSchema": _strip(r.get("DataBaseName") or r.get("DatabaseName")),
"TableName": _strip(r.get("TableName")),
"TableType": "BASE TABLE" if kind in _TERADATA_TABLE_KINDS else kind,
})
else:
result["tables"] = [
{k: _strip(v) for k, v in r.items() if k is not None}
for r in table_rows
]
if columns_fn == "dbc.ColumnsV.csv":
for r in column_rows:
result["columns"].append({
"TableCatalog": "",
"TableSchema": _strip(r.get("DatabaseName") or r.get("DataBaseName")),
"TableName": _strip(r.get("TableName")),
"ColumnName": _strip(r.get("ColumnName")),
# ColumnId is 1025-based per table; ordering is all that matters.
"OrdinalPosition": _strip(r.get("ColumnId")),
"DataType": _strip(r.get("ColumnType")).upper(),
"ColumnLength": _strip(r.get("ColumnLength")),
"NumericPrecision": _strip(r.get("DecimalTotalDigits")),
"NumericScale": _strip(r.get("DecimalFractionalDigits")),
"Nullable": _strip(r.get("Nullable")).upper() or "Y",
})
else:
result["columns"] = [
{k: _strip(v) for k, v in r.items() if k is not None}
for r in column_rows
]
return result
def load_metadata_from_config_dir(
config_dir: str,
) -> dict[str, list[dict[str, str]]]:
"""Loads table/column metadata from BQMS metadata/config/*.yaml files.
Args:
config_dir: Local path to the BQMS metadata config directory.
Returns:
A dictionary containing 'tables' and 'columns' metadata parsed from YAMLs.
"""
result: dict[str, list[dict[str, str]]] = {"tables": [], "columns": []}
if not os.path.isdir(config_dir):
return result
for root, _, files in os.walk(config_dir):
for f in sorted(files):
if not (f.endswith(".yaml") or f.endswith(".yml")):
continue
try:
with open(os.path.join(root, f), "r", encoding="utf-8") as yf:
cfg = yaml.safe_load(yf)
except (yaml.YAMLError, OSError):
continue
if not isinstance(cfg, dict):
continue
src_name = cfg.get("sourceName", "")
parts = src_name.split(".") if src_name else []
# Teradata names are DATABASE.TABLE; tolerate a leading catalog.
schema = parts[-2] if len(parts) >= 2 else ""
table = parts[-1] if parts else f.rsplit(".", 1)[0]
is_view = not bool(
cfg.get("externalTableName") or cfg.get("externalTableDdlPath")
)
result["tables"].append({
"TableCatalog": "",
"TableSchema": schema,
"TableName": table,
"TableType": "VIEW" if is_view else "BASE TABLE",
})
for idx, col in enumerate(cfg.get("columns") or [], start=1):
if not isinstance(col, dict):
continue
src_type = col.get("sourceType") or {}
tgt_type = col.get("targetType") or {}
src = (
src_type
if isinstance(src_type, dict)
else {"genericName": src_type}
)
tgt = tgt_type if isinstance(tgt_type, dict) else {"name": tgt_type}
raw_code = str(src.get("name") or "").strip().upper()
generic_name = str(src.get("genericName") or raw_code).strip().upper()
if raw_code.startswith("NUMBER"):
# Keep NUMBER(p): a precision-only DDL type means scale 0.
data_type = raw_code
elif raw_code == "N":
data_type = "NUMBER"
elif (
_normalize_data_type(raw_code, None, None)[0]
in _ALL_KNOWN_TERADATA_TYPES
):
data_type = raw_code
else:
data_type = generic_name or raw_code
result["columns"].append({
"TableCatalog": "",
"TableSchema": schema,
"TableName": table,
"ColumnName": col.get("sourceName", ""),
"OrdinalPosition": str(idx),
"DataType": data_type,
"NumericPrecision": str(src.get("precision", "")),
"NumericScale": str(src.get("scale", "")),
"TargetType": str(tgt.get("name") or ""),
"TargetPrecision": str(tgt.get("precision", "")),
"TargetScale": str(tgt.get("scale", "")),
"Nullable": "N" if col.get("notNull") else "Y",
})
return result
def _find_config_dir(dir_path: str) -> str | None:
"""Locates the directory containing BQMS table YAML configurations."""
for candidate in (
os.path.join(dir_path, "metadata", "config"),
os.path.join(dir_path, "config"),
):
if os.path.isdir(candidate):
return candidate
for _, _, files in os.walk(dir_path):
if any(f.endswith((".yaml", ".yml")) for f in files):
return dir_path
return None
def load_metadata_from_dir(dir_path: str) -> dict[str, list[dict[str, str]]]:
"""Discovers metadata in a directory (BQMS YAML configs or embedded zip)."""
config_dir = _find_config_dir(dir_path)
if config_dir:
res = load_metadata_from_config_dir(config_dir)
if res["tables"] and res["columns"]:
return res
for root, _, files in os.walk(dir_path):
for f in files:
if f.endswith(".zip") and "metadata" in f:
with open(os.path.join(root, f), "rb") as zf:
return load_metadata_from_zip(zf.read())
return {"tables": [], "columns": []}
def _resolve_and_load_metadata(
path_or_uri: str | None,
) -> dict[str, list[dict[str, str]]]:
"""Resolves local or Cloud Storage metadata and loads metadata dicts."""
if not path_or_uri:
return {"tables": [], "columns": []}
if path_or_uri.startswith("gs://"):
if path_or_uri.endswith(".zip"):
return load_metadata_from_zip(read_file_or_gcs(path_or_uri))
temp_dir = tempfile.mkdtemp(prefix="bqms_meta_")
try:
cmd = [
"gcloud",
"storage",
"cp",
"-r",
path_or_uri.rstrip("/") + "/*",
temp_dir,
]
_run_gcloud_copy(cmd, path_or_uri)
return load_metadata_from_dir(temp_dir)
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
if os.path.isdir(path_or_uri):
return load_metadata_from_dir(path_or_uri)
return load_metadata_from_zip(read_file_or_gcs(path_or_uri))
def _ordinal(col: dict[str, str]) -> int:
pos = str(col.get("OrdinalPosition", ""))
return int(pos) if pos.isdigit() else 999999
def _group_and_sort_columns(
columns: list[dict[str, str]],
) -> tuple[
dict[tuple[str, str], list[dict[str, str]]],
dict[str, list[dict[str, str]]],
]:
"""Groups columns by (schema, table) and table name, sorted by ordinal."""
by_schema_table: dict[tuple[str, str], list[dict[str, str]]] = {}
by_table: dict[str, list[dict[str, str]]] = {}
for col in columns:
key = (
col.get("TableSchema", "").upper(),
col.get("TableName", "").upper(),
)
by_schema_table.setdefault(key, []).append(col)
for (_, tbl), cols in by_schema_table.items():
cols.sort(key=_ordinal)
by_table.setdefault(tbl, cols)
return by_schema_table, by_table
def _lookup_table_columns(
by_schema_table: dict[tuple[str, str], list[dict[str, str]]],
raw_schema: str,
schema: str,
tbl: str,
) -> list[dict[str, str]]:
"""Finds a table's columns without borrowing them from another database.
Tries the metadata database, then the --default-database fallback, then
columns recorded without a database. A table without any database only
matches a same-named table when exactly one candidate exists; otherwise it
gets no column projections and falls back to SELECT *.
Args:
by_schema_table: Column metadata keyed by (database, table name).
raw_schema: The database recorded in the metadata for this table.
schema: The effective database after applying --default-database.
tbl: The table name.
Returns:
The table's column metadata, or an empty list when no unambiguous match
exists.
"""
for key in ((raw_schema, tbl), (schema, tbl), ("", tbl)):
cols = by_schema_table.get(key)
if cols:
return cols
if not schema:
matches = [c for (_, t), c in by_schema_table.items() if t == tbl and c]
if len(matches) == 1:
return matches[0]
return []
# CUSTOMIZE: Table & Row Filtering — Edit _filter_tables_to_export() to add
# custom database/table inclusion or exclusion rules.
def _filter_tables_to_export(
raw_tables: list[dict[str, str]],
columns_by_table: dict[str, list[dict[str, str]]],
databases: set[str] | None = None,
columns_by_schema_table: (
dict[tuple[str, str], list[dict[str, str]]] | None
) = None,
default_database: str = "",
) -> list[dict[str, str]]:
"""Filters tables to export: drops views/system objects, applies filters.
The database allow-list and duplicate check use the effective
database (TableSchema, else default_database), so database-less
entries match --database and don't duplicate qualified entries.
Args:
raw_tables: Table rows from the metadata (may be empty).
columns_by_table: Column metadata keyed by table name.
databases: Optional upper-cased database allow-list.
columns_by_schema_table: Column metadata keyed by (database, table name),
used when raw_tables is empty.
default_database: Fallback database for entries without a TableSchema.
Returns:
The table entries to export, without duplicates.
"""
out: list[dict[str, str]] = []
seen: set[tuple[str, str]] = set()
default_db = _strip(default_database).upper()
if raw_tables:
for t in raw_tables:
tbl = _strip(t.get("TableName")).upper()
schema = _strip(t.get("TableSchema")).upper() or default_db
tbl_type = _strip(t.get("TableType")).upper()
if tbl_type and tbl_type != "BASE TABLE" and tbl_type != "TABLE":
continue
if databases and schema not in databases:
continue
if (schema, tbl) in seen:
continue
seen.add((schema, tbl))
out.append(t)
elif columns_by_schema_table:
for raw_schema, tbl in columns_by_schema_table:
schema = raw_schema or default_db
if databases and schema not in databases:
continue
if (schema, tbl) not in seen:
seen.add((schema, tbl))
out.append({"TableSchema": raw_schema, "TableName": tbl})
else:
for tbl, cols in columns_by_table.items():
raw_schema = _strip(cols[0].get("TableSchema")).upper() if cols else ""
schema = raw_schema or default_db
if databases and schema not in databases:
continue
if (schema, tbl) not in seen:
seen.add((schema, tbl))
entry = {"TableName": tbl}
if raw_schema:
entry["TableSchema"] = raw_schema
out.append(entry)
return out
# ==============================================================================
# 2. Type-Safe SQL Generation Logic
# ==============================================================================
_VALID_IDENT_REGEX = re.compile(r"^[A-Za-z_][A-Za-z0-9_$#]*$")
# Teradata reserved and restricted words (ANSI SQL and Teradata extensions)
# that can collide with column, table, or database names. Anything matching
# is double-quoted; Teradata names are not case-specific, so quoting a name
# never changes which object it resolves to.
_TERADATA_RESERVED = frozenset("""
ABORT ABORTSESSION ABS ACCESS_LOCK ACCOUNT ACOS ACOSH ADD ADD_MONTHS ADMIN
AFTER AGGREGATE ALL ALTER AMP AND ANSIDATE ANY AS ASC ASIN ASINH AT ATAN
ATAN2 ATANH ATOMIC AUTHORIZATION AVE AVERAGE AVG BEFORE BEGIN BETWEEN
BIGINT BINARY BLOB BOTH BT BUT BY BYTE BYTEINT BYTES CALL CASE
CASESPECIFIC CASE_N CAST CD CHAR CHAR2HEXINT CHARACTER CHARACTERS
CHARACTER_LENGTH CHARS CHAR_LENGTH CHECK CHECKPOINT CLASS CLOB CLOSE
CLUSTER CM COALESCE COLLATION COLLECT COLUMN COMMENT COMMIT COMPRESS
CONNECT CONSTRAINT CONSTRUCTOR CONSUME CONTAINS CONTINUE
CONVERT_TABLE_HEADER CORR COS COSH COUNT COVAR_POP COVAR_SAMP CREATE CROSS
CS CSUM CT CTCONTROL CUBE CURRENT CURRENT_DATE CURRENT_ROLE CURRENT_TIME
CURRENT_TIMESTAMP CURRENT_USER CURSOR CV CYCLE DATABASE DATABLOCKSIZE DATE
DATEFORM DAY DEALLOCATE DEC DECIMAL DECLARE DEFAULT DEFERRED DEGREES DEL
DELETE DESC DETERMINISTIC DIAGNOSTIC DISABLED DISTINCT DO DOMAIN DOUBLE
DROP DUAL DUMP DYNAMIC EACH ECHO ELSE ELSEIF ENABLED END EQ EQUALS ERROR
ERRORFILES ERRORTABLES ESCAPE ET EXCEPT EXEC EXECUTE EXISTS EXIT EXP
EXPAND EXPANDING EXPLAIN EXTERNAL EXTRACT FALLBACK FASTEXPORT FETCH FIRST
FLOAT FOR FOREIGN FORMAT FOUND FREESPACE FROM FULL FUNCTION GE GENERATED
GET GIVE GRANT GRAPHIC GROUP GROUPING GT HANDLER HASH HASHAMP HASHBAKAMP
HASHBUCKET HASHROW HAVING HELP HOUR IDENTITY IF IMMEDIATE IN INCONSISTENT
INDEX INITIATE INNER INOUT INPUT INS INSERT INSTANCE INSTEAD INT INTEGER
INTEGERDATE INTERSECT INTERVAL INTO IS ITERATE JAR JOIN JOURNAL KEY
KURTOSIS LANGUAGE LARGE LE LEADING LEAVE LEFT LEVEL LIKE LIMIT LN LOADING
LOCAL LOCATOR LOCK LOCKING LOG LOGGING LOGON LONG LOOP LOWER LT MACRO MAP
MAVG MAX MAXIMUM MCHARACTERS MDIFF MERGE METHOD MIN MINDEX MINIMUM MINUS
MINUTE MLINREG MLOAD MOD MODE MODIFIES MODIFY MONITOR MONRESOURCE
MONSESSION MONTH MSUBSTR MSUM MULTISET NAMED NATURAL NE NEW NEW_TABLE NEXT
NO NONE NOT NOWAIT NULL NULLIF NULLIFZERO NUMERIC OBJECT OBJECTS
OCTET_LENGTH OF OFF OLD OLD_TABLE ON ONLY OPEN OPTION OR ORDER ORDERING
OUT OUTER OVER OVERLAPS OVERRIDE PARAMETER PASSWORD PERCENT PERCENT_RANK
PERM PERMANENT POSITION PRECISION PREPARE PRESERVE PRIMARY PRIVILEGES
PROCEDURE PROFILE PROTECTION PUBLIC QUALIFIED QUALIFY QUANTILE QUEUE
RADIANS RANDOM RANGE_N RANK READS REAL RECURSIVE REFERENCES REFERENCING
RELEASE RENAME REPEAT REPLACE REPLCONTROL REPLICATION REQUEST RESTART
RESTORE RESULT RESUME RET RETRIEVE RETURN RETURNS REVALIDATE REVOKE RIGHT
RIGHTS ROLE ROLLBACK ROLLFORWARD ROLLUP ROW ROWID ROWS ROW_NUMBER SAMPLE
SAMPLEID SCROLL SECOND SEL SELECT SESSION SET SETRESRATE SETS SETSESSRATE
SHOW SIN SINH SKEW SMALLINT SOME SOUNDEX SPECIFIC SPOOL SQL SQLEXCEPTION
SQLTEXT SQLWARNING SQRT SS START STARTUP STATEMENT STATISTICS STDDEV_POP
STDDEV_SAMP STEPINFO STRING_CS SUBSCRIBER SUBSTR SUBSTRING SUM SUMMARY
SUSPEND TABLE TAN TANH TBL_CS TEMPORARY TERMINATE THEN THRESHOLD TIME
TIMESTAMP TIMEZONE_HOUR TIMEZONE_MINUTE TITLE TO TOP TRACE TRAILING
TRANSACTION TRANSACTIONTIME TRANSFORM TRANSLATE TRANSLATE_CHK TRIGGER TRIM
TYPE UC UDTCASTAS UDTCASTLPAREN UDTMETHOD UDTTYPE UDTUSAGE UESCAPE
UNDEFINED UNDO UNION UNIQUE UNTIL UNTIL_CHANGED UNTIL_CLOSED UPD UPDATE
UPPER UPPERCASE USER USING VALIDTIME VALUE VALUES VARBYTE VARCHAR
VARGRAPHIC VARIANT_TYPE VARYING VAR_POP VAR_SAMP VIEW VOLATILE WHEN WHERE
WHILE WIDTH_BUCKET WITH WITHOUT WORK XMLPLAN YEAR ZEROIFNULL ZONE
""".split())
# dbc.ColumnsV.ColumnType codes (plus BQMS generic names) grouped by the
# projection they need. See "ColumnType" in the Teradata Data Dictionary.
_INT_TYPES = frozenset((
"I1",
"I2",
"I",
"I8",
"BYTEINT",
"TINYINT",
"SMALLINT",
"INTEGER",
"INT",
"BIGINT",
"INT64",
))
_DECIMAL_TYPES = frozenset(("D", "DECIMAL", "NUMERIC", "BIGNUMERIC"))
_NUMBER_TYPES = frozenset(("N", "NUMBER"))
_FLOAT_TYPES = frozenset((
"F",
"FLOAT",
"REAL",
"DOUBLE",
"DOUBLE PRECISION",
"FLOAT64",
))
_DATE_TYPES = frozenset(("DA", "DATE"))
_TIME_TYPES = frozenset(("AT", "TIME"))
_TIME_TZ_TYPES = frozenset(("TZ", "TIMETZ", "TIME WITH TIME ZONE"))
_TIMESTAMP_TYPES = frozenset(("TS", "TIMESTAMP", "DATETIME"))
_TIMESTAMP_TZ_TYPES = frozenset((
"SZ",
"TIMESTAMPTZ",
"TIMESTAMP WITH TIME ZONE",
))
_CHAR_TYPES = frozenset(("CF", "GF", "CHAR", "CHARACTER", "GRAPHIC"))
_VARCHAR_TYPES = frozenset((
"CV",
"GV",
"VARCHAR",
"CHARACTER VARYING",
"CHAR VARYING",
"LONG VARCHAR",
"VARGRAPHIC",
"STRING",
"CO",
"CLOB",
))
_BYTE_TYPES = frozenset((
"BF",
"BV",
"BO",
"BYTE",
"VARBYTE",
"BINARY",
"VARBINARY",
"BLOB",
"BYTES",
))
_JSON_TYPES = frozenset(("JN", "JSON"))
_PERIOD_TYPES = frozenset((
"PD",
"PT",
"PZ",
"PS",
"PM",
"PERIOD_DATE",
"PERIOD_TIME",
"PERIOD_TIMETZ",
"PERIOD_TIMESTAMP",
"PERIOD_TIMESTAMPTZ",
))
_INTERVAL_TYPES = frozenset((
"YR",
"YM",
"MO",
"DY",
"DH",
"DM",
"DS",
"HR",
"HM",
"HS",
"MI",
"MS",
"SC",
"INTERVAL",
))
_DBC_COLUMN_TYPE_CODES = frozenset((
"I1",
"I2",
"I",
"I8",
"D",
"N",
"F",
"DA",
"AT",
"TZ",
"TS",
"SZ",
"CF",
"CV",
"CO",
"GF",
"GV",
"BF",
"BV",
"BO",
"JN",
"XM",
"PD",
"PT",
"PZ",
"PS",
"PM",
"YR",
"YM",
"MO",
"DY",
"DH",
"DM",
"DS",
"HR",
"HM",
"HS",
"MI",
"MS",
"SC",
"A1",
"AN",
"UT",
"DT",
))
_ALL_KNOWN_TERADATA_TYPES = (
_DBC_COLUMN_TYPE_CODES
| _INT_TYPES
| _DECIMAL_TYPES
| _NUMBER_TYPES
| _FLOAT_TYPES
| _DATE_TYPES
| _TIME_TYPES
| _TIME_TZ_TYPES
| _TIMESTAMP_TYPES
| _TIMESTAMP_TZ_TYPES
| _CHAR_TYPES
| _VARCHAR_TYPES
| _BYTE_TYPES
| _JSON_TYPES
| _PERIOD_TYPES
| _INTERVAL_TYPES
)
# DEFAULT SCAFFOLDING: Identifier quoting helper.
def quote_ident(ident: str) -> str:
"""Double-quotes a Teradata identifier when it is not a plain name.
Args:
ident: The raw SQL identifier string.
Returns:
The properly quoted or unquoted identifier.
"""
if not ident:
return ""
if len(ident) >= 2 and ident.startswith('"') and ident.endswith('"'):
# Already quoted: re-escape any bare inner double quotes.
inner = ident[1:-1].replace('""', '"').replace('"', '""')
return f'"{inner}"'
if not _VALID_IDENT_REGEX.match(ident) or ident.upper() in _TERADATA_RESERVED:
escaped = ident.replace('"', '""')
return f'"{escaped}"'
return ident
_PARAM_TYPE_REGEX = re.compile(
r"^(?P<base>[A-Z0-9_ ]+?)\s*\(\s*(?P<p>-?\d+|\*)"
r"(?:\s*,\s*(?P<s>-?\d+))?\s*\)\s*(?P<rest>.*)$"
)
_COLUMN_ATTR_REGEX = re.compile(
r"\s+(?:CHARACTER\s+SET\s+\S+|(?:NOT\s+)?CASESPECIFIC|UPPERCASE"
r"|UNICODE|LATIN|KANJISJIS)\b"
)
def _to_int(value: str | None) -> int | None:
value = str(value or "").strip()
return int(value) if value.lstrip("-").isdigit() else None
def _normalize_data_type(
raw_type: str, precision: int | None, scale: int | None
) -> tuple[str, int | None, int | None]:
"""Normalizes a Teradata type code or DDL string into (base_type, p, s)."""
dt = " ".join(raw_type.upper().split())
dt = _COLUMN_ATTR_REGEX.sub("", dt).strip()
if dt.startswith("PERIOD") and "(" in dt:
return (
"PERIOD_TIMESTAMP" if "TIMESTAMP" in dt else "PERIOD_DATE",
precision,
scale,
)
if dt.startswith("INTERVAL "):
return "INTERVAL", precision, scale
m = _PARAM_TYPE_REGEX.match(dt)
if m:
rest = m.group("rest").strip()
tz_suffix = " WITH TIME ZONE" if "TIME ZONE" in rest else ""
base = f"{m.group('base').strip()}{tz_suffix}".strip()
if precision is None and m.group("p") != "*":
precision = _to_int(m.group("p"))
if scale is None and m.group("s") is not None:
scale = _to_int(m.group("s"))
return base, precision, scale
return dt, precision, scale
# CUSTOMIZE: Custom Type Projections — Edit format_column_cast() to change how
# a Teradata type is projected before Parquet serialization (e.g. keep CHAR
# padding, map PERIOD to BEGIN()/END() pairs, or widen DECIMAL precision).
def format_column_cast(
col: dict[str, str],
target_bq_type: str | None = None,
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Generates a type-safe Teradata projection expression for Parquet export.
The executor derives the Parquet schema from the result-set metadata, so the
CAST here is what decides the BigQuery column type:
BYTEINT/SMALLINT/INTEGER/BIGINT -> CAST AS BIGINT -> INT64
DECIMAL(p,s) -> CAST AS DECIMAL -> NUMERIC/BIGNUMERIC
NUMBER(*) -> DECIMAL(38,9) -> NUMERIC/BIGNUMERIC
FLOAT/REAL/DOUBLE -> CAST AS FLOAT -> FLOAT64
DATE -> CAST AS DATE -> DATE
TIME(n) -> CAST AS TIME(6) -> TIME
TIME(n) WITH TIME ZONE -> UTC TIME(6) -> TIME
TIMESTAMP(n) -> TIMESTAMP(6) -> TIMESTAMP
TIMESTAMP(n) WITH TIME ZONE -> UTC TIMESTAMP(6) -> TIMESTAMP
CHAR(n) -> TRIM(TRAILING) -> STRING
VARCHAR / CLOB -> col -> STRING
BYTE / VARBYTE / BLOB -> col -> BYTES
JSON -> CAST AS CLOB -> STRING
PERIOD -> VARCHAR(100) -> STRING
INTERVAL -> TRIM(VARCHAR) -> STRING
Args:
col: Column metadata dict containing ColumnName, DataType, etc.
target_bq_type: Optional BigQuery target type override.
rtrim_char: Strip CHAR(n) trailing pad spaces (BigQuery STRING has no
fixed-width semantics, so padded values would mismatch in validation).
unbounded_number_scale: Fractional scale for unbounded NUMBER / NUMBER(*)
columns (default 9, supporting up to 29 integer digits).
Returns:
A SQL projection expression, e.g. 'CAST(ss_item_sk AS BIGINT) AS
ss_item_sk'.
"""
col_name = quote_ident(_strip(col.get("ColumnName")))
data_type, precision, scale = _normalize_data_type(
str(col.get("DataType") or ""),
_to_int(col.get("NumericPrecision")),
_to_int(col.get("NumericScale")),
)
target_raw = (target_bq_type or col.get("TargetType") or "").upper().strip()
target = re.split(r"[(<]", target_raw, maxsplit=1)[0].strip()
# BQMS target types win when present: they are what the BigQuery DDL uses.
# Other cross-type targets (STRING / JSON on non-text columns, BYTES, BOOL)
# keep the default projection below.
if target:
if target in (
"INT64",
"INTEGER",
"BIGINT",
"SMALLINT",
"TINYINT",
"BYTEINT",
):
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if target in ("FLOAT64", "FLOAT", "DOUBLE"):
return f"CAST({col_name} AS FLOAT) AS {col_name}"
if target == "DATE":
return f"CAST({col_name} AS DATE) AS {col_name}"
if target in ("TIMESTAMP", "DATETIME"):
return (
f"CAST(({col_name} AT TIME ZONE 'GMT') AS TIMESTAMP(6)) AS {col_name}"
if data_type in _TIMESTAMP_TZ_TYPES
else f"CAST({col_name} AS TIMESTAMP(6)) AS {col_name}"
)
if target in ("NUMERIC", "BIGNUMERIC", "DECIMAL") and (
data_type not in _DECIMAL_TYPES and data_type not in _NUMBER_TYPES
):
tgt_p = precision or _to_int(col.get("TargetPrecision"))
tgt_s = scale if scale is not None else _to_int(col.get("TargetScale"))
if tgt_p and 0 < tgt_p <= 38:
p_val = tgt_p
elif data_type in _INT_TYPES and target != "BIGNUMERIC":
# BigQuery NUMERIC (alias DECIMAL) holds at most 29 integer digits.
p_val = 29
else:
p_val = 38
if tgt_s is not None and 0 <= tgt_s <= p_val:
s_val = tgt_s
else:
s_val = 0 if data_type in _INT_TYPES else min(9, p_val)
return f"CAST({col_name} AS DECIMAL({p_val},{s_val})) AS {col_name}"
if target == "TIME":
if data_type in _TIMESTAMP_TZ_TYPES or data_type in _TIME_TZ_TYPES:
return f"CAST(({col_name} AT TIME ZONE 'GMT') AS TIME(6)) AS {col_name}"
return f"CAST({col_name} AS TIME(6)) AS {col_name}"
if data_type in _INT_TYPES:
return f"CAST({col_name} AS BIGINT) AS {col_name}"
if 0 <= unbounded_number_scale <= 38:
default_unb_scale = unbounded_number_scale
else:
logging.warning(
"Out-of-range unbounded_number_scale=%d (expected 0..38); falling back"
" to 9.",
unbounded_number_scale,
)
default_unb_scale = 9
if data_type in _NUMBER_TYPES:
# BQMS YAML configs record unconstrained NUMBER as precision 38 without a
# scale; keep its fractional digits (TargetScale, else the unbounded
# scale) unless the DDL type itself is NUMBER(p), which means scale 0.
explicit_p_only = re.search(
r"\(\s*\d+\s*\)", str(col.get("DataType") or "")
)
if scale is None and precision and not explicit_p_only:
s_val = _to_int(col.get("TargetScale"))
if s_val is None or not 0 <= s_val <= 38:
s_val = default_unb_scale
return f"CAST({col_name} AS DECIMAL(38,{s_val})) AS {col_name}"
# NUMBER / NUMBER(*) report precision -128 or (40, 0) in dbc.ColumnsV.
if precision and 0 < precision <= 38:
s_val = scale if scale is not None and 0 <= scale <= precision else 0
return f"CAST({col_name} AS DECIMAL({precision},{s_val})) AS {col_name}"
if precision == 40 and scale == 0:
s_val = default_unb_scale
else:
s_val = (
scale if scale is not None and 0 <= scale <= 38 else default_unb_scale
)
return f"CAST({col_name} AS DECIMAL(38,{s_val})) AS {col_name}"
if data_type in _DECIMAL_TYPES:
if precision and precision < 0:
return (
f"CAST({col_name} AS DECIMAL(38,{default_unb_scale})) AS {col_name}"
)
p_val = precision if precision and 0 < precision <= 38 else 38
s_val = scale if scale is not None and 0 <= scale <= p_val else 0
return f"CAST({col_name} AS DECIMAL({p_val},{s_val})) AS {col_name}"
if data_type in _FLOAT_TYPES:
return f"CAST({col_name} AS FLOAT) AS {col_name}"
if data_type in _DATE_TYPES:
return f"CAST({col_name} AS DATE) AS {col_name}"
if data_type in _TIME_TYPES:
return f"CAST({col_name} AS TIME(6)) AS {col_name}"
if data_type in _TIME_TZ_TYPES:
return f"CAST(({col_name} AT TIME ZONE 'GMT') AS TIME(6)) AS {col_name}"
if data_type in _TIMESTAMP_TYPES:
return f"CAST({col_name} AS TIMESTAMP(6)) AS {col_name}"
if data_type in _TIMESTAMP_TZ_TYPES:
return (
f"CAST(({col_name} AT TIME ZONE 'GMT') AS TIMESTAMP(6)) AS {col_name}"
)
if data_type in _CHAR_TYPES:
if rtrim_char:
return f"TRIM(TRAILING FROM {col_name}) AS {col_name}"
return f"{col_name} AS {col_name}"
if data_type in _VARCHAR_TYPES or data_type in _BYTE_TYPES:
return f"{col_name} AS {col_name}"
if data_type in _JSON_TYPES:
return f"CAST({col_name} AS CLOB) AS {col_name}"
if data_type in _PERIOD_TYPES:
return f"CAST({col_name} AS VARCHAR(100)) AS {col_name}"
if data_type in _INTERVAL_TYPES:
return f"TRIM(CAST({col_name} AS VARCHAR(100))) AS {col_name}"
# XML, ST_GEOMETRY, UDTs, etc. (32000 fits both LATIN and UNICODE VARCHAR)
return f"CAST({col_name} AS VARCHAR(32000)) AS {col_name}"
# DEFAULT SCAFFOLDING: Table name qualification helper.
def _build_qualified_table_name(
table_meta: dict[str, str], default_database: str = ""
) -> str:
"""Builds a quoted DATABASE.TABLE name."""
tbl = _strip(table_meta.get("TableName"))
db = _strip(table_meta.get("TableSchema")) or _strip(default_database)
return f"{quote_ident(db)}.{quote_ident(tbl)}" if db else quote_ident(tbl)
# CUSTOMIZE: Row Filters — Edit _build_select_query() to add WHERE predicates
# (e.g. incremental extraction windows) or LOCKING modifiers.
def _build_select_query(
table_meta: dict[str, str],
columns: list[dict[str, str]],
default_database: str = "",
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Builds the explicit-cast SELECT statement for a single table.
LOCKING ROW FOR ACCESS allows dirty reads so the export never blocks (or is
blocked by) concurrent writers; drop it if a consistent snapshot matters more.
Args:
table_meta: Table metadata dictionary with TableSchema and TableName.
columns: Ordered list of column metadata dictionaries for the table.
default_database: Fallback database name when TableSchema is empty.
rtrim_char: Whether to TRIM(TRAILING) fixed-width CHAR(n) columns.
unbounded_number_scale: Fractional scale for unbounded NUMBER columns.
Returns:
A complete Teradata SELECT statement ending with a semicolon.
"""
qualified = _build_qualified_table_name(table_meta, default_database)
if columns:
body = ",\n".join(
" "
+ format_column_cast(
c,
rtrim_char=rtrim_char,
unbounded_number_scale=unbounded_number_scale,
)
for c in columns
)
else:
body = " *"
return f"LOCKING ROW FOR ACCESS\nSELECT\n{body}\nFROM {qualified};"
def _sanitize_comment_token(value: str) -> str:
"""Replaces control characters so SQL line comments stay single-line."""
return re.sub(r"[\x00-\x1f\x7f]+", " ", str(value)).strip()
# DEFAULT SCAFFOLDING: Primary SQL script generator and orchestration.
def generate_export_sql(
metadata_path_or_uri: str | None = None,
default_database: str | None = None,
databases: list[str] | None = None,
rtrim_char: bool = True,
unbounded_number_scale: int = 9,
) -> str:
"""Generates the unified Teradata export SQL script.
Each table section is introduced by a divider and a
`-- Unload Table: <DB>.<TABLE> -> Parquet` marker that the executor uses to
name the ./data_unload/[<DB>/]<TABLE>/ output directory.
Args:
metadata_path_or_uri: Path or Cloud Storage URI to translation metadata dir
or zip.
default_database: Fallback database when metadata omits it.
databases: Optional database allow-list (case-insensitive).
rtrim_char: Strip CHAR(n) trailing pad spaces.
unbounded_number_scale: Fractional scale for unbounded NUMBER columns.
Returns:
A complete Teradata SQL script string.
"""
metadata = _resolve_and_load_metadata(metadata_path_or_uri)
by_schema_table, by_table = _group_and_sort_columns(
metadata.get("columns", [])
)
db_filter = {d.upper() for d in databases} if databases else None
tables = _filter_tables_to_export(
metadata.get("tables", []),
by_table,
db_filter,
columns_by_schema_table=by_schema_table,
default_database=default_database or "",
)
if not tables and db_filter:
rows = metadata.get("tables", []) or metadata.get("columns", [])
available = sorted({_strip(t.get("TableSchema")) for t in rows} - {""})
print(
"WARNING: No tables match the --database filter. Available databases:"
f" {', '.join(available) or '(none)'}.",
file=sys.stderr,
)
generator_name = (
os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] else ""
) or "export_teradata_tables_template.py"
lines = [
"-- " + "=" * 77,
"-- Teradata to Parquet Type-Safe Data Export Script",
f"-- Generated by bigquery-migration-data-exporter / {generator_name}",
"-- Execute via teradatasql and stream results to Snappy Parquet",
"-- " + "=" * 77,
"",
]
divider = "-- " + "-" * 77
for t in tables:
tbl = _strip(t.get("TableName"))
raw_schema = _strip(t.get("TableSchema"))
schema = raw_schema or _strip(default_database)
cols = _lookup_table_columns(
by_schema_table, raw_schema.upper(), schema.upper(), tbl.upper()
)
stmt = _build_select_query(
t,
cols,
default_database or "",
rtrim_char=rtrim_char,
unbounded_number_scale=unbounded_number_scale,
)
label = _sanitize_comment_token(f"{schema}.{tbl}" if schema else tbl)
lines.append(f"{divider}\n-- Unload Table: {label} -> Parquet\n{divider}")
required = [
_sanitize_comment_token(_strip(c.get("ColumnName")))
for c in cols
if _strip(c.get("Nullable") or "Y").upper() == "N"
and _strip(c.get("ColumnName"))
]
if required:
# Consumed by the executor: marks these Parquet fields REQUIRED so they
# load into the translated NOT NULL BigQuery columns.
lines.append(f"-- Required Columns: {','.join(required)}")
lines.append(stmt + "\n")
return "\n".join(lines)
# ==============================================================================
# 3. CLI Main Router (DEFAULT SCAFFOLDING)
# ==============================================================================
# DEFAULT SCAFFOLDING: CLI argument parser and SQL file writer entrypoint.
def _parse_args(args: list[str] | None = None) -> argparse.Namespace:
"""Builds and parses CLI arguments for Teradata export SQL generation."""
parser = argparse.ArgumentParser(
description="Teradata Parquet Export SQL Generator (outputs .sql)."
)
parser.add_argument(
"--translation-metadata-dir",
"--translation-output",
"--metadata-dir",
"--config-dir",
"--metadata-zip",
dest="metadata_path",
required=True,
help=(
"Path or Cloud Storage URI to translation_output/metadata directory,"
" config directory, or Teradata extractor metadata.zip"
),
)
parser.add_argument(
"--output-sql", help="File path to write the unified export SQL script"
)
parser.add_argument(
"--output-dir",
help="Directory to write individual per-table *_export.sql files",
)
parser.add_argument(
"--default-database",
default=os.environ.get("TERADATA_DATABASE", ""),
help="Fallback source database name when omitted in metadata",
)
parser.add_argument(
"--database",
action="append",
dest="databases",
help="Only export tables in this database (repeatable)",
)
parser.add_argument(
"--keep-char-padding",
action="store_true",
help="Do not TRIM(TRAILING) CHAR(n) columns",
)
parser.add_argument(
"--unbounded-number-scale",
type=int,
default=9,
help=(
"Decimal scale (0..38) for unbounded NUMBER / NUMBER(*) columns"
" (default: 9, supporting up to 29 integer digits; 38 - scale"
" integer digits; scale=38 leaves 0 integer digits)"
),
)
parsed = parser.parse_args(args)
if not 0 <= parsed.unbounded_number_scale <= 38:
parser.error("--unbounded-number-scale must be between 0 and 38.")
return parsed
def _sanitize_sql_filename(label: str, used_filenames: set[str]) -> str:
"""Builds a safe, collision-free per-table SQL filename."""
unquoted = label.replace('"', "").strip()
safe_parts = [
re.sub(r"[^A-Za-z0-9_-]+", "_", p.strip()).strip("_") or "table"
for p in unquoted.split(".")
if p.strip()
]
stem = "_".join(safe_parts) if safe_parts else "table"
filename = f"{stem}_export.sql"
if filename.upper() in used_filenames and len(safe_parts) > 1:
filename = f"{'__'.join(safe_parts)}_export.sql"
idx = 2
base_stem = filename[: -len("_export.sql")]
while filename.upper() in used_filenames:
filename = f"{base_stem}_{idx}_export.sql"
idx += 1
used_filenames.add(filename.upper())
return filename
def _write_table_sql_files(sql: str, output_dir: str) -> list[str]:
"""Splits the unified SQL script and writes individual table SQL files."""
os.makedirs(output_dir, exist_ok=True)
divider = "-- " + "-" * 77
chunks = sql.split(f"{divider}\n-- Unload Table: ")
written: list[str] = []
used_filenames: set[str] = set()
for chunk in chunks[1:]:
label = chunk.split(" -> Parquet")[0].strip()
filename = _sanitize_sql_filename(label, used_filenames)
path = os.path.join(output_dir, filename)
with open(path, "w", encoding="utf-8") as f:
f.write(f"{divider}\n-- Unload Table: {chunk}")
written.append(path)
print(f"Generated table export SQL: {path}")
return written
def main() -> None:
"""CLI entrypoint for the Teradata Parquet export SQL generator."""
args = _parse_args()
sql = generate_export_sql(
metadata_path_or_uri=args.metadata_path,
default_database=args.default_database,
databases=args.databases,
rtrim_char=not args.keep_char_padding,
unbounded_number_scale=args.unbounded_number_scale,
)
if args.databases and "-- Unload Table:" not in sql:
sys.exit("ERROR: No tables to export; check --database.")
if args.output_sql:
out_dir = os.path.dirname(os.path.abspath(args.output_sql))
os.makedirs(out_dir, exist_ok=True)
with open(args.output_sql, "w", encoding="utf-8") as f:
f.write(sql)
print(f"Generated unified export SQL: {args.output_sql}")
if args.output_dir:
_write_table_sql_files(sql, args.output_dir)
if not args.output_sql and not args.output_dir:
print(sql)
if __name__ == "__main__":
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-data-exporter)" \
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-data-exporter)`
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-data-exporter)
```
- **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.
databricks_parquet_mapping.md 13.7 KB
# Databricks / Spark SQL to BigQuery Parquet Type Mapping & Export Reference
This reference defines the type-safe Spark SQL projection rules used by
`export_databricks_tables_template.py` (`bigquery-migration-data-exporter`) and
the Parquet staging and Arrow streaming execution patterns for Databricks and
Apache Spark SQL.
## Contents
- [1. End-to-End Databricks Parquet Export Architecture][s1]: Lines 22-49
- [2. Databricks and Spark SQL Data Type Mapping Matrix][s2]: Lines 52-79
- [3. Unity Catalog and Hive Metastore Portability][s3]: Lines 82-106
- [4. Generated Spark SQL Pattern][s4]: Lines 109-138
[s1]: #1-end-to-end-databricks-parquet-export-architecture
[s2]: #2-databricks-and-spark-sql-data-type-mapping-matrix
[s3]: #3-unity-catalog-and-hive-metastore-portability
[s4]: #4-generated-spark-sql-pattern
--------------------------------------------------------------------------------
## 1. End-to-End Databricks Parquet Export Architecture
Databricks and Apache Spark SQL environments support two primary data export
topologies:
1. **Catalog-Agnostic SQL Generation (`bigquery-migration-data-exporter` —
`export_databricks_tables_template.py`)**: Reads BigQuery Migration Service
(BQMS) `translation_output/metadata/config/*.yaml` (or extraction
`metadata.zip` files containing `columns.csv`, `tables.jsonl`, or DDL `.sql`
scripts) and emits type-safe Spark SQL statements using **catalog-agnostic
2-part `<schema>.<table>` references** by default (or optional 3-part
`<catalog>.<schema>.<table>` when `--catalog` is specified). This allows the
exact same generated `.sql` files to execute against either **Unity
Catalog** (such as `main` or `retail_catalog`) or the legacy **Hive
Metastore** (`hive_metastore`).
2. **SQL Execution & Parquet Staging**:
* **Databricks SQL Warehouse (Arrow Streaming)**: Issues ``USE CATALOG
\`<catalog>\` `` on the session when a target catalog is configured,
extracts the inner type-safe `SELECT` query, and streams Arrow batches
(`cursor.fetchmany_arrow()` by using `databricks-sql-connector`)
directly into Snappy-compressed `.snappy.parquet` files on local disk
before syncing to Cloud Storage.
* **Cloud URIs / Unity Catalog Volumes / Spark Hive Thrift Server (`INSERT
OVERWRITE DIRECTORY`)**: Executes `INSERT OVERWRITE DIRECTORY '...'
USING PARQUET OPTIONS ('compression' = 'snappy') SELECT ...`, cleans
non-Parquet sidecar files (`.crc`, `_SUCCESS`), and stages the Parquet
chunks to Cloud Storage.
--------------------------------------------------------------------------------
## 2. Databricks and Spark SQL Data Type Mapping Matrix
<!-- disableFinding(LINE_OVER_80) -->
Databricks / Spark SQL Source Type | BQMS `sourceType` | Parquet / Arrow Type | BigQuery Target Type | Export SQL Projection (`format_column_cast`) | Rationale & Validation Notes
:---------------------------------------------------------------------------------- | :---------------------------- | :------------------------------------------------------------ | :------------------------------------ | :--------------------------------------------------------- | :---------------------------
**`TINYINT` / `BYTE` / `BYTEINT`** | `TINYINT` / `BYTE` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Widens 8-bit integer to 64-bit `INT64` to match BigQuery `INT64` target schema.
**`SMALLINT` / `SHORT`** | `SMALLINT` / `SHORT` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Widens 16-bit integer to 64-bit `INT64` to match BigQuery `INT64` target schema.
**`INT` / `INTEGER`** | `INT` / `INTEGER` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Widens 32-bit integer to 64-bit `INT64` to match BigQuery `INT64` target schema.
**`BIGINT` / `LONG`** | `BIGINT` / `LONG` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Direct 1:1 64-bit integer load.
**`FLOAT` / `REAL`** | `FLOAT` | `DOUBLE` (`pa.float64()`) | **`FLOAT64`** | `CAST(col AS DOUBLE) AS col` | Widens 32-bit IEEE-754 float to 64-bit `DOUBLE` in Parquet to standardize 64-bit floating-point representation with BigQuery `FLOAT64`.
**`DOUBLE`** | `DOUBLE` | `DOUBLE` (`pa.float64()`) | **`FLOAT64`** | `CAST(col AS DOUBLE) AS col` | Standard IEEE-754 64-bit floating-point.
**`DECIMAL(p, 0)`** *(target `INT64`, or `p <= 18` with target unset)* | `DECIMAL` / `NUMERIC` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Avoids decimal logical type wrapper when `p <= 18` (or the target BigQuery column is `INT64`); an explicit `FLOAT64` or `STRING` target casts to `DOUBLE` or `STRING` instead; `19 <= p <= 38` with `s = 0` stays `DECIMAL(p, 0)` for `NUMERIC` / `BIGNUMERIC`.
**`DECIMAL(p, s)` / `DEC(p, s)` / `NUMERIC(p, s)`** *(where `p - s <= 29, s <= 9`)* | `DECIMAL` / `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`NUMERIC`** | `CAST(col AS DECIMAL(p, s)) AS col` | Preserves exact decimal precision and scale without IEEE-754 float drift.
**`DECIMAL(p, s)`** *(where `p - s > 29` or `s > 9`, for example, `DECIMAL(38, 10)`)* | `DECIMAL` / `BIGNUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`BIGNUMERIC`** | `CAST(col AS DECIMAL(p, s)) AS col` | Requires `--decimal_target_types=NUMERIC --decimal_target_types=BIGNUMERIC --decimal_target_types=STRING` during `bq load`.
**`BOOLEAN`** | `BOOLEAN` | `BOOLEAN` (`pa.bool_()`) | **`BOOL`** | `CAST(col AS BOOLEAN) AS col` | Direct 1:1 boolean mapping.
**`DATE`** | `DATE` | `DATE` (`pa.date32()`) | **`DATE`** | `CAST(col AS DATE) AS col` | Days since Unix epoch (`1970-01-01`).
**`TIMESTAMP`** | `TIMESTAMP` | `TIMESTAMP_MICROS` (`pa.timestamp('us', tz='UTC')`) | **`TIMESTAMP`** | `CAST(col AS TIMESTAMP) AS col` | Microsecond UTC instant; loads directly into BigQuery `TIMESTAMP`.
**`TIMESTAMP_NTZ`** | `TIMESTAMP_NTZ` / `TIMESTAMP` | `TIMESTAMP_MICROS` (`isAdjustedToUTC=false` or `tz='UTC'`) | **`DATETIME`** / **`TIMESTAMP`** | `col` *(if `DATETIME`)* or `CAST(col AS TIMESTAMP) AS col` | When target is `DATETIME`, left uncast (`isAdjustedToUTC=false` maps to BigQuery `DATETIME`). When target is `TIMESTAMP` (or unset), cast to `TIMESTAMP` (run in a UTC session, for example with the SQL warehouse `TIMEZONE` parameter or `spark.sql.session.timeZone` set to `UTC`, for deterministic UTC conversion).
**`INTERVAL`** *(`YEAR TO MONTH` / `DAY TO SECOND`)* | `INTERVAL` | `UTF8` (`pa.string()`) | **`STRING`** | `CAST(col AS STRING) AS col` | Spark `INTERVAL` types cannot be written to Parquet directly; serializes ANSI interval text to UTF-8 `STRING`.
**`STRING` / `VARCHAR(n)` / `CHAR(n)`** | `STRING` / `VARCHAR` / `CHAR` | `UTF8` (`pa.string()`) | **`STRING`** | `col` | Exported as UTF-8 `STRING`. Note: Since Spark 3.4 (`spark.sql.readSideCharPadding=true`), Spark right-pads `CHAR(n)` on read unless `RTRIM(col)` is projected or `spark.sql.readSideCharPadding=false`.
**`BINARY`** | `BINARY` | `BYTE_ARRAY` (`pa.binary()`) | **`BYTES`** | `CAST(col AS BINARY) AS col` | Raw byte sequence; maps directly to BigQuery `BYTES`.
**`MAP<K, V>`** *(and `STRUCT` / `ARRAY` when target is `JSON` or `STRING`)* | `MAP` / `STRUCT` / `ARRAY` | `UTF8` (`pa.string()`) | **`JSON`** / **`STRING`** | `TO_JSON(col) AS col` | Native Parquet `MAP` is nested key/value records in BigQuery and `CAST(struct_col AS STRING)` emits non-JSON `{a, b}`; `TO_JSON(col)` guarantees valid RFC-8259 JSON text.
**`STRUCT<...>` / `ARRAY<...>`** *(when target is `RECORD` / `ARRAY` or unset)* | `STRUCT` / `ARRAY` | Parquet `GROUP` / `LIST` (`pa.struct(...)` / `pa.list_(...)`) | **`STRUCT` (`RECORD`)** / **`ARRAY`** | `col` | Native Parquet nested struct/list passthrough. Note: `bq load --source_format=PARQUET` requires `--parquet_enable_list_inference=true` for native `ARRAY` columns.
**`VARIANT` / `JSON`** | `VARIANT` / `JSON` | `UTF8` (`pa.string()`) | **`JSON`** / **`STRING`** | `CAST(col AS STRING) AS col` | Serializes Spark 4.0+ / Databricks `VARIANT` values to UTF-8 JSON strings.
<!-- enableFinding(LINE_OVER_80) -->
--------------------------------------------------------------------------------
## 3. Unity Catalog and Hive Metastore Portability
By default, `export_databricks_tables_template.py` strips the leading catalog
identifier from 3-part `sourceName` entries (`<catalog>.<schema>.<table>` →
`<schema>.<table>`) so the generated `.sql` scripts are **catalog-agnostic**:
* **Default (Catalog-Agnostic 2-Part SQL)**: Omit `--catalog` when running
`export_databricks_tables.py`. At execution time, run ``USE CATALOG
\`<catalog>\` `` on the Databricks session before executing each statement.
* **Explicit 3-Part Qualification**: Pass `--catalog <catalog>` to
`export_databricks_tables.py` if you want 3-part
`<catalog>.<schema>.<table>` identifiers baked directly into the `FROM`
clause. Metadata entries that name a different catalog are skipped (the
`spark_catalog` placeholder matches any `--catalog`). Without `--catalog`,
a `<schema>.<table>` that appears in more than one catalog is exported
once, with a warning.
* **Export Modes (`--export-mode`)**:
* `insert_overwrite` (default): Emits `INSERT OVERWRITE DIRECTORY '...'
USING PARQUET OPTIONS ('compression' = 'snappy') SELECT ...;`. When
connecting to a Databricks SQL Warehouse and targeting a local stage
path, downstream execution scripts can strip the `INSERT OVERWRITE
DIRECTORY` prefix and stream Arrow batches directly to Parquet.
* `select`: Emits standalone `SELECT ... FROM <schema>.<table>;`
statements with `-- Unload Table: <schema>.<table> -> Parquet` headers.
--------------------------------------------------------------------------------
## 4. Generated Spark SQL Pattern
```sql
-- =============================================================================
-- Databricks / Spark SQL to Parquet Type-Safe Data Export Script
-- Generated by bigquery-migration-data-exporter / export_databricks_tables.py
-- NOTE: TIMESTAMP_NTZ <-> TIMESTAMP casts use the session time zone. Run
-- in a UTC session (SQL warehouse TIMEZONE or spark.sql.session.timeZone
-- set to UTC, or SET TIME ZONE 'UTC' first in a beeline session).
-- =============================================================================
-- -----------------------------------------------------------------------------
-- Unload Table: retail_db.item -> Parquet
-- -----------------------------------------------------------------------------
INSERT OVERWRITE DIRECTORY '/tmp/databricks_export/item'
USING PARQUET
OPTIONS ('compression' = 'snappy')
SELECT
CAST(i_item_sk AS BIGINT) AS i_item_sk,
i_item_id,
CAST(i_rec_start_date AS DATE) AS i_rec_start_date,
CAST(i_current_price AS DECIMAL(7, 2)) AS i_current_price,
CAST(i_wholesale_cost AS DECIMAL(18, 4)) AS i_wholesale_cost,
CAST(i_exact_valuation AS DECIMAL(38, 10)) AS i_exact_valuation,
CAST(i_weight_kg AS DOUBLE) AS i_weight_kg,
CAST(i_created_at AS TIMESTAMP) AS i_created_at,
CAST(i_local_updated_at AS TIMESTAMP) AS i_local_updated_at,
CAST(i_thumbnail_hash AS BINARY) AS i_thumbnail_hash
FROM retail_db.item;
```
oracle_parquet_mapping.md 17.8 KB
# Oracle to BigQuery Parquet Type Mapping & Export Reference
This reference defines the type-safe projection rules used by
`export_oracle_tables_template.py` (`bigquery-migration-data-exporter`) and the
`pyarrow` Parquet schema mapping for downstream Oracle Parquet streaming.
## Contents
- [1. End-to-End Oracle Parquet Export Architecture][s1]: Lines 19-44
- [2. Oracle Data Type Mapping Matrix][s2]: Lines 45-71
- [3. Critical Implementation Details][s3]: Lines 72-114
- [4. Generated Oracle Export SQL Example][s4]: Lines 115-135
[s1]: #1-end-to-end-oracle-parquet-export-architecture
[s2]: #2-oracle-data-type-mapping-matrix
[s3]: #3-critical-implementation-details
[s4]: #4-generated-oracle-export-sql-example
## 1. End-to-End Oracle Parquet Export Architecture
Unlike Snowflake (`COPY INTO 'gcs://...'`) or Databricks (`INSERT OVERWRITE
DIRECTORY`), standard Oracle Database (11g, 12c, 19c, 21c, 23ai on-premises or
Compute Engine) does not provide a native SQL statement that unloads arbitrary
relational tables to Parquet on local disk or Cloud Storage
(`DBMS_CLOUD.EXPORT_DATA` is Autonomous Database-only).
Instead, the migration pipeline separates SQL generation from database
execution:
1. **SQL Generation (`bigquery-migration-data-exporter` —
`export_oracle_tables_template.py`)**: Reads BigQuery Migration Service
(BQMS) `translation_output/metadata/config/*.yaml` or the Oracle extraction
`metadata.zip` (`tables.csv`, `columns.csv`) and emits pure Oracle `SELECT`
statements with explicit `CAST`/`RTRIM`/`TRUNC` expressions, `-- Unload
Table: <SCHEMA>.<TABLE> -> Parquet` markers, and `-- Required Columns:`
nullability metadata.
2. **SQL Execution & Parquet Streaming**: A downstream Python script connects
to Oracle by using the pure-Python `python-oracledb` driver in thin mode (no
Oracle Instant Client required), executes each generated `SELECT`, maps
`cursor.description` to an explicit `pyarrow.schema`, streams batches to
Snappy-compressed Parquet part files
(`./data_unload/[<SCHEMA>/]<TABLE>/part-*.snappy.parquet`), and uploads them
to Cloud Storage.
## 2. Oracle Data Type Mapping Matrix
<!-- disableFinding(LINE_OVER_80) -->
Oracle Source Type | `ALL_TAB_COLUMNS` `DATA_TYPE` | BQMS `sourceType` (`name` / `genericName`) | Parquet / Arrow Type | BigQuery Target Type | Export SQL Projection (`format_column_cast`) | Rationale & Validation Notes
:----------------------------------------------------------------------------------- | :---------------------------------------------------------- | :---------------------------------------------------------- | :--------------------------------------------------------------------- | :--------------------------------------------------- | :----------------------------------------------------------------------------------------------------------- | :---------------------------
**`NUMBER(p, 0)`** *(where `1 <= p <= 19`)* / **`SMALLINT`** | `NUMBER` | `NUMBER` / `NUMERIC` (`scale: 0`) | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS NUMBER(19, 0)) AS col` | Casting to `NUMBER(19, 0)` pins `cursor.description` to `(precision=19, scale=0)`, which the executor maps to `pa.int64()` so `bq load` creates a native `INT64` column matching BQMS DDL.
**`NUMBER(p, 0)`** *(where `20 <= p <= 38`)* / **`INTEGER`** | `NUMBER` | `NUMBER` / `NUMERIC` (`scale: 0`) | `DECIMAL(p, 0)` (`pa.decimal128(p, 0)`) | **`INT64`** / **`NUMERIC(p)`** / **`BIGNUMERIC(p)`** | `CAST(col AS NUMBER(p, 0)) AS col` *(or `CAST(col AS NUMBER(19, 0))` if target is `INT64`)* | Exceeds signed 64-bit integer precision (`> 19` digits); preserved as exact `DECIMAL128(p, 0)`.
**`NUMBER(p, s)`** *(where `s > 0`, `p - s <= 29`, `s <= 9`)* | `NUMBER` | `NUMBER` / `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`NUMERIC(p, s)`** | `CAST(col AS NUMBER(p, s)) AS col` | Preserves exact decimal precision and scale; loads directly into BigQuery `NUMERIC`.
**`NUMBER(p, s)`** *(where `p - s > 29` or `s > 9`, for example, `NUMBER(38, 10)`)* | `NUMBER` | `NUMBER` / `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`BIGNUMERIC(p, s)`** | `CAST(col AS NUMBER(p, s)) AS col` | Requires `--decimal_target_types=NUMERIC --decimal_target_types=BIGNUMERIC --decimal_target_types=STRING` on `bq load`.
**`NUMBER(p, s)`** *(negative scale `s < 0`, for example, `NUMBER(10, -2)`)* | `NUMBER` | `NUMBER` / `NUMERIC` | `INT64` or `DECIMAL(p+\|s\|, 0)` | **`INT64`** / **`NUMERIC`** / **`BIGNUMERIC`** | `CAST(col AS NUMBER(19, 0))` *(if `p+\|s\| <= 19`)* or `CAST(col AS NUMBER(min(p+\|s\|, 38), 0))` | Negative scale rounds to `10^\|s\|` left of the decimal point (`p + \|s\|` integer digits, `0` fractional digits); normalizing to scale `0` avoids PyArrow negative-scale decimal errors.
**`NUMBER` / `NUMBER(*)`** *(unconstrained; `DATA_PRECISION=NULL, DATA_SCALE=NULL`)* | `NUMBER` | `NUMBER` / `NUMERIC` (`precision: 38`, no `scale`) | `DECIMAL(38, 9)` (`pa.decimal128(38, 9)`) or `DOUBLE` (`pa.float64()`) | **`NUMERIC`** / **`BIGNUMERIC`** / **`FLOAT64`** | `CAST(col AS NUMBER(38, 9)) AS col` *(or `CAST(col AS BINARY_DOUBLE)` if target is `FLOAT64`)* | Unconstrained Oracle `NUMBER` returns `(precision=0, scale=-127)` in `cursor.description`; casting to `NUMBER(38, 9)` supports `<= 29` integer digits and `9` fractional digits (configurable by using `--unbounded-number-scale 0..38`).
**`FLOAT(b)`** / **`BINARY_FLOAT`** / **`BINARY_DOUBLE`** | `FLOAT`, `BINARY_FLOAT`, `BINARY_DOUBLE` | `FLOAT`, `BINARY_FLOAT`, `BINARY_DOUBLE` | `DOUBLE` (`pa.float64()`) | **`FLOAT64`** | `CAST(col AS BINARY_DOUBLE) AS col` | Oracle `FLOAT(126)` is a binary-precision subtype of `NUMBER` and returns `DB_TYPE_NUMBER` unless cast; casting to `BINARY_DOUBLE` emits native IEEE-754 64-bit float (`DB_TYPE_BINARY_DOUBLE` -> `pa.float64()` -> BigQuery `FLOAT64`).
**`DATE`** | `DATE` | `DATE` (`genericName: DATE` / `DATETIME`) | `TIMESTAMP_MICROS` (`pa.timestamp('us')`) or `DATE` (`pa.date32()`) | **`DATETIME`** / **`DATE`** | `CAST(col AS TIMESTAMP(6)) AS col` *(default / `DATETIME`)* or `TRUNC(col) AS col` *(when target is `DATE`)* | Oracle `DATE` carries a `YYYY-MM-DD HH24:MI:SS` time component and BQMS translates it to `DATETIME` by default; `CAST(col AS TIMESTAMP(6))` preserves the time-of-day as `pa.timestamp('us')`. When `targetType` is `DATE`, `TRUNC(col)` strips time-of-day to `pa.date32()`.
**`TIMESTAMP(n)`** | `TIMESTAMP(6)` | `TIMESTAMP` (`genericName: DATETIME`) | `TIMESTAMP_MICROS` (`pa.timestamp('us')`) | **`DATETIME`** / **`TIMESTAMP`** | `CAST(col AS TIMESTAMP(6)) AS col` | Truncates/pads `TIMESTAMP(0..9)` to microsecond precision (`TIMESTAMP(6)`) so `python-oracledb` and PyArrow serialize microsecond timestamps without nanosecond truncation errors.
**`TIMESTAMP(n) WITH TIME ZONE`** | `TIMESTAMP(6) WITH TIME ZONE` | `TIMESTAMP WITH TIME ZONE` (`genericName: TIMESTAMP`) | `TIMESTAMP_MICROS` (`pa.timestamp('us')`) | **`TIMESTAMP`** | `CAST(SYS_EXTRACT_UTC(col) AS TIMESTAMP(6)) AS col` | Converts any time zone offset or named region (for example, `'America/Los_Angeles'` or `'UTC'`) to UTC on the Oracle server and returns a microsecond `TIMESTAMP(6)`. Avoids `python-oracledb` thin-mode `DPY-3022: named time zones are not supported in thin mode`.
**`TIMESTAMP(n) WITH LOCAL TIME ZONE`** | `TIMESTAMP(6) WITH LOCAL TIME ZONE` | `TIMESTAMP WITH LOCAL TIME ZONE` (`genericName: TIMESTAMP`) | `TIMESTAMP_MICROS` (`pa.timestamp('us')`) | **`TIMESTAMP`** / **`DATETIME`** | `CAST(SYS_EXTRACT_UTC(CAST(col AS TIMESTAMP WITH TIME ZONE)) AS TIMESTAMP(6)) AS col` | Converts the session-local value to `TIMESTAMP WITH TIME ZONE` and extracts UTC, so the export doesn't depend on the session `TIME_ZONE`; truncates to microsecond precision (`TIMESTAMP(6)`).
**`CHAR(n)`** / **`NCHAR(n)`** | `CHAR`, `NCHAR` | `CHAR`, `NCHAR` | `UTF8` (`pa.string()`) | **`STRING`** | `RTRIM(col) AS col` | Oracle right-pads fixed-width `CHAR(n)` / `NCHAR(n)` with spaces; `RTRIM(col)` strips trailing pad spaces to match BigQuery `STRING`. Pass `--keep-char-padding` to preserve padding.
**`VARCHAR2(n)`** / **`NVARCHAR2(n)`** / **`CLOB`** / **`NCLOB`** / **`LONG`** | `VARCHAR2`, `NVARCHAR2`, `CLOB`, `NCLOB`, `LONG` | `VARCHAR2`, `NVARCHAR2`, `CLOB`, `NCLOB` | `UTF8` (`pa.string()`) | **`STRING`** | `col AS col` | Preserves intentional trailing spaces on variable-length strings; the executor fetches `CLOB`/`NCLOB` values directly as UTF-8 strings (`oracledb.defaults.fetch_lobs = False`, with a `v.read()` fallback).
**`RAW(n)`** / **`BLOB`** / **`LONG RAW`** / **`BFILE`** | `RAW`, `BLOB`, `LONG RAW`, `BFILE` | `RAW`, `BLOB` | `BYTE_ARRAY` (`pa.binary()`) | **`BYTES`** | `col AS col` | Emits raw byte sequences (`DB_TYPE_RAW` / `DB_TYPE_BLOB` -> `pa.binary()` -> BigQuery `BYTES`).
**`ROWID`** / **`UROWID`** | `ROWID`, `UROWID` | `ROWID`, `UROWID` | `UTF8` (`pa.string()`) | **`STRING`** | `ROWIDTOCHAR(col) AS col` (`ROWID`) / `CAST(col AS VARCHAR2(256)) AS col` (`UROWID`) | Serializes physical (`ROWID`) and logical (`UROWID`) row addresses to standard character strings.
**`INTERVAL YEAR(p) TO MONTH`** / **`INTERVAL DAY(p) TO SECOND(s)`** | `INTERVAL YEAR(2) TO MONTH`, `INTERVAL DAY(2) TO SECOND(6)` | `INTERVAL YEAR TO MONTH`, `INTERVAL DAY TO SECOND` | `UTF8` (`pa.string()`) | **`STRING`** | `TRIM(CAST(col AS VARCHAR2(100))) AS col` | `python-oracledb` raises `DPY-3007` on `INTERVAL YEAR TO MONTH` in thin mode unless converted to string, and maps `INTERVAL DAY TO SECOND` to `datetime.timedelta`; `TRIM(CAST(col AS VARCHAR2(100)))` serializes both cleanly as ANSI interval strings.
**`XMLTYPE`** | `XMLTYPE` | `XMLTYPE` | `UTF8` (`pa.string()`) | **`STRING`** | `XMLSERIALIZE(CONTENT col AS CLOB) AS col` | Serializes Oracle `XMLTYPE` to UTF-8 XML text (`CLOB`).
**`JSON`** *(Oracle 21c+)* | `JSON` | `JSON` | `UTF8` (`pa.string()`) | **`JSON`** / **`STRING`** | `JSON_SERIALIZE(col RETURNING CLOB) AS col` | Serializes native binary OSON `JSON` to UTF-8 JSON text.
<!-- enableFinding(LINE_OVER_80) -->
## 3. Critical Implementation Details
1. **Why `SYS_EXTRACT_UTC(col)` is Required for `TIMESTAMP WITH TIME ZONE` in
`python-oracledb` Thin Mode**: When an Oracle `TIMESTAMP WITH TIME ZONE`
column contains a named time zone region rather than a numeric `+HH:MM`
offset, `python-oracledb` thin mode raises `DPY-3022: named time zones are
not supported in thin mode` unless a full `tzdata` package is negotiated.
Projecting `CAST(SYS_EXTRACT_UTC(col) AS TIMESTAMP(6)) AS col` converts the
timestamp to UTC on the Oracle server and transmits a plain 11-byte
`TIMESTAMP(6)` over the wire, which loads into BigQuery `TIMESTAMP` with
zero timezone drift.
2. **Why `FLOAT(126)` Must Be Cast to `BINARY_DOUBLE`**: In Oracle, `FLOAT(p)`
is stored internally as a `NUMBER` with binary precision `p` (`1..126`), so
`ALL_TAB_COLUMNS` reports `DATA_TYPE = 'FLOAT', DATA_PRECISION = 126,
DATA_SCALE = NULL`. Without an explicit cast, `python-oracledb` sees
`DB_TYPE_NUMBER (precision=126, scale=-127)` instead of a float. Casting
`CAST(col AS BINARY_DOUBLE)` produces `DB_TYPE_BINARY_DOUBLE` ->
`pa.float64()` -> BigQuery `FLOAT64`.
3. **Distinguishing Unconstrained `NUMBER` vs. `NUMBER(38, 0)` in Metadata**:
In `columns.csv`, unconstrained `NUMBER` has empty `DATA_PRECISION` and
`DATA_SCALE` (whereas `INTEGER` has empty `DATA_PRECISION` and `DATA_SCALE =
0`). In BQMS `translation_output/metadata/config/*.yaml`, unconstrained
`NUMBER` has `precision: 38` and no `scale` key (`scale: None`), whereas
`INTEGER` or `NUMBER(38, 0)` has explicit `scale: 0`. `format_column_cast()`
checks `precision` and `scale` to distinguish unconstrained `NUMBER`
(`CAST(col AS NUMBER(38, 9))`) from integer `NUMBER(p, 0)` (`CAST(col AS
NUMBER(19, 0))` for `p <= 19` or `CAST(col AS NUMBER(p, 0))` for `p >= 20`).
4. **Filtering `DBA.TabColumns.csv` / `columns.csv` by Physical Base Tables**:
Oracle's `ALL_TAB_COLUMNS` / `DBA_TAB_COLUMNS` view includes columns for
both physical tables and views, as well as `BIN$...` Recycle Bin objects,
`NESTED = 'YES'` tables, and `SECONDARY = 'Y'` domain-index tables.
`load_metadata_from_zip()` and `_filter_tables_to_export()` cross-reference
`DBA.Tables.csv` / `ALL.Tables.csv` (`DROPPED`, `SECONDARY`, `NESTED`, and
`BIN$...` prefixes) or `tables.csv` (`TableType = 'BASE TABLE'` / `'TABLE'`)
so only physical base tables are exported.
5. **Cross-Type `TargetType` Overrides**: `format_column_cast()` converts
integer, `FLOAT64`, `NUMERIC`, `BIGNUMERIC`, `DATETIME`, and `TIMESTAMP`
targets, and `DATE` targets on `DATE` / `TIMESTAMP` columns. Other
targets, such as `STRING`, `JSON`, or `BYTES` on numeric, datetime, or
`RAW` columns, keep the default projection in the matrix above. If the
BigQuery table needs a different conversion, edit the template's
`# CUSTOMIZE: Custom Type Projections` hook.
## 4. Generated Oracle Export SQL Example
```sql
-- -----------------------------------------------------------------------------
-- Unload Table: SALES_SCHEMA.ITEM -> Parquet
-- -----------------------------------------------------------------------------
-- Required Columns: I_ITEM_SK,I_ITEM_ID
SELECT
CAST(I_ITEM_SK AS NUMBER(19, 0)) AS I_ITEM_SK,
RTRIM(I_ITEM_ID) AS I_ITEM_ID,
CAST(I_REC_START_DATE AS TIMESTAMP(6)) AS I_REC_START_DATE,
CAST(I_REC_END_DATE AS TIMESTAMP(6)) AS I_REC_END_DATE,
I_ITEM_DESC AS I_ITEM_DESC,
CAST(I_CURRENT_PRICE AS NUMBER(7, 2)) AS I_CURRENT_PRICE,
CAST(I_WHOLESALE_COST AS NUMBER(7, 2)) AS I_WHOLESALE_COST,
CAST(I_MEASURE_PRECISE AS BINARY_DOUBLE) AS I_MEASURE_PRECISE,
CAST(I_EXACT_VALUATION AS NUMBER(38, 10)) AS I_EXACT_VALUATION,
I_PRODUCT_SPEC_CLOB AS I_PRODUCT_SPEC_CLOB,
I_THUMBNAIL_HASH AS I_THUMBNAIL_HASH
FROM SALES_SCHEMA.ITEM;
```
postgres_parquet_mapping.md 19.8 KB
# PostgreSQL to BigQuery Parquet Type Mapping & Export Reference
This reference defines the type-safe projection rules used by
`export_postgres_tables_template.py` (`bigquery-migration-data-exporter`) and
the `pyarrow` Parquet schema mapping for downstream PostgreSQL Parquet
streaming.
## Contents
- [1. End-to-End PostgreSQL Parquet Export Architecture][s1]: Lines 20-43
- [2. PostgreSQL Data Type Mapping Matrix][s2]: Lines 44-71
- [3. Critical Implementation Details][s3]: Lines 72-104
- [4. Generated PostgreSQL Export SQL Example][s4]: Lines 106-126
[s1]: #1-end-to-end-postgresql-parquet-export-architecture
[s2]: #2-postgresql-data-type-mapping-matrix
[s3]: #3-critical-implementation-details
[s4]: #4-generated-postgresql-export-sql-example
## 1. End-to-End PostgreSQL Parquet Export Architecture
Standard PostgreSQL (`COPY ... TO`) exports text, CSV, or PostgreSQL-proprietary
binary streams, not Apache Parquet files, and requires superuser privileges for
server-side file output. To guarantee zero type drift and schema-aligned
BigQuery ingestion, the migration pipeline separates SQL generation from
database execution:
1. **SQL Generation (`bigquery-migration-data-exporter` —
`export_postgres_tables_template.py`)**: Reads BigQuery Migration Service
(BQMS) `translation_output/metadata/config/*.yaml` or the PostgreSQL
extraction `metadata.zip` (`is_columns_private.csv` and
`pg_views_private.csv`, or `tables.csv` and `columns.csv`) and emits pure
PostgreSQL `SELECT` statements with explicit `CAST`/`RTRIM` expressions, `--
Unload Table: <SCHEMA>.<TABLE> -> Parquet` markers, and `-- Required
Columns:` nullability metadata.
2. **SQL Execution & Parquet Streaming**: A downstream Python script connects
to PostgreSQL by using `psycopg2`, sets session `TIME ZONE 'UTC'`, streams
rows in batches (`fetchmany`), maps `cursor.description` (`type_code` OID,
`precision`, `scale`) to an explicit `pyarrow.schema`, writes
Snappy-compressed Parquet part files
(`./data_unload/[<SCHEMA>/]<TABLE>/part-*.snappy.parquet`), and uploads them
to Cloud Storage.
## 2. PostgreSQL Data Type Mapping Matrix
<!-- disableFinding(LINE_OVER_80) -->
PostgreSQL Source Type | `information_schema` `data_type` / `udt_name` | BQMS `sourceType` (`name` / `genericName`) | Parquet / Arrow Type | BigQuery Target Type | Export SQL Projection (`format_column_cast`) | Rationale & Validation Notes
:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------- | :-------------------------------------------------------------------- | :-------------------------------------------------- | :--------------------------------------------- | :------------------------------------------------------------------------------------ | :---------------------------
**`SMALLINT`** / **`INTEGER`** / **`BIGINT`** / **`SMALLSERIAL`** / **`SERIAL`** / **`BIGSERIAL`** / **`OID`** | `smallint` (`int2`), `integer` (`int4`), `bigint` (`int8`), `oid` | `SMALLINT`, `INTEGER`, `BIGINT`, `OID` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Widens 16-bit and 32-bit integers and unsigned 32-bit `OID`s to 64-bit signed `BIGINT` (`OID 20` -> `pa.int64()` -> BigQuery `INT64`).
**`NUMERIC(p, 0)`** / **`DECIMAL(p, 0)`** *(where `1 <= p <= 38`)* | `numeric` | `NUMERIC` (`scale: 0`) | `DECIMAL(p, 0)` (`pa.decimal128(p, 0)`) | **`NUMERIC`** / **`BIGNUMERIC`** / **`INT64`** | `CAST(col AS NUMERIC(p, 0)) AS col` *(or `CAST(col AS BIGINT)` if target is `INT64`)* | Preserves exact decimal precision `NUMERIC(p, 0)` (`pa.decimal128(p, 0)`), which `bq load` maps to `NUMERIC` (`p <= 29`) or `BIGNUMERIC` (`30 <= p <= 38`).
**`NUMERIC(p, s)`** / **`DECIMAL(p, s)`** *(where `s > 0`, `p - s <= 29`, `s <= 9`)* | `numeric` | `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`NUMERIC(p, s)`** | `CAST(col AS NUMERIC(p, s)) AS col` | Preserves exact precision and scale in `cursor.description` (`OID 1700`) and loads directly into BigQuery `NUMERIC`.
**`NUMERIC(p, s)`** / **`DECIMAL(p, s)`** *(where `p - s > 29` or `s > 9`, `p <= 38`)* | `numeric` | `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`BIGNUMERIC(p, s)`** | `CAST(col AS NUMERIC(p, s)) AS col` | Requires `--decimal_target_types=NUMERIC --decimal_target_types=BIGNUMERIC --decimal_target_types=STRING` on `bq load`.
**`NUMERIC(p, s)`** *(negative scale `s < 0`, for example, `NUMERIC(10, -2)` in PostgreSQL 15+)* | `numeric` | `NUMERIC` | `DECIMAL(min(p+\|s\|, 38), 0)` (`pa.decimal128`) | **`NUMERIC`** / **`BIGNUMERIC`** | `CAST(col AS NUMERIC(min(p+\|s\|, 38), 0)) AS col` | Negative scale rounds to `10^\|s\|` left of the decimal point (`p + \|s\|` integer digits, `0` fractional digits). Casting to scale `0` avoids two's-complement negative scale encoding (`2048 + s`) in `atttypmod` and PyArrow negative-scale errors.
**`NUMERIC`** / **`DECIMAL`** *(unconstrained; `numeric_precision=NULL, numeric_scale=NULL`)* | `numeric` | `NUMERIC` (`precision: None, scale: None`) | `DECIMAL(38, 9)` (`pa.decimal128(38, 9)`) | **`NUMERIC`** / **`BIGNUMERIC`** | `CAST(col AS NUMERIC(38, 9)) AS col` | Unconstrained PostgreSQL `NUMERIC` returns `precision=None, scale=None` (`atttypmod = -1`); casting to `NUMERIC(38, 9)` supports `<= 29` integer digits and `9` fractional digits (configurable by using `--unbounded-number-scale 0..38`).
**`MONEY`** | `money` | `MONEY` | `DECIMAL(38, 2)` (`pa.decimal128(38, 2)`) | **`BIGNUMERIC`** / **`NUMERIC`** | `CAST(col AS NUMERIC(38, 2)) AS col` | PostgreSQL `money` formats values with locale currency symbols (`$1,234.56`) over text wire protocol (`OID 790`); casting to `NUMERIC(38, 2)` strips currency symbols cleanly on the server.
**`REAL`** / **`FLOAT4`** / **`DOUBLE PRECISION`** / **`FLOAT8`** | `real` (`float4`), `double precision` (`float8`) | `REAL`, `DOUBLE PRECISION` | `DOUBLE` (`pa.float64()`) | **`FLOAT64`** | `CAST(col AS DOUBLE PRECISION) AS col` | Widens 32-bit `REAL` (`float4`) to 64-bit IEEE-754 `DOUBLE PRECISION` (`OID 701` -> `pa.float64()` -> BigQuery `FLOAT64`) and preserves `NaN` / `±Infinity`.
**`BOOLEAN`** | `boolean` (`bool`) | `BOOLEAN` | `BOOLEAN` (`pa.bool_()`) | **`BOOL`** | `col AS col` | Maps directly to `bool` (`OID 16` -> `pa.bool_()` -> BigQuery `BOOL`).
**`DATE`** | `date` | `DATE` | `DATE` (`pa.date32()`) | **`DATE`** | `col AS col` | Maps directly to `datetime.date` (`OID 1082` -> `pa.date32()` -> BigQuery `DATE`). A `TIMESTAMP` target projects `CAST((CAST(col AS TIMESTAMP) AT TIME ZONE 'UTC') AS TIMESTAMP(6) WITH TIME ZONE) AS col` (midnight UTC, whatever the session `TimeZone`).
**`TIME(p) [WITHOUT TIME ZONE]`** / **`TIME(p) WITH TIME ZONE`** (`timetz`) | `time without time zone` (`time`), `time with time zone` (`timetz`) | `TIME`, `TIMETZ` | `TIME_MICROS` (`pa.time64('us')`) | **`TIME`** | `CAST(col AS TIME(6)) AS col` | Normalizes `TIME(0..6)` and `TIMETZ` to microsecond wall-clock precision (`OID 1083` -> `pa.time64('us')` -> BigQuery `TIME`).
**`TIMESTAMP(p) [WITHOUT TIME ZONE]`** | `timestamp without time zone` (`timestamp`) | `TIMESTAMP` (`genericName: DATETIME`) | `TIMESTAMP_MICROS` (`pa.timestamp('us')`) | **`DATETIME`** / **`TIMESTAMP`** | `CAST(col AS TIMESTAMP(6) WITHOUT TIME ZONE) AS col` *(default / `DATETIME`)* or `CAST((CAST(col AS TIMESTAMP) AT TIME ZONE 'UTC') AS TIMESTAMP(6) WITH TIME ZONE) AS col` *(when target is `TIMESTAMP`)* | Emits naive `datetime.datetime` (`OID 1114` -> `pa.timestamp('us', tz=None)`, `isAdjustedToUTC=false`), which `bq load` maps to BigQuery `DATETIME`. A `TIMESTAMP` target reads the naive value as UTC, independent of the session `TimeZone`.
**`TIMESTAMP(p) WITH TIME ZONE`** (`timestamptz`) | `timestamp with time zone` (`timestamptz`) | `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE` (`genericName: TIMESTAMP`) | `TIMESTAMP_MICROS` (`pa.timestamp('us', tz='UTC')`) | **`TIMESTAMP`** / **`DATETIME`** | `CAST(col AS TIMESTAMP(6) WITH TIME ZONE) AS col` *(default / `TIMESTAMP`)* or `CAST((col AT TIME ZONE 'UTC') AS TIMESTAMP(6) WITHOUT TIME ZONE) AS col` *(when target is `DATETIME`, the UTC wall clock)* | Normalizes `timestamptz` to microsecond precision (`OID 1184` -> `pa.timestamp('us', tz='UTC')`, `isAdjustedToUTC=true`), loading cleanly into BigQuery `TIMESTAMP` with zero timezone offset drift.
**`INTERVAL`** | `interval` | `INTERVAL` | `UTF8` (`pa.string()`) | **`STRING`** | `CAST(col AS TEXT) AS col` | `psycopg2` cannot parse `YEAR`/`MONTH` intervals into `datetime.timedelta`; casting `CAST(col AS TEXT)` emits canonical text (`1 year 2 mons 3 days 04:05:06`).
**`CHAR(n)`** / **`CHARACTER(n)`** / **`BPCHAR`** | `character` (`bpchar`) | `CHAR`, `CHARACTER` | `UTF8` (`pa.string()`) | **`STRING`** | `RTRIM(col) AS col` | PostgreSQL blank-pads fixed-width `CHAR(n)` (`bpchar`); `RTRIM(col)` strips trailing pad spaces to match BigQuery `STRING`. Pass `--keep-char-padding` to preserve padding.
**`VARCHAR(n)`** / **`TEXT`** | `character varying` (`varchar`), `text` | `VARCHAR`, `TEXT` | `UTF8` (`pa.string()`) | **`STRING`** | `col AS col` | Preserves intentional trailing spaces on variable-length strings (`OID 1043` / `25` -> `pa.string()`).
**`BYTEA`** | `bytea` | `BYTEA` | `BYTE_ARRAY` (`pa.binary()`) | **`BYTES`** | `col AS col` | `psycopg2` decodes hex `bytea` (`OID 17`) to `memoryview`, which the executor converts by using `bytes(v)` into `pa.binary()` -> BigQuery `BYTES`.
**`JSON`** / **`JSONB`** | `json`, `jsonb` | `JSON`, `JSONB` | `UTF8` (`pa.string()`) | **`JSON`** / **`STRING`** | `CAST(col AS TEXT) AS col` | Serializes `json` (`OID 114`) and binary `jsonb` (`OID 3802`) as UTF-8 JSON text (`OID 25` -> `pa.string()`), which `bq load` ingests into both BigQuery `JSON` and `STRING` columns.
**`UUID`** / **`XML`** / **`INET`** / **`CIDR`** / **`MACADDR`** / **`MACADDR8`** / **`BIT(n)`** / **`VARBIT(n)`** / **`TSVECTOR`** / **`TSQUERY`** / **`PG_LSN`** / **Geometric** / **Range** / **`ARRAY`** | `uuid`, `xml`, `inet`, `cidr`, `macaddr`, `bit`, `ARRAY`, `USER-DEFINED` | `UUID`, `XML`, `INET`, `STRING`, `ARRAY` | `UTF8` (`pa.string()`) | **`STRING`** | `CAST(col AS TEXT) AS col` | Normalizes PostgreSQL network, bit-string, geometric, range, XML, UUID, array, and enum types to `TEXT` (`OID 25`) so `psycopg2` returns `str` -> `pa.string()` -> BigQuery `STRING`.
<!-- enableFinding(LINE_OVER_80) -->
## 3. Critical Implementation Details
1. **Why PostgreSQL 15+ Negative `NUMERIC(p, -s)` Scales Must Be Decoded and
Normalized to Scale `0`**: PostgreSQL 15+ allows negative scales in
`NUMERIC(p, -s)` (for example, `NUMERIC(10, -2)`), and `information_schema`
masks `((typmod - 4) & 0x7ff)` without sign extension, reporting
`numeric_scale = 2046` (`2048 - 2`). Because Parquet and PyArrow do not
support negative decimal scales, `_decode_pg_scale()` decodes `1024 <= scale
< 2048` back to `scale - 2048` and `format_column_cast()` widens the
precision to `min(p + |s|, 38)` with scale `0` (`CAST(col AS NUMERIC(p +
|s|, 0))`).
2. **Why `MONEY` Must Be Cast to `NUMERIC(38, 2)`**: PostgreSQL's `money` type
(`OID 790`) formats values over the text protocol using `lc_monetary` (for
example, `'$1,234.56'` or `'($50.00)'`), which `psycopg2` returns as a
formatted `str`. Casting `CAST(col AS NUMERIC(38, 2))` in the `SELECT`
projection performs a lossless server-side conversion to `NUMERIC(38, 2)`
(`OID 1700` -> `decimal.Decimal` -> `pa.decimal128(38, 2)` -> BigQuery
`BIGNUMERIC`).
3. **Restoring Exact `NUMERIC(p, s)` and `NOT NULL` Metadata When Using BQMS
YAML Configs**: BQMS `translate_metadata` for PostgreSQL emits a generic
placeholder (`precision: 18, scale: 0`) for `NUMERIC` columns in
`metadata/config/*.yaml`. Pass the extractor `metadata.zip`
(`is_columns_private.csv`) with `--metadata-zip` alongside
`--translation-metadata-dir` (local or `gs://`), or place it next to a
local `translated_output/`, and `load_metadata_from_dir()` enriches the
YAML column metadata with the exact catalog precision, scale, and `NOT
NULL` constraints.
4. **Filtering System Catalog Schemas and Views**: PostgreSQL extraction zips
(`postgresql-metadata.zip`) include `is_columns_private.csv` (which contains
both base tables and views) and `pg_views_private.csv`, as well as
`pg_catalog` and `information_schema`. `load_metadata_from_zip()` and
`_filter_tables_to_export()` cross-reference `pg_views_private.csv` and
exclude `_SYSTEM_SCHEMAS` so only physical user base tables are exported.
## 4. Generated PostgreSQL Export SQL Example
```sql
-- -----------------------------------------------------------------------------
-- Unload Table: public.item -> Parquet
-- -----------------------------------------------------------------------------
-- Required Columns: i_item_sk,i_item_id
SELECT
CAST(i_item_sk AS BIGINT) AS i_item_sk,
RTRIM(i_item_id) AS i_item_id,
i_rec_start_date AS i_rec_start_date,
i_rec_end_date AS i_rec_end_date,
i_item_desc AS i_item_desc,
CAST(i_current_price AS NUMERIC(7, 2)) AS i_current_price,
CAST(i_wholesale_cost AS NUMERIC(7, 2)) AS i_wholesale_cost,
CAST(i_measure_precise AS DOUBLE PRECISION) AS i_measure_precise,
CAST(i_exact_valuation AS NUMERIC(38, 10)) AS i_exact_valuation,
CAST(i_product_spec_json AS TEXT) AS i_product_spec_json,
i_thumbnail_bytes AS i_thumbnail_bytes
FROM public.item;
```
snowflake_parquet_mapping.md 5.8 KB
# Snowflake to Parquet Type Mapping Reference for BigQuery
This reference details the exact column casting and logical type mappings
required when exporting data from **Snowflake** to **Parquet** to ensure
clean ingestion into **BigQuery** without type drift, truncation, or
JSON deserialization errors.
## Contents
- [1. Complete Type Mapping Matrix][s1]: Lines 20-40
- [2. Essential Snowflake Session Parameters][s2]: Lines 44-55
- [3. Recommended COPY INTO Parquet File Options][s3]: Lines 58-91
[s1]: #1-complete-type-mapping-matrix
[s2]: #2-essential-snowflake-session-parameters
[s3]: #3-recommended-copy-into-parquet-file-options
--------------------------------------------------------------------------------
## 1. Complete Type Mapping Matrix
<!-- disableFinding(LINE_OVER_80) -->
| Snowflake Source Type | Parquet Physical & Logical Type | BigQuery Target Type | Snowflake Export Cast Expression | Rationale & Ingestion Details |
| :-------------------- | :------------------------------ | :------------------- | :------------------------------- | :---------------------------- |
| **`VARIANT` / `OBJECT` / `ARRAY`** | `BYTE_ARRAY` (`UTF8` String) | **`JSON`** | `TO_VARCHAR(col) AS col` | BigQuery Parquet reader expects valid JSON-formatted UTF-8 strings to load directly into native `JSON` columns. Raw Snowflake binary objects fail ingestion. |
| **`NUMBER(P, S)`** *(where `S > 0`)* | `FIXED_LEN_BYTE_ARRAY` (`DECIMAL(P, S)`) | **`NUMERIC(P, S)`** *(where `P - S <= 29, S <= 9`)* or **`BIGNUMERIC(P, S)`** | `CAST(col AS DECIMAL(P, S)) AS col` | Preserves exact fractional scale without converting to floating-point `DOUBLE` (which introduces IEEE-754 precision loss). Pass `--decimal_target_types=NUMERIC --decimal_target_types=BIGNUMERIC --decimal_target_types=STRING` on `bq load` when `P - S > 29` or `S > 9`. |
| **`NUMBER(P, 0)`** *(where `1 <= P <= 19`)* / **`INT` / `BIGINT` / `SMALLINT` / `TINYINT` / `BYTEINT`** | `INT64` | **`INT64`** | `CAST(col AS BIGINT) AS col` | Prevents unnecessary decimal wrapper; loads directly as standard 64-bit integer. |
| **`NUMBER(P, 0)`** *(where `20 <= P <= 38`)* | `FIXED_LEN_BYTE_ARRAY` (`DECIMAL(P, 0)`) | **`NUMERIC(P)`** *(where `P <= 29`)* / **`BIGNUMERIC(P)`** / **`INT64`** | `CAST(col AS DECIMAL(P, 0)) AS col` *(or `CAST(col AS BIGINT)` if target is `INT64`)* | Exceeds signed 64-bit integer precision (`> 19` digits); preserved as exact `DECIMAL(P, 0)` when `TargetType` is unset so 20–38 digit integers do not overflow `BIGINT`. |
| **`NUMBER` / `DECIMAL` / `NUMERIC`** *(unconstrained; scale omitted)* | `FIXED_LEN_BYTE_ARRAY` (`DECIMAL(38, 9)`) | **`NUMERIC`** / **`BIGNUMERIC`** | `CAST(col AS DECIMAL(38, 9)) AS col` | Preserves up to `29` integer digits and `9` fractional digits without truncating scale when `TargetType` and `NumericScale` are omitted. |
| **`FLOAT` / `REAL` / `DOUBLE`** | `DOUBLE` | **`FLOAT64`** | `CAST(col AS DOUBLE) AS col` | Standard 64-bit floating point. |
| **`BOOLEAN`** | `BOOLEAN` | **`BOOL`** | `CAST(col AS BOOLEAN) AS col` | Direct 1:1 boolean mapping. |
| **`DATE`** | `INT32` (`DATE`) | **`DATE`** | `CAST(col AS DATE) AS col` | Days since Unix epoch (1970-01-01). |
| **`TIME` / `TIME(9)`** | `INT64` (`TIME_MICROS`) | **`TIME`** | `CAST(col AS TIME(6)) AS col` | Microseconds past midnight. Set session `TIME_OUTPUT_FORMAT = 'HH24:MI:SS.FF6'`. |
| **`TIMESTAMP_NTZ` / `TIMESTAMP_NTZ(9)`** | `INT64` (`TIMESTAMP_MICROS`) | **`DATETIME`** / **`TIMESTAMP`** | `CAST(col AS TIMESTAMP_NTZ(6)) AS col` | BigQuery supports microsecond precision. Avoids nanosecond overflow. |
| **`TIMESTAMP_TZ` / `TIMESTAMP_LTZ`** | `INT64` (`TIMESTAMP_MICROS`) | **`TIMESTAMP`** | `CAST(CONVERT_TIMEZONE('UTC', col) AS TIMESTAMP_NTZ(6)) AS col` | Normalized to UTC timestamp. |
| **`TEXT` / `VARCHAR` / `STRING` / `CHAR`** | `BYTE_ARRAY` (`UTF8`) | **`STRING`** | `CAST(col AS VARCHAR) AS col` | UTF-8 string encoding. |
| **`BINARY` / `VARBINARY`** | `BYTE_ARRAY` | **`BYTES`** | `CAST(col AS BINARY) AS col` | Raw byte sequence. |
<!-- enableFinding(LINE_OVER_80) -->
--------------------------------------------------------------------------------
## 2. Essential Snowflake Session Parameters
Before executing `COPY INTO`, set these session parameters to ensure uniform
microsecond and timestamp output formatting:
```sql
-- Ensure microsecond timestamp and time formatting
ALTER SESSION SET TIME_OUTPUT_FORMAT = 'HH24:MI:SS.FF6';
ALTER SESSION SET TIMESTAMP_NTZ_OUTPUT_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF6';
ALTER SESSION SET TIMESTAMP_TZ_OUTPUT_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF6 TZHTZM';
```
--------------------------------------------------------------------------------
## 3. Recommended COPY INTO Parquet File Options
```sql
COPY INTO 'gcs://my-bucket/path/TABLE_NAME/'
FROM (
SELECT
CAST(col1 AS BIGINT) AS col1,
CAST(col2 AS DECIMAL(38, 4)) AS col2,
TO_VARCHAR(col3) AS col3
FROM MY_DB.MY_SCHEMA.TABLE_NAME
)
STORAGE_INTEGRATION = my_gcs_integration
FILE_FORMAT = (
TYPE = PARQUET
COMPRESSION = SNAPPY
)
HEADER = TRUE
OVERWRITE = TRUE
MAX_FILE_SIZE = 104857600; -- 100MB chunk size optimal for BigQuery parallel ingestion
```
### Key Option Rationale
* **`STORAGE_INTEGRATION = my_gcs_integration`**: Required when unloading
directly to a private `gcs://` bucket (Snowflake doesn't accept inline
credentials for Cloud Storage). The generator emits this clause when you
pass `--storage-integration`; omit it for Snowflake stage targets such as
`@~/bqms_export/`.
* **`COMPRESSION = SNAPPY`**: Standard high-throughput compression supported
natively by BigQuery.
* **`HEADER = TRUE`**: Embeds column names into Parquet file schema header.
* **`OVERWRITE = TRUE`**: Ensures idempotency during re-runs.
* **`MAX_FILE_SIZE = 104857600`** (100MB): Splits large tables into ~100MB
partitions, allowing BigQuery parallel load slots to ingest concurrently.
teradata_parquet_mapping.md 11.0 KB
# Teradata to BigQuery Parquet Type Mapping & Export Reference
This reference defines the type-safe projection rules used by
`export_teradata_tables_template.py` (`bigquery-migration-data-exporter`) and
the `pyarrow` Parquet schema mapping for downstream Teradata Parquet streaming.
## Contents
- [1. End-to-End Teradata Parquet Export Architecture][s1]: Lines 21-45
- [2. Teradata Data Type Mapping Matrix][s2]: Lines 48-76
- [3. Critical Implementation Details][s3]: Lines 80-114
- [4. Generated Teradata Export SQL Example][s4]: Lines 118-134
[s1]: #1-end-to-end-teradata-parquet-export-architecture
[s2]: #2-teradata-data-type-mapping-matrix
[s3]: #3-critical-implementation-details
[s4]: #4-generated-teradata-export-sql-example
--------------------------------------------------------------------------------
## 1. End-to-End Teradata Parquet Export Architecture
Unlike Snowflake (`COPY INTO 'gcs://...'`) or Databricks (`INSERT OVERWRITE
DIRECTORY`), Teradata does not have a single universal SQL statement for
unloading arbitrary on-prem or cloud Vantage tables directly to Cloud Storage
without TPT/NOS infrastructure.
Instead, the migration pipeline separates SQL generation from database
execution:
1. **SQL Generation (`bigquery-migration-data-exporter` —
`export_teradata_tables_template.py`)**: Reads BigQuery Migration Service
(BQMS) `translation_output/metadata/config/*.yaml` or the Teradata
extraction `metadata.zip` (`dbc.TablesV.csv`, `dbc.ColumnsV.csv`) and emits
pure Teradata `SELECT` statements with explicit `CAST`/`TRIM` expressions,
`-- Unload Table: <DB>.<TABLE> -> Parquet` markers, and `-- Required
Columns:` nullability metadata.
2. **SQL Execution & Parquet Streaming**: A downstream Python script connects
to Teradata by using the Python `teradatasql` driver, executes each
generated `SELECT`, maps `cursor.description` to an explicit
`pyarrow.schema`, streams batches to Snappy-compressed Parquet part files
(`./data_unload/<DB>/<TABLE>/part-*.snappy.parquet`, or
`./data_unload/<TABLE>/part-*.snappy.parquet` when unqualified), and uploads
them to Cloud Storage.
--------------------------------------------------------------------------------
## 2. Teradata Data Type Mapping Matrix
<!-- disableFinding(LINE_OVER_80) -->
| Teradata Source Type | `dbc.ColumnsV` Code | BQMS `sourceType` | Parquet / Arrow Type | BigQuery Target Type | Export SQL Projection (`format_column_cast`) | Rationale & Validation Notes |
| :------------------- | :------------------ | :---------------- | :------------------- | :------------------- | :------------------------------------------- | :--------------------------- |
| **`BYTEINT`** | `I1` | `TINYINT` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Direct 1:1 64-bit integer load. |
| **`SMALLINT`** | `I2` | `SMALLINT` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Direct 1:1 64-bit integer load. |
| **`INTEGER`** | `I` | `INTEGER` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Direct 1:1 64-bit integer load. |
| **`BIGINT`** | `I8` | `BIGINT` | `INT64` (`pa.int64()`) | **`INT64`** | `CAST(col AS BIGINT) AS col` | Direct 1:1 64-bit integer load. |
| **`DECIMAL(p, s)`** *(where `p - s <= 29, s <= 9`)* | `D` | `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`NUMERIC(29+s, s)`** | `CAST(col AS DECIMAL(p, s)) AS col` | Preserves exact fixed scale; loads directly into `NUMERIC`. |
| **`DECIMAL(p, s)`** *(where `p - s > 29` or `s > 9`, for example, `DECIMAL(38,0)` or `DECIMAL(38,12)`)* | `D` | `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`BIGNUMERIC`** | `CAST(col AS DECIMAL(p, s)) AS col` | Requires `--decimal_target_types=NUMERIC --decimal_target_types=BIGNUMERIC --decimal_target_types=STRING` on `bq load`. |
| **`NUMBER(p, s)`** *(bounded)* | `N` | `NUMERIC` | `DECIMAL(p, s)` (`pa.decimal128(p, s)`) | **`NUMERIC`** / **`BIGNUMERIC`** | `CAST(col AS DECIMAL(p, s)) AS col` | Preserves exact precision and scale (or `CAST(col AS BIGINT)` when `TargetType` is `INT64`). |
| **`NUMBER` / `NUMBER(*)`** *(unbounded; `precision=-128` in `dbc.ColumnsV`)* | `N` | `NUMERIC` | `DECIMAL(38, 9)` (`pa.decimal128(38, 9)`) | **`NUMERIC(29)`** / **`BIGNUMERIC`** | `CAST(col AS DECIMAL(38, 9)) AS col` | Unbounded `NUMBER` reports `precision=40, scale=0` in `cursor.description` even when storing fractional values; `DECIMAL(38, 9)` supports `<= 29` integer digits (`38 - scale`; `scale=38` leaves `0` integer digits) and `9` fractional digits (configurable by using `--unbounded-number-scale 0..38` or `CAST(col AS VARCHAR(64))` for arbitrary scale; note that `--unbounded-number-scale > 9` or `VARCHAR` promotes the column to `BIGNUMERIC` or `STRING` during `bq load`, which requires matching target DDL types when loading into pre-created tables with `--replace=false`). |
| **`FLOAT` / `REAL` / `DOUBLE PRECISION`** | `F` | `DOUBLE` | `DOUBLE` (`pa.float64()`) | **`FLOAT64`** | `CAST(col AS FLOAT) AS col` | Standard IEEE-754 64-bit float. |
| **`DATE`** | `DA` | `DATE` | `DATE` (`pa.date32()`) | **`DATE`** | `CAST(col AS DATE) AS col` | Days since `1970-01-01`; supports `0001-01-01`..`9999-12-31`. |
| **`TIME(n)`** | `AT` | `TIME` | `TIME_MICROS` (`pa.time64('us')`) | **`TIME`** | `CAST(col AS TIME(6)) AS col` | Normalizes `TIME(0)`..`TIME(6)` to microsecond precision. |
| **`TIME(n) WITH TIME ZONE`** | `TZ` | `TIMETZ` | `TIME_MICROS` (`pa.time64('us')`) | **`TIME`** | `CAST((col AT TIME ZONE 'GMT') AS TIME(6)) AS col` | Normalizes to UTC and strips `tzinfo` (`pyarrow.time64` rejects tz-aware `datetime.time`), matching BQMS target `TIME`. |
| **`TIMESTAMP(n)`** | `TS` | `TIMESTAMP` | `TIMESTAMP_MICROS` (`pa.timestamp('us')`) | **`TIMESTAMP`** / **`DATETIME`** | `CAST(col AS TIMESTAMP(6)) AS col` | Microsecond precision; loads into BigQuery `TIMESTAMP` or `DATETIME`. |
| **`TIMESTAMP(n) WITH TIME ZONE`** | `SZ` | `TIMESTAMPTZ` | `TIMESTAMP_MICROS` (`pa.timestamp('us')`) | **`TIMESTAMP`** | `CAST((col AT TIME ZONE 'GMT') AS TIMESTAMP(6)) AS col` | Converts to UTC inside Teradata and emits a naive UTC `TIMESTAMP(6)`. |
| **`CHAR(n)` / `GRAPHIC(n)`** *(`LATIN`, `UNICODE`, or `GRAPHIC`)* | `CF`, `GF` | `CHAR` | `UTF8` (`pa.string()`) | **`STRING`** | `TRIM(TRAILING FROM col) AS col` | Teradata pads `CHAR(n)` (and `CHAR(n) UNICODE` to `2n` to `3n` byte length); `TRIM(TRAILING)` prevents trailing-space mismatches against BigQuery `STRING`. |
| **`VARCHAR(n)` / `VARGRAPHIC(n)` / `CLOB`** | `CV`, `GV`, `CO` | `VARCHAR`, `CLOB` | `UTF8` (`pa.string()`) | **`STRING`** | `col AS col` | Preserves intentional trailing spaces on variable-length strings. |
| **`BYTE(n)` / `VARBYTE(n)` / `BLOB`** | `BF`, `BV`, `BO` | `BINARY`, `VARBINARY`, `BLOB` | `BYTE_ARRAY` (`pa.binary()`) | **`BYTES`** | `col AS col` | Raw byte sequence; never cast `BYTE` to `VARCHAR` (Teradata raises a syntax/type error). |
| **`JSON`** | `JN` | `JSON` | `UTF8` (`pa.string()`) | **`JSON`** / **`STRING`** | `CAST(col AS CLOB) AS col` | Serializes Teradata `JSON` to a UTF-8 JSON text string. |
| **`PERIOD(DATE)` / `PERIOD(TIMESTAMP)`** | `PD`, `PT`, `PZ`, `PS`, `PM` | `PERIOD_*` | `UTF8` (`pa.string()`) | **`RANGE<DATE>`** / **`RANGE<TIMESTAMP>`** / **`STRING`** | `CAST(col AS VARCHAR(100)) AS col` | Parquet has no native `RANGE` logical type; exported as formatted period text `'(start, end)'`. |
| **`INTERVAL ...`** | `YR`, `YM`, `MO`, `DY`, `DH`, `DM`, `DS`, `HR`, `HM`, `HS`, `MI`, `MS`, `SC` | `INTERVAL` | `UTF8` (`pa.string()`) | **`INTERVAL`** / **`STRING`** | `TRIM(CAST(col AS VARCHAR(100))) AS col` | Teradata prefixes positive interval strings with a leading sign space (for example, `' 12-11'`); `TRIM` removes it. |
| **`XML` / `ST_GEOMETRY` / `UDT` / `ARRAY`** | `XM`, `UT`, `A1`, `AN` | `XML`, `UDT`, `ARRAY` | `UTF8` (`pa.string()`) | **`STRING`** / **`GEOGRAPHY`** | `CAST(col AS VARCHAR(32000)) AS col` | Serialized as UTF-8 text (`VARCHAR(32000)` fits both `LATIN` and `UNICODE`; WKT for `ST_GEOMETRY`). |
<!-- enableFinding(LINE_OVER_80) -->
--------------------------------------------------------------------------------
## 3. Critical Implementation Details
1. **`cursor.description` Nullability on Cast Expressions**: The `teradatasql`
driver reports `null_ok=True` on raw nullable table columns, but reports
`null_ok=False` on **every** `CAST(...)` or `TRIM(...)` projection
expression. To preserve exact column nullability in the Parquet schema,
`export_teradata_tables_template.py` emits a `-- Required Columns:
col1,col2` comment above each `SELECT` listing only columns where
`dbc.ColumnsV.Nullable = 'N'` (or BQMS `notNull: true`). The executor reads
that marker and sets `pa.field(name, dtype, nullable=name.lower() not in
required_columns)`.
2. **`--decimal_target_types` for High-Precision `DECIMAL(38, s)`**: Parquet
`DECIMAL(p, s)` columns where `p - s > 29` or `s > 9` (such as `DECIMAL(38,
0)` or `DECIMAL(38, 12)`) exceed BigQuery's 29-integer-digit /
9-fractional-digit `NUMERIC` limit. Pass `--decimal_target_types=NUMERIC
--decimal_target_types=BIGNUMERIC --decimal_target_types=STRING` to `bq
load` so BigQuery widens those columns to `BIGNUMERIC` automatically.
3. **Dirty-Read Export Concurrency (`LOCKING ROW FOR ACCESS`)**: Each generated
query starts with `LOCKING ROW FOR ACCESS` so large table exports do not
acquire read locks that block concurrent Teradata writers. Remove `LOCKING
ROW FOR ACCESS` in `_build_select_query()` if strict serializable read locks
are required.
4. **UTF-8 Session Encoding (`CHARACTER SET UNICODE`)**: The `teradatasql`
Python driver defaults to UTF-8 session encoding (`charset='UTF8'`), which
preserves non-ASCII `CHAR`/`VARCHAR CHARACTER SET UNICODE` characters
end-to-end into Parquet. Note that Teradata's JDBC driver defaults to
`ASCII` and replaces non-ASCII characters with `'?'` unless `CHARSET=UTF8`
is explicitly set on the JDBC connection.
5. **Cross-Type `TargetType` Overrides**: `format_column_cast()` converts
integer, `FLOAT64`, `NUMERIC`, `BIGNUMERIC`, `DATE`, `TIME`, `DATETIME`,
and `TIMESTAMP` targets. `STRING`, `JSON`, `BYTES`, and `BOOL` targets
keep the default projection in the matrix above, so numeric, datetime,
and `BYTE` / `VARBYTE` / `BLOB` columns keep their type. For a different
conversion, edit the template's `# CUSTOMIZE: Custom Type Projections`
hook.
--------------------------------------------------------------------------------
## 4. Generated Teradata Export SQL Example
```sql
-- -----------------------------------------------------------------------------
-- Unload Table: SALES_DB.ORDERS -> Parquet
-- -----------------------------------------------------------------------------
-- Required Columns: o_orderkey,o_custkey
LOCKING ROW FOR ACCESS
SELECT
CAST(o_orderkey AS BIGINT) AS o_orderkey,
CAST(o_custkey AS BIGINT) AS o_custkey,
TRIM(TRAILING FROM o_orderstatus) AS o_orderstatus,
CAST(o_totalprice AS DECIMAL(15,2)) AS o_totalprice,
CAST(o_orderdate AS DATE) AS o_orderdate,
CAST((o_created_tz AT TIME ZONE 'GMT') AS TIMESTAMP(6)) AS o_created_tz
FROM SALES_DB.ORDERS;
```
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