Generated banner for Bigquery Migration SQL Translator
Generated logo for Bigquery Migration SQL Translator

Bigquery Migration SQL Translator

GoogleOfficialPublished by Google

  • Skill
  • Tool integration
  • Data and AI
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

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).
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The BigQuery Migration Service (BQMS) SQL Translator skill provides a structured approach for migrating legacy database dialects—including Teradata, Oracle, Redshift, Snowflake, SparkSQL, and HiveQL—to BigQuery GoogleSQL. It supports both interactive translation for single queries and batch translation for large-scale migrations. The skill manages the translation lifecycle, including staging files in Cloud Storage, configuring translation rules via YAML, and triaging compiler errors categorized by correctness, completeness, and compatibility.

What it does

  • Translates SQL scripts, DDL schemas, and stored procedures to GoogleSQL.
  • Supports batch migration of multiple files and metadata archives via Cloud Storage.
  • Provides iterative workflows for resolving translation errors and warnings.
  • Allows custom translation configurations using YAML for object renaming and schema redirection.
  • Generates detailed translation reports to identify and track migration progress.
  • Includes diagnostic tools to explain syntax differences and behavioral conversions.

When to use it

  • When migrating legacy database workloads to BigQuery.
  • When you need to convert proprietary SQL syntax or stored procedures to GoogleSQL.
  • When performing large-scale batch migrations of SQL files and DDL schemas.
  • When you need to apply specific translation rules or schema mappings during migration.
  • When debugging translation errors in complex SQL queries.

Advantages

  • Automates complex dialect-to-dialect syntax conversions.
  • Resolves cross-file dependencies during batch migrations.
  • Provides structured error reporting to guide manual remediation.
  • Supports advanced configuration for fine-tuned translation control.
  • Reduces manual effort in refactoring legacy database codebases.

Usage examples

“Translate this Oracle SQL query to BigQuery GoogleSQL: SELECT * FROM employees WHERE rownum <= 10;”
The agent uses the translate_query tool to convert the Oracle-specific rownum syntax into the equivalent BigQuery LIMIT clause, providing the translated SQL and any relevant logs.
“I have a directory of Teradata SQL files in gs://my-bucket/input. How do I migrate them to BigQuery?”
The agent initiates a batch translation workflow using translate_batch_queries, monitors the job status, and provides a summary report of the migration results.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/google/bigquery-migration-sql-translator/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip bigquery-migration-sql-translator.zip -d .agents/skills

Documentation by Google

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.

Before you begin

Before translating queries or schemas, verify the following prerequisites:

  1. Google Cloud SDK & Project Setup: Ensure the Google Cloud SDK is installed, verify that your Google Cloud project has an active Cloud Billing account attached, and select the target project:

    gcloud config set project {project_id}
  2. Enable the API: Enable the BigQuery Migration API (bigquerymigration.googleapis.com) in your Google Cloud project:

    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.

  5. Cost & Cloud Storage Cleanup: Review Google Cloud Pricing for Cloud Storage and BigQuery usage details. After completing a batch migration, clean up temporary staged input and output folders in Cloud Storage:

    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:

    IterationStatusTotal ErrorsCorrectness ErrorsCompleteness ErrorsCompatibility ErrorsKey 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 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), 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 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:

    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:

    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, 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 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 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
EffectCommon CausesReference Guide
CORRECTNESSSyntax errors, unescaped literals, application script wrappers, NoSuchFunction.effect_correctness.md
COMPLETENESSMissing tables, views, columns (RelationNotFound, AttributeNotFound), DDL suggestions.effect_completeness.md
COMPATIBILITYFunctions or features without direct GoogleSQL mapping.effect_compatibility.md
Configuration & Setup Guides
TaskDescriptionReference Guide
YAML ConfigurationsDatabase/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
MCP Server SetupConfiguring the remote BigQuery Migration Service (BQMS) MCP server, OAuth scopes, and IAM roles.mcp_config.md
Dialect-Specific Gotchas
DialectKey ConsiderationsReference Guide
TeradataSET/MULTISET tables, SAMPLE clause, primary index mapping.teradata_gotchas.md
OraclePL/SQL procedures, ROWNUM emulation, outer join (+), sequences.oracle_gotchas.md
SnowflakeDynamic templates, USE statements, metadata merging, lateral joins.snowflake_gotchas.md

Files

references/effect_correctness.md

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 (lines 15–26)

  • 1. Syntax, Lexical & Dialect-Specific Errors (lines 28–71)

  • 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.

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.

    3. If the error is caused by a proprietary dialect construct or macro, consult the dialect-specific gotchas reference:

      • Snowflake: See the Snowflake gotchas for QUALIFY, LATERAL FLATTEN, dynamic templates, and stored procedures.

      • Teradata: See the Teradata gotchas for macros, SET/MULTISET tables, QUALIFY, SAMPLE, and INDEX clauses.

      • Oracle: See the 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).

    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.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs a command-line tool, Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/bigquery-migration-sql-translator · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download bigquery-migration-sql-translator.zip