[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M755TJS5RPMQSD72Z2JHJR0R":3,"skill-same:01M755TJS5RPMQSD72Z2JHJR0R":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":13,"repositoryHtmlUrl":26,"repositoryHomepageUrl":6,"ownerHtmlUrl":27,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":28,"install":29,"resources":42},"01M755TJS5RPMQSD72Z2JHJR0R","snowflake-development",null,"Use when writing Snowflake SQL, building data pipelines with Dynamic Tables or Streams\u002FTasks, using Cortex AI functions, creating Cortex Agents, writing Snowpark Python, configuring dbt for Snowflake, or troubleshooting Snowflake errors.","msm47\u002FGitskil","msm47","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F288053465?v=4","01M754J0R2V3Q31DD8BV9CCDEN","01M754J0S8Q6Y7P0S3AYCY0YQ5",0,"MIT","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fengineering-team\u002Fsnowflake-development\u002Fskills\u002Fsnowflake-development\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: \"snowflake-development\"\ndescription: \"Use when writing Snowflake SQL, building data pipelines with Dynamic Tables or Streams\u002FTasks, using Cortex AI functions, creating Cortex Agents, writing Snowpark Python, configuring dbt for Snowflake, or troubleshooting Snowflake errors.\"\n---\n\n# Snowflake Development\n\nSnowflake SQL, data pipelines, Cortex AI, and Snowpark Python development. Covers the colon-prefix rule, semi-structured data, MERGE upserts, Dynamic Tables, Streams+Tasks, Cortex AI functions, agent specs, performance tuning, and security hardening.\n\n> Originally contributed by [James Cha-Earley](https:\u002F\u002Fgithub.com\u002Fjamescha-earley) — enhanced and integrated by the claude-skills team.\n\n## Quick Start\n\n```bash\n# Generate a MERGE upsert template\npython scripts\u002Fsnowflake_query_helper.py merge --target customers --source staging_customers --key customer_id --columns name,email,updated_at\n\n# Generate a Dynamic Table template\npython scripts\u002Fsnowflake_query_helper.py dynamic-table --name cleaned_events --warehouse transform_wh --lag \"5 minutes\"\n\n# Generate RBAC grant statements\npython scripts\u002Fsnowflake_query_helper.py grant --role analyst_role --database analytics --schemas public,staging --privileges SELECT,USAGE\n```\n\n---\n\n## SQL Best Practices\n\n### Naming and Style\n\n- Use `snake_case` for all identifiers. Avoid double-quoted identifiers -- they force case-sensitive names that require constant quoting.\n- Use CTEs (`WITH` clauses) over nested subqueries.\n- Use `CREATE OR REPLACE` for idempotent DDL.\n- Use explicit column lists -- never `SELECT *` in production. Snowflake's columnar storage scans only referenced columns, so explicit lists reduce I\u002FO.\n\n### Stored Procedures -- Colon Prefix Rule\n\nIn SQL stored procedures (BEGIN...END blocks), variables and parameters **must** use the colon `:` prefix inside SQL statements. Without it, Snowflake treats them as column identifiers and raises \"invalid identifier\" errors.\n\n```sql\n-- WRONG: missing colon prefix\nSELECT name INTO result FROM users WHERE id = p_id;\n\n-- CORRECT: colon prefix on both variable and parameter\nSELECT name INTO :result FROM users WHERE id = :p_id;\n```\n\nThis applies to DECLARE variables, LET variables, and procedure parameters when used inside SELECT, INSERT, UPDATE, DELETE, or MERGE.\n\n### Semi-Structured Data\n\n- VARIANT, OBJECT, ARRAY for JSON\u002FAvro\u002FParquet\u002FORC.\n- Access nested fields: `src:customer.name::STRING`. Always cast with `::TYPE`.\n- VARIANT null vs SQL NULL: JSON `null` is stored as the string `\"null\"`. Use `STRIP_NULL_VALUE = TRUE` on load.\n- Flatten arrays: `SELECT f.value:name::STRING FROM my_table, LATERAL FLATTEN(input => src:items) f;`\n\n### MERGE for Upserts\n\n```sql\nMERGE INTO target t USING source s ON t.id = s.id\nWHEN MATCHED THEN UPDATE SET t.name = s.name, t.updated_at = CURRENT_TIMESTAMP()\nWHEN NOT MATCHED THEN INSERT (id, name, updated_at) VALUES (s.id, s.name, CURRENT_TIMESTAMP());\n```\n\n> See `references\u002Fsnowflake_sql_and_pipelines.md` for deeper SQL patterns and anti-patterns.\n\n---\n\n## Data Pipelines\n\n### Choosing Your Approach\n\n| Approach | When to Use |\n|----------|-------------|\n| Dynamic Tables | Declarative transformations. **Default choice.** Define the query, Snowflake handles refresh. |\n| Streams + Tasks | Imperative CDC. Use for procedural logic, stored procedure calls, complex branching. |\n| Snowpipe | Continuous file loading from cloud storage (S3, GCS, Azure). |\n\n### Dynamic Tables\n\n```sql\nCREATE OR REPLACE DYNAMIC TABLE cleaned_events\n    TARGET_LAG = '5 minutes'\n    WAREHOUSE = transform_wh\n    AS\n    SELECT event_id, event_type, user_id, event_timestamp\n    FROM raw_events\n    WHERE event_type IS NOT NULL;\n```\n\nKey rules:\n- Set `TARGET_LAG` progressively: tighter at the top of the DAG, looser downstream.\n- Incremental DTs cannot depend on Full-refresh DTs.\n- `SELECT *` breaks on upstream schema changes -- use explicit column lists.\n- Views cannot sit between two Dynamic Tables in the DAG.\n\n### Streams and Tasks\n\n```sql\nCREATE OR REPLACE STREAM raw_stream ON TABLE raw_events;\n\nCREATE OR REPLACE TASK process_events\n    WAREHOUSE = transform_wh\n    SCHEDULE = 'USING CRON 0 *\u002F1 * * * America\u002FLos_Angeles'\n    WHEN SYSTEM$STREAM_HAS_DATA('raw_stream')\n    AS INSERT INTO cleaned_events SELECT ... FROM raw_stream;\n\n-- Tasks start SUSPENDED. You MUST resume them.\nALTER TASK process_events RESUME;\n```\n\n> See `references\u002Fsnowflake_sql_and_pipelines.md` for DT debugging queries and Snowpipe patterns.\n\n---\n\n## Cortex AI\n\n### Function Reference\n\n| Function | Purpose |\n|----------|---------|\n| `AI_COMPLETE` | LLM completion (text, images, documents) |\n| `AI_CLASSIFY` | Classify text into categories (up to 500 labels) |\n| `AI_FILTER` | Boolean filter on text or images |\n| `AI_EXTRACT` | Structured extraction from text\u002Fimages\u002Fdocuments |\n| `AI_SENTIMENT` | Sentiment score (-1 to 1) |\n| `AI_PARSE_DOCUMENT` | OCR or layout extraction from documents |\n| `AI_REDACT` | PII removal from text |\n\n**Deprecated names (do NOT use):** `COMPLETE`, `CLASSIFY_TEXT`, `EXTRACT_ANSWER`, `PARSE_DOCUMENT`, `SUMMARIZE`, `TRANSLATE`, `SENTIMENT`, `EMBED_TEXT_768`.\n\n### TO_FILE -- Common Pitfall\n\nStage path and filename are **separate** arguments:\n\n```sql\n-- WRONG: single combined argument\nTO_FILE('@stage\u002Ffile.pdf')\n\n-- CORRECT: two arguments\nTO_FILE('@db.schema.mystage', 'invoice.pdf')\n```\n\n### Cortex Agents\n\nAgent specs use a JSON structure with top-level keys: `models`, `instructions`, `tools`, `tool_resources`.\n\n- Use `$spec$` delimiter (not `$$`).\n- `models` must be an object, not an array.\n- `tool_resources` is a separate top-level key, not nested inside `tools`.\n- Tool descriptions are the single biggest factor in agent quality.\n\n> See `references\u002Fcortex_ai_and_agents.md` for full agent spec examples and Cortex Search patterns.\n\n---\n\n## Snowpark Python\n\n```python\nfrom snowflake.snowpark import Session\nimport os\n\nsession = Session.builder.configs({\n    \"account\": os.environ[\"SNOWFLAKE_ACCOUNT\"],\n    \"user\": os.environ[\"SNOWFLAKE_USER\"],\n    \"password\": os.environ[\"SNOWFLAKE_PASSWORD\"],\n    \"role\": \"my_role\", \"warehouse\": \"my_wh\",\n    \"database\": \"my_db\", \"schema\": \"my_schema\"\n}).create()\n```\n\n- Never hardcode credentials. Use environment variables or key pair auth.\n- DataFrames are lazy -- executed on `collect()` \u002F `show()`.\n- Do NOT call `collect()` on large DataFrames. Process server-side with DataFrame operations.\n- Use **vectorized UDFs** (10-100x faster) for batch and ML workloads.\n\n## dbt on Snowflake\n\n```sql\n-- Dynamic table materialization (streaming\u002Fnear-real-time marts):\n{{ config(materialized='dynamic_table', snowflake_warehouse='transforming', target_lag='1 hour') }}\n\n-- Incremental materialization (large fact tables):\n{{ config(materialized='incremental', unique_key='event_id') }}\n\n-- Snowflake-specific configs (combine with any materialization):\n{{ config(transient=true, copy_grants=true, query_tag='team_daily') }}\n```\n\n- Do NOT use `{{ this }}` without `{% if is_incremental() %}` guard.\n- Use `dynamic_table` materialization for streaming or near-real-time marts.\n\n## Performance\n\n- **Cluster keys**: Only for multi-TB tables. Apply on WHERE \u002F JOIN \u002F GROUP BY columns.\n- **Search Optimization**: `ALTER TABLE t ADD SEARCH OPTIMIZATION ON EQUALITY(col);`\n- **Warehouse sizing**: Start X-Small, scale up. Set `AUTO_SUSPEND = 60`, `AUTO_RESUME = TRUE`.\n- **Separate warehouses** per workload (load, transform, query).\n\n## Security\n\n- Follow least-privilege RBAC. Use database roles for object-level grants.\n- Audit ACCOUNTADMIN regularly: `SHOW GRANTS OF ROLE ACCOUNTADMIN;`\n- Use network policies for IP allowlisting.\n- Use masking policies for PII columns and row access policies for multi-tenant isolation.\n\n---\n\n## Proactive Triggers\n\nSurface these issues without being asked when you notice them in context:\n\n- **Missing colon prefix** in SQL stored procedures -- flag immediately, this causes \"invalid identifier\" at runtime.\n- **`SELECT *` in Dynamic Tables** -- flag as a schema-change time bomb.\n- **Deprecated Cortex function names** (`CLASSIFY_TEXT`, `SUMMARIZE`, etc.) -- suggest the current `AI_*` equivalents.\n- **Task not resumed** after creation -- remind that tasks start SUSPENDED.\n- **Hardcoded credentials** in Snowpark code -- flag as a security risk.\n\n---\n\n## Common Errors\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| \"Object does not exist\" | Wrong database\u002Fschema context or missing grants | Fully qualify names (`db.schema.table`), check grants |\n| \"Invalid identifier\" in procedure | Missing colon prefix on variable | Use `:variable_name` inside SQL statements |\n| \"Numeric value not recognized\" | VARIANT field not cast | Cast explicitly: `src:field::NUMBER(10,2)` |\n| Task not running | Forgot to resume after creation | `ALTER TASK task_name RESUME;` |\n| DT refresh failing | Schema change upstream or tracking disabled | Use explicit columns, verify change tracking |\n| TO_FILE error | Combined path as single argument | Split into two args: `TO_FILE('@stage', 'file.pdf')` |\n\n---\n\n## Practical Workflows\n\n### Workflow 1: Build a Reporting Pipeline (30 min)\n\n1. **Stage raw data**: Create external stage pointing to S3\u002FGCS\u002FAzure, set up Snowpipe for auto-ingest\n2. **Clean with Dynamic Table**: Create DT with `TARGET_LAG = '5 minutes'` that filters nulls, casts types, deduplicates\n3. **Aggregate with downstream DT**: Second DT that joins cleaned data with dimension tables, computes metrics\n4. **Expose via Secure View**: Create `SECURE VIEW` for the BI tool \u002F API layer\n5. **Grant access**: Use `snowflake_query_helper.py grant` to generate RBAC statements\n\n### Workflow 2: Add AI Classification to Existing Data\n\n1. **Identify the column**: Find the text column to classify (e.g., support tickets, reviews)\n2. **Test with AI_CLASSIFY**: `SELECT AI_CLASSIFY(text_col, ['bug', 'feature', 'question']) FROM table LIMIT 10;`\n3. **Create enrichment DT**: Dynamic Table that runs `AI_CLASSIFY` on new rows automatically\n4. **Monitor costs**: Cortex AI is billed per token — sample before running on full tables\n\n### Workflow 3: Debug a Failing Pipeline\n\n1. **Check task history**: `SELECT * FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY()) WHERE STATE = 'FAILED' ORDER BY SCHEDULED_TIME DESC;`\n2. **Check DT refresh**: `SELECT * FROM TABLE(INFORMATION_SCHEMA.DYNAMIC_TABLE_REFRESH_HISTORY('my_dt')) ORDER BY REFRESH_END_TIME DESC;`\n3. **Check stream staleness**: `SHOW STREAMS; -- check stale_after column`\n4. **Consult troubleshooting reference**: See `references\u002Ftroubleshooting.md` for error-specific fixes\n\n---\n\n## Anti-Patterns\n\n| Anti-Pattern | Why It Fails | Better Approach |\n|---|---|---|\n| `SELECT *` in Dynamic Tables | Schema changes upstream break the DT silently | Use explicit column lists |\n| Missing colon prefix in procedures | \"Invalid identifier\" runtime error | Always use `:variable_name` in SQL blocks |\n| Single warehouse for all workloads | Contention between load, transform, and query | Separate warehouses per workload type |\n| Hardcoded credentials in Snowpark | Security risk, breaks in CI\u002FCD | Use `os.environ[]` or key pair auth |\n| `collect()` on large DataFrames | Pulls entire result set to client memory | Process server-side with DataFrame operations |\n| Nested subqueries instead of CTEs | Unreadable, hard to debug, Snowflake optimizes CTEs better | Use `WITH` clauses |\n| Using deprecated Cortex functions | `CLASSIFY_TEXT`, `SUMMARIZE` etc. will be removed | Use `AI_CLASSIFY`, `AI_COMPLETE` etc. |\n| Tasks without `WHEN SYSTEM$STREAM_HAS_DATA` | Task runs on schedule even with no new data, wasting credits | Add the WHEN clause for stream-driven tasks |\n| Double-quoted identifiers | Forces case-sensitive names across all queries | Use `snake_case` unquoted identifiers |\n\n---\n\n## Cross-References\n\n| Skill | Relationship |\n|-------|-------------|\n| `engineering\u002Fsql-database-assistant` | General SQL patterns — use for non-Snowflake databases |\n| `engineering\u002Fdatabase-designer` | Schema design — use for data modeling before Snowflake implementation |\n| `engineering-team\u002Fsenior-data-engineer` | Broader data engineering — pipelines, Spark, Airflow, data quality |\n| `engineering-team\u002Fsenior-data-scientist` | Analytics and ML — use alongside Snowpark for feature engineering |\n| `engineering-team\u002Fsenior-devops` | CI\u002FCD for Snowflake deployments (Terraform, GitHub Actions) |\n\n---\n\n## Reference Documentation\n\n| Document | Contents |\n|----------|----------|\n| `references\u002Fsnowflake_sql_and_pipelines.md` | SQL patterns, MERGE templates, Dynamic Table debugging, Snowpipe, anti-patterns |\n| `references\u002Fcortex_ai_and_agents.md` | Cortex AI functions, agent spec structure, Cortex Search, Snowpark |\n| `references\u002Ftroubleshooting.md` | Error reference, debugging queries, common fixes |\n","# Snowflake Development\n\nSnowflake SQL, data pipelines, Cortex AI, and Snowpark Python development. Covers the colon-prefix rule, semi-structured data, MERGE upserts, Dynamic Tables, Streams+Tasks, Cortex AI functions, agent specs, performance tuning, and security hardening.\n\n> Originally contributed by [James Cha-Earley](https:\u002F\u002Fgithub.com\u002Fjamescha-earley) — enhanced and integrated by the claude-skills team.\n\n## Quick Start\n\n```bash\n# Generate a MERGE upsert template\npython scripts\u002Fsnowflake_query_helper.py merge --target customers --source staging_customers --key customer_id --columns name,email,updated_at\n\n# Generate a Dynamic Table template\npython scripts\u002Fsnowflake_query_helper.py dynamic-table --name cleaned_events --warehouse transform_wh --lag \"5 minutes\"\n\n# Generate RBAC grant statements\npython scripts\u002Fsnowflake_query_helper.py grant --role analyst_role --database analytics --schemas public,staging --privileges SELECT,USAGE\n```\n\n---\n\n## SQL Best Practices\n\n### Naming and Style\n\n- Use `snake_case` for all identifiers. Avoid double-quoted identifiers -- they force case-sensitive names that require constant quoting.\n- Use CTEs (`WITH` clauses) over nested subqueries.\n- Use `CREATE OR REPLACE` for idempotent DDL.\n- Use explicit column lists -- never `SELECT *` in production. Snowflake's columnar storage scans only referenced columns, so explicit lists reduce I\u002FO.\n\n### Stored Procedures -- Colon Prefix Rule\n\nIn SQL stored procedures (BEGIN...END blocks), variables and parameters **must** use the colon `:` prefix inside SQL statements. Without it, Snowflake treats them as column identifiers and raises \"invalid identifier\" errors.\n\n```sql\n-- WRONG: missing colon prefix\nSELECT name INTO result FROM users WHERE id = p_id;\n\n-- CORRECT: colon prefix on both variable and parameter\nSELECT name INTO :result FROM users WHERE id = :p_id;\n```\n\nThis applies to DECLARE variables, LET variables, and procedure parameters when used inside SELECT, INSERT, UPDATE, DELETE, or MERGE.\n\n### Semi-Structured Data\n\n- VARIANT, OBJECT, ARRAY for JSON\u002FAvro\u002FParquet\u002FORC.\n- Access nested fields: `src:customer.name::STRING`. Always cast with `::TYPE`.\n- VARIANT null vs SQL NULL: JSON `null` is stored as the string `\"null\"`. Use `STRIP_NULL_VALUE = TRUE` on load.\n- Flatten arrays: `SELECT f.value:name::STRING FROM my_table, LATERAL FLATTEN(input => src:items) f;`\n\n### MERGE for Upserts\n\n```sql\nMERGE INTO target t USING source s ON t.id = s.id\nWHEN MATCHED THEN UPDATE SET t.name = s.name, t.updated_at = CURRENT_TIMESTAMP()\nWHEN NOT MATCHED THEN INSERT (id, name, updated_at) VALUES (s.id, s.name, CURRENT_TIMESTAMP());\n```\n\n> See `references\u002Fsnowflake_sql_and_pipelines.md` for deeper SQL patterns and anti-patterns.\n\n---\n\n## Data Pipelines\n\n### Choosing Your Approach\n\n| Approach | When to Use |\n|----------|-------------|\n| Dynamic Tables | Declarative transformations. **Default choice.** Define the query, Snowflake handles refresh. |\n| Streams + Tasks | Imperative CDC. Use for procedural logic, stored procedure calls, complex branching. |\n| Snowpipe | Continuous file loading from cloud storage (S3, GCS, Azure). |\n\n### Dynamic Tables\n\n```sql\nCREATE OR REPLACE DYNAMIC TABLE cleaned_events\n    TARGET_LAG = '5 minutes'\n    WAREHOUSE = transform_wh\n    AS\n    SELECT event_id, event_type, user_id, event_timestamp\n    FROM raw_events\n    WHERE event_type IS NOT NULL;\n```\n\nKey rules:\n- Set `TARGET_LAG` progressively: tighter at the top of the DAG, looser downstream.\n- Incremental DTs cannot depend on Full-refresh DTs.\n- `SELECT *` breaks on upstream schema changes -- use explicit column lists.\n- Views cannot sit between two Dynamic Tables in the DAG.\n\n### Streams and Tasks\n\n```sql\nCREATE OR REPLACE STREAM raw_stream ON TABLE raw_events;\n\nCREATE OR REPLACE TASK process_events\n    WAREHOUSE = transform_wh\n    SCHEDULE = 'USING CRON 0 *\u002F1 * * * America\u002FLos_Angeles'\n    WHEN SYSTEM$STREAM_HAS_DATA('raw_stream')\n    AS INSERT INTO cleaned_events SELECT ... FROM raw_stream;\n\n-- Tasks start SUSPENDED. You MUST resume them.\nALTER TASK process_events RESUME;\n```\n\n> See `references\u002Fsnowflake_sql_and_pipelines.md` for DT debugging queries and Snowpipe patterns.\n\n---\n\n## Cortex AI\n\n### Function Reference\n\n| Function | Purpose |\n|----------|---------|\n| `AI_COMPLETE` | LLM completion (text, images, documents) |\n| `AI_CLASSIFY` | Classify text into categories (up to 500 labels) |\n| `AI_FILTER` | Boolean filter on text or images |\n| `AI_EXTRACT` | Structured extraction from text\u002Fimages\u002Fdocuments |\n| `AI_SENTIMENT` | Sentiment score (-1 to 1) |\n| `AI_PARSE_DOCUMENT` | OCR or layout extraction from documents |\n| `AI_REDACT` | PII removal from text |\n\n**Deprecated names (do NOT use):** `COMPLETE`, `CLASSIFY_TEXT`, `EXTRACT_ANSWER`, `PARSE_DOCUMENT`, `SUMMARIZE`, `TRANSLATE`, `SENTIMENT`, `EMBED_TEXT_768`.\n\n### TO_FILE -- Common Pitfall\n\nStage path and filename are **separate** arguments:\n\n```sql\n-- WRONG: single combined argument\nTO_FILE('@stage\u002Ffile.pdf')\n\n-- CORRECT: two arguments\nTO_FILE('@db.schema.mystage', 'invoice.pdf')\n```\n\n### Cortex Agents\n\nAgent specs use a JSON structure with top-level keys: `models`, `instructions`, `tools`, `tool_resources`.\n\n- Use `$spec$` delimiter (not `$$`).\n- `models` must be an object, not an array.\n- `tool_resources` is a separate top-level key, not nested inside `tools`.\n- Tool descriptions are the single biggest factor in agent quality.\n\n> See `references\u002Fcortex_ai_and_agents.md` for full agent spec examples and Cortex Search patterns.\n\n---\n\n## Snowpark Python\n\n```python\nfrom snowflake.snowpark import Session\nimport os\n\nsession = Session.builder.configs({\n    \"account\": os.environ[\"SNOWFLAKE_ACCOUNT\"],\n    \"user\": os.environ[\"SNOWFLAKE_USER\"],\n    \"password\": os.environ[\"SNOWFLAKE_PASSWORD\"],\n    \"role\": \"my_role\", \"warehouse\": \"my_wh\",\n    \"database\": \"my_db\", \"schema\": \"my_schema\"\n}).create()\n```\n\n- Never hardcode credentials. Use environment variables or key pair auth.\n- DataFrames are lazy -- executed on `collect()` \u002F `show()`.\n- Do NOT call `collect()` on large DataFrames. Process server-side with DataFrame operations.\n- Use **vectorized UDFs** (10-100x faster) for batch and ML workloads.\n\n## dbt on Snowflake\n\n```sql\n-- Dynamic table materialization (streaming\u002Fnear-real-time marts):\n{{ config(materialized='dynamic_table', snowflake_warehouse='transforming', target_lag='1 hour') }}\n\n-- Incremental materialization (large fact tables):\n{{ config(materialized='incremental', unique_key='event_id') }}\n\n-- Snowflake-specific configs (combine with any materialization):\n{{ config(transient=true, copy_grants=true, query_tag='team_daily') }}\n```\n\n- Do NOT use `{{ this }}` without `{% if is_incremental() %}` guard.\n- Use `dynamic_table` materialization for streaming or near-real-time marts.\n\n## Performance\n\n- **Cluster keys**: Only for multi-TB tables. Apply on WHERE \u002F JOIN \u002F GROUP BY columns.\n- **Search Optimization**: `ALTER TABLE t ADD SEARCH OPTIMIZATION ON EQUALITY(col);`\n- **Warehouse sizing**: Start X-Small, scale up. Set `AUTO_SUSPEND = 60`, `AUTO_RESUME = TRUE`.\n- **Separate warehouses** per workload (load, transform, query).\n\n## Security\n\n- Follow least-privilege RBAC. Use database roles for object-level grants.\n- Audit ACCOUNTADMIN regularly: `SHOW GRANTS OF ROLE ACCOUNTADMIN;`\n- Use network policies for IP allowlisting.\n- Use masking policies for PII columns and row access policies for multi-tenant isolation.\n\n---\n\n## Proactive Triggers\n\nSurface these issues without being asked when you notice them in context:\n\n- **Missing colon prefix** in SQL stored procedures -- flag immediately, this causes \"invalid identifier\" at runtime.\n- **`SELECT *` in Dynamic Tables** -- flag as a schema-change time bomb.\n- **Deprecated Cortex function names** (`CLASSIFY_TEXT`, `SUMMARIZE`, etc.) -- suggest the current `AI_*` equivalents.\n- **Task not resumed** after creation -- remind that tasks start SUSPENDED.\n- **Hardcoded credentials** in Snowpark code -- flag as a security risk.\n\n---\n\n## Common Errors\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| \"Object does not exist\" | Wrong database\u002Fschema context or missing grants | Fully qualify names (`db.schema.table`), check grants |\n| \"Invalid identifier\" in procedure | Missing colon prefix on variable | Use `:variable_name` inside SQL statements |\n| \"Numeric value not recognized\" | VARIANT field not cast | Cast explicitly: `src:field::NUMBER(10,2)` |\n| Task not running | Forgot to resume after creation | `ALTER TASK task_name RESUME;` |\n| DT refresh failing | Schema change upstream or tracking disabled | Use explicit columns, verify change tracking |\n| TO_FILE error | Combined path as single argument | Split into two args: `TO_FILE('@stage', 'file.pdf')` |\n\n---\n\n## Practical Workflows\n\n### Workflow 1: Build a Reporting Pipeline (30 min)\n\n1. **Stage raw data**: Create external stage pointing to S3\u002FGCS\u002FAzure, set up Snowpipe for auto-ingest\n2. **Clean with Dynamic Table**: Create DT with `TARGET_LAG = '5 minutes'` that filters nulls, casts types, deduplicates\n3. **Aggregate with downstream DT**: Second DT that joins cleaned data with dimension tables, computes metrics\n4. **Expose via Secure View**: Create `SECURE VIEW` for the BI tool \u002F API layer\n5. **Grant access**: Use `snowflake_query_helper.py grant` to generate RBAC statements\n\n### Workflow 2: Add AI Classification to Existing Data\n\n1. **Identify the column**: Find the text column to classify (e.g., support tickets, reviews)\n2. **Test with AI_CLASSIFY**: `SELECT AI_CLASSIFY(text_col, ['bug', 'feature', 'question']) FROM table LIMIT 10;`\n3. **Create enrichment DT**: Dynamic Table that runs `AI_CLASSIFY` on new rows automatically\n4. **Monitor costs**: Cortex AI is billed per token — sample before running on full tables\n\n### Workflow 3: Debug a Failing Pipeline\n\n1. **Check task history**: `SELECT * FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY()) WHERE STATE = 'FAILED' ORDER BY SCHEDULED_TIME DESC;`\n2. **Check DT refresh**: `SELECT * FROM TABLE(INFORMATION_SCHEMA.DYNAMIC_TABLE_REFRESH_HISTORY('my_dt')) ORDER BY REFRESH_END_TIME DESC;`\n3. **Check stream staleness**: `SHOW STREAMS; -- check stale_after column`\n4. **Consult troubleshooting reference**: See `references\u002Ftroubleshooting.md` for error-specific fixes\n\n---\n\n## Anti-Patterns\n\n| Anti-Pattern | Why It Fails | Better Approach |\n|---|---|---|\n| `SELECT *` in Dynamic Tables | Schema changes upstream break the DT silently | Use explicit column lists |\n| Missing colon prefix in procedures | \"Invalid identifier\" runtime error | Always use `:variable_name` in SQL blocks |\n| Single warehouse for all workloads | Contention between load, transform, and query | Separate warehouses per workload type |\n| Hardcoded credentials in Snowpark | Security risk, breaks in CI\u002FCD | Use `os.environ[]` or key pair auth |\n| `collect()` on large DataFrames | Pulls entire result set to client memory | Process server-side with DataFrame operations |\n| Nested subqueries instead of CTEs | Unreadable, hard to debug, Snowflake optimizes CTEs better | Use `WITH` clauses |\n| Using deprecated Cortex functions | `CLASSIFY_TEXT`, `SUMMARIZE` etc. will be removed | Use `AI_CLASSIFY`, `AI_COMPLETE` etc. |\n| Tasks without `WHEN SYSTEM$STREAM_HAS_DATA` | Task runs on schedule even with no new data, wasting credits | Add the WHEN clause for stream-driven tasks |\n| Double-quoted identifiers | Forces case-sensitive names across all queries | Use `snake_case` unquoted identifiers |\n\n---\n\n## Cross-References\n\n| Skill | Relationship |\n|-------|-------------|\n| `engineering\u002Fsql-database-assistant` | General SQL patterns — use for non-Snowflake databases |\n| `engineering\u002Fdatabase-designer` | Schema design — use for data modeling before Snowflake implementation |\n| `engineering-team\u002Fsenior-data-engineer` | Broader data engineering — pipelines, Spark, Airflow, data quality |\n| `engineering-team\u002Fsenior-data-scientist` | Analytics and ML — use alongside Snowpark for feature engineering |\n| `engineering-team\u002Fsenior-devops` | CI\u002FCD for Snowflake deployments (Terraform, GitHub Actions) |\n\n---\n\n## Reference Documentation\n\n| Document | Contents |\n|----------|----------|\n| `references\u002Fsnowflake_sql_and_pipelines.md` | SQL patterns, MERGE templates, Dynamic Table debugging, Snowpipe, anti-patterns |\n| `references\u002Fcortex_ai_and_agents.md` | Cortex AI functions, agent spec structure, Cortex Search, Snowpark |\n| `references\u002Ftroubleshooting.md` | Error reference, debugging queries, common fixes |\n",{"name":5,"description":7},"main","56d41613d1ca1e2b0614a19c3816ec97a6159ec2","engineering-team\u002Fsnowflake-development\u002Fskills\u002Fsnowflake-development","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil","https:\u002F\u002Fgithub.com\u002Fmsm47","2026-06-22 18:36:50",{"source":8,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add msm47\u002FGitskil --skill snowflake-development",{"tool":35,"command":36},"bunx","bunx skills add msm47\u002FGitskil --skill snowflake-development",{"tool":38,"command":39},"pnpm","pnpm dlx skills add msm47\u002FGitskil --skill snowflake-development","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fengineering-team\u002Fsnowflake-development\u002Fskills\u002Fsnowflake-development\u002FSKILL.md",true,[43,49,53,57],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"references\u002Fcortex_ai_and_agents.md","REFERENCE","参考文档",7724,"https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fengineering-team\u002Fsnowflake-development\u002Fskills\u002Fsnowflake-development\u002Freferences\u002Fcortex_ai_and_agents.md",{"path":50,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":51,"sourceHtmlUrl":52},"references\u002Fsnowflake_sql_and_pipelines.md",7553,"https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fengineering-team\u002Fsnowflake-development\u002Fskills\u002Fsnowflake-development\u002Freferences\u002Fsnowflake_sql_and_pipelines.md",{"path":54,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":55,"sourceHtmlUrl":56},"references\u002Ftroubleshooting.md",5364,"https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fengineering-team\u002Fsnowflake-development\u002Fskills\u002Fsnowflake-development\u002Freferences\u002Ftroubleshooting.md",{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"scripts\u002Fsnowflake_query_helper.py","SCRIPT","脚本",8444,"https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fengineering-team\u002Fsnowflake-development\u002Fskills\u002Fsnowflake-development\u002Fscripts\u002Fsnowflake_query_helper.py",[64,71,78,85,92,99],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":18},"01M76S8VB9Q65XVZXC99QVF20M","syllabus","Generates a curated supplementary reading list from any course syllabus using Consensus academic search. Grill-me intake (syllabus input format + course audience + year range) plus a grouping forcing-options checkpoint before any search runs — so the reading list matches the course's level and recency need. Parses the syllabus to extract topics and learning outcomes, searches Consensus for recent peer-reviewed papers per topic, and produces a professionally formatted .docx with clickable Consensus links, plain-language summaries calibrated to audience level, and Bloom-higher-order discussion questions tied to course learning goals. Triggers whenever a user uploads a syllabus, course outline, or curriculum document and wants supplementary readings. Also triggers on: 'syllabus reading list', 'find papers for my course', 'create a reading list from this syllabus', 'recent research for my class', 'supplementary readings', 'find journal articles for these topics', 'what recent papers cover this material', 'any new research on these course topics', 'update my syllabus with recent papers'. Even casual mentions when a syllabus is attached should trigger this skill.","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fresearch\u002Fsyllabus\u002Fskills\u002Fsyllabus\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":18},"01M76S8K8X17M3CV7RENS6KA32","research","Default entry point for any research request — a hybrid router that classifies the question deterministically and either delegates to a specialist research skill (pulse for trends\u002Fsentiment, grants for NIH funding, litreview for academic literature, syllabus for course reading, patent for prior-art + IP landscape, dossier for entity research) or runs its own plan-decompose-multi-source-search-synthesize-cite fallback workflow when no specialist matches. Always surfaces the routing decision so users can override. Triggers — \"research [topic]\", \"look into [topic]\", \"what do we know about [topic]\", \"investigate [topic]\", \"find me information on [topic]\", \"do some research on [topic]\", \"I need to understand [topic]\", or any research request that doesn't obviously match a more-specific specialist skill. Output is a markdown briefing (default) or .docx document (on request) with full citations and an audit log.","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fresearch\u002Fresearch\u002Fskills\u002Fresearch\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":18},"01M76S8AZCNS7Q5M4G1SBQ8HDV","pulse","Multi-source recency research skill that takes the pulse of any topic across Reddit, Hacker News, the open web, and optionally X\u002FTwitter within a configurable recent window (default 30 days). Forcing intake clarifies topic specificity, angle (trend\u002Fsentiment\u002Fproblems\u002Fopportunities\u002Fcomparison), time window, and platform scope before searching. Returns a synthesized briefing with citations, engagement metrics, and cross-platform pattern analysis. Triggers: 'pulse on [topic]', 'what's happening with [topic]', 'what are people saying about [topic]', 'current conversation about [topic]', 'take the pulse of [topic]', 'trending: [topic]', 'find me info on [topic]', or any variation requesting multi-source recency intelligence on a topic. Also use for competitor research, trend discovery, tool comparisons, and audience sentiment analysis.","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fresearch\u002Fpulse\u002Fskills\u002Fpulse\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":18},"01M76S7YVS0NHD51AFTZM5965R","patent","Patent prior-art and landscape intelligence skill — not generic patent help. Commits to one of five sub-use-cases via forcing intake (novelty search \u002F freedom-to-operate \u002F competitive landscape \u002F acquisition diligence \u002F litigation prior-art) before any search runs. Searches Google Patents, Espacenet, USPTO, and optionally Lens.org for citation-graph signals. Output is an editable Word document (.docx) with verdict, ranked closest art (claim-text extracted), CPC-class-aware landscape, family-resolved hits, geographic coverage, FTO flags where applicable, strategy recommendations, and full audit log. Triggers: 'prior art search for [invention]', 'patent search on [topic]', 'freedom to operate analysis', 'FTO for [product]', 'patent landscape for [field]', 'is [invention] novel', 'patents on [topic]', 'competitive patent analysis', 'prior art for litigation', 'patent diligence on [company]'. Produces search signal, not legal advice — always recommends consulting a patent attorney before filing or licensing decisions. Trademark, copyright, and trade-secret questions are out of scope.","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fresearch\u002Fpatent\u002Fskills\u002Fpatent\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":18},"01M76S7MQDZR49Y3DRXF394R2F","notebooklm","Browser automation skill for controlling Google's NotebookLM. Handles reading and querying notebooks, adding sources (URLs, text, files, YouTube links, synthesized content), generating Studio outputs (Audio Overview, infographics, slide decks, study guides, briefing docs, mind maps, timelines, FAQs), and creating new notebooks. Triggers on any phrase involving NotebookLM — 'open NotebookLM', 'check my [name] notebook', 'pull info from NotebookLM', 'ask my notebook about X', 'add [source] to NotebookLM', 'create an infographic in NotebookLM', 'use NotebookLM Studio', 'generate a slide deck from my notebook', or any variation where the goal involves NotebookLM. Requires browser automation environment — fails gracefully when unavailable.","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fresearch\u002Fnotebooklm\u002Fskills\u002Fnotebooklm\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":18},"01M76S78K1ZJ092YYRKX0KBTYJ","litreview","Academic literature orientation skill that searches papers via Consensus, builds a strategic search plan using PICO (default) or SPIDER \u002F Decomposition \u002F hybrid as fallbacks, and synthesizes findings into a professionally formatted Word document (.docx) research guide. Grill-me intake (research question specificity + framework hint + tentative depth) before the recon search; a second forcing checkpoint after Phase 2 confirms framework + sub-areas + depth before searches consume budget. Configurable depth (5\u002F10\u002F20 queries) controls coverage vs. speed. Output is a 'launching pad' — not a finished review, but an orientation guide that lets a researcher dive in confidently. Triggers: 'litreview on [topic]', 'literature review on [topic]', 'I'm starting a literature review on X', 'I'm writing a paper on X', 'help me research X', 'I'm doing research on X', 'can you help me research X'. Do NOT trigger for single one-off paper searches where the user just wants a quick list — that's a plain Consensus search.","https:\u002F\u002Fgithub.com\u002Fmsm47\u002FGitskil\u002Fblob\u002Fmain\u002Fresearch\u002Flitreview\u002Fskills\u002Flitreview\u002FSKILL.md",[],[]]