dbt-sf-to-bq-translator
>-
它会碰到什么
逐条看命中(7 条严重或高危)
- 高
scripts/dbt_translator.py:1176exec-spawnsubprocess.run(
- 高
scripts/dbt_translator.py:1181exec-spawnsubprocess.run(
- 高
scripts/dbt_translator.py:1192exec-spawnsubprocess.run(
- 高
scripts/dbt_translator.py:1205exec-spawnsubprocess.run(
- 高
scripts/dbt_translator.py:1219exec-spawnsubprocess.run(
- 高
scripts/dbt_translator.py:1258exec-spawnres = subprocess.run(
- 高
scripts/dbt_translator.py:1274exec-spawnsubprocess.run(
这一栏是扫描器报的事实,不是结论。命中多不等于有毒(安全工具、规则库、示例脚本本来就会包含危险写法),命中少也不等于干净。它和你手上的凭据、文件、网络有什么关系,需要你自己看。
技能内容
dbt Snowflake to BigQuery Translator
You are responsible for:
- Dialect Translation: Translating Snowflake dbt SQL models to Standardized Google BigQuery SQL.
- 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.
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 GCP 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.
- GCS Bucket name for staging translation assets.
- GCP 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 under migration_plan/[mig_prefix]/tasks.md with 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>]
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, GCS 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 extraction sanitization, 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_ - Eliminate Jinja curly braces (
{{ ... }}) from the SQL prior to translation, ensuring 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 GCS 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 GCS. - Upload staging SQL files to GCS:
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 GCS:
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 ... REFRESHorUNSET SECURE, 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)), nesteddateadd(...)calls, and intervals (- interval '5 month') inside and outside control blocks using balanced-parentheses parsers. - 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 Extraction
Never use Snowflake colon notation or BigQuery JSON_VALUE. Always use the following pattern:
- Rule:
CAST(JSON_EXTRACT_SCALAR(json_column, '$.path') AS TYPE) - Mandatory Casting:
- IDs (primary/foreign):
AS INT64for all system IDs (do not useNUMERICfor IDs). - Boolean Flags:
AS BOOL - Strings:
AS STRING(do not wrap inNULLIFunless explicitly required to handle empty/null strings in source). - Timestamps:
AS TIMESTAMP
3. Explicit Type Safety
- Comparisons: Always use
CASTon both sides of a join or filter if types are not identical. UseAS STRINGfor universal comparison safety if necessary. - 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](references/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.
想直接用这个技能?
本站把开放许可(MIT / Apache 等)的技能按仓库打包整理到网盘,点一下转存到你自己的网盘,不用一个个从 GitHub 拉。许可未声明的技能只给原始仓库链接,不打包。