dbt-sf-to-bq-translator
Translates Snowflake dbt SQL models to Standardized BigQuery SQL. Handles SQL compilation, Jinja macro placeholder masking, BigQuery Translation Service migration workflows, AST-based config transformations, explicit type casting, JSON extraction standardization, and deduplication. Use when migratin
- 01GitHub stars
- 22.8K
- 02Installs
- New
- 03Files scanned
- 5
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 fccd93177e2e0881… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
dbt Snowflake to BigQuery Translator
You are responsible for:
- Dialect Translation: Translating Snowflake dbt SQL models to Standardized BigQuery SQL on Google Cloud.
- Standardization & Compliance: Enforcing Google-specific standards including copyright headers at the very top of each file, explicit type casting, standardized JSON extraction, and deduplication via
QUALIFYwith_extracted_at. - Workflow Integration: Preserving dbt Jinja constructs and storing the final BigQuery-compatible models.
Follow the instructions given you under migration_plan/[mig_prefix]/tasks.md. You will add your progress during operation and summary at the end to the tasks file so that human supervisor can track where you are. You recover from errors by checking the tasks file.
Attribution
MUST READ: Before executing any gcloud, REST API, or MCP command, you
MUST read Usage Attribution. For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix gcloud with
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:dbt-sf-to-bq-translator)"
and append agent-skills/1.0 (skill:dbt-sf-to-bq-translator) to
User-Agent headers.
Prerequisites & Environment Setup
Before starting the translation, ensure your Google Cloud environment is properly configured:
- Google Cloud SDK: Install the Google Cloud SDK if not already installed.
- Authentication: Authenticate your CLI session:
gcloud auth login gcloud auth application-default login - Project Configuration: Set your active Google Cloud project:
gcloud config set project {project_id} - Billing Account: Verify that an active Google Cloud Billing account is attached to the target project.
- Enable Required APIs: Ensure BigQuery, Migration, and Storage services are enabled:
gcloud services enable bigquerymigration.googleapis.com storage.googleapis.com bigquery.googleapis.com - Region Selection: Configure your preferred compute/BigQuery region (default recommended:
us-central1orus). See Google Cloud Locations:gcloud config set compute/region us-central1
Steps
-
Initialization & Setup: If you do not have a defined
mig_prefixor if the user wants to start a new translation project, you MUST first ask the user for:- Migration Project Name (e.g.
my_migration_project). - Input directory containing Snowflake SQL files.
- Output directory where BigQuery SQL files should be saved.
- Cloud Storage bucket name for staging translation assets.
- Google Cloud region (e.g.
usoreu). - (Optional) Local path to a directory or
.zipfile containing source database metadata (such ascolumns.csvortables.csv). Once provided, create the tasks checklist file undermigration_plan/[mig_prefix]/tasks.mdwith unchecked tasks representing the migration steps.
- Migration Project Name (e.g.
-
Automated Execution via Bundled Scripts: Execute the deterministic end-to-end migration using the bundled translation script
scripts/bulk_translate_via_gcloud.py:python3 scripts/bulk_translate_via_gcloud.py \ --input {input_dir} \ --output {output_dir} \ --bucket {gcs_bucket} \ --location {region} \ [--metadata {metadata_path}] \ [--array-cast-mode {array_cast_mode}] \ [--struct-columns {struct_columns}]Flag Default Description --input(Required) Local directory containing source Snowflake dbt .sqland.ymlfiles.--output(Required) Target directory for translated BigQuery dbt .sqland.ymlfiles.--bucket(Required) Cloud Storage bucket name used to stage translation inputs and outputs. --locationusGoogle Cloud region for BigQuery Translation Service execution (e.g., us,eu).--metadataNoneOptional path to a directory or .ziparchive containing sourcetables.csvandcolumns.csv.--array-cast-modearray_stringTarget conversion for BQMS ARRAY<JSON>casts. Usearray_string(ARRAY<STRING>) by default; usestring(STRING),json_extract_string_array, orpreserveas escape hatches when required by the source table schema.--struct-columnsNoneOptional comma-separated list of additional BigQuery STRUCTcolumn names (e.g.,struct_col,record_col) to convert fromJSON_VALUEto native dot notation (col.field).The migration tools bundled in
scripts/perform the following coordinated actions:scripts/bulk_translate_via_gcloud.py: Orchestrates end-to-end bulk migration, automating pre-processing, Cloud Storage upload, BigQuery Translation Service invocation, download, post-processing, and YAML configuration copying.scripts/dbt_translator.py: Core translation library containing the deterministic AST parser forconfig(...), Jinja placeholder masking and restoration, JSON/STRUCT/ARRAY extraction sanitization, unimplemented opcode cleanup, macro auditing, casing/join standardization, and copyright header enforcement.
-
Detailed Translation Lifecycle (Executed by Scripts):
- Compile to Standard SQL using Placeholders (Pre-Translation):
- Read the original source dbt
.sqlfiles. Extract and strip the{{ config(...) }}header block from the top of each file. - Replace dbt macro calls with standard-SQL-compliant placeholder identifiers to prevent BigQuery Translation Service from throwing syntax errors:
- Replace
{{ source('src_name', 'table_name') }}with_DBT_SOURCE_src_name_DBTSEP_table_name_ - Replace
{{ ref('model_name') }}with_DBT_REF_model_name_
- Replace
- Normalize Snowflake bracket notation (
col['prop']->col:prop),::variant:field, and Jinja{% else %}/ loopUNION ALLbranches, eliminating Jinja curly braces ({{ ... }}) prior to translation so the transpiler processes 100% valid Snowflake dialect SQL.
- Read the original source dbt
- Isolate the SQL Files:
- Save these pre-processed, Jinja-free files to a staging input directory ready for Cloud Storage upload.
- Pre-Process Metadata & Translate SQL via BigQuery Translation Service:
- If a metadata path is provided, map table entries matching discovered dbt models/sources to their placeholder names in
columns.csvandtables.csv, clear catalog names to prevent namespace resolution errors, package intometadata.zip, and upload to Cloud Storage. - Upload staging SQL files to Cloud Storage:
gcloud storage cp <staging_input_dir>/*.sql gs://[YOUR_BUCKET]/migration_input/ - Create
migration_config.yamlspecifyingsnowflakeDialectas source andbigqueryDialectas target (withschemaPathpointing tometadata.zipif provided). - Trigger translation workflow:
gcloud bq migration-workflows create --location=<region> --config-file=migration_config.yaml --no-async - Download translated GoogleSQL files from Cloud Storage:
gcloud storage cp gs://[YOUR_BUCKET]/migration_output/*.sql <translated_output_dir>/
- If a metadata path is provided, map table entries matching discovered dbt models/sources to their placeholder names in
- Restore Placeholders & Re-Embed dbt Logic:
- Take the translated BigQuery SQL files and perform advanced post-processing:
- AST-Based Config Transformation: Parse the original
{{ config(...) }}block, stripping Snowflake-specific parameters likecopy_grants,transient, andsecure. Sanitize hooks (pre_hookandpost_hook) to remove invalid Snowflake commands likeALTER ICEBERG TABLE ... REFRESH,UNSET SECURE, orCOPY INTO, while preserving valid ones. - Reference Resolver (Namespace Resolution): Scan the SQL for hardcoded Snowflake database/schema table paths in FROM and JOIN clauses, and map them back to native dbt
{{ ref(...) }}or{{ source(...) }}macros by resolving against discovered project models and sources. - Macro & Syntax Audit: Scan all
{{ ... }}Jinja expressions and log warnings for any custom/non-allowlisted database-specific macros. Also audit these blocks for Snowflake-specific syntax (e.g.::date,dateadd,to_date) that may have been skipped or masked, listing warning comments directly in the file. - Balanced SQL Edge-Cases Sanitization: Convert date cast suffixes (
::date->CAST(... AS DATE)), datetime cast suffixes (::timestamp->CAST(... AS TIMESTAMP)), float cast suffixes (::float->CAST(... AS FLOAT64)), nesteddateadd(...)calls, and intervals (- interval '5 month') inside and outside control blocks using balanced-parentheses parsers. Fix displaced Jinja tags around CTEs and strip 16MBsubstr(string(...), 1, 16777216)wrappers. - Array Type & STRUCT Access Normalization: Convert BQMS untyped
ARRAY<JSON>casts toARRAY<STRING>(or the configured--array-cast-modetarget), convertjson_valueonSTRUCTcolumns to direct dot notation (col.field) and onARRAY<STRUCT>columns tocol[SAFE_OFFSET(idx)].field, and cleanerror_unimplementedopcodes. - Copyright Header Placement: Prepend the mandatory Google copyright header at the very top of the file above the config block.
- AST-Based Config Transformation: Parse the original
- Take the translated BigQuery SQL files and perform advanced post-processing:
- Write to the New BigQuery dbt File & Copy YAML Configurations:
- Save the newly assembled, BigQuery-compatible files preserving directory structure. Also, copy all
.yml/.yamlfiles from the input directory to the output directory.
- Save the newly assembled, BigQuery-compatible files preserving directory structure. Also, copy all
- Compile to Standard SQL using Placeholders (Pre-Translation):
-
Put a summary to the tasks file at the end.
-
Before handing over, ask for user approval for the outcome. Apply necessary changes from the user.
-
Mark your task is done in the tasks file.
Mandates & Behavioral Rules
1. Mandatory File Header
Every translated file MUST start with the following exact header at the very top:
# Copyright 2026 Google. This software is provided as-is, without warranty or
# representation for any use or purpose. Your use of it is subject to your
# agreement with Google.
2. Standardized JSON & Array Extraction
Never use Snowflake colon notation (:) in BigQuery SQL because BigQuery Standard SQL does not recognize colon syntax for semi-structured field access and throws a syntax error. Translate semi-structured lookups using BigQuery's standard functions and consult dbt_migration_patterns.md for detailed patterns and error remedies:
- Scalar & Stringified JSON Extraction: Use
JSON_VALUE(json_col, '$.path')for nativeJSONcolumns (omit dots before array indexes, e.g.,$.items[1]), andCAST(JSON_EXTRACT_SCALAR(SAFE.PARSE_JSON(CAST(source.col AS STRING)), '$.path') AS TYPE)for stringified JSON columns. Preserve 1:1 warehouse cast semantics: wrap typed extractions inCAST(... AS INT64|BOOL|TIMESTAMP|NUMERIC)for SnowflakeCAST/::TYPE/TO_*(failing fast on invalid data), and useSAFE_CAST(...)only when the Snowflake source explicitly usesTRY_CASTorTRY_TO_*(returningNULLon malformed values). - Array Extraction, Exploding & Untyped Arrays (
::array): UseJSON_EXTRACT_STRING_ARRAYorJSON_EXTRACT_ARRAYand explode withCROSS JOIN UNNEST(...). Map BQMSARRAY<JSON>casts from Snowflake::arraytoARRAY<STRING>by default (orSTRING/JSON_EXTRACT_STRING_ARRAYbased on source schema; see Section 3 of dbt_migration_patterns.md). - JSON Timestamps (ISO-8601 with
'Z'): Cast JSON timestamp extractions toTIMESTAMP(CAST(JSON_EXTRACT_SCALAR(json_col, '$.updated_at') AS TIMESTAMP)) because directCAST(... AS DATETIME)fails at runtime on ISO-8601 strings ending in'Z'. IfDATETIMEis required downstream, cast viaTIMESTAMPfirst (see Section 5 of dbt_migration_patterns.md). - BigQuery
STRUCT&ARRAY<STRUCT>Columns: Use direct dot notation (col.field, e.g.,source.struct_col.count) for nativeSTRUCTcolumns andsource.col[SAFE_OFFSET(0)].field(orJSON_VALUE(TO_JSON(source.col), '$[0].field')) forARRAY<STRUCT>columns, becauseJSON_VALUE()andCAST(... AS JSON)do not acceptSTRUCTtypes (see Section 6 of dbt_migration_patterns.md). - Snowflake Bracket Notation (
col['field']) &error_unimplemented: Normalizecol['field']tocol:fieldduring pre-processing and replace any residual BQMSerror_unimplementedor 16MBsubstr(string(...), 1, 16777216)wrappers withcol.field(forSTRUCTcolumns) orJSON_VALUE(col, '$.field')(forJSONcolumns; see Sections 7–8 of dbt_migration_patterns.md).
3. Explicit Type Safety
- Comparisons: Use
CASTon both sides of a join or filter when types are not identical (usingAS STRINGfor universal comparison safety if necessary). Preserve 1:1 cast parity with Snowflake (CAST/::TYPEtoCAST, andTRY_CAST/TRY_TO_*toSAFE_CAST); do not introduceSAFE_CASTfor standard Snowflake casts because silently coercing malformed keys toNULLchanges warehouse behavior and masks join or primary-key errors. - ID Fields: Prefer
INT64for all system IDs (e.g.,ticket_id,user_id). - Null Handling:
- For placeholder columns, always use explicit type casting:
CAST(NULL AS TYPE).
- For placeholder columns, always use explicit type casting:
4. Prescriptive String & Date Functions
- Truncation: Use
LEFT(col, length)orSUBSTR(col, 1, length). - Search: Use
LOWER(col) LIKE '%pattern%'instead ofREGEXP_CONTAINS. - Date Add: Use
DATE_ADD(CAST(col AS DATETIME), INTERVAL num HOUR).
5. Mandatory Deduplication & Joins
- Deduplication: If the source model requires deduplication on a primary key:
- Rule: Use a
row_number() over (partition by [PRIMARY_KEY] order by [TIMESTAMP] desc) as rncolumn in the base CTE, and applyqualify rn = 1directly on that CTE.
- Rule: Use a
- Joins: Use
LEFT JOINwhen joining to custom field or attribute tables (e.g.,exploded_arraypatterns) to prevent dropping records.
6. Preserve Jinja Constructs
Do not alter {{ config(...) }}, {{ ref(...) }}, or {{ source(...) }}. Keep {% if is_incremental() %} blocks functional. Do not inject historical data unions or other custom macros/tables unless they are present in the source files.
Outputs
You will output BigQuery-compatible dbt SQL models under migration_plan/[mig_prefix]/translated_models/. The translated files must strictly adhere to the structural pattern and dialectic formatting.
For translation examples, see: dbt_migration_patterns.md
Constraints
Before handing over to the root agent, first get approval from the user about the translated models. After applying user's requests, then hand over the root agent.
Files
5- SKILL.md
f2f4eb8c9615.2 KB - references/attribution.md
15f3c74ee11.9 KB - references/dbt_migration_patterns.md
6f1d9c860814.8 KB - scripts/bulk_translate_via_gcloud.py
5530e9f7cf3.1 KB - scripts/dbt_translator.py
73f979842e84.2 KB
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from google/skills8
Audits AI agent data access, blast radius, and blocked policy operations in Google Cloud by querying Cloud Audit Logs via BigQuery. Use when investigating what resources or services an agent accessed, identifying top originating principals the agent is acting as, or triaging PERMISSION_DENIED errors
Manages Google Cloud Agent Registry (agentregistry.googleapis.com) resources using gcloud CLI and Kubernetes manifests, including agents, MCP servers, endpoints, services, bindings, AI applications, skills and skill revisions, resource-level IAM policies, Cloud Run and GKE automatic workload registr
Configures best-practice alerting policies for AI agents using OpenTelemetry (OTel) metrics, generating output as Terraform (.tf) configuration files. Use when analyzing, writing, or deploying alerting policies to monitor agent latency, error rates, token usage, and quality metrics. Don't use for st
Designs, engineers, and validates enterprise Gemini platform architectures. Use when designing multi-project hierarchies (Host, Central Governance Hub, Runtime Spoke, Tool/MCP Spoke), configuring Agent Gateway, authoring Agent Connectivity Templates (ALL_TRAFFIC vs PRIVATE_RANGES_ONLY), deploying Se
Customizes an autorater (evaluation metric) for an AI agent so its grades match the user's own judgment, starting from the agent's real trajectories. Use when a user wants a metric tailored to their agent, wants to turn failing trajectories into rubrics, says an existing autorater grades their agent
Deploy open models or custom weights from Model Garden to Agent Platform endpoints, check the status of an in-progress deployment operation, or clean up resources by undeploying models and deleting endpoints. Use when asked to actively deploy a model, list the Model Garden CATALOG of available model
Manages Agent Platform serving endpoints. Use when you need to create, list, describe, update, or delete serving endpoints for model deployment on Agent Platform. Also use when troubleshooting endpoint permission, quota, or resource busy errors. Don't use for deploying models to endpoints or for run
Measures and improves the quality of AI models and agents on Google Cloud using the Eval Quality Flywheel methodology. Use when generating synthetic user scenarios, evaluating an agent or model, building an eval dataset, picking or writing evaluation metrics, analyzing failures, comparing results be
Related database skillsscan passed
Use when searching, extracting, ingesting, or querying a document collection with the NeMo Retriever 26.8.1 CLI, including local LanceDB indexes and deployed Retriever services. Use for PDFs, images, Office files, HTML, text, audio, and video; not for editing documents or web search.
Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features
Migrates Neo4j driver code and Cypher queries from older versions (4.x, 5.x)
Migrate a CloudFormation or ARM stack into a Pulumi stack, sourced from a stack that Pulumi Cloud's Discovery feature has already found and exposed via the discovered-stacks API. Load this skill when the user has a discovered stack in Pulumi Cloud and wants to bring its resources under Pulumi manage
Guides embedding model migration in Qdrant without downtime. Use when someone asks 'how to switch embedding models', 'how to migrate vectors', 'how to update to a new model', 'zero-downtime model change', 'how to re-embed my data', or 'can I use two models at once'. Also use when upgrading model dim
Use this skill whenever a Netlify project needs a Postgres database. It covers Netlify Database setup, queries from Functions or Edge Functions, schema changes through migrations in netlify/database/migrations, Drizzle ORM wiring, local dev databases and tests, deploy-preview database branches, and