Dbt Sf To Bq Translator
GoogleOfficialPublished by Google
- Skill
- Workflow
- Software development
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The dbt-sf-to-bq-translator is a specialized workflow tool designed to automate the conversion of Snowflake-dialect dbt models to BigQuery-compatible SQL. It manages the entire migration lifecycle, including pre-processing Jinja constructs, executing translation via the BigQuery Translation Service, and applying post-translation fixes such as standardized JSON extraction, explicit type casting, and deduplication logic. The tool ensures compliance with Google Cloud standards by enforcing mandatory copyright headers and providing a structured approach to resolving Snowflake-specific syntax and metadata.
What it does
- Compiles and pre-processes Snowflake dbt SQL by masking Jinja macros.
- Orchestrates bulk translation using the BigQuery Translation Service.
- Applies post-translation fixes for JSON, ARRAY, and STRUCT data types.
- Enforces Google-specific SQL standards and mandatory copyright headers.
- Resolves Snowflake-specific syntax like bracket notation and date casting.
- Maintains dbt project integrity by preserving ref and source macros.
When to use it
- When migrating existing dbt data pipelines from Snowflake to BigQuery.
- When you need to standardize semi-structured data extraction during a warehouse migration.
- When you require a repeatable, audited process for bulk SQL dialect conversion.
- When you need to ensure that dbt configuration blocks remain functional post-migration.
Advantages
- Reduces manual effort by automating complex dialect translation tasks.
- Ensures consistent code quality through standardized transformation patterns.
- Maintains project structure and dbt macro compatibility.
- Provides a clear audit trail via task tracking files.
Usage examples
- “I need to start a new migration project for my Snowflake dbt models to BigQuery. What information do you need?”
- The agent will prompt for the migration project name, input/output directories, GCS bucket, region, and optional metadata paths to initialize the migration task file.
- “Run the bulk translation for my models located in ./models_sf to ./models_bq.”
- The agent will execute the translation script, handling pre-processing, GCS staging, BigQuery Translation Service invocation, and post-processing of the output files.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/google/dbt-sf-to-bq-translator/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip dbt-sf-to-bq-translator.zip -d .agents/skills
Documentation by Google
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 loginProject 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.comRegion 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.
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_
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.
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-asyncDownload translated GoogleSQL files from Cloud Storage:
gcloud storage cp gs://[YOUR_BUCKET]/migration_output/*.sql <translated_output_dir>/
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.
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.
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).
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.
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
- ATTRIBUTION.mdAdded by AutoGineer864 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md15.2 KiB
- references/attribution.md1.9 KiB
- references/dbt_migration_patterns.md14.8 KiB
- scripts/bulk_translate_via_gcloud.pyScript3.1 KiB
- scripts/dbt_translator.pyScript84.2 KiB
references/dbt_migration_patterns.md
Standardized dbt Dialect Migration Patterns (Snowflake to BigQuery)
This reference guide provides "Before vs. After" code patterns that match the target code standard for BigQuery curated models.
Table of Contents
1. File Structure Template: Lines 16-47
2. Comparison Patterns: Lines 49-78
3. Array Handling & Casting Standards: Lines 79-109
4. Post-Hook Standards: Lines 110-118
5. Datetime and Timestamp Standards for JSON Extractions: Lines 119-141
6. BigQuery STRUCT (RECORD) vs. JSON Columns: Lines 142-217
7. Snowflake Bracket Notation & BQMS
error_unimplemented: Lines 218-2538. BQMS 16MB String Wrappers &
STRING()Function Signature: Lines 254-284
1. File Structure Template
Every model should follow this structural flow:
# 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.
{{ config(...) }}
WITH raw_json AS (
SELECT
a.data as json_data,
a._extracted_at,
CAST(JSON_EXTRACT_SCALAR(a.data, '$.id') AS INT64) as primary_id,
row_number() over (partition by JSON_EXTRACT_SCALAR(a.data, '$.id') order by a._extracted_at desc) as rn
FROM {{ source('...', '...') }} as a
{% if is_incremental() %}
WHERE _extracted_at >= (SELECT MAX(_extracted_at) FROM {{ this }})
{% endif %}
QUALIFY rn = 1
),
transform_layer AS (
SELECT
primary_id,
CAST(JSON_EXTRACT_SCALAR(json_data, '$.field_name') AS STRING) as field_name,
CAST(JSON_EXTRACT_SCALAR(json_data, '$.is_active') AS BOOL) as is_active,
_extracted_at
FROM raw_json
)
SELECT * FROM transform_layer2. Comparison Patterns
| Feature | Snowflake Source | Standardized BigQuery Target |
|---|---|---|
| JSON Path | data:user:id::int | json_value(data, '$.user.id') |
| JSON Array Element | data:items[1]::varchar | json_value(data, '$.items[1]') |
| JSON Scalar (Numeric) | TRY_PARSE_JSON(json_col):val::number | cast(json_extract_scalar(safe.parse_json(cast(source.json_col as STRING)), '$.val') as NUMERIC) |
Safe Cast (TRY_CAST / TRY_TO_*) | TRY_CAST(data:val::string AS INT) | safe_cast(json_value(data, '$.val') as INT64) |
| JSON Timestamp (ISO-8601 with Z) | TRY_PARSE_JSON(json_col):updated_at::TIMESTAMP_NTZ | cast(json_extract_scalar(safe.parse_json(cast(source.json_col as STRING)), '$.updated_at') as TIMESTAMP) |
| JSON Datetime (via Timestamp) | TRY_PARSE_JSON(json_col):updated_at::TIMESTAMP_NTZ | cast(cast(json_extract_scalar(safe.parse_json(cast(source.json_col as STRING)), '$.updated_at') as TIMESTAMP) as DATETIME) |
| JSON String Array | data:tags | json_extract_string_array(safe.parse_json(cast(source.data as STRING)), '$.tags') |
| JSON Object Array | data:items | json_extract_array(safe.parse_json(cast(source.data as STRING)), '$.items') |
| Array Column (Raw String) | arr_col::array | cast(source.arr_col as STRING) as arr_col |
| Array Column (Native Array) | arr_col::array | cast(source.arr_col as ARRAY<STRING>) as arr_col |
| Array Column (Stringified JSON) | arr_col::array | json_extract_string_array(source.arr_col) as arr_col |
| Null Strings | data:status::string | json_value(data, '$.status') |
| Boolean | data:active::boolean | json_value(data, '$.active') |
| Truncation | LEFT(comment, 2000) | SUBSTR(comment, 1, 2000) |
| Search | comment LIKE '%urgent%' | LOWER(comment) LIKE '%urgent%' |
| Array Explode | LATERAL FLATTEN(input => data:tags) | CROSS JOIN UNNEST(JSON_EXTRACT_ARRAY(data, '$.tags')) |
| Date Add | DATEADD(hour, 1, date) | DATE_ADD(CAST(date AS DATETIME), INTERVAL 1 HOUR) |
| Window Alias | SELECT id, ROW_NUMBER() OVER(PARTITION BY id...) | SELECT CAST(JSON_EXTRACT_SCALAR(data, '$.id') AS INT64) as id, ROW_NUMBER() OVER(PARTITION BY CAST(JSON_EXTRACT_SCALAR(data, '$.id') AS INT64)...) |
| STRUCT Field Access | struct_col:count::numeric | cast(source.struct_col.count as NUMERIC) |
| STRUCT Field Access (Named / Quoted) | obj_col:"id"::varchar | obj_col.id as obj_id |
| STRUCT Nested Access | struct_col:nested:flag | source.struct_col.nested.flag |
| JSON Escaped Path | json_col:"Field Name"::string | json_value(json_col, '$."Field Name"') |
| Bracket Notation (STRUCT) | record_col['status']::TEXT | cast(source.record_col.status as STRING) |
| Bracket Notation (JSON) | json_col['status']::TEXT | json_value(source.json_col, '$.status') |
ARRAY<STRUCT> Element Access (Native) | col[0]:field::string | source.col[SAFE_OFFSET(0)].field |
ARRAY<STRUCT> JSONPath (Serialized) | col[0]:field::string | json_value(to_json(source.col), '$[0].field') |
3. Array Handling & Casting Standards
Snowflake allows untyped array casting (column::array / ARRAY), whereas BigQuery Standard SQL requires strongly typed arrays (e.g. ARRAY<STRING>, ARRAY<JSON>). BigQuery Migration Service (BQMS) defaults Snowflake untyped ::array to ARRAY<JSON>, which can cause type mismatches if the BigQuery source table is not ARRAY<JSON>.
When standardizing array column casts in BigQuery models, determine the target expression depending on whether the column (e.g., arr_col) in the BigQuery source table is stored as a raw STRING or an ARRAY<STRING>:
If column should be
STRING: If the BigQuery source table stores the data as a raw string:cast(source.arr_col as STRING) as arr_col,If column should be
ARRAY<STRING>:If
source.arr_colis already an array in BigQuery:cast(source.arr_col as ARRAY<STRING>) as arr_col,If
source.arr_colis a stringified JSON array string in BigQuery:json_extract_string_array(source.arr_col) as arr_col,
When extracting array elements from a nested JSON / stringified JSON column:
Extracting array of strings (e.g.
data:tags):json_extract_string_array(safe.parse_json(cast(source.data as STRING)), '$.tags') as tags,Extracting array of JSON objects:
json_extract_array(safe.parse_json(cast(source.data as STRING)), '$.items') as items,
4. Post-Hook Standards
When updating tables in a post_hook, always use explicit type casting in the WHERE clause:
Incorrect:
where t.ticket_id = stage.id
Correct:
where CAST(t.ticket_id AS STRING) = CAST(stage.id AS STRING)
5. Datetime and Timestamp Standards for JSON Extractions
In BigQuery Standard SQL, CAST(string_expr AS DATETIME) strictly requires strings formatted as YYYY-[M]M-[D]D[ { |T}[H]H:[M]M:[S]S[.F_SCHEME]] without any trailing timezone offsets or trailing 'Z'. When parsing ISO-8601 UTC timestamp strings ending in 'Z' (e.g. '2026-09-07T17:04:54.811Z'), BigQuery raises a runtime query error:
Invalid datetime string "2026-09-07T17:04:54.811Z"
Snowflake's ::TIMESTAMP_NTZ cast is frequently converted by BQMS to DATETIME. When applied to JSON extractions, this produces invalid BigQuery queries.
Standard Patterns
Direct Timestamp Cast (Recommended): Always cast JSON timestamp strings to
TIMESTAMP, which natively parses ISO-8601 strings with trailing'Z':cast(JSON_EXTRACT_SCALAR(safe.parse_json(cast(source.json_col as STRING)), '$.updated_at') as TIMESTAMP) as updated_atWhen DATETIME Type is Mandated Downstream: If the downstream table or dbt model strictly requires a
DATETIMEdata type, first cast the string toTIMESTAMPand then cast the resultingTIMESTAMPtoDATETIME:cast(cast(JSON_EXTRACT_SCALAR(safe.parse_json(cast(source.json_col as STRING)), '$.updated_at') as TIMESTAMP) as DATETIME) as updated_atAvoid Direct DATETIME Cast on JSON Extractions:
Incorrect:
cast(JSON_EXTRACT_SCALAR(...) as DATETIME)(fails on ISO-8601 strings ending in'Z')Correct:
cast(JSON_EXTRACT_SCALAR(...) as TIMESTAMP)orcast(cast(JSON_EXTRACT_SCALAR(...) as TIMESTAMP) as DATETIME)
6. BigQuery STRUCT (RECORD) vs. JSON Columns
In Snowflake, both object maps and JSON are typically stored as VARIANT or OBJECT and accessed using colon notation (col:field or col:sub:field).
In BigQuery:
Ingested tables (e.g. from MongoDB, Iceberg, or Datastream) often define nested objects as native BigQuery
STRUCT(RECORD) types.Raw API tables often store semi-structured data as native
JSONor stringified JSON (STRING).
The Runtime Error
If a table column is a STRUCT or ARRAY<STRUCT<...>>, calling JSON_VALUE() directly on it causes the following BigQuery query failure:
No matching signature for function JSON_VALUE
Argument types: ARRAY<STRUCT<error STRING, code STRING, state STRING>>, STRING
Signature: JSON_VALUE(STRING, [STRING])
Argument 1: Unable to coerce type ARRAY<STRUCT<...>> to expected type STRING
Signature: JSON_VALUE(JSON, [STRING])
Argument 1: Unable to coerce type ARRAY<STRUCT<...>> to expected type JSONIn BigQuery, CAST(struct AS JSON) is also not supported (Unable to coerce type STRUCT to expected type JSON).
Standard Patterns
For BigQuery STRUCT Columns: Use direct dot notation without
json_value:-- Direct struct field access source.struct_col.name as struct_name, obj_col.id as obj_id, obj_col.name as obj_name, obj_col.type as obj_type, -- Struct field with explicit numeric cast cast(source.struct_col.count as NUMERIC) as struct_count, -- Nested struct field access source.struct_col.nested.flag as nested_flag,For BigQuery JSON Columns: Use
json_value()with standard JSONPath (Option A with double quotes for escaped characters/spaces):-- Standard field json_value(json_col, '$.created_date') as created_date, -- Field with space / special characters json_value(json_col, '$."Field Name"') as field_name, cast(json_value(json_col, '$."Total Value"') as FLOAT64) as total_value,For
ARRAY<STRUCT>orSTRUCTColumns: If a column is typed as a native BigQueryARRAY<STRUCT<...>>(arrays containing nested structs[STRUCT(...)]):Recommended: Native BigQuery Indexing (
SAFE_OFFSET): Directly access the array element using[SAFE_OFFSET(0)]and the struct field using dot notation.field. This avoids JSON serialization overhead and handles empty arrays safely:-- Native BigQuery element & struct access (strongly typed, no JSON serialization) source.col[SAFE_OFFSET(0)].field as field, source.col[SAFE_OFFSET(0)].is_primary as is_primary, source.col[SAFE_OFFSET(0)].code as codeAlternative: JSONPath via
TO_JSON: If evaluating dynamic JSONPath expressions, you must wrap the array into_json(...)becauseJSON_VALUE()only acceptsSTRINGorJSON:-- Correct: Wraps ARRAY<STRUCT> with to_json(...) json_value(to_json(source.col), '$[0].field') as field
Note: Calling
json_value(source.col, '$[0].field')directly on anARRAY<STRUCT>column withoutto_json(...)will fail with:No matching signature for function JSON_VALUE Argument types: ARRAY<STRUCT<...>>, STRING Signature: JSON_VALUE(STRING, [STRING]) Signature: JSON_VALUE(JSON, [STRING])Either replace with
source.col[SAFE_OFFSET(0)].fieldor wrap withto_json(source.col).
7. Snowflake Bracket Notation & BQMS error_unimplemented
In Snowflake, bracket indexing is overloaded for both array indexing (arr[0]) and object attribute access (col['field']).
The BQMS Translation Defect
When BQMS encounters Snowflake object bracket notation col['field'], it attempts to interpret it as an array lookup opcode (JsonFieldJsonNumericAsJsonOpcode), causing translation failure and emitting:
substr(string(error_unimplemented(/* No implementation for JsonFieldJsonNumericAsJsonOpcode in BigQuery. */ source.COL, 'field')), 1, 16777216)or for numeric/timestamp types:
cast(lax_float64(error_unimplemented(/* No implementation for JsonFieldJsonNumericAsJsonOpcode in BigQuery. */ source.COL, 'count')) as BIGNUMERIC)
cast(json_value(error_unimplemented(/* No implementation for JsonFieldJsonNumericAsJsonOpcode in BigQuery. */ source.COL, 'created')) as TIMESTAMP)In BigQuery, error_unimplemented is not a valid SQL function and will fail immediately at query execution time.
Automated Mitigation & Patterns
Pre-processing (Snowflake -> Clean Snowflake): The migration pipeline rewrites bracket notation on identifiers
col['field']to colon notationcol:fieldprior to calling BQMS.Post-processing (BigQuery Cleanup): Any residual
error_unimplementedfunctions are automatically cleaned:For BigQuery STRUCT columns (e.g.
*_STRUCT,STRUCT_COL,*_RECORD,RECORD_COL,*_OBJ,OBJ_COL):-- String cast(source.record_col.status as STRING) as status -- Numeric cast(source.obj_col.count as NUMERIC) as item_count -- Timestamp cast(source.obj_col.created_at as TIMESTAMP) as created_at -- Raw subfield / array source.record_col.tags as tagsFor BigQuery JSON columns:
json_value(source.json_col, '$.field')
8. BQMS 16MB String Wrappers & STRING() Function Signature
The Runtime Error
No matching signature for function STRING
Argument types: STRING
Signature: STRING(TIMESTAMP, [STRING])
Argument 1: Unable to coerce type STRING to expected type TIMESTAMP
Signature: STRING(DATE)
Signature: STRING(TIME)
Signature: STRING(DATETIME)
Signature: STRING(JSON)
Argument 1: Unable to coerce type STRING to expected type JSONRoot Cause
BQMS translates Snowflake ::varchar / ::text (which have a 16MB maximum length in Snowflake) into length-limiting wrappers:
substr(string(col), 1, 16777216)In BigQuery Standard SQL, STRING() is a type constructor specifically for temporal and JSON types (TIMESTAMP, DATE, TIME, DATETIME, JSON). BigQuery has no STRING(STRING) signature. When col is already a STRING (such as a CTE column, extracted struct field, or string scalar), calling string(col) throws a signature mismatch error.
Rule & Pattern
Always replace substr(string(col), 1, 16777216) with clean BigQuery casting:
-- Incorrect:
substr(string(col_name), 1, 16777216) as col_name
-- Correct:
cast(col_name as STRING) as col_nameRequirements 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 a command-line tool, Needs Python
Security
What our scanner noticed· Low risk
- 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
- Publisher
- Google (Official)
- Source
- google/skills · skills/cloud/dbt-sf-to-bq-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 or Google.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download dbt-sf-to-bq-translator.zip