Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-migration-sql-translator@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin bigquery-migration-sql-translator v1.0.0 follows the Agent Plugins spec.
gh skills-hub install bigquery-migration-sql-translator Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/bigquery-migration-sql-translator/ Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-migration-sql-translator for Copilot to auto-discover it.
Skill Files (34)
SKILL.md 16.0 KB
---
name: bigquery-migration-sql-translator
metadata:
version: "1.0.2"
category: BigDataAndAnalytics
publisher: google
description: >-
Translates SQL queries, DDL schemas, and stored procedures from legacy database
dialects (Teradata, Oracle, Redshift, Snowflake, SparkSQL, HiveQL) to BigQuery
GoogleSQL using the BigQuery Migration Service (BQMS) MCP server. Use when
translating legacy SQL queries, migrating schemas or metadata zip archives,
or configuring BigQuery Migration Service (BQMS) YAML translation settings.
Don't use for executing BigQuery queries or managing datasets and tables (use
bigquery-basics), diagnosing runtime job errors (use bigquery-troubleshooting),
or tuning slot reservations (use bigquery-optimization).
---
# BigQuery Migration Service (BQMS) SQL Translator
The BigQuery Migration Service (BQMS) translates legacy database SQL scripts,
queries, and schemas into GoogleSQL. This skill coordinates translation
workflows, Cloud Storage staging, compiler error triage, and YAML configuration.
## 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
Before translating queries or schemas, verify the following prerequisites:
1. **Google Cloud SDK & Project Setup**: Ensure the
[Google Cloud SDK](https://cloud.google.com/sdk/docs/install) is installed,
verify that your Google Cloud project has an active Cloud Billing account
attached, and select the target project:
```bash
gcloud config set project {project_id}
```
2. **Enable the API**: Enable the BigQuery Migration API
(`bigquerymigration.googleapis.com`) in your Google Cloud project:
```bash
gcloud services enable bigquerymigration.googleapis.com
```
3. **Required IAM Roles**: Verify that your identity or service account has:
- `roles/mcp.toolUser` (MCP Tool User)
- `roles/bigquerymigration.editor` (Migration Workflow Editor)
- For batch translation, `roles/storage.objectViewer` and
`roles/storage.objectCreator` (or `roles/storage.objectAdmin`) on the
Cloud Storage buckets that hold the input and output files.
4. **MCP Server Connection**: If BigQuery Migration Service (BQMS) tools (e.g.
`translate_query`, `translate_batch_queries`) are not present in your active
tool list, configure the remote BigQuery Migration Service (BQMS) MCP
server. For setup instructions across clients (Claude, Cursor, Gemini CLI,
VS Code), see [mcp_config.md](references/mcp_config.md).
5. **Cost & Cloud Storage Cleanup**: Review
[Google Cloud Pricing](https://cloud.google.com/pricing) for Cloud Storage
and BigQuery usage details. After completing a batch migration, clean up
temporary staged input and output folders in Cloud Storage:
```bash
gcloud storage rm -r gs://{bucket}/{folder}
```
6. **Translation Tracking**: For batch translations, and for queries that need
more than one translation iteration, keep a translation tracker (e.g.
`translation_tracker.md`) to document goals, planned steps, and progress.
After each translation, record one row with this template:
Iteration | Status | Total Errors | Correctness Errors | Completeness Errors | Compatibility Errors | Key Actions / Transformations
--------- | ------ | ------------ | ------------------ | ------------------- | -------------------- | -----------------------------
A single query that translates cleanly on the first attempt needs no
tracker: report its translation ID and logs in your response.
## Workflow Selection
Choose the workflow based on your migration scope:
- **Interactive Translation (Single Query)**: Best for ad-hoc queries,
exploratory testing, dialect syntax comparison, or quick error debugging.
- **Batch Translation (Multiple Files & Cloud Storage)**: Use for more than
one file or a directory, including SQL embedded in application code (extract
it into `.sql` files first). For multi-file Python codebases containing
embedded SQL, use
[python_embedded_sql_migrator_template.py](assets/python_embedded_sql_migrator_template.py)
to extract queries into staged files and re-inject translated SQL. Batch
translation is faster and cheaper than translating files one by one, and it
resolves cross-file dependencies, so it usually gives better results. Run
`translate_batch_queries` on the staged files first; use `translate_query`
only afterwards if needed to debug a specific statement from
`translation_report.csv`.
## 1. Interactive Translation Workflow
Use the interactive workflow to translate a single query string, inspect
compiler logs, and iteratively resolve issues.
### Steps
1. **Submit Query (`translate_query`)**: Call `translate_query` with
`projectNumber`, `location`, `inputQuery`, `sourceDialect`, and
`targetDialect` (`BigQuery`). Include optional parameters:
- `metadataFilePath`: Cloud Storage URI to a metadata zip file
(`gs://.../metadata.zip`) for schema resolution.
- `translationConfigs`: Inline YAML configurations (e.g. object renaming,
schema redirection, optimizer rules). Show the YAML you used in your
response so the user can reuse it (e.g. in batch translation).
2. **Poll Status (`get_translation`)**: If the returned `translation_state` is
`RUNNING` or `PENDING`, poll `get_translation` using the `translation` ID,
`projectNumber`, and `location` until `translation.state` is `SUCCEEDED` or
`FAILED`, at the interval given in the BigQuery Migration Service (BQMS) MCP
tool descriptions. While the job runs, do work that doesn't need the result
(e.g. read the dialect gotchas reference).
3. **Inspect Output & Logs**:
- Examine `translated_query` for the converted GoogleSQL.
- Review each entry in `translation_logs`: inspect `severity` (`ERROR`,
`WARNING`), `category` (e.g. `RelationNotFound`), and `effect`
(`CORRECTNESS`, `COMPLETENESS`, `COMPATIBILITY`).
- Check the SQL itself, not only the logs: BigQuery Migration Service
(BQMS) emits `ERROR_TYPE(...)` for types it cannot map, sometimes with
no log entry. Treat any `ERROR_TYPE` or inline error comment as an
error, and when a BigQuery project is available, dry-run the result (`bq
query --dry_run --use_legacy_sql=false`). A `Not found` or `must be
qualified with a dataset` error still means the SQL is syntactically
valid; the referenced objects just don't exist in BigQuery yet. Say so
and move on, even if the error suggests a fix: don't stub tables or
change the SQL or `bq` flags to get past it.
- A `NoSuchFunction` error means BigQuery Migration Service (BQMS) copied
that call unchanged, sometimes with the function name in backticks.
Treat it as untranslated even if BigQuery has a function with that name:
a dry run that stops at missing tables doesn't check it.
- If the source dialect has a gotchas reference (see
[Dialect-Specific Gotchas](#dialect-specific-gotchas)), read it and
check the output for the patterns it lists. Some semantic differences
produce no log entry and still pass a dry run.
4. **Iterate Until Clean**: If the logs contain errors or warnings, the
translated SQL contains `ERROR_TYPE` or inline error comments, the dry run
fails, or the output matches a dialect gotcha, resolve the issues as
described in [Resolving Translation Issues](#resolving-translation-issues)
and re-translate.
5. **Explain & Compare Differences (`explain_translation`)**: When requested to
explain a translation, compare syntax differences, or understand how
specific query logic was converted, call `explain_translation` with
`translation` (the translation ID), `projectNumber`, and `location`. This
returns a structured explanation of the query's purpose and a detailed
breakdown of syntax, function, and behavioral differences between the source
query and the translated GoogleSQL. The explanation doesn't validate the
output, so check the translation as in step 3 rather than relying on it.
## 2. Batch Translation Workflow
Batch translation handles multiple files staged in Cloud Storage. It resolves
cross-file dependencies and produces a consolidated translation summary report
(`translation_report.csv`).
### Steps
1. **Stage Input Files to Cloud Storage**: Upload the raw SQL files,
configuration files (`*.config.yaml`), and any metadata file from the local
workspace to a Cloud Storage input folder:
```bash
gcloud storage cp input/*.sql gs://my-bucket/migration/input/
gcloud storage cp *.config.yaml gs://my-bucket/migration/input/
```
*Note: Do not pass configuration file paths in tool parameters if those
files are already located inside `sourceBaseUri`.*
Use new, empty Cloud Storage input and output folders for each run (e.g.
with a timestamp suffix). Stage only files from the local workspace or
generated in this run. Never reuse or copy inputs, DDL, or outputs that are
already in a bucket from earlier runs: they may come from different inputs
or settings.
2. **Initiate Batch Translation**:
- **Translating SQL Queries (`translate_batch_queries`)**: Call
`translate_batch_queries` with `projectNumber`, `location`,
`sourceDialect`, `targetDialect`, `sourceBaseUri`, and `targetBaseUri`.
- **Translating Metadata Zip Files (`translate_metadata`)**: To aid batch
translation by generating target BigQuery DDL schema definitions from an
extracted database metadata zip file (`metadata.zip` from Teradata,
Oracle, etc.), call `translate_metadata` specifying `sourceBaseUri`
(Cloud Storage URI to `metadata.zip`) and `targetBaseUri` (destination
Cloud Storage folder).
3. **Poll Completion (`fetch_batch_translation`)**: Poll using the returned
workflow ID until `translation.state` is `SUCCEEDED` or `FAILED`, at the
interval given in the BigQuery Migration Service (BQMS) MCP tool
descriptions.
4. **Retrieve & Inspect Outputs**: Download the generated files from
`translation.target_base_uri`:
```bash
gcloud storage cp -r gs://my-bucket/migration/output/ ./local_output/
```
Locate and inspect `report/translation_report.csv` to review all warnings,
errors, and line-level diagnostics. Then scan the generated `.sql` files for
`ERROR_TYPE(...)` and inline error comments, which the report can miss, and
dry-run the generated SQL when a BigQuery project is available (handle `Not
found` errors as in the interactive workflow). Check the output for the
patterns in the source dialect's gotchas reference, if one exists. Resolve
or clearly report every remaining issue; do not describe the output as clean
until this check passes.
5. **Iterate Until Clean**: Resolve the issues found in step 4 as described in
[Resolving Translation Issues](#resolving-translation-issues), and re-run
from step 1 with the changed inputs.
6. **Post-processing (Final Step Only)**: Only after resolving every compiler
error that re-translation can fix, execute any application-level
post-processing (e.g. AST re-injection) to restore host source files.
[effect_correctness.md](references/effect_correctness.md) lists the errors
that may remain when re-injecting embedded SQL.
## Resolving Translation Issues
Both workflows resolve issues the same way:
- Identify the **Effect** (`CORRECTNESS`, `COMPLETENESS`, `COMPATIBILITY`) of
each issue, and resolve them in order of compiler phase dependencies:
`CORRECTNESS` (parse errors) first, then `COMPLETENESS` (missing objects),
then `COMPATIBILITY` (unsupported features).
- **MUST Read the Reference Guide** for each effect in
[Troubleshooting by Error Effect](#troubleshooting-by-error-effect) BEFORE
applying fixes, and follow its resolution workflow.
- Fixes can preprocess the input (e.g. prepend DDL) or post-process the
BigQuery Migration Service (BQMS) output (e.g. a rewrite that a dialect
gotcha calls for). Run BigQuery Migration Service (BQMS) on the preprocessed
input rather than translating it yourself.
- Keep the source system's dialect for every re-translation. Another dialect
may accept the same SQL but translate it with different semantics (e.g.
return types, numeric types, or identifier case), so don't switch dialects
to get cleaner output.
- Rewrites of the BigQuery Migration Service (BQMS) output, including
optimizations the user asks for, must return the same rows as the source
query. For example, a filter that runs after a row limit (`TOP`, `LIMIT`)
can't be merged into the query before the limit.
- Wait for each re-translation to finish, record its translation ID, error
counts, and any pre- or post-processing in the tracker, and compare the
counts with the previous iteration. Repeat until no errors remain or all
options are exhausted.
- Report the final SQL from the tracked iteration, the pre- and
post-processing you applied, and any errors that remain.
## Reference Lookup Index
Use these reference guides when troubleshooting errors or authoring
configuration files:
### Troubleshooting by Error Effect
Effect | Common Causes | Reference Guide
:-------------- | :----------------------------------------------------------------------------------------- | :--------------
`CORRECTNESS` | Syntax errors, unescaped literals, application script wrappers, `NoSuchFunction`. | [effect_correctness.md](references/effect_correctness.md)
`COMPLETENESS` | Missing tables, views, columns (`RelationNotFound`, `AttributeNotFound`), DDL suggestions. | [effect_completeness.md](references/effect_completeness.md)
`COMPATIBILITY` | Functions or features without direct GoogleSQL mapping. | [effect_compatibility.md](references/effect_compatibility.md)
### Configuration & Setup Guides
Task | Description | Reference Guide
:---------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------
**YAML Configurations** | Database/schema redirection, name mapping, table partitioning and clustering injection, optimizer transformations, statement rewriters, and environment settings. Schemas in `assets/translation_config_schemas/` and examples in `assets/translation_config_examples/`. | [translation_yaml_config.md](references/translation_yaml_config.md)
**MCP Server Setup** | Configuring the remote BigQuery Migration Service (BQMS) MCP server, OAuth scopes, and IAM roles. | [mcp_config.md](references/mcp_config.md)
### Dialect-Specific Gotchas
Dialect | Key Considerations | Reference Guide
:------------ | :-------------------------------------------------------------------- | :--------------
**Teradata** | SET/MULTISET tables, `SAMPLE` clause, primary index mapping. | [teradata_gotchas.md](references/teradata_gotchas.md)
**Oracle** | PL/SQL procedures, `ROWNUM` emulation, outer join `(+)`, sequences. | [oracle_gotchas.md](references/oracle_gotchas.md)
**Snowflake** | Dynamic templates, `USE` statements, metadata merging, lateral joins. | [snowflake_gotchas.md](references/snowflake_gotchas.md)
python_embedded_sql_migrator_template.py 41.8 KB
#!/usr/bin/env python3
r"""Template Script for Automated Python Embedded SQL AST Migration.
This asset template script provides a reference implementation for preprocessing
and postprocessing application codebases for BigQuery Migration Service (BQMS):
1. Preprocessing (AST Extraction): Scans Python codebase, extracts full SQL
statements, parameterized queries, and partial SQL expression/predicate
segments (e.g. df.filter(), df.selectExpr(), expr(), sqlalchemy.text()),
discovers non-SQL DataFrame views (df.createOrReplaceTempView()), and
writes manifest.json plus staged .sql files with unambiguous wrappers.
2. Transpilation: Staged .sql files are transpiled via BigQuery Migration
Service (BQMS) batch migration.
3. Postprocessing (AST Re-injection): Reads BigQuery Migration Service (BQMS)
translated SQL, structurally unwraps fragments, preserves quote
styles/triple-quotes for multi-line injection, maps queries via manifest
bottom-up by occurrence span, and safely re-injects GoogleSQL back into
Python codebases.
Usage Pattern:
AI agents and engineers should copy this template file to a local working
directory or scratch space and adjust it per situational needs (e.g., custom
database framework calls, project-specific AST visitors, or dialect rules).
Example Execution:
python3 python_embedded_sql_migrator_template.py --preprocess \
--src ./my_project --staging ./staging_input --manifest ./manifest.json
python3 python_embedded_sql_migrator_template.py --postprocess \
--src ./my_project --staging-out ./staging_output \
--manifest ./manifest.json --out ./output/my_project
"""
import argparse
import ast
import glob
import json
import os
import re
import shutil
import subprocess
import sys
from typing import Any, Optional
# Strict SQL clause regex to prevent false-positives on plain strings.
STRICT_SQL_CLAUSE_REGEX = re.compile(
r"^(?:\s|/\*[\s\S]*?\*/|--[^\r\n]*|#[^\r\n]*)*"
r"(?:"
r"SELECT\s+(?:.*?\s+FROM\b|[^;\n]+)|"
r"INSERT\s+(?:INTO|OVERWRITE)\b|"
r"REPLACE\s+INTO\b|"
r"UPDATE\s+.*?\s+SET\b|"
r"DELETE\s+FROM\b|"
r"TRUNCATE\s+TABLE\b|"
r"CREATE\s+(?:OR\s+REPLACE\s+)?"
r"(?:TEMP|TEMPORARY|TABLE|VIEW|PROCEDURE|FUNCTION|SCHEMA|DATABASE)\b|"
r"DROP\s+(?:TABLE|VIEW|FUNCTION|PROCEDURE|SCHEMA|DATABASE)\b|"
r"ALTER\s+(?:TABLE|VIEW|SCHEMA|DATABASE)\b|"
r"WITH\s+.*?\s+AS\s*\(|"
r"MERGE\s+INTO\b|"
r"COPY\s+INTO\b|"
r"CALL\s+[A-Za-z0-9_.`\"'\[\]]+\s*\(|"
r"DECLARE\s+[A-Za-z_]|"
r"BEGIN\b[\s\S]+\bEND\b|"
r"GRANT\s+.*?\s+ON\b|"
r"REVOKE\s+.*?\s+ON\b"
r")",
re.IGNORECASE | re.DOTALL,
)
# Recognized DB/ORM execution method names across Python SQL frameworks.
EXECUTE_METHOD_NAMES = (
"execute",
"execute_async",
"executemany",
"read_gbq",
"query",
"sql",
"text",
"sql_expr",
"raw_sql",
)
# DataFrame methods taking partial SQL expression or predicate fragments.
DATAFRAME_FRAGMENT_METHODS = {
"expr": "expression",
"selectExpr": "select_list",
"filter": "predicate",
"where": "predicate",
}
# DataFrame view registration methods.
VIEW_REGISTRATION_METHODS = (
"createOrReplaceTempView",
"createTempView",
"createOrReplaceGlobalTempView",
"createGlobalTempView",
"registerTempTable",
)
# Common SQL placeholder patterns for parameterized queries, plus SQL string
# literals and `::` type-cast operators that must be skipped during masking.
SQL_LITERAL_OR_PLACEHOLDER_REGEX = re.compile(
r"('(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"|::)"
r"|(%[sdf]|%\([^)]+\)s|\?|(?<!:):[a-zA-Z_]\w*|\$\d+|\{[^{}]*\})"
)
PARAMETER_PLACEHOLDER_REGEX = re.compile(
r"(%[sdf]|%\([^)]+\)s|\?|(?<!:):[a-zA-Z_]\w*|\$\d+|\{[^{}]*\})"
)
# Markers placed around fragments during staging for BigQuery Migration Service
# (BQMS) compilation.
FRAGMENT_EXPR_HEADER = "/* BQMS_FRAGMENT:EXPR */ SELECT "
FRAGMENT_PRED_HEADER = (
"/* BQMS_FRAGMENT:PREDICATE */ SELECT * FROM __placeholder_table__ WHERE "
)
class SQLExtractor(ast.NodeVisitor):
"""AST Visitor to discover and extract SQL strings and fragments."""
def __init__(self, file_path: str, relative_path: str) -> None:
self.file_path = file_path
self.relative_path = relative_path
self.rel_path = relative_path # Alias for backward compatibility
self.extracted_queries: list[dict[str, Any]] = []
self.discovered_views: list[dict[str, Any]] = []
self._extracted_nodes: set[int] = set()
def _is_strict_sql(self, text: Any) -> bool:
"""Checks if string matches top-level SQL structure."""
if not text or not isinstance(text, str):
return False
clean = text.strip()
if len(clean) < 8:
return False
return STRICT_SQL_CLAUSE_REGEX.search(clean) is not None
def _detect_parameterization(self, sql_text: str) -> dict[str, Any]:
"""Detects if SQL string contains placeholders or parameter bindings."""
matches = [
m.group(2)
for m in SQL_LITERAL_OR_PLACEHOLDER_REGEX.finditer(sql_text)
if m.group(2) is not None
]
is_param = len(matches) > 0
style = "none"
if is_param:
sample = matches[0]
if sample.startswith("%"):
style = "py_printf"
elif sample == "?":
style = "qmark"
elif sample.startswith(":"):
style = "named_colon"
elif sample.startswith("$"):
style = "numeric_dollar"
elif sample.startswith("{") and sample.endswith("}"):
style = "format_brace"
return {
"is_parameterized": is_param,
"parameter_style": style,
"placeholders": matches,
}
def _generate_query_id(self, line_number: int) -> str:
"""Generates unique query ID from file path, line number, and index."""
normalized = self.relative_path.replace("\\", "/").replace("/", "__")
clean_path = re.sub(r"[^a-zA-Z0-9_]", "_", normalized)
sequence_index = len(self.extracted_queries) + 1
return f"{clean_path}_{line_number}_{sequence_index}"
def _record_span(self, target_node: ast.AST) -> dict[str, Optional[int]]:
"""Extracts source line and column span metadata from an AST node."""
return {
"col_offset": getattr(target_node, "col_offset", None),
"end_lineno": getattr(target_node, "end_lineno", None),
"end_col_offset": getattr(target_node, "end_col_offset", None),
}
def _record_assignment_node(
self, lineno: int, value_node: ast.AST, node_type: str
) -> None:
"""Extracts SQL strings from assignment value nodes."""
sql_val = self._extract_node_str(value_node)
if sql_val and self._is_strict_sql(sql_val):
self._extracted_nodes.add(id(value_node))
query_id = self._generate_query_id(lineno)
param_info = self._detect_parameterization(sql_val)
entry = {
"query_id": query_id,
"file_path": self.file_path,
"relative_path": self.relative_path,
"rel_path": self.relative_path,
"line_number": lineno,
"line_no": lineno,
"original_sql": sql_val,
"node_type": node_type,
"fragment_type": "statement",
"is_parameterized": param_info["is_parameterized"],
"parameter_style": param_info["parameter_style"],
}
entry.update(self._record_span(value_node))
self.extracted_queries.append(entry)
# pylint: disable=invalid-name
def visit_Assign(self, node: ast.Assign) -> None:
"""Extracts SQL strings from assignments requiring strict SQL structure."""
self._record_assignment_node(node.lineno, node.value, "Assign")
self.generic_visit(node)
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
"""Extracts SQL strings from type-annotated assignments."""
if node.value is not None:
self._record_assignment_node(node.lineno, node.value, "AnnAssign")
self.generic_visit(node)
def visit_Call(self, node: ast.Call) -> None: # pylint: disable=invalid-name
"""Extracts SQL or fragments from recognized DB, ORM & DataFrame calls."""
if id(node) in self._extracted_nodes:
self.generic_visit(node)
return
method_name: Optional[str] = None
receiver_name: Optional[str] = None
if isinstance(node.func, ast.Attribute):
method_name = node.func.attr
if isinstance(node.func.value, ast.Name):
receiver_name = node.func.value.id
elif isinstance(node.func, ast.Name):
method_name = node.func.id
# 1. Non-SQL DataFrame view registration
if method_name in VIEW_REGISTRATION_METHODS and node.args:
view_arg = self._extract_node_str(node.args[0])
if view_arg:
self.discovered_views.append({
"view_name": view_arg,
"line_number": node.lineno,
"dataframe_var": receiver_name or "df",
"file_path": self.file_path,
"relative_path": self.relative_path,
})
# 2. Recognized DB & ORM execution wrappers
elif method_name in EXECUTE_METHOD_NAMES and node.args:
first_arg = node.args[0]
if id(first_arg) not in self._extracted_nodes:
sql_str = self._extract_node_str(first_arg)
if sql_str and self._is_strict_sql(sql_str):
self._extracted_nodes.add(id(first_arg))
query_id = self._generate_query_id(node.lineno)
param_info = self._detect_parameterization(sql_str)
entry = {
"query_id": query_id,
"file_path": self.file_path,
"relative_path": self.relative_path,
"rel_path": self.relative_path,
"line_number": node.lineno,
"line_no": node.lineno,
"original_sql": sql_str,
"node_type": type(first_arg).__name__,
"fragment_type": "statement",
"is_parameterized": param_info["is_parameterized"],
"parameter_style": param_info["parameter_style"],
}
entry.update(self._record_span(first_arg))
self.extracted_queries.append(entry)
# 3. Partial SQL segment methods (df.filter(), df.selectExpr(), expr())
elif method_name is not None and method_name in DATAFRAME_FRAGMENT_METHODS:
fragment_kind = DATAFRAME_FRAGMENT_METHODS[method_name]
args_to_check = (
node.args if method_name == "selectExpr" else node.args[:1]
)
for arg in args_to_check:
if id(arg) in self._extracted_nodes:
continue
frag_str = self._extract_node_str(arg)
if frag_str and frag_str.strip():
self._extracted_nodes.add(id(arg))
query_id = self._generate_query_id(node.lineno)
param_info = self._detect_parameterization(frag_str)
entry = {
"query_id": query_id,
"file_path": self.file_path,
"relative_path": self.relative_path,
"rel_path": self.relative_path,
"line_number": node.lineno,
"line_no": node.lineno,
"original_sql": frag_str,
"node_type": type(arg).__name__,
"fragment_type": fragment_kind,
"method_call": method_name,
"is_parameterized": param_info["is_parameterized"],
"parameter_style": param_info["parameter_style"],
}
entry.update(self._record_span(arg))
self.extracted_queries.append(entry)
self.generic_visit(node)
def _extract_binop_str(self, binop_node: ast.BinOp) -> Optional[str]:
"""Extracts concatenated strings from binary add or modulo operations."""
if isinstance(binop_node.op, ast.Add):
left_str = self._extract_node_str(binop_node.left)
right_str = self._extract_node_str(binop_node.right)
if left_str is not None and right_str is not None:
return left_str + right_str
elif isinstance(binop_node.op, ast.Mod):
return self._extract_node_str(binop_node.left)
return None
def _extract_joined_str(self, joined_node: ast.JoinedStr) -> Optional[str]:
"""Extracts string representation from Python f-string AST nodes."""
parts: list[str] = []
conv_map = {97: "!a", 114: "!r", 115: "!s"}
for part in joined_node.values:
if isinstance(part, ast.Constant) and isinstance(part.value, str):
parts.append(part.value)
elif isinstance(part, ast.FormattedValue):
expr_src = (
ast.unparse(part.value) if hasattr(ast, "unparse") else "param"
)
conv_str = conv_map.get(getattr(part, "conversion", -1), "")
spec_str = ""
if getattr(part, "format_spec", None) is not None and isinstance(
part.format_spec, ast.JoinedStr
):
extracted_spec = self._extract_joined_str(part.format_spec)
if extracted_spec:
spec_str = f":{extracted_spec}"
parts.append(f"{{{expr_src}{conv_str}{spec_str}}}")
return "".join(parts) if parts else None
def _extract_node_str(self, node: ast.AST) -> Optional[str]:
"""Extracts string content from constant, binop, joined, or call nodes."""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
elif isinstance(node, ast.BinOp):
return self._extract_binop_str(node)
elif isinstance(node, ast.JoinedStr):
return self._extract_joined_str(node)
elif isinstance(node, ast.Call):
if isinstance(node.func, ast.Attribute) and node.func.attr == "format":
self._extracted_nodes.add(id(node))
return self._extract_node_str(node.func.value)
elif isinstance(node.func, ast.Name) and node.func.id in (
"text",
"sql_expr",
):
if node.args:
self._extracted_nodes.add(id(node))
self._extracted_nodes.add(id(node.args[0]))
return self._extract_node_str(node.args[0])
return None
def mask_sql_placeholders(sql_text: str) -> tuple[str, dict[str, str]]:
"""Masks parameter placeholders with valid SQL identifiers for BigQuery Migration Service (BQMS) staging."""
placeholder_map: dict[str, str] = {}
counter = 0
def _replacer(match: re.Match[str]) -> str:
if match.group(1) is not None:
return match.group(1)
nonlocal counter
counter += 1
token = f"__BQMS_PARAM_{counter}__"
placeholder_map[token] = match.group(2)
return token
masked_sql = SQL_LITERAL_OR_PLACEHOLDER_REGEX.sub(_replacer, sql_text)
return masked_sql, placeholder_map
def restore_sql_placeholders(
sql_text: str, placeholder_map: Optional[dict[str, str]]
) -> str:
"""Restores original parameter placeholders into translated SQL."""
if not placeholder_map:
return sql_text
result = sql_text
# Sort tokens longest-first to avoid partial prefix replacements.
for token in sorted(placeholder_map.keys(), key=len, reverse=True):
orig = placeholder_map[token]
result = re.sub(
r"`?" + re.escape(token) + r"`?",
lambda _, r=orig: r,
result,
flags=re.IGNORECASE,
)
return result
def wrap_fragment_for_staging(sql_text: str, fragment_type: str) -> str:
"""Wraps partial SQL fragments into valid statements for BigQuery Migration Service (BQMS) translation."""
clean = sql_text.strip()
if fragment_type in ("expression", "select_list"):
return f"{FRAGMENT_EXPR_HEADER}{clean};"
elif fragment_type == "predicate":
return f"{FRAGMENT_PRED_HEADER}{clean};"
else:
if not clean.endswith(";"):
clean += ";"
return clean
def unwrap_fragment_after_translation(
translated_sql: str, fragment_type: str
) -> Optional[str]:
"""Anchor-based structural unwrapping of expression or predicate fragments."""
clean = translated_sql.strip()
if clean.endswith(";"):
clean = clean[:-1].strip()
if fragment_type in ("expression", "select_list"):
# Strip anchor marker header at index 0 without matching subqueries
prefix_match = re.search(
r"^(?:/\*.*?\*/\s*)?select\s+", clean, re.IGNORECASE | re.DOTALL
)
if prefix_match:
return clean[prefix_match.end() :].strip()
return None
elif fragment_type == "predicate":
# Strip outer placeholder selection wrapper anchor at index 0
prefix_match = re.search(
r"^(?:/\*.*?\*/\s*)?select\s+\*\s+from"
r"\s+(?:[`\w.-]+\.)*`?__placeholder_table__`?\s+where\s+",
clean,
re.IGNORECASE | re.DOTALL,
)
if prefix_match:
return clean[prefix_match.end() :].strip()
return None
return clean
def format_sql_for_python(
translated_sql: str, original_sql: Optional[str] = None
) -> str:
del original_sql
clean_sql = translated_sql.strip()
if "\n" not in clean_sql:
return clean_sql
lines = clean_sql.split("\n")
if len(lines) <= 2:
return " ".join(line.strip() for line in lines if line.strip())
return f"\n{clean_sql}\n"
def _compute_span_offsets(
content: str,
line_number: Optional[int],
col_offset: Optional[int],
end_lineno: Optional[int],
end_col_offset: Optional[int],
) -> Optional[tuple[int, int]]:
"""Computes character start/end offsets in content from 1-based AST span."""
if (
line_number is None
or col_offset is None
or end_lineno is None
or end_col_offset is None
or line_number < 1
or end_lineno < line_number
):
return None
lines = content.splitlines(keepends=True)
if end_lineno > len(lines):
return None
start_line_offset = sum(len(l) for l in lines[: line_number - 1])
end_line_offset = sum(len(l) for l in lines[: end_lineno - 1])
start_idx = start_line_offset + len(
lines[line_number - 1]
.encode("utf-8")[:col_offset]
.decode("utf-8", errors="ignore")
)
end_idx = end_line_offset + len(
lines[end_lineno - 1]
.encode("utf-8")[:end_col_offset]
.decode("utf-8", errors="ignore")
)
if 0 <= start_idx < end_idx <= len(content):
return start_idx, end_idx
return None
def safe_reinject_into_python(
content: str,
original_sql: str,
translated_sql: str,
line_number: Optional[int] = None,
col_offset: Optional[int] = None,
end_lineno: Optional[int] = None,
end_col_offset: Optional[int] = None,
) -> str:
"""Safely injects translated SQL string into Python code."""
replacement = translated_sql.strip()
target_str = original_sql if original_sql in content else original_sql.strip()
def _escape_triple_body(text: str, quote: str) -> str:
escaped = text.replace(quote, f"\\{quote[0]}" * 3)
if escaped.endswith(quote[0]):
escaped = escaped[:-1] + f"\\{quote[0]}"
return escaped
def _prepare_triple_replacement(text: str, quote: str) -> str:
return f"{quote}{_escape_triple_body(text, quote)}{quote}"
def _prepare_single_replacement(text: str, quote: str) -> str:
escaped = text.replace(quote, f"\\{quote}")
return f"{quote}{escaped}{quote}"
span_bounds = _compute_span_offsets(
content, line_number, col_offset, end_lineno, end_col_offset
)
search_start = 0
if span_bounds is not None:
search_start = span_bounds[0]
elif line_number and line_number > 1:
lines = content.splitlines(keepends=True)
if line_number <= len(lines):
search_start = sum(len(l) for l in lines[: line_number - 1])
target_escaped_double = target_str.replace('"', '\\"')
target_escaped_single = target_str.replace("'", "\\'")
patterns_to_try = [
(f'"""{target_str}"""', "triple_double"),
(f"'''{target_str}'''", "triple_single"),
(f'"{target_str}"', "double"),
(f"'{target_str}'", "single"),
]
if target_escaped_double != target_str:
patterns_to_try.append((f'"{target_escaped_double}"', "double"))
if target_escaped_single != target_str:
patterns_to_try.append((f"'{target_escaped_single}'", "single"))
patterns_to_try.append((target_str, "bare"))
for pat, kind in patterns_to_try:
idx = content.find(pat, search_start)
if idx == -1 and search_start > 0:
idx = content.find(pat)
if idx != -1:
# If bare match is inside single-line quotes and replacement is multiline,
# promote enclosing single-line quotes to triple quotes.
if kind == "bare" and "\n" in replacement:
line_start = content.rfind("\n", 0, idx) + 1
line_end = content.find("\n", idx + len(pat))
if line_end == -1:
line_end = len(content)
before_on_line = content[line_start:idx]
after_on_line = content[idx + len(pat) : line_end]
for q_char, triple_q in (('"', '"""'), ("'", "'''")):
if (
q_char in before_on_line
and q_char in after_on_line
and triple_q not in before_on_line
):
q_open = line_start + before_on_line.rfind(q_char)
q_close = idx + len(pat) + after_on_line.find(q_char)
inner_prefix = content[q_open + 1 : idx]
inner_suffix = content[idx + len(pat) : q_close]
rep_val = _prepare_triple_replacement(
inner_prefix + replacement + inner_suffix, triple_q
)
return content[:q_open] + rep_val + content[q_close + 1 :]
if "\n" in replacement:
if kind == "triple_double":
rep_val = _prepare_triple_replacement(replacement, '"""')
elif kind == "triple_single":
rep_val = _prepare_triple_replacement(replacement, "'''")
elif kind == "double":
if '"""' in replacement and "'''" not in replacement:
rep_val = _prepare_triple_replacement(replacement, "'''")
else:
rep_val = _prepare_triple_replacement(replacement, '"""')
elif kind == "single":
if "'''" in replacement and '"""' not in replacement:
rep_val = _prepare_triple_replacement(replacement, '"""')
else:
rep_val = _prepare_triple_replacement(replacement, "'''")
else:
if content.rfind('"""', 0, idx) > content.rfind("'''", 0, idx):
rep_val = _escape_triple_body(replacement, '"""')
elif content.rfind("'''", 0, idx) > content.rfind('"""', 0, idx):
rep_val = _escape_triple_body(replacement, "'''")
else:
rep_val = replacement
else:
if kind == "triple_double":
rep_val = _prepare_triple_replacement(replacement, '"""')
elif kind == "triple_single":
rep_val = _prepare_triple_replacement(replacement, "'''")
elif kind == "double":
rep_val = _prepare_single_replacement(replacement, '"')
elif kind == "single":
rep_val = _prepare_single_replacement(replacement, "'")
else:
if content.rfind('"""', 0, idx) > content.rfind("'''", 0, idx):
rep_val = _escape_triple_body(replacement, '"""')
elif content.rfind("'''", 0, idx) > content.rfind('"""', 0, idx):
rep_val = _escape_triple_body(replacement, "'''")
else:
rep_val = replacement
return content[:idx] + rep_val + content[idx + len(pat) :]
# AST span-based literal replacement fallback (handles string literals with
# raw escape sequences like \n or \t where literal substring search differs).
if span_bounds is not None:
s_start, s_end = span_bounds
node_src = content[s_start:s_end]
m_lit = re.fullmatch(
r"([fFrRbBuU]*)(?P<q>\"\"\"|'''|\"|')(?P<body>.*)(?P=q)",
node_src,
flags=re.DOTALL,
)
if m_lit:
prefix = m_lit.group(1)
quote = m_lit.group("q")
if "\n" in replacement and len(quote) == 1:
triple_q = quote * 3
rep_lit = prefix + _prepare_triple_replacement(replacement, triple_q)
elif len(quote) == 3:
rep_lit = prefix + _prepare_triple_replacement(replacement, quote)
else:
rep_lit = prefix + _prepare_single_replacement(replacement, quote)
return content[:s_start] + rep_lit + content[s_end:]
# Fallback for concatenated string literals
tokens = [re.escape(t) for t in re.split(r"\s+", target_str) if t]
if tokens:
sep = r"""(?:\s*(?:['"]\s*(?:\+\s*)?['"]|\s)\s*)"""
pat_str = r"""(['"]?)""" + sep.join(tokens) + r"""(['"]?)"""
match = re.search(pat_str, content[search_start:], flags=re.IGNORECASE)
offset = search_start
if not match and search_start > 0:
match = re.search(pat_str, content, flags=re.IGNORECASE)
offset = 0
if match:
m_start = offset + match.start()
m_end = offset + match.end()
matched_text = match.group(0)
if matched_text.startswith(('"', "'")) and matched_text.endswith(
('"', "'")
):
is_single_quote = matched_text.startswith("'")
if "\n" in replacement:
quote = "'''" if is_single_quote else '"""'
rep_val = _prepare_triple_replacement(replacement, quote)
else:
quote = "'" if is_single_quote else '"'
rep_val = _prepare_single_replacement(replacement, quote)
return content[:m_start] + rep_val + content[m_end:]
return content[:m_start] + replacement + content[m_end:]
return content
# Most elements one BigQuery GENERATE_ARRAY call may return.
GENERATE_ARRAY_MAX_ELEMENTS = 1048576
# Inner array size when a range needs a cross join of two arrays.
_RANGE_CHUNK = 1000000
def range_to_googlesql(start: int, end: int) -> Optional[str]:
"""Returns a GoogleSQL table expression for Spark `range(start, end)`.
Like Spark's `range`, the result has one INT64 column named `id`, so
references such as `t.id` keep working. BigQuery's `GENERATE_ARRAY` returns
at most `GENERATE_ARRAY_MAX_ELEMENTS` values, so larger ranges cross join two
arrays.
Args:
start: First value (inclusive).
end: Last value (exclusive).
Returns:
A parenthesized subquery, or None if the range is too large to express.
"""
count = end - start
if count <= GENERATE_ARRAY_MAX_ELEMENTS:
return f"(SELECT id FROM UNNEST(GENERATE_ARRAY({start}, {end - 1})) AS id)"
chunks = -(-count // _RANGE_CHUNK)
if chunks > GENERATE_ARRAY_MAX_ELEMENTS:
return None
offset = f"{start} + " if start else ""
where = (
f" WHERE hi * {_RANGE_CHUNK} + lo < {count}"
if count % _RANGE_CHUNK
else ""
)
return (
f"(SELECT {offset}hi * {_RANGE_CHUNK} + lo AS id"
f" FROM UNNEST(GENERATE_ARRAY(0, {chunks - 1})) AS hi"
f" CROSS JOIN UNNEST(GENERATE_ARRAY(0, {_RANGE_CHUNK - 1})) AS lo{where})"
)
def apply_fallback_rules(sql_statement: str) -> str:
"""Applies heuristic fallback transforms for non-standard dialect syntax."""
result = sql_statement
def _replace_from_unixtime(match: re.Match[str]) -> str:
ts_expr = match.group(1).strip()
fmt_literal = match.group(2).strip()
if "%" not in fmt_literal:
fmt_literal = (
fmt_literal.replace("yyyy", "%Y")
.replace("yy", "%y")
.replace("MM", "%m")
.replace("dd", "%d")
.replace("HH", "%H")
.replace("mm", "%M")
.replace("ss", "%S")
)
return (
f"FORMAT_TIMESTAMP({fmt_literal}, TIMESTAMP_SECONDS(CAST({ts_expr} AS"
" INT64)))"
)
result = re.sub(
r"FROM_UNIXTIME\s*\(\s*([^,]+)\s*,\s*('[^']+')\s*\)",
_replace_from_unixtime,
result,
flags=re.IGNORECASE,
)
range_rules = [
(r"(\d+)\s*\*\s*(\d+)", lambda m: (0, int(m[1]) * int(m[2]))),
(r"(\d+)", lambda m: (0, int(m[1]))),
(r"(\d+)\s*,\s*(\d+)", lambda m: (int(m[1]), int(m[2]))),
]
# The lookbehind skips qualified names such as `db.range(10)`, which would
# otherwise become the invalid `db.(SELECT ...)`.
for args, bounds in range_rules:
result = re.sub(
rf"(?<![.\w])RANGE\s*\(\s*{args}\s*\)",
lambda m, bounds=bounds: range_to_googlesql(*bounds(m)) or m[0],
result,
flags=re.IGNORECASE,
)
result = re.sub(
r"\bCAST\s*\(\s*([^)]+?)\s+AS\s+INT\s*\)",
r"CAST(\1 AS INT64)",
result,
flags=re.IGNORECASE,
)
result = re.sub(
r"\bcurrent_user\s*\(\s*\)",
"SESSION_USER()",
result,
flags=re.IGNORECASE,
)
# Assumes a Spark, Databricks, or Hive source, where current_database() and
# current_schema() both name the schema (a BigQuery dataset). BigQuery has no
# CURRENT_SCHEMA(); @@dataset_id is the job's default dataset, or NULL if the
# job sets none. In Snowflake, Redshift, and PostgreSQL, CURRENT_DATABASE()
# is the BigQuery project instead.
result = re.sub(
r"\bcurrent_(?:database|schema)\s*\(\s*\)",
"@@dataset_id",
result,
flags=re.IGNORECASE,
)
return result
def _validate_directory_safety(
source_dir: str, target_dir: str, label: str
) -> None:
"""Ensures staging/output directories do not overlap with source_dir."""
real_src = os.path.realpath(source_dir)
real_target = os.path.realpath(target_dir)
if (
real_src == real_target
or real_target.startswith(real_src + os.sep)
or real_src.startswith(real_target + os.sep)
):
raise ValueError(
f"Unsafe {label} directory '{target_dir}': must not be equal to or"
f" overlap with source directory '{source_dir}'."
)
def preprocess(
source_dir: str,
staging_dir: str,
manifest_path: str,
gcs_input_uri: Optional[str],
) -> None:
"""Step 1: Walk codebase, extract embedded SQL via AST, and stage files."""
print("==================================================")
print("STEP 1: AST PREPROCESSING & SQL EXTRACTION")
print("==================================================")
_validate_directory_safety(source_dir, staging_dir, "staging")
if os.path.exists(staging_dir):
shutil.rmtree(staging_dir)
os.makedirs(staging_dir, exist_ok=True)
manifest: list[dict[str, Any]] = []
all_discovered_views: list[dict[str, Any]] = []
total_files = 0
for root, _, files in os.walk(source_dir):
for file in files:
if file.endswith(".py"):
total_files += 1
full_path = os.path.join(root, file)
relative_path = os.path.relpath(full_path, source_dir)
try:
with open(full_path, "r", encoding="utf-8") as f:
source = f.read()
tree = ast.parse(source, filename=full_path)
extractor = SQLExtractor(full_path, relative_path)
extractor.visit(tree)
all_discovered_views.extend(extractor.discovered_views)
for item in extractor.extracted_queries:
manifest.append(item)
sql_filename = f"{item['query_id']}.sql"
sql_file_path = os.path.join(staging_dir, sql_filename)
item["staged_sql_file"] = sql_filename
frag_type = item.get("fragment_type", "statement")
masked_sql, placeholder_map = mask_sql_placeholders(
item["original_sql"]
)
item["placeholder_map"] = placeholder_map
staged_sql = wrap_fragment_for_staging(masked_sql, frag_type)
with open(sql_file_path, "w", encoding="utf-8") as sf:
sf.write(staged_sql + "\n")
except Exception as e: # pylint: disable=broad-exception-caught
print(f"Warning: Could not parse {relative_path}: {e}")
# Cross-reference extracted queries against non-SQL DataFrame views
view_names = {v["view_name"] for v in all_discovered_views}
for item in manifest:
sql_text = item["original_sql"]
refs = [
vn for vn in view_names if re.search(rf"\b{re.escape(vn)}\b", sql_text)
]
item["referenced_dataframe_views"] = refs
# Generate relation stub DDLs for non-SQL DataFrame views so BigQuery
# Migration Service (BQMS) can resolve the relation name across any source
# dialect without triggering RelationNotFound on a nonexistent upstream table.
for view_info in all_discovered_views:
vn = view_info["view_name"]
inferred_cols: list[str] = []
for item in manifest:
for col in re.findall(
rf"\b{re.escape(vn)}\.([A-Za-z_]\w*)\b",
item["original_sql"],
re.IGNORECASE,
):
if col.lower() not in {c.lower() for c in inferred_cols}:
inferred_cols.append(col)
col_defs = (
", ".join(f"{c} VARCHAR(255)" for c in inferred_cols)
if inferred_cols
else "id INT"
)
stub_file = f"_dataframe_view_{vn}.sql"
stub_path = os.path.join(staging_dir, stub_file)
with open(stub_path, "w", encoding="utf-8") as sf:
sf.write(
f"-- Auto-generated DDL stub for non-SQL DataFrame relation: {vn}\n"
f"CREATE TABLE {vn} ({col_defs});\n"
)
manifest_output = {
"queries": manifest,
"discovered_dataframe_views": all_discovered_views,
}
with open(manifest_path, "w", encoding="utf-8") as mf:
json.dump(manifest_output, mf, indent=2)
print(f"Scanned {total_files} files.")
print(f"Extracted {len(manifest)} embedded SQL queries/fragments.")
print(f"Discovered {len(all_discovered_views)} non-SQL DataFrame views.")
print(f"Manifest written to: {manifest_path}")
print(f"Staged SQL files written to: {staging_dir}")
if gcs_input_uri:
print("\nUploading staged SQL files to Cloud Storage...")
gcs_target = (
gcs_input_uri if gcs_input_uri.endswith("/") else f"{gcs_input_uri}/"
)
staged_files = sorted(glob.glob(os.path.join(staging_dir, "*")))
if staged_files:
cmd = ["gcloud", "storage", "cp"] + staged_files + [gcs_target]
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
print(f"GCS upload error: {result.stderr}")
sys.exit(1)
print(f"Successfully uploaded staged files to {gcs_target}\n")
else:
print("No staged SQL files found to upload.\n")
def postprocess(
source_dir: str,
output_dir: str,
translated_dir: str,
manifest_path: str,
force: bool = False,
enable_fallback_rules: bool = False,
) -> None:
"""Step 3: Read translated SQL, map queries via manifest, and re-inject."""
print("==================================================")
print("STEP 3: POSTPROCESSING & AST RE-INJECTION")
print("==================================================")
_validate_directory_safety(source_dir, output_dir, "output")
if not os.path.exists(manifest_path):
print(f"Error: Manifest file {manifest_path} not found!")
sys.exit(1)
with open(manifest_path, "r", encoding="utf-8") as mf:
raw_manifest = json.load(mf)
if isinstance(raw_manifest, dict):
manifest = raw_manifest.get("queries", [])
else:
manifest = raw_manifest
if os.path.exists(output_dir):
if os.listdir(output_dir) and not force:
raise FileExistsError(
f"Output directory '{output_dir}' already exists and is non-empty."
" Pass --force (or force=True) to overwrite."
)
shutil.rmtree(output_dir)
sql_dir = os.path.join(translated_dir, "sql")
search_dir = sql_dir if os.path.exists(sql_dir) else translated_dir
translated_map: dict[str, str] = {}
if os.path.exists(search_dir):
for root, _, files in os.walk(search_dir):
for file in files:
if file.endswith(".sql") and not file.startswith("_dataframe_view_"):
query_id = os.path.splitext(file)[0]
file_path = os.path.join(root, file)
with open(file_path, "r", encoding="utf-8") as sf:
raw_content = sf.read().strip()
if (
raw_content.startswith("-- ERROR")
or "ERROR:" in raw_content[:100]
):
continue
lines = raw_content.splitlines()
start_idx = 0
while start_idx < len(lines) and (
not lines[start_idx].strip()
or lines[start_idx].strip().startswith("--")
):
start_idx += 1
translated_sql = "\n".join(lines[start_idx:]).strip()
translated_map[query_id] = translated_sql
queries_by_file: dict[str, list[dict[str, Any]]] = {}
for item in manifest:
file_rel_path = item.get("relative_path") or item.get("rel_path", "")
queries_by_file.setdefault(file_rel_path, []).append(item)
total_migrated = 0
total_substituted = 0
for root, _, files in os.walk(source_dir):
for file in files:
full_src_path = os.path.join(root, file)
relative_path = os.path.relpath(full_src_path, source_dir)
dest_path = os.path.join(output_dir, relative_path)
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
if file.endswith(".py"):
with open(full_src_path, "r", encoding="utf-8") as f:
content = f.read()
modified_content = content
if relative_path in queries_by_file:
# Sort queries bottom-up and right-to-left to prevent overlapping
# string replacements from invalidating earlier AST spans.
sorted_queries = sorted(
queries_by_file[relative_path],
key=lambda q: (
q.get("line_number", 0),
q.get("col_offset", 0),
),
reverse=True,
)
for query_info in sorted_queries:
qid = query_info["query_id"]
original_sql = query_info["original_sql"]
frag_type = query_info.get("fragment_type", "statement")
line_no = query_info.get("line_number")
col_off = query_info.get("col_offset")
end_line_no = query_info.get("end_lineno")
end_col_off = query_info.get("end_col_offset")
placeholder_map = query_info.get("placeholder_map")
if qid in translated_map and translated_map[qid]:
unwrapped = unwrap_fragment_after_translation(
translated_map[qid], frag_type
)
if unwrapped is None:
print(
"Warning: Could not unwrap translated SQL fragment for"
f" query '{qid}' ({relative_path}:{line_no}); skipping"
" re-injection."
)
continue
restored = restore_sql_placeholders(unwrapped, placeholder_map)
new_content = safe_reinject_into_python(
modified_content,
original_sql,
restored,
line_number=line_no,
col_offset=col_off,
end_lineno=end_line_no,
end_col_offset=end_col_off,
)
if new_content != modified_content:
modified_content = new_content
total_substituted += 1
elif restored != original_sql:
print(
"Warning: Could not locate original SQL literal for"
f" query '{qid}' ({relative_path}:{line_no}); skipping"
" re-injection."
)
else:
print(
"Warning: Missing clean BigQuery Migration Service (BQMS)"
f" translation for query '{qid}' ({relative_path}:{line_no})."
)
if enable_fallback_rules:
fallback_sql = apply_fallback_rules(original_sql)
if fallback_sql != original_sql:
new_content = safe_reinject_into_python(
modified_content,
original_sql,
fallback_sql,
line_number=line_no,
col_offset=col_off,
end_lineno=end_line_no,
end_col_offset=end_col_off,
)
if new_content != modified_content:
modified_content = new_content
total_substituted += 1
with open(dest_path, "w", encoding="utf-8") as df:
df.write(modified_content)
total_migrated += 1
else:
shutil.copy2(full_src_path, dest_path)
print(f"Successfully migrated {total_migrated} Python files.")
print(f"Re-injected {total_substituted} translated SQL queries into files.")
print(f"Migrated codebase saved to: {output_dir}\n")
def main() -> None:
parser = argparse.ArgumentParser(
description=(
"Automated Python Codebase AST Migration Tool for Embedded SQL"
)
)
parser.add_argument(
"--preprocess",
action="store_true",
help="Run Step 1 (AST SQL extraction and staging)",
)
parser.add_argument(
"--postprocess",
action="store_true",
help="Run Step 3 (Re-inject translated SQL into target codebase)",
)
parser.add_argument(
"--src",
dest="source_dir",
required=True,
help="Path to source Python codebase directory to scan or migrate.",
)
parser.add_argument(
"--out",
dest="output_dir",
default="./output/python",
help=(
"Output directory for the migrated codebase (default:"
" ./output/python)."
),
)
parser.add_argument(
"--staging",
dest="staging_dir",
default="./staging_input",
help=(
"Staging directory to store extracted .sql files (default:"
" ./staging_input)."
),
)
parser.add_argument(
"--staging-out",
dest="translated_dir",
default="./staging_output",
help=(
"Directory containing translated .sql files from BigQuery Migration"
" Service (BQMS) (default: ./staging_output)."
),
)
parser.add_argument(
"--manifest",
default="./manifest.json",
help=(
"Path to the query extraction manifest JSON file (default:"
" ./manifest.json)."
),
)
parser.add_argument(
"--gcs-input",
help=(
"Optional Cloud Storage URI for uploading staged SQL files (e.g."
" gs://my-bucket/input/)."
),
)
parser.add_argument(
"--force",
action="store_true",
help="Overwrite non-empty output directory during --postprocess.",
)
parser.add_argument(
"--enable-fallback-rules",
action="store_true",
help=(
"Apply heuristic regex fallback rules when a query has no clean"
" BigQuery Migration Service (BQMS) translation."
),
)
args = parser.parse_args()
if args.preprocess:
preprocess(args.source_dir, args.staging_dir, args.manifest, args.gcs_input)
elif args.postprocess:
postprocess(
args.source_dir,
args.output_dir,
args.translated_dir,
args.manifest,
force=args.force,
enable_fallback_rules=args.enable_fallback_rules,
)
else:
parser.print_help()
if __name__ == "__main__":
main()
environment_example.yaml 0.2 KB
# Configuration to specify a default database and schema search path:
type: environment
session:
defaultDatabase: myproject
schemaSearchPath: [dataset1, dataset2]
experimental_input_formats_example.yaml 0.2 KB
# Configuration to specify the explicit character encoding of the input file as ISO-8859-1:
type: experimental_input_formats
formats:
- source:
pathGlob: "*.sql"
contents:
raw:
charset: iso-8859-1
experimental_metadata_example.yaml 0.1 KB
# Convert all names starting with `a_` as aliases to the same name with `a_` stripped.
type: experimental_metadata
nameAlias:
stripRegex: a_(.*)
experimental_object_rewriter_example.yaml 1.5 KB
type: experimental_object_rewriter
# Convert a `TIMESTAMP` and a `TIMESTAMP WITH TIME ZONE` data type to `DATETIME`, with the target
# time zone set to `Europe/Paris`. Also, change the output names of all objects (database, schema,
# relation, and attributes) in the script according to the configured rules:
global:
typeConvert:
timestamp:
target: DATETIME
timezone: Europe/Paris
timestamptz:
target: DATETIME
timezone: Europe/Paris
outputName:
# Change table names to uppercase and everything else to lowercase. Also do the name cleaning
# for all the object names.
relation:
case: UPPERCASE
all:
case: LOWERCASE
replace:
# replace all whitespace characters with underscores.
- regex: '\s'
replaceWith: '_'
# replace '>=' symbol with 'gte' string.
- regex: '>='
replaceWith: 'gte'
# Change all names that don't start with a letter or an underscore to start with an
# underscore.
- regex: '^[^a-zA-Z_].*'
replaceWith: '_$0'
# Change the name of the table from `my_db.my_schema.my_table` to `my_new_db.my_schema.my_new_table`
# . And change the name of all tables by adding the prefix `stg_` to those that belong to the staging
# schema, and then moves those tables to the production schema:
relation:
- match: "my_db.my_schema.my_table"
outputName:
database: "my_new_db"
relation: "my_new_table"
- match:
schema: staging
outputName:
schema: production
relation: "stg_${relation}"
experimental_optimizer_example.yaml 0.3 KB
# Configuration to enable optional transformations. The configuration accepts a list of
# optimizations and, for optimizations which accept parameters, a section with optional parameter
# values
type: experimental_optimizer
transformations:
- name: PRECOMPUTE_INDEPENDENT_SUBSELECTS
- name: REWRITE_CTE_TO_TEMP_TABLE
parameters:
threshold: 1
experimental_statement_rewriter_example.yaml 0.4 KB
type: experimental_statement_rewriter
select:
# Configure the star projection to `EXPAND`:
starProjection: EXPAND
# By default, BigQuery Migration Service increases numeric precision to the highest precision
# available for a given scale. Override this behavior by configuring the precision strictness to
# retain the decimal precision of the source statement:
common:
decimalPrecision: STRICT
input_formats_example.yaml 0.2 KB
# Configuration to specify the explicit character encoding of the input file as ISO-8859-1:
type: input_formats
formats:
- source:
pathGlob: "*.sql"
contents:
raw:
charset: iso-8859-1
metadata_example.yaml 0.2 KB
# Configuration to specify the signature of user-defined functions (UDFs) that are used in the source
# scripts:
type: metadata
udfs:
- "date parse_short_date(dt int)"
object_rewriter_example.yaml 0.7 KB
type: object_rewriter
# Change the upper or lower-casing of object names:
global:
case:
all: UPPERCASE
database: LOWERCASE
attribute: LOWERCASE
# Select the `testdb.acme.employee` table for a temporary table transformation and change all
# relations from `tmp_schema` schema in `testdb` to temporary, as long as their name starts with
# `tmp_`
relation:
- match: "testdb.testschema.x"
temporary: true
- match:
schema: tmp_schema
relationRegex: "tmp_.*"
temporary: true
# Change the data type for an attribute of a relation:
attribute:
- match:
database: testdb
schema: testschema
attributeRegex: "a+"
type:
target: NUMERIC(10,2)
optimizer_example.yaml 0.3 KB
# Configuration to enable optional transformations. The configuration accepts a list of
# optimizations and, for optimizations which accept parameters, a section with optional parameter
# values
type: optimizer
transformations:
- name: PRECOMPUTE_INDEPENDENT_SUBSELECTS
- name: REWRITE_CTE_TO_TEMP_TABLE
parameters:
threshold: 1
statement_rewriter_example.yaml 0.4 KB
type: statement_rewriter
select:
# Configure the star projection to `EXPAND`:
starProjection: EXPAND
# By default, BigQuery Migration Service increases numeric precision to the highest precision
# available for a given scale. Override this behavior by configuring the precision strictness to
# retain the decimal precision of the source statement:
common:
decimalPrecision: STRICT
environment.json 0.5 KB
{
"type" : "object",
"properties" : {
"session" : {
"type" : "object",
"properties" : {
"dateFormat" : {
"type" : "string"
},
"defaultDatabase" : {
"type" : "string"
},
"schemaSearchPath" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "environment"
}
}
}
experimental_input_formats.json 1.0 KB
{
"type" : "object",
"properties" : {
"formats" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"contents" : {
"type" : "object",
"properties" : {
"raw" : {
"type" : "object",
"properties" : {
"charset" : {
"type" : "string"
}
}
}
}
},
"source" : {
"type" : "object",
"properties" : {
"pathGlob" : {
"type" : "string"
},
"pathRegex" : {
"type" : "string"
},
"path" : {
"type" : "string"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_input_formats"
}
}
}
experimental_metadata.json 0.6 KB
{
"type" : "object",
"properties" : {
"nameAlias" : {
"type" : "object",
"properties" : {
"stripPrefix" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripRegex" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripSuffix" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_metadata"
}
}
}
experimental_object_rewriter.json 19.5 KB
{
"type" : "object",
"properties" : {
"attribute" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"attribute" : {
"type" : "string"
},
"attributeRegex" : {
"type" : "string"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"alias" : {
"type" : "string",
"enum" : [ "UPDATE", "PRESERVE" ]
},
"attribute" : {
"type" : "string"
}
}
}
}
}
},
"database" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
}
}
}
}
}
},
"function" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"function" : {
"type" : "string"
},
"functionRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"function" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"global" : {
"type" : "object",
"properties" : {
"outputName" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"attribute" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"database" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"function" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"index" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"matchNameParts" : {
"type" : "array",
"items" : {
"type" : "string",
"enum" : [ "database", "schema", "relation", "attribute" ]
}
},
"projection" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"regex" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
},
"relation" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"schema" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"sequence" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"variable" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
}
}
},
"strip" : {
"type" : "object",
"properties" : {
"stripPrefix" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripRegex" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripSuffix" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"typeConvert" : {
"type" : "object",
"properties" : {
"char" : {
"type" : "object",
"properties" : {
"comparisonBehavior" : {
"type" : "string",
"enum" : [ "STRICT", "PADDING_AWARE", "CASE_AWARE", "NONE" ]
},
"precisionAction" : {
"type" : "string",
"enum" : [ "PRESERVE", "DROP" ]
},
"target" : {
"type" : "string",
"required" : true,
"enum" : [ "VARCHAR" ]
}
}
},
"datetime" : {
"type" : "object",
"properties" : {
"target" : {
"type" : "string",
"enum" : [ "DATETIME", "TIMESTAMP", "TIMESTAMPTZ" ]
},
"timezone" : {
"type" : "string"
}
}
},
"timestamp" : {
"type" : "object",
"properties" : {
"target" : {
"type" : "string",
"enum" : [ "DATETIME", "TIMESTAMP", "TIMESTAMPTZ" ]
},
"timezone" : {
"type" : "string"
}
}
},
"timestamptz" : {
"type" : "object",
"properties" : {
"target" : {
"type" : "string",
"enum" : [ "DATETIME", "TIMESTAMP", "TIMESTAMPTZ" ]
},
"timezone" : {
"type" : "string"
}
}
},
"varchar" : {
"type" : "object",
"properties" : {
"comparisonBehavior" : {
"type" : "string",
"enum" : [ "STRICT", "PADDING_AWARE", "CASE_AWARE", "NONE" ]
},
"precisionAction" : {
"type" : "string",
"enum" : [ "PRESERVE", "DROP" ]
},
"target" : {
"type" : "string",
"required" : true,
"enum" : [ "VARCHAR" ]
}
}
}
}
}
}
},
"index" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"index" : {
"type" : "string"
},
"indexRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"index" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"projection" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"projection" : {
"type" : "string"
},
"projectionRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"projection" : {
"type" : "string"
}
}
}
}
}
},
"relation" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"alias" : {
"type" : "string",
"enum" : [ "UPDATE", "PRESERVE", "EXCLUSIVE_UPDATE" ]
},
"database" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"schema" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"sequence" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
},
"sequence" : {
"type" : "string"
},
"sequenceRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"sequence" : {
"type" : "string"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_object_rewriter"
},
"variable" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"variable" : {
"type" : "string"
},
"variableRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"variable" : {
"type" : "string"
}
}
}
}
}
}
}
}
experimental_optimizer.json 0.6 KB
{
"type" : "object",
"properties" : {
"transformations" : {
"type" : "array",
"description" : "A list of optimization transformations to apply to the input. Each transformation consists of an optimization name and an optional list of optimization-specific parameters.",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"parameters" : {
"type" : "any"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_optimizer"
}
}
}
experimental_statement_rewriter.json 1.3 KB
{
"type" : "object",
"properties" : {
"common" : {
"type" : "object",
"properties" : {
"decimalPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
},
"defaultValueValidation" : {
"type" : "boolean"
},
"identityNumericCastAsTruncate" : {
"type" : "boolean"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stringPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
}
}
},
"emitterCharset" : {
"type" : "string",
"enum" : [ "UTF8", "US_ASCII" ]
},
"select" : {
"type" : "object",
"properties" : {
"groupBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"orderBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"starProjection" : {
"type" : "string",
"enum" : [ "ALLOW", "PRESERVE", "EXPAND" ]
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_statement_rewriter"
}
}
}
input_formats.json 0.9 KB
{
"type" : "object",
"properties" : {
"formats" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"contents" : {
"type" : "object",
"properties" : {
"raw" : {
"type" : "object",
"properties" : {
"charset" : {
"type" : "string"
}
}
}
}
},
"source" : {
"type" : "object",
"properties" : {
"pathGlob" : {
"type" : "string"
},
"pathRegex" : {
"type" : "string"
},
"path" : {
"type" : "string"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "input_formats"
}
}
}
metadata.json 0.9 KB
{
"type" : "object",
"properties" : {
"nameAlias" : {
"type" : "object",
"properties" : {
"stripPrefix" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripRegex" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripSuffix" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "metadata"
},
"udfs" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"udf" : {
"type" : "string"
}
}
}
}
}
}
object_rewriter.json 9.2 KB
{
"type" : "object",
"properties" : {
"attribute" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"attribute" : {
"type" : "string"
},
"attributeRegex" : {
"type" : "string"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"type" : {
"type" : "object",
"properties" : {
"sourceToTarget" : {
"type" : "string"
},
"target" : {
"type" : "string"
},
"targetToSource" : {
"type" : "string"
}
}
}
}
}
},
"global" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"attribute" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"database" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"function" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"index" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"projection" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"relation" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"schema" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"sequence" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"variable" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
}
}
}
}
},
"relation" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"clustering" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"mode" : {
"type" : "string"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"description" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
},
"text" : {
"type" : "string"
}
}
},
"ephemeral" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
},
"expireAfterSeconds" : {
"type" : "integer"
}
}
},
"external" : {
"type" : "object",
"properties" : {
"connection_id" : {
"type" : "string"
},
"enable" : {
"type" : "boolean"
},
"format" : {
"type" : "string"
},
"location_expression" : {
"type" : "string"
},
"locations" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"properties" : {
"type" : "object",
"additionalProperties" : {
"type" : "string"
}
},
"table_format" : {
"type" : "string",
"enum" : [ "ICEBERG" ]
}
}
},
"index" : {
"type" : "object",
"properties" : {
"primary" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"unique" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"name" : {
"type" : "string"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
}
},
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"partition" : {
"type" : "object",
"properties" : {
"range_bucket" : {
"type" : "object",
"properties" : {
"column" : {
"type" : "string"
},
"end" : {
"type" : "integer"
},
"options" : {
"type" : "object",
"additionalProperties" : {
"type" : "string"
}
},
"start" : {
"type" : "integer"
},
"step" : {
"type" : "integer"
}
}
},
"simple" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
}
},
"partitionLifetime" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
},
"expireAfterSeconds" : {
"type" : "integer"
}
}
},
"temporary" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "object_rewriter"
}
}
}
optimizer.json 0.6 KB
{
"type" : "object",
"properties" : {
"transformations" : {
"type" : "array",
"description" : "A list of optimization transformations to apply to the input. Each transformation consists of an optimization name and an optional list of optimization-specific parameters.",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"parameters" : {
"type" : "any"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "optimizer"
}
}
}
statement_rewriter.json 1.2 KB
{
"type" : "object",
"properties" : {
"common" : {
"type" : "object",
"properties" : {
"decimalPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
},
"defaultValueValidation" : {
"type" : "boolean"
},
"identityNumericCastAsTruncate" : {
"type" : "boolean"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stringPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
}
}
},
"emitterCharset" : {
"type" : "string",
"enum" : [ "UTF8", "US_ASCII" ]
},
"select" : {
"type" : "object",
"properties" : {
"groupBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"orderBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"starProjection" : {
"type" : "string",
"enum" : [ "ALLOW", "PRESERVE", "EXPAND" ]
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "statement_rewriter"
}
}
}
transpiler_config_spec.json 38.9 KB
{
"type" : "object",
"oneOf" : [ {
"properties" : {
"session" : {
"type" : "object",
"properties" : {
"dateFormat" : {
"type" : "string"
},
"defaultDatabase" : {
"type" : "string"
},
"schemaSearchPath" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "environment"
}
}
}, {
"properties" : {
"formats" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"contents" : {
"type" : "object",
"properties" : {
"raw" : {
"type" : "object",
"properties" : {
"charset" : {
"type" : "string"
}
}
}
}
},
"source" : {
"type" : "object",
"properties" : {
"pathGlob" : {
"type" : "string"
},
"pathRegex" : {
"type" : "string"
},
"path" : {
"type" : "string"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_input_formats"
}
}
}, {
"properties" : {
"nameAlias" : {
"type" : "object",
"properties" : {
"stripPrefix" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripRegex" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripSuffix" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_metadata"
}
}
}, {
"properties" : {
"attribute" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"attribute" : {
"type" : "string"
},
"attributeRegex" : {
"type" : "string"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"alias" : {
"type" : "string",
"enum" : [ "UPDATE", "PRESERVE" ]
},
"attribute" : {
"type" : "string"
}
}
}
}
}
},
"database" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
}
}
}
}
}
},
"function" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"function" : {
"type" : "string"
},
"functionRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"function" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"global" : {
"type" : "object",
"properties" : {
"outputName" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"attribute" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"database" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"function" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"index" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"matchNameParts" : {
"type" : "array",
"items" : {
"type" : "string",
"enum" : [ "database", "schema", "relation", "attribute" ]
}
},
"projection" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"regex" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
},
"relation" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"schema" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"sequence" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
},
"variable" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"replace" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "string"
},
"replaceWith" : {
"type" : "string"
}
}
}
}
}
}
}
},
"strip" : {
"type" : "object",
"properties" : {
"stripPrefix" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripRegex" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripSuffix" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"typeConvert" : {
"type" : "object",
"properties" : {
"char" : {
"type" : "object",
"properties" : {
"comparisonBehavior" : {
"type" : "string",
"enum" : [ "STRICT", "PADDING_AWARE", "CASE_AWARE", "NONE" ]
},
"precisionAction" : {
"type" : "string",
"enum" : [ "PRESERVE", "DROP" ]
},
"target" : {
"type" : "string",
"required" : true,
"enum" : [ "VARCHAR" ]
}
}
},
"datetime" : {
"type" : "object",
"properties" : {
"target" : {
"type" : "string",
"enum" : [ "DATETIME", "TIMESTAMP", "TIMESTAMPTZ" ]
},
"timezone" : {
"type" : "string"
}
}
},
"timestamp" : {
"type" : "object",
"properties" : {
"target" : {
"type" : "string",
"enum" : [ "DATETIME", "TIMESTAMP", "TIMESTAMPTZ" ]
},
"timezone" : {
"type" : "string"
}
}
},
"timestamptz" : {
"type" : "object",
"properties" : {
"target" : {
"type" : "string",
"enum" : [ "DATETIME", "TIMESTAMP", "TIMESTAMPTZ" ]
},
"timezone" : {
"type" : "string"
}
}
},
"varchar" : {
"type" : "object",
"properties" : {
"comparisonBehavior" : {
"type" : "string",
"enum" : [ "STRICT", "PADDING_AWARE", "CASE_AWARE", "NONE" ]
},
"precisionAction" : {
"type" : "string",
"enum" : [ "PRESERVE", "DROP" ]
},
"target" : {
"type" : "string",
"required" : true,
"enum" : [ "VARCHAR" ]
}
}
}
}
}
}
},
"index" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"index" : {
"type" : "string"
},
"indexRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"index" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"projection" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"projection" : {
"type" : "string"
},
"projectionRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"projection" : {
"type" : "string"
}
}
}
}
}
},
"relation" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"alias" : {
"type" : "string",
"enum" : [ "UPDATE", "PRESERVE", "EXCLUSIVE_UPDATE" ]
},
"database" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"schema" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"schema" : {
"type" : "string"
}
}
}
}
}
},
"sequence" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
},
"sequence" : {
"type" : "string"
},
"sequenceRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"database" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"sequence" : {
"type" : "string"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_object_rewriter"
},
"variable" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"variable" : {
"type" : "string"
},
"variableRegex" : {
"type" : "string"
}
}
},
"outputName" : {
"type" : "object",
"properties" : {
"variable" : {
"type" : "string"
}
}
}
}
}
}
}
}, {
"properties" : {
"transformations" : {
"type" : "array",
"description" : "A list of optimization transformations to apply to the input. Each transformation consists of an optimization name and an optional list of optimization-specific parameters.",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"parameters" : {
"type" : "any"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_optimizer"
}
}
}, {
"properties" : {
"common" : {
"type" : "object",
"properties" : {
"decimalPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
},
"defaultValueValidation" : {
"type" : "boolean"
},
"identityNumericCastAsTruncate" : {
"type" : "boolean"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stringPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
}
}
},
"emitterCharset" : {
"type" : "string",
"enum" : [ "UTF8", "US_ASCII" ]
},
"select" : {
"type" : "object",
"properties" : {
"groupBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"orderBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"starProjection" : {
"type" : "string",
"enum" : [ "ALLOW", "PRESERVE", "EXPAND" ]
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "experimental_statement_rewriter"
}
}
}, {
"properties" : {
"formats" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"contents" : {
"type" : "object",
"properties" : {
"raw" : {
"type" : "object",
"properties" : {
"charset" : {
"type" : "string"
}
}
}
}
},
"source" : {
"type" : "object",
"properties" : {
"pathGlob" : {
"type" : "string"
},
"pathRegex" : {
"type" : "string"
},
"path" : {
"type" : "string"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "input_formats"
}
}
}, {
"properties" : {
"nameAlias" : {
"type" : "object",
"properties" : {
"stripPrefix" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripRegex" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stripSuffix" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "metadata"
},
"udfs" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"udf" : {
"type" : "string"
}
}
}
}
}
}, {
"properties" : {
"attribute" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"attribute" : {
"type" : "string"
},
"attributeRegex" : {
"type" : "string"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"type" : {
"type" : "object",
"properties" : {
"sourceToTarget" : {
"type" : "string"
},
"target" : {
"type" : "string"
},
"targetToSource" : {
"type" : "string"
}
}
}
}
}
},
"global" : {
"type" : "object",
"properties" : {
"case" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"attribute" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"database" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"function" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"index" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"projection" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"relation" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"schema" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"sequence" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
},
"variable" : {
"type" : "string",
"enum" : [ "UPPERCASE", "LOWERCASE" ]
}
}
}
}
},
"relation" : {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"clustering" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"mode" : {
"type" : "string"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"description" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
},
"text" : {
"type" : "string"
}
}
},
"ephemeral" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
},
"expireAfterSeconds" : {
"type" : "integer"
}
}
},
"external" : {
"type" : "object",
"properties" : {
"connection_id" : {
"type" : "string"
},
"enable" : {
"type" : "boolean"
},
"format" : {
"type" : "string"
},
"location_expression" : {
"type" : "string"
},
"locations" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"properties" : {
"type" : "object",
"additionalProperties" : {
"type" : "string"
}
},
"table_format" : {
"type" : "string",
"enum" : [ "ICEBERG" ]
}
}
},
"index" : {
"type" : "object",
"properties" : {
"primary" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
},
"unique" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"name" : {
"type" : "string"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
}
},
"match" : {
"type" : "object",
"properties" : {
"all" : {
"type" : "boolean"
},
"database" : {
"type" : "string"
},
"databaseRegex" : {
"type" : "string"
},
"relation" : {
"type" : "string"
},
"relationRegex" : {
"type" : "string"
},
"schema" : {
"type" : "string"
},
"schemaRegex" : {
"type" : "string"
}
}
},
"partition" : {
"type" : "object",
"properties" : {
"range_bucket" : {
"type" : "object",
"properties" : {
"column" : {
"type" : "string"
},
"end" : {
"type" : "integer"
},
"options" : {
"type" : "object",
"additionalProperties" : {
"type" : "string"
}
},
"start" : {
"type" : "integer"
},
"step" : {
"type" : "integer"
}
}
},
"simple" : {
"type" : "object",
"properties" : {
"add" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"set" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
}
},
"partitionLifetime" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
},
"expireAfterSeconds" : {
"type" : "integer"
}
}
},
"temporary" : {
"type" : "object",
"properties" : {
"enable" : {
"type" : "boolean"
}
}
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "object_rewriter"
}
}
}, {
"properties" : {
"transformations" : {
"type" : "array",
"description" : "A list of optimization transformations to apply to the input. Each transformation consists of an optimization name and an optional list of optimization-specific parameters.",
"items" : {
"type" : "object",
"properties" : {
"name" : {
"type" : "string"
},
"parameters" : {
"type" : "any"
}
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "optimizer"
}
}
}, {
"properties" : {
"common" : {
"type" : "object",
"properties" : {
"decimalPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
},
"defaultValueValidation" : {
"type" : "boolean"
},
"identityNumericCastAsTruncate" : {
"type" : "boolean"
},
"remove" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"stringPrecision" : {
"type" : "string",
"enum" : [ "STRICT", "MAXIMIZE" ]
}
}
},
"emitterCharset" : {
"type" : "string",
"enum" : [ "UTF8", "US_ASCII" ]
},
"select" : {
"type" : "object",
"properties" : {
"groupBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"orderBy" : {
"type" : "string",
"enum" : [ "EXPRESSION", "ALIAS", "INDEX" ]
},
"starProjection" : {
"type" : "string",
"enum" : [ "ALLOW", "PRESERVE", "EXPAND" ]
}
}
},
"type" : {
"type" : "string",
"required" : true,
"pattern" : "statement_rewriter"
}
}
} ]
}
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-sql-translator)" \
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-sql-translator)`
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-sql-translator)
```
- **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.
effect_compatibility.md 2.3 KB
# Effect: COMPATIBILITY (unsupported features)
Guides the resolution of translation-time errors where the compiler parsed the
SQL but encountered features not supported by the target dialect or not yet
implemented in BigQuery Migration Service (BQMS).
## Common categories
- `UnsupportedFeatureError`
- `NoTargetSupportForFeature`
**Official Documentation**: For information on how to review translation
results, see the official guide on
[reviewing translation results][review_results].
## 1. Unsupported features & not yet implemented
These errors occur when the compiler successfully parses the SQL syntax but does
not have an automated translation rule implemented for that specific feature.
### Resolution workflow
#### 1. Identify the feature
- Locate the error location (line/column) in the translation log or output.
- Identify the specific function, statement, or syntax structure that is
reported as unsupported.
#### 2. Source workaround (modify source)
- If possible, modify the source SQL to use a different, supported syntax or
simpler standard SQL (e.g., replacing a proprietary function).
- Re-translate the query.
#### 3. Output patching (post-translation fix)
- If the source cannot be modified, or if BigQuery Migration Service (BQMS)
translates other parts successfully but leaves error placeholders (e.g., `/*
ERROR: Unsupported ... */`), use your knowledge of both dialects to manually
rewrite that specific block in the generated BigQuery output.
- This is often required for complex procedural blocks or proprietary system
functions.
--------------------------------------------------------------------------------
## 2. Dialect-specific unsupported features
For dialect-specific unsupported features or language wrappers, refer to the
single source of truth for your source database:
- **Snowflake**: See [snowflake_gotchas.md](snowflake_gotchas.md) for
JavaScript stored procedures, Streams, Stages, and Tags.
- **Teradata**: See [teradata_gotchas.md](teradata_gotchas.md) for `SET`
tables, `SAMPLE` clause, and primary/secondary indexes.
- **Oracle**: See [oracle_gotchas.md](oracle_gotchas.md) for PL/SQL packages,
`ROWNUM`, and `SEQUENCE` objects.
[review_results]: https://cloud.google.com/bigquery/docs/batch-sql-translator#summary_report
effect_completeness.md 5.1 KB
# Effect: COMPLETENESS (missing metadata)
Guides the resolution of `RelationNotFound` (RNF), `AttributeNotFound` (ANF),
and other metadata-related errors by loading database context.
## Table of Contents
- [Common categories](#common-categories) (lines 12–20)
- [RelationNotFound (RNF) / AttributeNotFound (ANF)](#relationnotfound-rnf-attributenotfound-anf)
(lines 22–108)
## Common categories
- `RelationNotFound` (RNF)
- `AttributeNotFound` (ANF)
- `TypeError`
- `SymbolError`
**Official Documentation**: For information on how to extract metadata from your
source system, see [Generate metadata for translation][generate_metadata].
## RelationNotFound (RNF) / AttributeNotFound (ANF)
These errors occur when the compiler cannot find the schema definitions or type
information for tables, views, columns, or types referenced in the query. While
RNF and ANF are the most common indicators of missing metadata, `TypeError` or
`SymbolError` can also arise from incomplete type definitions in the metadata
package.
### Resolution workflow
RNF and ANF mean the translation is not clean. Don't stop at reporting them: the
best fix is the real object definitions (step 1). Without them, use DDL
suggestions (step 2).
#### 1. Verify metadata configuration
- If a metadata zip package (generated by the BigQuery Migration Service
(BQMS) metadata extractor) is provided:
- Ensure it is uploaded to a Cloud Storage bucket.
- Pass its Cloud Storage path to `metadataFilePath` in `translate_query`
(Interactive) or `metadataFilePaths` in `translate_batch_queries`
(Batch).
- If metadata is configured but RNF persists:
- **Check Schema Search Path / Database Redirection**: Verify if the
compiler is looking in the correct schema. If the source queries use
three-part names (db.schema.table) that need to be mapped to BigQuery
project.dataset.table, you must configure database/schema redirection.
Use `experimental_object_rewriter` in the
[BigQuery Migration Service (BQMS) YAML configuration](translation_yaml_config.md)
to redirect entire databases or schemas to their target BigQuery
counterparts.
- **Inspect Metadata**: If you have tools to unzip or view the file, check
if the missing table actually exists in the metadata package. If not,
ask the user to verify the extraction inputs.
#### 2. Generate DDL suggestion (primary method for missing DDLs)
Always prioritize using the BigQuery Migration Service (BQMS) DDL generation
tools to automatically infer and suggest schema DDLs for missing relations
(`RelationNotFound`) over manually authoring DDL statements.
- **Interactive Workflow**:
1. Call `generate_ddl_suggestion` specifying the input query and
project/location details.
2. Poll `fetch_ddl_suggestion` with the returned ID until successful,
retrieving SQL from `suggestion.suggestion_content`.
3. Prepend the generated DDL statements to the query and re-translate.
- **Batch Workflow**:
1. Call `generate_batch_ddl_suggestion` specifying `sourceBaseUri` (Cloud
Storage input folder) and `targetBaseUri` (Cloud Storage output folder).
2. Poll `fetch_batch_ddl_suggestion` using the returned suggestion ID until
completed.
3. Download the generated DDL file (e.g., `generated_metadata.sql`) from
the Cloud Storage output path returned in
`suggestion.cloud_storage_uri`.
4. Inspect the generated DDL statements to ensure static database names and
valid schema references are present.
5. Copy/upload the generated DDL file(s) into the Cloud Storage input
directory alongside input queries and re-run `translate_batch_queries`.
Note that DDL SQL files generated for missing metadata should be plain
`.sql` files, not zipped. The `.zip` format is strictly reserved for
metadata zip files generated by the official BigQuery Migration Service
(BQMS) metadata extractor dumper tool.
#### 3. Review the re-translated output
Suggestions are in the source dialect and inferred from usage, and may not cover
every object.
- Compare error counts with the previous iteration, fix or report what
remains, and recommend providing a metadata zip for exact results.
- **Interactive**: The re-translated output contains the BigQuery version of
the suggested DDL: show it in your response for the user to review. The
prepended DDL only helps BigQuery Migration Service (BQMS) resolve objects,
so keep it out of the translated query you deliver.
- The re-translated query can also change because of the guessed schema (e.g.
`*` expanded into the inferred columns, or casts for guessed types). Compare
it with the first translation; where they differ only because of the guessed
schema, keep the first translation's form and tell the user why.
#### 4. Manual mock DDL (fallback only)
Only manually construct mock `CREATE TABLE` statements if DDL generation tools
are unavailable or fail to produce valid table definitions.
[generate_metadata]: https://cloud.google.com/bigquery/docs/generate-metadata
effect_correctness.md 8.6 KB
# Effect: CORRECTNESS (Syntax & Parse Errors)
Guides the resolution of translation-time errors where the compiler failed to
parse the input SQL (e.g., syntax errors, invalid characters, dialect-specific
macros, or application code wrappers).
## Table of Contents
- [Common Categories](#common-categories) (lines 15–26)
- [1. Syntax, Lexical & Dialect-Specific Errors](#1-syntax-lexical-dialect-specific-errors)
(lines 28–71)
- [2. Application Code Wrappers & Embedded SQL (.py, .js, Stored Procedures)](#2-application-code-wrappers-embedded-sql-py-js-stored-procedures)
(lines 73–143)
## Common Categories
- `SyntaxError`
- `LexicalError`
- `ConstantError`
- `SemanticError`
- `FeatureNotYetImplementedError`
- `NoSuchFunction`
**Official Documentation**: For information on how to review translation
results, see the official guide on
[reviewing translation results][review_results].
## 1. Syntax, Lexical & Dialect-Specific Errors
- **The Problem**: The BigQuery Migration Service (BQMS) compiler failed to
parse the input SQL. This occurs due to non-standard dialect syntax,
unparsed custom functions, invalid character encodings, or dialect-specific
macros/templates.
- **The Symptom**: `SyntaxError`, `LexicalError`, `NoSuchFunction`, or
`FeatureNotYetImplementedError` (e.g.,
`CreateMacroStatementNotYetImplementedError` or
`NotYetImplementedStatementError`).
- **Resolution Workflow**:
1. Inspect `impacted_object` and `message` in `translation_logs` (or
`translation_report.csv`) to locate the exact position of the syntax
error.
2. Check for invalid or unescaped characters (e.g., non-printable control
characters, unescaped quotes). If invalid characters are systemic across
the codebase, use `global.outputName.replace` in your
[BigQuery Migration Service (BQMS) YAML configuration][translation-yaml-config].
3. If the error is caused by a proprietary dialect construct or macro,
consult the dialect-specific gotchas reference:
- **Snowflake**: See the [Snowflake gotchas][snowflake-gotchas] for
`QUALIFY`, `LATERAL FLATTEN`, dynamic templates, and stored
procedures.
- **Teradata**: See the [Teradata gotchas][teradata-gotchas] for
macros, SET/MULTISET tables, `QUALIFY`, `SAMPLE`, and `INDEX`
clauses.
- **Oracle**: See the [Oracle gotchas][oracle-gotchas] for PL/SQL
packages, procedures, `(+)` join syntax, and `ROWNUM`.
4. If the error comes from template syntax (e.g. dbt Jinja or `${VAR}`
variables), mask the templates with valid SQL identifiers, re-translate,
and restore them in the final output (see the
[Snowflake gotchas reference][snowflake-gotchas]).
5. Apply the recommended dialect transformation (e.g., converting macros to
CTEs/procedures or rewriting syntax constructs) and re-translate.
6. If `translation_logs` reports `NoSuchFunction`, BigQuery Migration
Service (BQMS) did not recognize the function and copied the call
unchanged, sometimes with the name in backticks. For an
application-defined UDF, provide its definition in metadata and
re-translate; do not stub built-in dialect functions as UDFs. For a
built-in function of the source dialect, rewrite only that call in the
BigQuery Migration Service (BQMS) output to the equivalent BigQuery
function and dry-run the rewritten call on its own with literal
arguments, since a dry run of the full query stops at missing tables
before checking function calls.
## 2. Application Code Wrappers & Embedded SQL (.py, .js, Stored Procedures)
- **Symptom**: `LexicalError` (e.g., `Unknown token: #`) or `SyntaxError`
(e.g., `Unexpected identifier 'import'/'def'`) reported in
`translation_report.csv`.
- **Root Cause**: BigQuery Migration Service (BQMS) expects raw SQL
statements. Application language syntax (Python, JavaScript, etc.) wrapping
SQL execution calls cannot be parsed directly as native SQL statements by
BigQuery Migration Service (BQMS).
- **Resolution Workflow**:
1. **Preprocessing**: For a single file with one query, extract the query
string directly, translate it with the interactive workflow
(`translate_query`), and update the file in place without a manifest
script. For multi-file codebases, extract the embedded static SQL
statements from the application script files into staged `.sql` files
and record a mapping manifest (`manifest.json`).
- *Python Codebases*: Run
`assets/python_embedded_sql_migrator_template.py` directly (`python3
.../python_embedded_sql_migrator_template.py --preprocess --src
<src_dir> --staging <staging_dir> --manifest <manifest.json>
[--gcs-input <gs://...>]`). It already extracts static SQL strings,
masks `%s`, `:name`, and `{var}` placeholders, and writes DataFrame
view DDL stubs without needing edits for standard Python DB-API,
Spark, or SQLAlchemy code.
- *Other Languages (Java/JS/Go)*: AI agents should dynamically author
a lightweight parser script using regex or AST parsing tailored to
the target language framework following the same manifest extraction
pattern.
2. **Translate & Iterate**: Upload staged `.sql` files to Cloud Storage,
run `translate_batch_queries`, and analyze
`report/translation_report.csv`. Resolve any remaining schema metadata
DDLs or dialect warnings through further iterations.
3. **Post-processing (FINAL STEP ONLY)**: **ONLY AFTER resolving every
issue in `translation_report.csv` that re-translation can fix**,
download the final BigQuery Migration Service (BQMS) BigQuery output and
re-inject the translated queries back into the application source files,
preserving non-SQL application code, functions, comments, and parameter
kwargs (`query_tags=...`). The only rows that may remain in the report
are `-- ERROR` files for Spark, Databricks, or Hive constructs that
BigQuery Migration Service (BQMS) cannot parse and that the fallback
rewrites below cover, and `NoSuchFunction` files whose calls you have
already rewritten in `sql/`.
- *Why wait?*: Postprocessing early while translation errors are still
present pollutes application target files with intermediate broken
code states.
- *Python Codebases*: Run
`assets/python_embedded_sql_migrator_template.py` (`--postprocess
--src <src_dir> --staging-out <translated_dir> --out <out_dir>
--manifest <manifest.json> [--enable-fallback-rules] [--force]`).
Pass `--enable-fallback-rules` only when the remaining `-- ERROR`
files are Spark, Databricks, or Hive constructs that the fallback
rewrites cover; otherwise leave it off so those queries keep their
source SQL and get reported.
- *Verify*: `postprocess` re-injects every `.sql` file in `sql/`
except `_dataframe_view_*` DDL stubs and files that start with `--
ERROR` or contain `ERROR:` in their first 100 characters. For the
skipped error files, it keeps the source SQL and prints `Warning:
Missing clean BigQuery Migration Service (BQMS) translation for
query ...`, or—when `--enable-fallback-rules` is passed—re-injects
regex rewrites of the source SQL for Spark, Databricks, or Hive
constructs that BigQuery Migration Service (BQMS) could not parse
(such as table-valued `RANGE` or `FROM_UNIXTIME` format strings;
`current_database()` becomes `@@dataset_id`, which is `NULL` unless
the job sets a default dataset, whereas Snowflake's or Redshift's
`CURRENT_DATABASE()` is the BigQuery project). Because
`NoSuchFunction` outputs in `sql/` do not start with `-- ERROR`,
`postprocess` re-injects them from `sql/` without running
`--enable-fallback-rules`; rewrite any `NoSuchFunction` calls in
their `sql/*.sql` files before running `--postprocess`. Dry-run
every re-injected statement when a BigQuery project is available,
and fix and report any that fail.
[review_results]: https://cloud.google.com/bigquery/docs/batch-sql-translator#summary_report
[translation-yaml-config]: translation_yaml_config.md
[snowflake-gotchas]: snowflake_gotchas.md
[teradata-gotchas]: teradata_gotchas.md
[oracle-gotchas]: oracle_gotchas.md
mcp_config.md 10.0 KB
# BigQuery Migration Service (BQMS) remote MCP server configuration reference
This guide helps you troubleshoot and validate connections, permissions, and
request headers for the remote BigQuery Migration Service (BQMS) MCP server.
## Table of Contents
- [Connection Troubleshooting & Permissions](#connection-troubleshooting-permissions)
(lines 23–43)
- [Connection Parameters](#connection-parameters) (lines 45–59)
- [Verifying Endpoint Connectivity](#verifying-endpoint-connectivity) (lines
61–76)
- [Option A: Quick Automatic Install via `add-mcp`](#option-a-quick-automatic-install-via-add-mcp)
(lines 78–121)
- [Option B: Manual JSON Configuration](#option-b-manual-json-configuration)
(lines 123–144)
- [Example Configuration Blocks](#example-configuration-blocks) (lines
146–218)
- [Initiating the Connection](#initiating-the-connection) (lines 220–241)
- [Sample Prompts for MCP Clients](#sample-prompts-for-mcp-clients) (lines
243–256)
## Connection Troubleshooting & Permissions
If tool calls return authorization, billing, or quota errors, verify that:
1. **API Enabled**: The BigQuery Migration Service API
(`bigquerymigration.googleapis.com`) is enabled in the target project.
2. **IAM Roles**: The agent or user identity has:
- `roles/mcp.toolUser` (MCP Tool User)
- `roles/bigquerymigration.editor` (Migration Workflow Editor)
- `roles/storage.objectViewer` and `roles/storage.objectCreator` (or
`roles/storage.objectAdmin`) on the staging and output Cloud Storage
buckets when running Batch Translation workflows.
3. **OAuth Scopes**: The client token includes:
- `https://www.googleapis.com/auth/bigquerymigration` (or
`https://www.googleapis.com/auth/cloud-platform`)
- `https://www.googleapis.com/auth/devstorage.read_write` (or
`https://www.googleapis.com/auth/devstorage.read_only` for read-only
Cloud Storage access)
4. **Billing Header**: All requests must include the `x-goog-user-project`
header set to your Google Cloud Project ID (**must be the string ID, not the
numeric project number**).
## Connection Parameters
When configuring an MCP client (such as Claude Code, Cursor, Gemini CLI, or VS
Code) to connect to the remote BigQuery Migration Service MCP server, use the
following parameters:
Parameter | Value / Description
:------------------------ | :------------------
**Server Name** | Any name, e.g. `bigquery-migration-service`
**Server URL / Endpoint** | `https://bigquerymigration.googleapis.com/mcp`
**Transport** | Streamable HTTP (`httpUrl`)
**Authentication** | Google Cloud Credentials (`google_credentials`) or Application Default Credentials (ADC)
**OAuth Scopes** | `https://www.googleapis.com/auth/bigquerymigration`<br>`https://www.googleapis.com/auth/devstorage.read_write`
**Headers** | `x-goog-user-project: {project_id}` (Cloud Project ID string)
**Timeout** | `30000` (30 seconds)
## Verifying Endpoint Connectivity
Before configuring an AI client, you can test connectivity to the remote
BigQuery Migration Service (BQMS) MCP endpoint without authentication by sending
an unauthenticated `tools/list` JSON-RPC request:
```bash
curl -s -X POST https://bigquerymigration.googleapis.com/mcp \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}'
```
A successful response returns a JSON-RPC envelope listing all available BigQuery
Migration Service (BQMS) MCP tools (`translate_query`, `get_translation`,
`explain_translation`, `generate_ddl_suggestion`, `fetch_ddl_suggestion`, etc.).
## Option A: Quick Automatic Install via `add-mcp`
You do **not** need to manually locate or edit configuration files when using
[`add-mcp`](https://github.com/neondatabase/add-mcp). The `add-mcp` tool
automatically detects your installed AI clients (Claude Code, Cursor, Gemini
CLI, VS Code, etc.) and registers the remote Streamable HTTP BigQuery Migration
Service (BQMS) MCP server into their configuration paths:
- **All Auto-Detected Clients**:
```bash
npx -y add-mcp@latest https://bigquerymigration.googleapis.com/mcp --name bqms --header "x-goog-user-project: {project_id}"
```
- **Claude Code**:
```bash
npx -y add-mcp@latest https://bigquerymigration.googleapis.com/mcp --name bqms --header "x-goog-user-project: {project_id}" -a claude-code
```
- **Cursor**:
```bash
npx -y add-mcp@latest https://bigquerymigration.googleapis.com/mcp --name bqms --header "x-goog-user-project: {project_id}" -a cursor
```
- **Gemini CLI**:
```bash
npx -y add-mcp@latest https://bigquerymigration.googleapis.com/mcp --name bqms --header "x-goog-user-project: {project_id}" -a gemini-cli
```
- **VS Code**:
```bash
npx -y add-mcp@latest https://bigquerymigration.googleapis.com/mcp --name bqms --header "x-goog-user-project: {project_id}" -a vscode
```
> **Note on Google Cloud Authentication (`google_credentials`)**: `add-mcp`
> emits standard MCP fields and does not automatically add Google Cloud
> credential settings. After running `add-mcp`, add your Google Cloud
> authentication settings (`"authProviderType": "google_credentials"` in Gemini
> CLI, or an `"Authorization": "Bearer {access_token}"` header in other clients)
> as shown in [Example Configuration Blocks](#example-configuration-blocks).
## Option B: Manual JSON Configuration
If you prefer to edit configuration files manually, locate the file for your
tool or IDE below and add the corresponding configuration from
[Example Configuration Blocks](#example-configuration-blocks):
- **Gemini CLI**:
- Global: `~/.gemini/settings.json`
- Project level: `.gemini/settings.json`
- **Claude Code**:
- Global: `~/.claude.json`
- Project level: `.mcp.json`
- **Claude Desktop**:
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- **Cursor**:
- Global: `~/.cursor/mcp.json` (or Project level: `.cursor/mcp.json`), or
managed via **Settings > Features > MCP**
- **VS Code**:
- Project level: `.vscode/mcp.json`
- Global (via settings): Open Command Palette (`Cmd/Ctrl+Shift+P`), choose
"MCP: Open User Configuration", and add the server under `"servers"`.
## Example Configuration Blocks
Replace `{project_id}` with your actual Google Cloud Project ID (must be the
string ID, not the numeric project number).
### 1. Gemini CLI (`~/.gemini/settings.json` or `.gemini/settings.json`)
Gemini CLI natively supports Google Application Default Credentials via
`"authProviderType": "google_credentials"` and `"httpUrl"`:
```json
{
"mcpServers": {
"bqms": {
"httpUrl": "https://bigquerymigration.googleapis.com/mcp",
"authProviderType": "google_credentials",
"oauth": {
"scopes": [
"https://www.googleapis.com/auth/bigquerymigration",
"https://www.googleapis.com/auth/devstorage.read_write"
]
},
"timeout": 30000,
"headers": {
"x-goog-user-project": "{project_id}"
}
}
}
}
```
### 2. Cursor / Claude Code (`~/.cursor/mcp.json` or `.mcp.json`)
Standard Streamable HTTP MCP clients use `"url"` and pass an OAuth bearer token
(e.g., from `gcloud auth print-access-token`) in `"headers"`:
```json
{
"mcpServers": {
"bqms": {
"type": "http",
"url": "https://bigquerymigration.googleapis.com/mcp",
"headers": {
"Authorization": "Bearer {access_token}",
"x-goog-user-project": "{project_id}"
}
}
}
}
```
### 3. VS Code (`.vscode/mcp.json`)
VS Code uses the top-level `"servers"` key with `"type": "http"` and `"url"`:
```json
{
"servers": {
"bqms": {
"type": "http",
"url": "https://bigquerymigration.googleapis.com/mcp",
"headers": {
"Authorization": "Bearer {access_token}",
"x-goog-user-project": "{project_id}"
}
}
}
}
```
*Note: The `"bqms"` JSON key dictates the server name. If you rename it (e.g.,
to `"BigQueryMigration"`), use that new name when configuring permissions and
invoking tools.*
## Initiating the Connection
Once the configuration file is in place, initiate the connection so the BigQuery
Migration Service (BQMS) MCP tools (like `translate_query`) become available to
the agent:
- **Gemini CLI**:
- **Automatic**: The CLI reads `~/.gemini/settings.json` (and project
`.gemini/settings.json`) during startup and connects to the Streamable
HTTP endpoint automatically. Run `/mcp` inside Gemini CLI to verify the
server status.
- **Claude Desktop / Claude Code**:
- **Restart or Reload**: Restart the application or session so it reads
the updated config and connects to the Streamable HTTP endpoint.
- **Cursor**:
- **Settings UI**: Navigate to **Settings > Features > MCP**. If using
`.cursor/mcp.json`, click the **Refresh** icon next to the server to
establish the Streamable HTTP connection.
- **VS Code**:
- **Auto-Reload**: VS Code watches `.vscode/mcp.json` and connects on
save, or you can run `MCP: List Servers` from the Command Palette
(`Cmd/Ctrl+Shift+P`) to start or restart the server.
## Sample Prompts for MCP Clients
The following natural language prompts demonstrate standard workflows when
interacting with the BigQuery Migration Service (BQMS) MCP server:
- **Ad-hoc Query Translation**: "Translate this query from `{dialect}`:
`{query}`. Use `{project_id}` and `{location}`."
- **Quality & Error Assessment**: "Assess the translation quality and
summarize compiler errors."
- **Translation Explanation**: "Explain the translation and behavioral
differences between the source query and BigQuery GoogleSQL."
- **DDL Suggestion for Missing Schemas**: "Generate DDL for this input query."
- **Prepend Schema and Retranslate**: "Prepend the generated DDL statements to
the input query and retranslate."
oracle_gotchas.md 3.1 KB
# Oracle translation gotchas reference
Optimizes Oracle SQL and PL/SQL translation to BigQuery (GoogleSQL) and
addresses syntax emulation.
**Official Documentation**: For the complete list of Oracle SQL translation
differences, see the [Oracle SQL translation guide][oracle_guide].
## 1. PL/SQL stored procedures & packages
- **BigQuery Translation**: BigQuery Migration Service (BQMS) translates
Oracle PL/SQL procedures, functions, and packages into BigQuery Stored
Procedures (using BigQuery scripting).
- **Best Practices**:
- Warn the user that Oracle packages are translated into individual
BigQuery stored procedures prefixed with the package name (e.g.,
`package_name.procedure_name` becomes
`dataset.package_name__procedure_name`).
- Examine the translated code to ensure variables and parameter modes
(`IN`, `OUT`, `INOUT`) mapped correctly to BigQuery equivalents.
## 2. ROWNUM emulation
- **BigQuery Migration Service (BQMS) Translation**:
- A comparison against a constant (`ROWNUM <= 10`, `ROWNUM < 10`) becomes
a `LIMIT` clause (`LIMIT 10`, `LIMIT 9`).
- A comparison against a non-constant expression (`ROWNUM <= col`) can't
become `LIMIT`. Check the output for `ROW_NUMBER()` in a `WHERE` clause,
which BigQuery rejects, and rewrite it with `QUALIFY` or a subquery.
- `ROWNUM` in a projection becomes `ROW_NUMBER() OVER ()`.
- **Patterns to verify in the output**:
- **`ROWNUM` with `ORDER BY` in the same query**: Oracle applies `ROWNUM`
before sorting, so the query returns an arbitrary set of rows, sorted.
Keep that behavior (apply `LIMIT` in a subquery, then sort), or use
top-N after sorting and tell the user the rows change. Dry-run the
output: the emitted `LIMIT` placement can be invalid.
- **Pagination (`ROWNUM rn` over an ordered subquery)**: BigQuery doesn't
keep subquery order, and `ROW_NUMBER()` without `ORDER BY` is
non-deterministic ([numbering functions][bq_numbering]). Use
`ROW_NUMBER() OVER (ORDER BY ...)` and filter on the row number, or
`ORDER BY ... LIMIT n OFFSET m` for small offsets. Large `OFFSET` values
sort on a single compute unit; see
[Troubleshoot query issues][bq_troubleshoot].
## 3. Sequence emulation
- **Oracle Behavior**: Oracle uses `SEQUENCE` objects to generate unique
sequential numbers.
- **BigQuery Behavior**: BigQuery does not support native sequence objects.
- **Emulation Strategies**:
- Suggest using `GENERATE_UUID()` if unique identifiers are needed and
strict sequentiality is not required.
- If sequential IDs are strictly required (e.g., for business logic),
explain that they must be emulated using Spark/Dataflow during data
load, or by using identity columns (if applicable) or a control table
(with performance caveats).
[oracle_guide]: https://cloud.google.com/bigquery/docs/migration/oracle-sql
[bq_numbering]: https://cloud.google.com/bigquery/docs/reference/standard-sql/numbering_functions#row_number
[bq_troubleshoot]: https://cloud.google.com/bigquery/docs/troubleshoot-queries
snowflake_gotchas.md 7.4 KB
# Snowflake translation gotchas reference
Optimizes Snowflake SQL translation to BigQuery (GoogleSQL) and addresses common
dialect differences.
**Official Documentation**: For the complete list of Snowflake SQL translation
rules, see [Snowflake to BigQuery translation reference][snowflake_ref].
## Table of Contents
- [1. Template Variables (`&VAR` / `${VAR}`)](#1-template-variables-var-var)
(lines 29–47)
- [2. Multi-Statement Files / USE Statements](#2-multi-statement-files-use-statements)
(lines 51–74)
- [3. Metadata Files (.zip vs DDL SQL)](#3-metadata-files-zip-vs-ddl-sql)
(lines 78–89)
- [4. Lateral Joins and FLATTEN](#4-lateral-joins-and-flatten) (lines 93–103)
- [5. Streams and Change Data Capture (CDC)](#5-streams-and-change-data-capture-cdc)
(lines 107–114)
- [6. Schema Search Path / Database Redirection](#6-schema-search-path-database-redirection)
(lines 118–148)
- [7. EXECUTE IMMEDIATE Dynamic SQL](#7-execute-immediate-dynamic-sql) (lines
152–165)
- [8. Stored Procedures (JavaScript / Snowflake Scripting)](#8-stored-procedures-javascript-snowflake-scripting)
(lines 169–182)
--------------------------------------------------------------------------------
## 1. Template Variables (`&VAR` / `${VAR}`)
Snowflake SQL scripts often use session parameters or deployment template
variables like `&MY_VAR` or `${MY_VAR}`.
- **The Problem**: BigQuery Migration Service (BQMS) parses `&` or `$` as
invalid syntax, resulting in `SyntaxError` or `LexicalError`.
- **Baseline Translation First**: Send raw files to BigQuery Migration Service
(BQMS) first. If the variables are inside standard string literals or static
SQL comments, BigQuery Migration Service (BQMS) may process them without
issue.
- **Error-Driven Fix**: If translation fails:
1. Inspect `translation_report.csv` to identify the failing lines.
2. Write a custom Python script (e.g., `preprocess_templates.py`) to mask
`&VAR` or `${VAR}` with a valid SQL identifier format (e.g.,
`TMPL_VAR_1`) and re-translate.
- **Post-processing**: After achieving a clean translation, write a custom
script or use tools to restore the original templates in the translated
BigQuery output.
--------------------------------------------------------------------------------
## 2. Multi-Statement Files / USE Statements
Snowflake scripts often contain `USE DATABASE db;` or `USE SCHEMA schema;`
statements.
- **The Problem**: BigQuery does not support `USE` statements. BigQuery
Migration Service (BQMS) might ignore them or throw warnings, causing
subsequent table references without qualifiers to fail with
`RelationNotFound`.
- **Baseline Translation First**: Test the batch translation with default
settings first.
- **Error-Driven YAML Configuration**: If `RelationNotFound` errors appear in
the report:
1. Create an `environment.config.yaml` specifying default database and
schema search paths.
2. Include `environment.config.yaml` in your BigQuery Migration Service
(BQMS) batch input.
```yaml
type: environment
session:
defaultDatabase: MY_DEFAULT_DB
schemaSearchPath: [SCHEMA1, SCHEMA2]
```
--------------------------------------------------------------------------------
## 3. Metadata Files (.zip vs DDL SQL)
When extracting metadata from Snowflake:
- **DO NOT** upload multiple unzipped metadata DDL `.sql` files directly into
the input folder alongside queries if you are also supplying a metadata
`.zip` package.
- If using the official BigQuery Migration Service (BQMS) metadata extractor
tool, compress the JSON/YAML outputs into a single `metadata.zip` file and
pass its Cloud Storage path to `metadataFilePaths`.
- If you manually authored mock `CREATE TABLE` DDLs, leave them as plain
`.sql` files inside `sourceBaseUri`.
--------------------------------------------------------------------------------
## 4. Lateral Joins and FLATTEN
Snowflake `LATERAL FLATTEN(input => ...)` constructs translate to BigQuery's
`UNNEST` operator.
- **Gotcha**: BigQuery Migration Service (BQMS) automatically converts most
`FLATTEN` calls to `UNNEST(JSON_EXTRACT_ARRAY(...))`.
- **Verification**: Ensure that target BigQuery JSON paths match the unnested
array structure. If BigQuery Migration Service (BQMS) leaves `FLATTEN`
un-translated, manually rewrite the clause using BigQuery's `UNNEST` and
`JSON_QUERY_ARRAY` functions.
--------------------------------------------------------------------------------
## 5. Streams and Change Data Capture (CDC)
Snowflake `STREAM` objects and `CHANGES(INFORMATION => ...)` clauses do not have
direct equivalents in GoogleSQL.
- **Action**: Mask or extract `CHANGES` clauses during iteration, or rewrite
the pipeline to use BigQuery Change Data Capture (CDC) with `MERGE`
statements or Datastream.
--------------------------------------------------------------------------------
## 6. Schema Search Path / Database Redirection
In Snowflake, unqualified object names resolve using the current session's `USE
DATABASE` and `USE SCHEMA`. BigQuery requires fully qualified table names
(`project.dataset.table`).
- **Action**: Use `experimental_object_rewriter` in a BigQuery Migration
Service (BQMS) configuration YAML file to map Snowflake database and schema
pairs to BigQuery project and dataset pairs:
```yaml
type: experimental_object_rewriter
relation:
- match:
database: "SNOWFLAKE_PROD"
schema: "ANALYTICS"
outputName:
database: "my-gcp-project-id"
schema: "bq_analytics"
relation: "${relation}"
```
- **Search Path Fallback**: If full qualifications are unavailable, use
`environment.config.yaml`:
```yaml
type: environment
session:
defaultDatabase: "MIGRATION_DB"
schemaSearchPath: ["PUBLIC", "RAW_POS"]
```
--------------------------------------------------------------------------------
## 7. EXECUTE IMMEDIATE Dynamic SQL
BigQuery Migration Service (BQMS) cannot evaluate `EXECUTE IMMEDIATE` statements
dynamically at compile time if they use string concatenation or external
variables. This causes `ExecuteImmediateStatementNotYetImplementedError` or
`LexicalError`.
### Pattern: Error-Driven Static Evaluation
- **Action**: If translation fails due to dynamic SQL compile errors, write a
custom Python script (e.g., `fix_dynamic_sql.py`) to parse the source files
and replace the offending dynamic `EXECUTE IMMEDIATE` blocks with their
statically evaluated equivalent statements (e.g., `INSERT`, `MERGE`), then
re-translate.
--------------------------------------------------------------------------------
## 8. Stored Procedures (JavaScript / Snowflake Scripting)
Snowflake stored procedures written in JavaScript or Snowflake Scripting (PL/SQL
style loops, `VAR`, `LET`) cannot be transpiled automatically if they mix
procedural control flow with dynamic SQL generation.
- **Symptom**: `UnsupportedFeatureError` with message `Unsupported SQL` or
`FeatureNotYetImplementedError` (for procedural loops or cursors).
- **Resolution Workflow**:
1. Extract the embedded SQL queries from the procedural wrapper.
2. Translate the raw SQL statements using BigQuery Migration Service
(BQMS).
3. Convert procedural control flow to BigQuery Procedural Language (`CREATE
PROCEDURE` with `LOOP`, `WHILE`, `IF...ELSE`).
[snowflake_ref]: https://cloud.google.com/bigquery/docs/migration/snowflake-sql
teradata_gotchas.md 2.4 KB
# Teradata translation gotchas reference
Optimizes Teradata SQL translation to GoogleSQL (BigQuery) and addresses common
dialect differences.
**Official Documentation**: For the complete list of Teradata SQL translation
differences, see the [Teradata SQL translation guide][teradata_guide].
## 1. SET vs MULTISET tables
- **Teradata Behavior**: Teradata supports `SET` tables which automatically
enforce uniqueness by rejecting duplicate rows.
- **BigQuery Behavior**: BigQuery only supports `MULTISET` behavior (allows
duplicates). BigQuery Migration Service (BQMS) translates `SET` tables to
standard BigQuery tables without uniqueness enforcement.
- **Optimization**:
- Flag any `SET` tables to the user and warn them that uniqueness will not
be enforced.
- If uniqueness is critical, propose a deduplication query structure
(e.g., using `ROW_NUMBER()` or a `MERGE` statement) for their target
ingestion pipeline.
## 2. SAMPLE clause
- **Teradata Behavior**: Teradata uses `SAMPLE N` to return N random rows.
- **BigQuery Behavior**: BigQuery Migration Service (BQMS) translates `SAMPLE
N` to `ORDER BY rand() LIMIT N`.
- **Performance Impact**: `ORDER BY rand()` forces BigQuery to perform a full
table scan and global sort, which is extremely expensive on large tables.
- **Optimization**:
- Suggest replacing `SAMPLE N` with `TABLESAMPLE SYSTEM (N PERCENT)` if an
exact row count is not required (this is much faster as it avoids full
scans).
- If a specific number of rows is needed, suggest pre-filtering or using a
partitioned/clustered column to limit the scan.
## 3. Indexes (UPI, USI, NUPI, NUSI)
- **Teradata Behavior**: Teradata relies heavily on primary and secondary
indexes for data distribution and query performance.
- **BigQuery Behavior**: BigQuery does not support indexes. BigQuery Migration
Service (BQMS) ignores Teradata index definitions during DDL translation.
- **Optimization**:
- Guide the user to configure **Partitioning** and **Clustering** in
BigQuery to replace Teradata indexes.
- Suggest partitioning by date/time columns that are frequently used in
filters.
- Suggest clustering by high-cardinality columns frequently used in joins
or filters (similar to Teradata Secondary Indexes).
[teradata_guide]: https://cloud.google.com/bigquery/docs/migration/teradata-sql
translation_yaml_config.md 12.3 KB
# Translation configuration YAML reference
Guides the configuration of various translation settings using unified BigQuery
Migration Service (BQMS) configuration YAML files.
**Official Documentation**: For the complete list of YAML options and advanced
examples, see
[Transform SQL translations using configuration YAML files][yaml_guide].
All configuration YAML files must have names ending in `.config.yaml` (e.g.,
`mapping.config.yaml`).
## Table of Contents
- [Passing configuration files to the BigQuery Migration Service (BQMS) MCP tools](#passing-configuration-files-to-the-bigquery-migration-service-bqms-mcp-tools)
(lines 31–48)
- [Schemas and Reference Examples](#schemas-and-reference-examples) (lines
52–89)
- [1. Object rewriter](#1-object-rewriter) (lines 93–252)
- [2. Environment configuration (`type: environment`)](#2-environment-configuration-type-environment)
(lines 256–267)
- [3. Metadata configuration (`type: metadata`)](#3-metadata-configuration-type-metadata)
(lines 271–280)
- [4. Optimizer configuration (`type: optimizer`)](#4-optimizer-configuration-type-optimizer)
(lines 284–313)
- [5. Statement rewriter (`type: experimental_statement_rewriter`)](#5-statement-rewriter-type-experimental_statement_rewriter)
(lines 317–339)
- [6. Input formats (`type: experimental_input_formats`)](#6-input-formats-type-experimental_input_formats)
(lines 343–355)
## Passing configuration files to the BigQuery Migration Service (BQMS) MCP tools
- **`translate_query`**: pass each file inline in `translationConfigs`, as an
object with a `displayName` that ends in `.config.yaml` and the YAML text as
`content`. The tool rejects a bare YAML string or a parsed YAML object.
```json
"translationConfigs": [
{
"displayName": "optimizer.config.yaml",
"content": "type: optimizer\ntransformations:\n - name: DROP_TEMP_TABLE\n"
}
]
```
- **`translate_batch_queries`**: upload the `.config.yaml` files to the Cloud
Storage folder in `sourceBaseUri`, next to the input SQL files. To keep them
elsewhere, list their Cloud Storage paths in `configurationFilePaths`.
--------------------------------------------------------------------------------
## Schemas and Reference Examples
Before writing or debugging a configuration file, inspect the corresponding JSON
schema in `assets/translation_config_schemas/` and reference YAML example in
`assets/translation_config_examples/`:
- **Root Combined Schema**:
`assets/translation_config_schemas/transpiler_config_spec.json`
- **Object Rewriter**:
- Schema: `assets/translation_config_schemas/object_rewriter.json` (or
`experimental_object_rewriter.json`)
- Example:
`assets/translation_config_examples/object_rewriter_example.yaml` (or
`experimental_object_rewriter_example.yaml`)
- **Environment Configuration**:
- Schema: `assets/translation_config_schemas/environment.json`
- Example: `assets/translation_config_examples/environment_example.yaml`
- **Metadata Configuration**:
- Schema: `assets/translation_config_schemas/metadata.json` (or
`experimental_metadata.json`)
- Example: `assets/translation_config_examples/metadata_example.yaml` (or
`experimental_metadata_example.yaml`)
- **Optimizer Configuration**:
- Schema: `assets/translation_config_schemas/optimizer.json` (or
`experimental_optimizer.json`)
- Example: `assets/translation_config_examples/optimizer_example.yaml` (or
`experimental_optimizer_example.yaml`)
- **Statement Rewriter**:
- Schema: `assets/translation_config_schemas/statement_rewriter.json` (or
`experimental_statement_rewriter.json`)
- Example:
`assets/translation_config_examples/statement_rewriter_example.yaml` (or
`experimental_statement_rewriter_example.yaml`)
- **Input Formats**:
- Schema: `assets/translation_config_schemas/input_formats.json` (or
`experimental_input_formats.json`)
- Example: `assets/translation_config_examples/input_formats_example.yaml`
(or `experimental_input_formats_example.yaml`)
--------------------------------------------------------------------------------
## 1. Object rewriter
Transforms object names, types, and properties. Configured using `type:
object_rewriter` or `type: experimental_object_rewriter`.
`experimental_object_rewriter` may be required for advanced features like regex
replacements or dynamic naming.
### 1.1 Object mapping (database/schema redirection)
Redirects source database and schema references to target BigQuery projects and
datasets.
```yaml
type: experimental_object_rewriter
relation:
- match:
database: "SOURCE_DATABASE"
schema: "SOURCE_SCHEMA"
outputName:
database: "target-gcp-project-id"
schema: "target_bigquery_dataset"
relation: "${relation}"
```
### 1.2 Name mapping (identifier overrides)
Renames specific tables, columns, or functions.
#### Renaming tables (relations)
```yaml
type: experimental_object_rewriter
relation:
- match: "SOURCE_DB.SOURCE_SCHEMA.OFFENDING#TABLE"
outputName:
relation: "clean_table_name"
```
#### Renaming columns (attributes)
```yaml
type: experimental_object_rewriter
attribute:
- match:
database: "SOURCE_DB"
schema: "SOURCE_SCHEMA"
relation: "MY_TABLE"
attribute: "OLD#COLUMN"
outputName:
attribute: "new_column_name"
```
### 1.3 Global name rules (regex & case)
Automatically clean invalid characters or change case across all objects.
```yaml
type: experimental_object_rewriter
global:
outputName:
# Change table names to uppercase and everything else to lowercase.
relation:
case: UPPERCASE
all:
case: LOWERCASE
# Replace invalid characters
replace:
- regex: "#"
replaceWith: "_"
- regex: '\$'
replaceWith: "_dollar_"
# Replace whitespace with underscore
- regex: '\s'
replaceWith: "_"
```
### 1.4 Temporary tables
Transform specific relations to temporary tables.
```yaml
type: object_rewriter
relation:
- match: "testdb.testschema.x"
temporary: true
- match:
schema: tmp_schema
relationRegex: "tmp_.*"
temporary: true
```
### 1.5 Attribute type conversion
Override data types for specific columns.
```yaml
type: object_rewriter
attribute:
- match:
database: testdb
schema: testschema
attributeRegex: "a+"
type:
target: NUMERIC(10,2)
```
### 1.6 Table partitioning and clustering
Inject or modify table partitioning and clustering specifications directly in
translated BigQuery DDL.
#### Simple column partitioning
Partitions tables by date, timestamp, or datetime columns:
```yaml
type: object_rewriter
relation:
- match: "testdb.testschema.x"
partition:
simple:
add: [a]
- match: "testdb.testschema.y"
partition:
simple:
remove: [a]
```
#### Integer range bucket partitioning
Partitions tables by integer range using `RANGE_BUCKET`:
```yaml
type: object_rewriter
relation:
- key: "testdb.testschema.mytable"
partition:
range_bucket:
column: "id"
start: 0
end: 100
step: 10
options:
require_partition_filter: "TRUE"
```
#### Table clustering
Clusters tables by up to four columns:
```yaml
type: object_rewriter
relation:
- match: "testdb.testschema.x"
clustering:
add: [a]
- match: "testdb.testschema.y"
clustering:
remove: [b]
```
--------------------------------------------------------------------------------
## 2. Environment configuration (`type: environment`)
Specifies session defaults including default database, schema search paths, and
session date formatting (e.g., Oracle `NLS_DATE_FORMAT`).
```yaml
type: environment
session:
defaultDatabase: target-gcp-project-id
schemaSearchPath: [dataset_primary, dataset_secondary]
dateFormat: "DD/MM/YYYY" # Formats date literals; equivalent to Oracle NLS_DATE_FORMAT
```
--------------------------------------------------------------------------------
## 3. Metadata configuration (`type: metadata`)
Specifies signatures of user-defined functions (UDFs) to improve translation
accuracy.
```yaml
type: metadata
udfs:
- "date parse_short_date(dt int)"
```
--------------------------------------------------------------------------------
## 4. Optimizer configuration (`type: optimizer`)
Enables optional transformations that can improve the performance or cost of the
translated SQL. Their effect depends on the query, so compare the result against
the unmodified translation.
Transformation | Effect | Parameters
:------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- | :---------
`PRECOMPUTE_INDEPENDENT_SUBSELECTS` | Extracts independent scalar subqueries into `DECLARE` variables that are evaluated once, reducing the data scanned in `WHERE` and `JOIN-ON` clauses. | `scope: [PREDICATE, PROJECTION]` (default `PREDICATE`)
`REWRITE_CTE_TO_TEMP_TABLE` | Rewrites a CTE that is referenced multiple times into a temporary table, so it is evaluated once. | `threshold: N`, the minimum number of references
`REWRITE_ZERO_SCALE_NUMERIC_AS_INTEGER` | Rewrites zero-scale `NUMERIC`/`BIGNUMERIC` columns (such as Snowflake `NUMBER(38,0)` / `INTEGER`) to `INT64`. | `bigint: N`, the maximum precision to convert (default 18)
`DROP_TEMP_TABLE` | Appends `DROP TABLE` statements for temporary tables that the script creates but doesn't drop. | None
`REGEXP_CONTAINS_TO_LIKE` | Rewrites `REGEXP_CONTAINS` calls into `LIKE` when `LIKE` can express the pattern. | None
`ADD_DISTINCT_TO_SUBQUERY_IN_SET_COMPARISON` | Adds `DISTINCT` to subqueries used as the value set of `[NOT] IN` predicates. | None
`APPROXIMATE_RANGE_PARTITIONS` | Approximates irregular integer partitioning (such as Teradata `RANGE_N`) with contiguous, equal-size `RANGE_BUCKET` ranges. | None
Values that need more than 18 digits don't fit in `INT64`. Don't raise `bigint`
above 18 unless the data stays within the `INT64` range.
```yaml
type: optimizer
transformations:
- name: PRECOMPUTE_INDEPENDENT_SUBSELECTS
parameters:
scope: PREDICATE
- name: REWRITE_CTE_TO_TEMP_TABLE
parameters:
threshold: 2
- name: DROP_TEMP_TABLE
```
--------------------------------------------------------------------------------
## 5. Statement rewriter (`type: experimental_statement_rewriter`)
Controls statement-level syntax generation, clause representation, and decimal
precision behavior.
- **`select.starProjection`**: Controls wildcard expansion (`ALLOW`,
`PRESERVE` [default], `EXPAND`).
- **`select.groupBy`**: Controls `GROUP BY` clause output format
(`EXPRESSION`, `ALIAS`, `INDEX`).
- **`select.orderBy`**: Controls `ORDER BY` clause output format
(`EXPRESSION`, `ALIAS`, `INDEX`).
- **`common.decimalPrecision`**: `STRICT` keeps the source decimal precision.
- **`common.stringPrecision`**: `STRICT` keeps the source string length.
```yaml
type: experimental_statement_rewriter
select:
starProjection: EXPAND # Expand SELECT * into explicit column lists
groupBy: ALIAS # GROUP BY column_alias instead of full expression
orderBy: INDEX # ORDER BY 1, 2 positional column indices
common:
decimalPrecision: STRICT # Enforce strict decimal precision matching
```
--------------------------------------------------------------------------------
## 6. Input formats (`type: experimental_input_formats`)
Specifies character encoding (charset) of input files.
```yaml
type: experimental_input_formats
formats:
- source:
pathGlob: "*.sql"
contents:
raw:
charset: iso-8859-1
```
[yaml_guide]: https://cloud.google.com/bigquery/docs/config-yaml-translation
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