[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73AYQQ2ACH3AZ59GJM97SC9":3,"skill-same:01M73AYQQ2ACH3AZ59GJM97SC9":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M73AYQQ2ACH3AZ59GJM97SC9","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.","kalash33\u002Fkstack","kalash33","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F90259149?v=4","01M7365X8Q0B73NYHA730SMZWN","Kalash Poddar","01M7365X9D0JK47C3Q0YCCK9Z2",0,"MIT","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fnginity-snowflake-development\u002FSKILL.md",[],[],"2026-11-11 15:11:14",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","b30820b3248f6676d5389f0ccabd4e5250c9c536","skills\u002Fnginity-snowflake-development","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack","https:\u002F\u002Fgithub.com\u002Fkalash33","kalashpoddar.me","Tech-savvy Full Stack Developer 🚀 | Cybersecurity enthusiast 🔒 | Passionate about innovation and securing the digital world 🌐 | Let's code securely! 💻🔐","2026-05-20 04:11:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add kalash33\u002Fkstack --skill snowflake-development",{"tool":38,"command":39},"bunx","bunx skills add kalash33\u002Fkstack --skill snowflake-development",{"tool":41,"command":42},"pnpm","pnpm dlx skills add kalash33\u002Fkstack --skill snowflake-development","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fnginity-snowflake-development\u002FSKILL.md",true,[46,52,56,60,64],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},".claude-plugin\u002Fplugin.json","REFERENCE","参考文档",582,"https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fnginity-snowflake-development\u002F.claude-plugin\u002Fplugin.json",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"references\u002Fcortex_ai_and_agents.md",7724,"https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fnginity-snowflake-development\u002Freferences\u002Fcortex_ai_and_agents.md",{"path":57,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fsnowflake_sql_and_pipelines.md",7553,"https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fnginity-snowflake-development\u002Freferences\u002Fsnowflake_sql_and_pipelines.md",{"path":61,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Ftroubleshooting.md",5364,"https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fnginity-snowflake-development\u002Freferences\u002Ftroubleshooting.md",{"path":65,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":69},"scripts\u002Fsnowflake_query_helper.py","SCRIPT","脚本",8444,"https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fnginity-snowflake-development\u002Fscripts\u002Fsnowflake_query_helper.py",[71,78,85,92,99,106],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M73CFERCR43JCAP606E41EFB","zustand-store-ts","Create Zustand stores with TypeScript, subscribeWithSelector middleware, and proper state\u002Faction separation. Use when building React state management, creating global stores, or implementing reacti...","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-ts\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M73CFCMFVTAQEMTZ5HR10X8V","zoom-automation","Automate Zoom meeting creation, management, recordings, webinars, and participant tracking via Rube MCP (Composio). Always search tools first for current schemas.","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fzoom-automation\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M73CFAA7EBWXJVXDQ1X555MB","zoho-crm-automation","Automate Zoho CRM tasks via Rube MCP (Composio): create\u002Fupdate records, search contacts, manage leads, and convert leads. Always search tools first for current schemas.","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fzoho-crm-automation\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M73CF80XCM9K81567MJ8QZFW","zod-validation-expert","Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC.","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fzod-validation-expert\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M73CF4YPMF3RA8ZJDXZSMD93","zeroize-audit","Detects missing zeroization of sensitive data in source code and identifies zeroization removed by compiler optimizations, with assembly-level analysis, and control-flow verification. Use for auditing C\u002FC++\u002FRust code handling secrets, keys, passwords, or other sensitive data.","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fzeroize-audit\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M73CF2S25EN3XNAMKY47XHPS","zendesk-automation","Automate Zendesk tasks via Rube MCP (Composio): tickets, users, organizations, replies. Always search tools first for current schemas.","https:\u002F\u002Fgithub.com\u002Fkalash33\u002Fkstack\u002Fblob\u002Fmain\u002Fskills\u002Fzendesk-automation\u002FSKILL.md",[],[]]