<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Keshav M. on Medium]]></title>
        <description><![CDATA[Stories by Keshav M. on Medium]]></description>
        <link>https://medium.com/@misrakeshav?source=rss-dbd510e68880------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Keshav M. on Medium</title>
            <link>https://medium.com/@misrakeshav?source=rss-dbd510e68880------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:44:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@misrakeshav/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Tested Snowflake’s Two Brand New AI Tools by Building a Self-Running Data Modelling Pipeline]]></title>
            <link>https://medium.com/@misrakeshav/i-tested-snowflakes-two-brand-new-ai-tools-by-building-a-self-running-data-modelling-pipeline-31cdcd50fe91?source=rss-dbd510e68880------2</link>
            <guid isPermaLink="false">https://medium.com/p/31cdcd50fe91</guid>
            <category><![CDATA[snowflake-cortex]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Keshav M.]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 17:23:56 GMT</pubDate>
            <atom:updated>2026-06-15T20:16:42.754Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>CoCo Desktop launched at Snowflake Summit two weeks ago, so I thought of a use case for it, to understand when to use it. Here’s what I built!</strong></p><p>Snowflake Summit 2026 launched a lot of things. One that caught my attention as a data architect:</p><p><strong>CoCo Desktop: </strong>a brand new native IDE for data engineers that launched June 2. Before Summit, CoCo was a CLI tool and a panel inside Snowsight. We’d hear users using VSCode IDE to connect to Snowflake and run the code. Now it’s a full desktop application: it connects to your live Snowflake environment, reads your schemas and lineage, writes SQL and Python, executes code, and runs dbt pipelines from a chat interface on your desktop.</p><p><strong>CoWork</strong>: the rebrand of Snowflake Intelligence, announced June 2, 2026. A personal AI agent for knowledge workers that lets business users query governed Snowflake data, run multi-step tasks, and take action across connected tools in natural language.</p><p>I built something real with it, to see if it can help speed up development. Not a hello-world demo. A production-grade (I hope) agentic pipeline that takes a business requirement through intake, spec generation, source mapping, dbt model generation, validation, testing, and release, with humans in the loop at the two moments that actually matter.</p><h3>What I Built</h3><p>A self-running data modelling pipeline for a fictional global technology company (QuantixCorp — hardware, software, support, training, sold globally through account managers).</p><p>Three source systems: Salesforce, SAP, HCM. One target: a Kimball star schema in Snowflake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*lZQqrNSQaGl4NkajB0xwlg.png" /></figure><p>The pipeline has six stages. Each one is a SKILL.md file — a structured markdown document that tells the AI agent what to do, what SQL to run, what to generate, and what to log.</p><h3>The Intake Portal (Streamlit in Snowflake)</h3><p>Before any AI touches the data, a business analyst submits their requirement through a Streamlit portal running natively inside Snowflake.</p><figure><img alt="The intake portal:  a Streamlit in Snowflake, zero external infrastructure" src="https://cdn-images-1.medium.com/max/1024/1*63EgJWWaoJMHfxmy0P_lig.png" /><figcaption>The intake portal: a Streamlit in Snowflake, zero external infrastructure</figcaption></figure><p>The portal has three modes: a guided 8-step wizard, a downloadable YAML template for offline workshops of the same wizard questions, and an upload path for completed templates. Everything lands in a Snowflake table as a VARIANT object entry.</p><p>The one hard gate is the grain- you cannot submit without confirming a precise grain statement. The pipeline refuses to guess the most important answer in dimensional modelling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtsGMg-bm61_fgkP4nGOeA.png" /><figcaption>The grain gate — no submission without a confirmed grain</figcaption></figure><p>An admin (data architect) reviews every submission before it enters the agent queue. Nothing reaches the pipeline without a human sign-off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SShvHfYnR4uFaPablMfmsA.png" /><figcaption>The architect approval gate</figcaption></figure><h3>CoCo Desktop — The Developer’s Tool</h3><p>This is where the pipeline actually runs. I opened my project folder in CoCo Desktop, pointed it at the six SKILL.md files, and typed one prompt:</p><blockquote>“Check the queue and run the data modelling pipeline”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ij-kfULAjlmkh1kG8DSiCA.png" /><figcaption>CoCo Desktop running the pipeline — generating a full dbt project from a business intake (generated files on the right)</figcaption></figure><p>What CoCo Desktop did next, autonomously:</p><ol><li>Queried INTAKE_REQUESTS for the approved request</li><li>Read the intake payload and generated spec.yaml — a structured Kimball model spec with fact tables, dimensions, SCD types, and business rules</li><li>Introspected Snowflake INFORMATION_SCHEMA across all three landing schemas and mapped every source column to a target</li><li>Generated a complete dbt project — staging models, snapshots for SCD Type 2, dimension and fact tables, schema YAML with 34 tests</li><li><strong>Paused and asked me to review the design document before continuing</strong></li><li>Ran validation against 14 checks — naming standards, layer discipline, anti-pattern detection</li><li>Ran dbt build --target dev — 34 tests, 77 passing, 1 intentional flag</li><li>Produced release notes, a deployment runbook, and a final gate check</li></ol><p>The pause in step 5 is intentional. The data modeller generates a human-readable design document — star schema diagram, design decisions log, sign-off checklist. The release manager blocks without it.</p><p><strong>This is where CoCo Desktop shines:</strong> it has genuine file system access, executes real SQL against your Snowflake account, runs shell commands, and writes files to your local machine. It’s a real development environment, not a chat window that asks you to paste things back in.</p><p><strong>CoCo has no persistent file system in CoWork.</strong> When running through CoWork (the chat interface), the agent generates artifacts in session memory. CoCo Desktop writes files to your local machine.</p><p>At the end of the build, the data modeller agent even generated documentation (yay!) on how it joined the data, based on a prompt in the skills files-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*B1tzg-Dzq-GRQtQNnsqimw.png" /></figure><h3>Cortex Analyst — The Business User’s Tool powering CoWork</h3><p>Once the star schema is deployed and the semantic view created, Cortex Analyst (and then CoWork using it) is where a business user would actually consume it.</p><p>Cortex Analyst lets business users query governed Snowflake data, generate multi-step research reports, and take action across connected tools in natural language. You don’t write SQL. You ask questions.</p><p>In this context: a sales VP opens Cortex Analyst and asks:</p><blockquote>“What were our top three regions by net sales last quarter, and how does that compare to the same quarter last year?”</blockquote><p>Cortex Analyst queries the marts we just built via the semantic view— fct_sales_order_line, dim_customer, dim_date — and returns an answer with the numbers, the comparison, and context. Governed, traceable back to the star schema, no BI tool required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JemMlwOHNyzktlZ1YZ4kww.png" /><figcaption>Cortex Analyst querying the star schema we just built — business users, no SQL</figcaption></figure><p><strong>This is where Cortex Analyst shines:</strong> It’s where the pipeline’s output gets consumed.</p><p>I have had many times where the business users won’t know SQL, but would want to be able to “self serve” and create their custom dataset output. Cortex Analyst lets them do this, assuming the build process follows the steps of creating the models, AND creating a semantic view for those models.</p><h3>CoWork</h3><p>(shout out to Ripu from Snowflake for suggestion I use CoCo to debug this D’Oh!)</p><p>Once the star schema is deployed and the semantic view is live, CoWork is where a business can ask questions of the data in plain English.</p><p>In order to have CoWork query your data, <strong>y</strong>ou have to create an agent and explicitly connect it to a semantic view. Here’s what that looks like:</p><p><strong>Step 1 — Create the semantic view</strong></p><pre>CREATE OR REPLACE SEMANTIC VIEW PROD_ANALYTICS.MARTS_SALES.SV_SALES_PERFORMANCE<br>  TABLES ( ... )<br>  RELATIONSHIPS ( ... )<br>  FACTS ( ... )<br>  DIMENSIONS ( ... )<br>  METRICS ( ... );</pre><p>The semantic view is a native Snowflake schema object that describes your star schema in business language — what the tables mean, how they join, what the measures are. It’s the governed vocabulary the AI uses to translate natural language into correct SQL.</p><p><strong>Step 2 — Grant access</strong></p><p>Grant access to the semantic view and the agent to the CoWork module.</p><p><strong>Step 3 — Create a CoWork agent and connect the semantic view</strong></p><p>In Snowsight: <strong>AI &amp; ML → Agents → Create agent</strong>. Give it a name. Go to the <strong>Tools</strong> tab, find <strong>Cortex Analyst</strong>, click <strong>+ Add</strong>, select <strong>Semantic view</strong>, choose PROD_ANALYTICS.MARTS_SALES.SV_SALES_PERFORMANCE, select your warehouse, click <strong>Add</strong>.</p><p><strong>Step 4 — Open CoWork and select your agent</strong></p><p>AI &amp; ML → CoWork → agent picker at the top → select your new agent → ask your question:</p><blockquote>“What were our top three regions by net sales last quarter, and how does that compare to the same quarter last year?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImONuR4_5na3kOVRMXNa3g.png" /><figcaption>CoWork answering a natural language question against the star schema we just built</figcaption></figure><p>The key thing CoWork does is that it generates SQL over the semantic view using Cortex Analyst, retrieves the results, and returns a governed answer. A sales VP can ask this question with the same confidence they’d have running a vetted dashboard because it’s querying the same governed definitions.</p><h3>The Lineage View</h3><p>After everything runs, here’s where to show the data journey end-to-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuY-PFqkjMddcuHC2qMFiw.png" /><figcaption>Full lineage — from Salesforce, SAP, and HCM raw data to the fact table, in Snowsight</figcaption></figure><p><strong>CoCo Desktop is a great IDE for data engineering work.</strong> It knows your Snowflake environment before it generates anything. It doesn’t write SQL and hope it matches your tables — it reads your schemas first. The SKILL.md files are a clean way to encode institutional knowledge that the agent then executes consistently.</p><h3>What This Demonstrates About the Agentic Future</h3><p>The pipeline works. An approved intake form goes in, a tested, deployed star schema comes out, with a complete audit trail in Snowflake showing every agent’s start time, completion status, and output.</p><p>But what I find more interesting is <strong>where the humans stayed in the loop</strong>:</p><ol><li><strong>The BA still runs the discovery sessions.</strong> The wizard captures the output but doesn’t replace the conversation. The playbook has 7 layers of questions that came from a human BA knowing to ask it.</li><li><strong>The architect still reviews the design.</strong> The portal’s admin approval gate and the mandatory sign-off in data_modeller_intake.md are not theatre. The release manager blocks without them.</li></ol><p>The agents handle the mechanical translation — spec to SQL, mapping to dbt config, dbt output to test results. The humans handle the decisions that require context.</p><p>That’s the right split.</p><p><em>If you’re experimenting with CoCo Desktop or CoWork and want to compare notes, find me on LinkedIn.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31cdcd50fe91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Reusable Snowflake Infrastructure-as-Code Platform with Snowflake DCM Projects]]></title>
            <link>https://medium.com/@misrakeshav/building-a-reusable-snowflake-infrastructure-as-code-platform-with-snowflake-dcm-projects-d9ea3c5a8a16?source=rss-dbd510e68880------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ea3c5a8a16</guid>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[jinja2]]></category>
            <dc:creator><![CDATA[Keshav M.]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 02:57:05 GMT</pubDate>
            <atom:updated>2026-04-09T03:17:34.263Z</atom:updated>
            <content:encoded><![CDATA[<p>I noticed this feature pop up recently in preview and it reminded me of an article I had written almost 2 years ago now (shameless self plug: <a href="https://medium.com/@misrakeshav/using-jinja2-templates-to-create-tables-c1326b3f1c8b">Using Jinja2 templates to create tables</a>)! So I thought why not see what it can do, and hopefully easier than when I had originally written that article.</p><p>One of the things I’ve seen in Snowflake, other database, or even other tools’ is managing permissions can get really messy the more you scale.</p><p>The intention here is to have a set of files/templates that you can use to quickly establish a CICD practice of having a disciplined IaC approach from the start.</p><p>I wanted to make this a simple user friendly way of managing Snowflake infrastructure, because you never know- the person you’re working with to do a greenfield Snowflake implementation (or clean up) may not be familiar with Snowflake syntax, or the IT Security team might immediately want an audit of your Snowflake grants.</p><h4>The Architecture</h4><p>What caught my eye from the DCM documentation was supporting Jinja style templating macros, so I decided to see what it can do. I structured the project as below in my Git repo.</p><pre>project/<br>├── manifest.yml                    # Slim template — auto-generated by merge script<br>├── config/<br>│   ├── databases.yml               # Database + schema definitions<br>│   ├── business_units.yml          # BU config: roles, access, service accounts<br>│   ├── environments.yml            # Per-env overrides + account identifiers<br>│   └── connections.toml            # Snowflake CLI connection config<br>├── sources/<br>│   ├── macros/<br>│   │   └── role_macros.sql         # Naming convention macros<br>│   └── definitions/<br>│       ├── 01_databases_schemas.sql<br>│       ├── 02_warehouses.sql<br>│       ├── 03_roles.sql<br>│       ├── 04_grants.sql<br>│       ├── 05_scim_bindings.sql<br>│       ├── 06_service_accounts.sql<br>│       └── 07_governance.sql<br>├── scripts/<br>│   └── merge_config.py             # Merges config/*.yml into manifest.yml<br>├── post_deploy/<br>│   └── account_privileges.sql      # ON ACCOUNT grants (unsupported by DCM)<br>└── .github/workflows/<br>    ├── dcm_deploy.yml              # Push-to-main deploy pipeline<br>    └── dcm_pr_plan.yml             # PR plan preview</pre><h3>The Four Design Principles</h3><ol><li><strong>Decoupled access roles</strong> - Access roles are named by database + schema + access level (e.g., AR_FINANCE_DW_CORE_READ), not by BU. Multiple BUs can share the same access role. This means adding a new BU doesn&#39;t create duplicate roles.</li><li><strong>Single sandbox database</strong> - Instead of sandbox schemas scattered inside each business database, one SANDBOX_DB with per-BU schemas (SANDBOX_DB.FINANCE, SANDBOX_DB.DATA_ENGINEERING).</li><li><strong>Externalized configuration</strong> - Business Units and databases are defined in config/*.yml, not in the manifest. A Python merge script combines them before deploy. This keeps the manifest slim and lets different teams own different config files. I can have 100s of schemas and 10+ BUs, I don’t want them all in one file. This unfortunately added some complexity to the deployment (the python script needed)</li><li><strong>Automated CI/CD</strong> - Push to main triggers DEV → TST → PROD deployment. Because “just copy the statements and run it in the UI as ACCOUNTADMIN” is sadly not in fashion any more :(</li></ol><h2>The Config Files</h2><h3>config/databases.yml</h3><p>The simplest file. Define your databases and their schemas:</p><pre>databases:<br>  - name: ANALYTICS<br>    schemas:<br>      - RAW<br>      - CURATED<br>      - REPORTING<br> - name: FINANCE_DW<br>    schemas:<br>      - STAGING<br>      - CORE<br>      - MARTS<br> - name: MARKETING<br>    schemas:<br>      - INGESTION<br>      - MODELS<br>      - DASHBOARDS<br>  - name: SHARED_DATA<br>    schemas:<br>      - REFERENCE<br>      - LOOKUP</pre><p>Adding a new database? Add it here. Adding a new schema to a database? Add it here. The Jinja templates will pick it up automatically.</p><h3>config/business_units.yml</h3><p>Each BU: what warehouse size it needs, which schemas it can access (and at what level), SCIM group mappings (if you’re using AD groups to manage access and roles, but also wanting to map them to Snowflake roles), and service accounts per BU.</p><p>This is the file I imagine admins working in the most.</p><pre>business_units:<br>  - name: FINANCE<br>    wh_size: &quot;MEDIUM&quot;<br>    needs_sandbox: true<br>    schema_access:<br>      - database: FINANCE_DW<br>        schemas: [&quot;STAGING&quot;, &quot;CORE&quot;, &quot;MARTS&quot;]<br>        access: READWRITE<br>      - database: ANALYTICS<br>        schemas: [&quot;RAW&quot;, &quot;CURATED&quot;, &quot;REPORTING&quot;]<br>        access: READ<br>      - database: SHARED_DATA<br>        schemas: ALL          # ALL = every schema in that database<br>        access: READ<br>    scim_roles:<br>      - AD_GRP_FINANCE_ANALYSTS<br>      - AD_GRP_FINANCE_MANAGERS<br>    service_accounts:<br>      - name: SVC_FINANCE_ETL<br>        comment: &quot;Finance ETL pipeline service account&quot;<br>        access_role: READWRITE<br>   - name: MARKETING<br>    wh_size: &quot;SMALL&quot;<br>    needs_sandbox: false<br>    schema_access:<br>      - database: MARKETING<br>        schemas: [&quot;INGESTION&quot;, &quot;MODELS&quot;, &quot;DASHBOARDS&quot;]<br>        access: READWRITE<br>      - database: ANALYTICS<br>        schemas: [&quot;CURATED&quot;, &quot;REPORTING&quot;]<br>        access: READ<br>      - database: SHARED_DATA<br>        schemas: ALL<br>        access: READ<br>    scim_roles:<br>      - AD_GRP_MARKETING_TEAM<br>    service_accounts:<br>      - name: SVC_MARKETING_LOADER<br>        comment: &quot;Marketing data loader&quot;<br>        access_role: READWRITE<br><br>  - name: DATA_ENGINEERING<br>    wh_size: &quot;LARGE&quot;<br>    needs_sandbox: true<br>    schema_access:<br>      - database: ANALYTICS<br>        schemas: ALL<br>        access: READWRITE<br>      - database: FINANCE_DW<br>        schemas: ALL<br>        access: READWRITE<br>      - database: MARKETING<br>        schemas: ALL<br>        access: READWRITE<br>      - database: SHARED_DATA<br>        schemas: ALL<br>        access: READWRITE<br>    scim_roles:<br>      - AD_GRP_DATA_ENGINEERS<br>    service_accounts:<br>      - name: SVC_AIRFLOW<br>        comment: &quot;Airflow orchestration service account&quot;<br>        access_role: READWRITE</pre><p>The schemas: ALL shorthand means &quot;every schema defined for that database in databases.yml.&quot; The merge script resolves this to individual entries. Saves you from writing out every single schema in a database.</p><h3>config/environments.yml</h3><p>Per-environment overrides. The {{ env.SNOWFLAKE_ACCOUNT_XXX }} pattern — these get resolved from environment variables defined in my Git repo, no plain text in a file that any user can see.</p><pre>environments:<br>  DEV:<br>    account_identifier: &quot;{{ env.SNOWFLAKE_ACCOUNT_DEV }}&quot;<br>    env_suffix: _DEV<br>    wh_default_size: &quot;XSMALL&quot;<br>    default_retention_days: 7<br>    sandbox_retention_days: 1<br>    wh_auto_suspend: 300<br>    scim_enabled: false<br>  TST:<br>    account_identifier: &quot;{{ env.SNOWFLAKE_ACCOUNT_TST }}&quot;<br>    env_suffix: _TST<br>    wh_default_size: &quot;XSMALL&quot;<br>    default_retention_days: 7<br>    sandbox_retention_days: 1<br>    wh_auto_suspend: 300<br>    scim_enabled: false<br>  PROD:<br>    account_identifier: &quot;{{ env.SNOWFLAKE_ACCOUNT_PRD }}&quot;<br>    env_suffix: _PROD<br>    wh_default_size: &quot;SMALL&quot;<br>    default_retention_days: 90<br>    sandbox_retention_days: 1<br>    wh_auto_suspend: 300<br>    scim_enabled: true</pre><h2>The Merge Script</h2><p>scripts/merge_config.py Unfortunately, I did still need to have a python file :( Maybe this goes away in later iterations of DCM Projects. I needed it so that it does the below tasks. The key one for me was keeping all the configurations in the config/ folder, as there can be 100s of lines of roles and schemas, so I wanted to separate them into their own files to manage.</p><p>I envision the admins mainly working in the BU yaml file to add /remove schema accesses from roles. No need to mess anything else up!</p><ol><li><strong>Auto-discovers</strong> every .yml file in config/ and merges all top-level keys</li><li><strong>Resolves </strong><strong>{{ env.VAR_NAME }}</strong> patterns from Git environment variables</li><li><strong>Flattens </strong><strong>schema_access</strong> — turns {database, schemas: [list], access} into individual {database, schema, access} entries (critical for staying within DCM&#39;s nesting limit)</li></ol><p>The key insight: adding a new config file (say config/integrations.yml) requires <strong>zero changes</strong> to this script. Just add the file and reference the new keys in your Jinja templates.</p><p>This file is also ~150 or so lines, so I won’t post it here, message if you want to see it, but it essentially performs the above 3 functions.</p><h2>The Jinja Templates</h2><h3>sources/macros/role_macros.sql — Naming Conventions</h3><p>Every object name is generated by a macro, ensuring consistency:</p><pre>{% macro access_role_name(database, schema, access) -%}<br>AR_{{ database | upper }}_{{ schema | upper }}_{{ access | upper }}{{ env_suffix }}<br>{%- endmacro %}{% macro functional_role_name(bu_name) -%}<br>FR_{{ bu_name | upper }}{{ env_suffix }}<br>{%- endmacro %}<br>{% macro db_name_env(db_name) -%}<br>{{ db_name | upper }}{{ env_suffix }}<br>{%- endmacro %}</pre><p>access_role_name takes database, schema, access level , this is what gets assigned to the BU roles.</p><p>AR for access role associated with a database_schema and FR for functional roles- your BU roles. Remember, the BU roles are defined in the config/business_units.yml file. And if your scripts and PRs merge, you will see all the databases/roles created like below!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*_352eRDiLvZRlfETuBdeBw.jpeg" /></figure><h3>01_databases_schemas.sql — Databases, Schemas, Sandbox</h3><p>Creates all business databases plus the single sandbox database:</p><pre>{% for db in databases %}<br>DEFINE DATABASE {{ db_name_env(db.name) }}<br>    DATA_RETENTION_TIME_IN_DAYS = {{ default_retention_days }};<br>{% for schema in db.schemas %}<br>DEFINE SCHEMA {{ db_name_env(db.name) }}.{{ schema }};<br>{% endfor %}<br>{% endfor %}<br>DEFINE DATABASE {{ sandbox_db_name() }}<br>    DATA_RETENTION_TIME_IN_DAYS = {{ sandbox_retention_days | default(1) }};<br>{% for bu in business_units %}<br>{% if bu.needs_sandbox | default(false) %}<br>DEFINE SCHEMA {{ sandbox_db_name() }}.{{ bu.name | upper }}<br>    DATA_RETENTION_TIME_IN_DAYS = {{ sandbox_retention_days | default(1) }};<br>{% endif %}<br>{% endfor %}</pre><h3>03_roles.sql — The Role Hierarchy</h3><p>This one took a while to wrangle my brain around. Thankfully there was CoCo!</p><ol><li><strong>Access roles</strong> — deduplicated across BUs using a tracking list</li><li><strong>Sandbox access roles</strong> — one per BU that needs sandbox</li><li><strong>Functional roles</strong> — one per BU, granted the appropriate access roles</li></ol><p>The deduplication pattern uses a Jinja list to track what’s already been defined:</p><pre>{% set _defined_ar = [] %}<br>{% for bu in business_units %}<br>{% for sa in bu.schema_access %}<br>{% set ar_read = access_role_name(sa.database, sa.schema, &#39;READ&#39;) %}<br>{% if ar_read not in _defined_ar %}<br>DEFINE ROLE {{ ar_read }}<br>    COMMENT = &#39;READ on {{ db_name_env(sa.database) }}.{{ sa.schema }}&#39;;<br>{% if _defined_ar.append(ar_read) %}{% endif %}<br>{% endif %}<br>{% endfor %}<br>{% endfor %}</pre><h3>04_grants.sql — Schema-Level Grants</h3><p>Uses the same deduplication pattern, but for grants. A macro handles the repetitive grant structure:</p><p>This was key, as an Admin, I wouldn’t have to write out every single grant statement myself… although that’s a personal preference. Easier if you did, so you wouldn’t have to create macros for every type of grant.</p><pre>{% macro _grant_schema_access(database, schema, access, role) %}<br>GRANT USAGE ON DATABASE {{ db_name_env(database) }} TO ROLE {{ role }};<br>GRANT USAGE ON SCHEMA {{ db_name_env(database) }}.{{ schema }} TO ROLE {{ role }};<br>GRANT SELECT ON ALL TABLES IN SCHEMA {{ db_name_env(database) }}.{{ schema }} TO ROLE {{ role }};<br>GRANT SELECT ON ALL VIEWS IN SCHEMA {{ db_name_env(database) }}.{{ schema }} TO ROLE {{ role }};<br>{% if access == &#39;READWRITE&#39; %}<br>GRANT INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ... TO ROLE {{ role }};<br>GRANT CREATE TABLE ON SCHEMA ... TO ROLE {{ role }};<br>GRANT CREATE VIEW ON SCHEMA ... TO ROLE {{ role }};<br>{% endif %}<br>{% endmacro %}</pre><h3>05_scim_bindings.sql — Conditional AD Integration</h3><p>This code was if there was a Business Unit role getting created via SCIM integration, and you wanted to map that role to a Snowflake Functional Role. Define the relationship in the BU yaml and this will take care of the grants</p><pre>{% if scim_enabled | default(false) %}<br>{% for bu in business_units %}<br>{% for scim_group in bu.scim_roles %}<br>GRANT ROLE {{ functional_role_name(bu.name) }} TO ROLE {{ scim_group }};<br>{% endfor %}<br>{% endfor %}<br>{% endif %}</pre><h3>07_governance.sql — Governance BU</h3><p>Uses the is_governance flag to grant cross-database SELECT to the governance team:</p><pre>{% for bu in business_units %}<br>{% if bu.is_governance | default(false) %}<br>{% for db in databases %}<br>GRANT USAGE ON DATABASE {{ db_name_env(db.name) }} TO ROLE {{ functional_role_name(bu.name) }};<br>...<br>{% endfor %}<br>{% endif %}<br>{% endfor %}</pre><h2>The CI/CD Pipeline</h2><h3>.github/workflows/dcm_deploy.yml</h3><p>The deploy workflow:</p><ol><li><strong>merge-and-deploy-dev</strong> — Runs the merge script (with account secrets as env vars), uploads the generated manifest as an artifact, deploys to DEV</li><li><strong>deploy-tst</strong> — Downloads the manifest artifact, deploys to TST</li><li><strong>deploy-prod</strong> — Downloads the manifest artifact, deploys to PROD (with GitHub Environment protection rules for approval gates)</li></ol><p>Each environment uses GitHub Environments (DCM_DEV, DCM_TST, DCM_PROD) for secrets isolation and approval gates.</p><p>Below is a sample of the GitHub actions file,</p><pre>name: DCM Deploy<br><br>on:<br>  push:<br>    branches: [main]<br>    paths:<br>      - &#39;manifest.yml&#39;<br>      - &#39;config/**&#39;<br>      - &#39;sources/**&#39;<br><br>permissions:<br>  contents: read<br><br>jobs:<br>  merge-and-deploy-dev:<br>    runs-on: ubuntu-latest<br>    environment: DCM_DEV<br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - uses: actions/setup-python@v5<br>        with:<br>          python-version: &#39;3.11&#39;<br><br>      - run: pip install pyyaml<br><br>      - run: python scripts/merge_config.py<br>        env:<br>          SNOWFLAKE_ACCOUNT_DEV: ${{ secrets.SNOWFLAKE_ACCOUNT_DEV }}<br>          SNOWFLAKE_ACCOUNT_TST: ${{ secrets.SNOWFLAKE_ACCOUNT_TST }}<br>          SNOWFLAKE_ACCOUNT_PRD: ${{ secrets.SNOWFLAKE_ACCOUNT_PRD }}<br><br>      - uses: actions/upload-artifact@v4<br>        with:<br>          name: manifest<br>          path: manifest.yml<br>          retention-days: 1<br><br>      - uses: snowflakedb/snowflake-cli-action@v2.0<br>        with:<br>          default-config-file-path: config/connections.toml<br><br>      - name: Deploy DEV<br>        env:<br>          SNOWFLAKE_CONNECTIONS_DEFAULT_PRIVATE_KEY_RAW: ${{ secrets.SNOWFLAKE_PRIVATE_KEY }}<br>        run: snow dcm deploy --target DEV --alias &quot;${{ github.sha }}&quot;</pre><h2>The Bootstrap Script</h2><p>Before any of this works, you need a one-time setup on the Snowflake account. DCM_Set_up.sql (run as ACCOUNTADMIN) creates:</p><ol><li>The deployer role (CICD_DCM_ROLE) with CREATE DATABASE, CREATE WAREHOUSE, CREATE ROLE, and MANAGE GRANTS</li><li>A service account (CICD_SVC) with key-pair auth</li><li>The admin database and schema (ADMIN_DB.DCM_STATE)</li><li>Three DCM project objects (PLATFORM_DEV, PLATFORM_TST, PLATFORM_PROD)</li><li>Ownership transfers to CICD_DCM_ROLE</li></ol><p>Script-</p><pre>----------------------------------------------------------------------<br>-- DCM BOOTSTRAP SCRIPT<br>-- Run top-to-bottom as ACCOUNTADMIN in Snowsight<br>-- User: CICD_SVC | Role: CICD_DCM_ROLE<br>----------------------------------------------------------------------<br><br>USE ROLE ACCOUNTADMIN;<br><br>----------------------------------------------------------------------<br>-- 1. CREATE THE DEPLOYER ROLE<br>----------------------------------------------------------------------<br>CREATE ROLE IF NOT EXISTS CICD_DCM_ROLE<br>    COMMENT = &#39;Dedicated role for DCM project management and deployment&#39;;<br><br>GRANT ROLE CICD_DCM_ROLE TO ROLE SYSADMIN;<br><br>GRANT CREATE DATABASE ON ACCOUNT TO ROLE CICD_DCM_ROLE;<br>GRANT CREATE WAREHOUSE ON ACCOUNT TO ROLE CICD_DCM_ROLE;<br>GRANT CREATE ROLE ON ACCOUNT TO ROLE CICD_DCM_ROLE;<br>GRANT MANAGE GRANTS ON ACCOUNT TO ROLE CICD_DCM_ROLE;<br>GRANT MONITOR ON ACCOUNT TO ROLE CICD_DCM_ROLE;<br>GRANT APPLY TAG ON ACCOUNT TO ROLE CICD_DCM_ROLE;<br><br>----------------------------------------------------------------------<br>-- 2. CREATE SERVICE ACCOUNT<br>----------------------------------------------------------------------<br>USE ROLE SECURITYADMIN;<br><br>CREATE USER IF NOT EXISTS CICD_SVC<br>  TYPE = SERVICE<br>  DEFAULT_ROLE = CICD_DCM_ROLE<br>  COMMENT = &#39;GitHub Actions deployer - key-pair auth only&#39;;<br><br>GRANT ROLE CICD_DCM_ROLE TO USER CICD_SVC;<br><br>----------------------------------------------------------------------<br>-- 3. SET RSA PUBLIC KEY FOR KEY-PAIR AUTH<br>----------------------------------------------------------------------<br>USE ROLE ACCOUNTADMIN;<br><br>ALTER USER CICD_SVC SET RSA_PUBLIC_KEY=&#39;<br>-----BEGIN PUBLIC KEY-----<br>Just adding this here because sometimes I forget that one needs to<br>include the BEGIN and END KEY lines as well. Definitely have not spent<br>a lot of time trying/crying to debug why it can not log in nope nope nope <br>not me! so including this....<br>-----END PUBLIC KEY-----&#39;;<br><br>----------------------------------------------------------------------<br>-- 4. CREATE ADMIN DATABASE, SCHEMA, AND WAREHOUSE<br>----------------------------------------------------------------------<br>USE ROLE ACCOUNTADMIN;<br><br>CREATE DATABASE IF NOT EXISTS ADMIN_DB;<br>CREATE SCHEMA IF NOT EXISTS ADMIN_DB.DCM_STATE;<br><br>GRANT OWNERSHIP ON DATABASE ADMIN_DB TO ROLE CICD_DCM_ROLE COPY CURRENT GRANTS;<br>GRANT OWNERSHIP ON SCHEMA ADMIN_DB.DCM_STATE TO ROLE CICD_DCM_ROLE COPY CURRENT GRANTS;<br><br>CREATE WAREHOUSE IF NOT EXISTS ADMIN_WH<br>  WAREHOUSE_SIZE      = XSMALL<br>  AUTO_SUSPEND        = 60<br>  AUTO_RESUME         = TRUE<br>  INITIALLY_SUSPENDED = TRUE<br>  COMMENT             = &#39;Admin warehouse for DCM deployments and CI/CD&#39;;<br><br>GRANT USAGE ON WAREHOUSE ADMIN_WH TO ROLE CICD_DCM_ROLE;<br><br>----------------------------------------------------------------------<br>-- 5. GRANT STAGE CREATION (REQUIRED BY SNOW CLI FOR DCM DEPLOY)<br>----------------------------------------------------------------------<br>GRANT CREATE STAGE ON SCHEMA ADMIN_DB.DCM_STATE TO ROLE CICD_DCM_ROLE;<br><br>----------------------------------------------------------------------<br>-- 6. SET DEFAULTS ON SERVICE ACCOUNT<br>----------------------------------------------------------------------<br>ALTER USER CICD_SVC SET<br>  DEFAULT_WAREHOUSE = &#39;ADMIN_WH&#39;<br>  DEFAULT_NAMESPACE = &#39;ADMIN_DB.DCM_STATE&#39;;<br><br>----------------------------------------------------------------------<br>-- 7. CREATE DCM PROJECT OBJECTS (AS THE OWNER ROLE)<br>----------------------------------------------------------------------<br>USE ROLE CICD_DCM_ROLE;<br><br>CREATE DCM PROJECT IF NOT EXISTS ADMIN_DB.DCM_STATE.PLATFORM_DEV;<br>CREATE DCM PROJECT IF NOT EXISTS ADMIN_DB.DCM_STATE.PLATFORM_TST;<br>CREATE DCM PROJECT IF NOT EXISTS ADMIN_DB.DCM_STATE.PLATFORM_PROD;<br><br>----------------------------------------------------------------------<br>-- 8. VERIFY<br>----------------------------------------------------------------------<br>SHOW DCM PROJECTS IN SCHEMA ADMIN_DB.DCM_STATE;<br>DESC USER CICD_SVC;</pre><h2>Lessons Learned (The Hard Way)</h2><h3>1. DCM Has a 5-Level Nesting Limit for Template Variables</h3><p>This was the biggest surprise. DCM’s templating.defaults section enforces a maximum of 5 levels of YAML nesting. My original config had:</p><pre>business_units → [item] → schema_access → [item] → schemas → [list items]<br>   Level 1        L2          L3            L4        L5         L6</pre><p><strong>The fix:</strong> The merge script flattens schema_access from:</p><pre>schema_access:<br>  - database: FINANCE_DW<br>    schemas: [&quot;STAGING&quot;, &quot;CORE&quot;, &quot;MARTS&quot;]<br>    access: READWRITE</pre><p>to:</p><pre>schema_access:<br>  - database: FINANCE_DW<br>    schema: STAGING        # singular, not a list<br>    access: READWRITE<br>  - database: FINANCE_DW<br>    schema: CORE<br>    access: READWRITE</pre><p>This keeps the nesting at exactly 5 levels. The Jinja templates use sa.schema (singular) instead of iterating sa.schemas.</p><h3>2. DCM Cannot Define Its Own Parent Database/Schema</h3><p>If your project is ADMIN_DB.DCM_STATE.PLATFORM_DEV, you cannot DEFINE DATABASE ADMIN_DB or DEFINE SCHEMA ADMIN_DB.DCM_STATE in your definitions. These must exist before the project runs.</p><h3>3. Storage Integrations and Other Unsupported Objects</h3><p>DCM cannot DEFINE storage integrations, streams, alerts, or external stages. These go in pre_deploy.sql or post_deploy.sql companion scripts. However, GRANT USAGE ON INTEGRATION <strong>is</strong> supported in definition files, so you can manage access to integrations via DCM even if you can&#39;t create them.</p><h3>4. project_owner Is Required in Manifest v2</h3><p>If you’re using Snowsight Workspaces, DCM will refuse to run operations without project_owner set in each target. Add it to your manifest.</p><h3>5. Ownership Matters — A Lot</h3><p>DCM can only manage objects owned by its deployer role. If warehouses, databases, or the DCM project objects themselves are owned by ACCOUNTADMIN (common when bootstrapping), you&#39;ll get &quot;Insufficient privileges&quot; errors. Transfer ownership before deploying:</p><pre>GRANT OWNERSHIP ON WAREHOUSE WH_SHARED_DEV<br>    TO ROLE CICD_DCM_ROLE COPY CURRENT GRANTS;</pre><h2>What’s Next</h2><p>This template handles the core infrastructure: databases, schemas, warehouses, roles, grants, service accounts, SCIM bindings, and governance. The next steps would be:</p><ul><li><strong>Storage integrations</strong> - Add config/integrations.yml with integration definitions and BU grants</li><li><strong>Tag governance</strong> - Add config/tags.yml for classification tags (requires APPLY TAG grant, done in post-deploy)</li><li><strong>Dynamic tables and tasks</strong> - Extend the definitions for pipeline objects</li><li><strong>Multi-region</strong> - Use separate account_identifier values per target to deploy across regions</li></ul><p>Credits:</p><ol><li><a href="https://docs.snowflake.com/en/user-guide/dcm-projects/dcm-projects-overview">Snowflake DCM Projects</a></li><li><a href="https://www.snowflake.com/en/developers/guides/get-started-snowflake-dcm-projects/">Get Started with Snowflake DCM Projects</a></li><li>Surprisingly (and at times frustratingly: Snowflake Cortex Code). It did do a better job than Claude itself in writing the jinja code.</li><li>Prajwal NS’s blog is quite good too on this! — <a href="https://prajwal-ns.github.io/prajwal.xyz/posts/Building-a-Production-Ready-CICD-Pipeline-for-Snowflake-Using-DCM-Projects--and--GitHub-Actions">Building a Production-Ready CI/CD Pipeline for Snowflake Using DCM Projects &amp; GitHub Actions</a> . Definitely helped debug some things. I like his approach on this as well.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ea3c5a8a16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Microsoft Teams Bot to Query Snowflake with an LLM Backend]]></title>
            <link>https://medium.com/@misrakeshav/creating-a-microsoft-teams-bot-to-query-snowflake-with-an-llm-backend-436d798919cc?source=rss-dbd510e68880------2</link>
            <guid isPermaLink="false">https://medium.com/p/436d798919cc</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Keshav M.]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 01:53:30 GMT</pubDate>
            <atom:updated>2025-07-27T01:53:30.346Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Premise</h3><p>I sometimes get asked questions like:</p><p><em>“Does this user have a Snowflake account?” or “Does my business unit exist in Snowflake?” or “I need access similar to &lt;colleague&gt; in Snowflake, can you tell me what role they have in Snowflake?” or “For which AD group should I raise a Snowflake access request ticket?”</em></p><p>These are common questions from users who don’t have direct access to Snowflake and have to rely on the admins for answers. So I thought why not build a Teams bot that can handle these queries interactively? This would make users self sufficient, and not reliant on the availability of Admins (hopefully), or at least have the bot interpret detailed multi-scenario documents to find information relevant to them (e.g. “how to get access” guides).</p><p>Also, the inspiration behind this was this quickstart (much better than the code blocks in this article) <a href="https://quickstarts.snowflake.com/guide/integrate_snowflake_cortex_agents_with_microsoft_teams/index.html#0">https://quickstarts.snowflake.com/guide/integrate_snowflake_cortex_agents_with_microsoft_teams/index.html#0</a></p><h3>Architecture</h3><p>The project uses Python with FastAPI and the Microsoft Bot Framework SDK to build the backend bot service, which connects with Microsoft Teams. I ran this all via the Microsoft Bot Framework Emulator for local testing, but can be extended to an actual Azure Tenant to work in Teams… I am sure (not an expert in Azure). The core logic involves:</p><p>Calling Snowflake via Python (using Snowflake Connector) to check user or role exists.</p><p>Querying an OpenAI LLM to answer more general or complex questions beyond the Snowflake user/role lookups.</p><p>A hypothetical wiki maintained by the Governance team (outside of Snowflake) serves as an additional knowledge source where they can keep their Onboarding instructions to handle the different scenarios itself.</p><p>My philosophy — BI (and extending to data engineering I suppose) should always be a reflection of normal business processes, not require businesses to change/add more steps to their processes. The bot should be able to retrieve information from current process documents (wiki/SharePoint).</p><h3>Setup</h3><p>Here’s a brief overview of the files created and their purposes. I won’t make this a how-to article on how to set everything up, as that would be going through a lot of steps outlined in Microsoft and OpenAI documentation. Treat this as a demo of a thought exercise.</p><p>In my project folder (e.g. snowflake-bot) I had the below files and a subfolder called services, where I kept all the modular code files related to Snowflake logic, and LLM logic, or the wiki documentation logic -</p><ul><li>services/snowflake.py: Contains Snowflake connection details and functions that execute queries to check for users or roles</li></ul><pre>.. set up parts<br><br>def user_exists_partial(username_partial: str):<br>    try:<br>        conn = get_connection()<br>        cursor = conn.cursor()<br>        pattern = f&quot;%{username_partial.upper()}%&quot;<br>        cursor.execute(f&quot;SHOW USERS LIKE &#39;{pattern}&#39;&quot;)<br>        results = cursor.fetchall()<br>        cursor.close()<br>        conn.close()<br><br>        # Username is first column in results from SHOW USERS<br>        return [str(row[0]) for row in results]<br><br>    except Exception as e:<br>        print(f&quot;Error checking users: {e}&quot;)<br>        return []</pre><ul><li>services/llm.py: Wraps OpenAI API calls with prompt construction and queries the data</li></ul><pre>...setup parts, and then main llm def-<br><br>def ask_llm(question: str) -&gt; str:<br>    # Fetch wiki context using the actual question<br>    wiki_context = get_onboarding_scenario(question) or &quot;No relevant documentation found.&quot;<br><br>    # Prompt sent to the LLM<br>    prompt = f&quot;&quot;&quot;<br>You are a helpful assistant that answers internal Snowflake questions.<br><br>You have access to the following onboarding and governance documentation:<br><br>{wiki_context}<br><br>When the user&#39;s question is related to how to get access or Snowflake governance, answer it using the above documentation. <br>Otherwise, answer using your general Snowflake knowledge or pass the question back to the admin tools.<br><br>User&#39;s question: {question}<br>&quot;&quot;&quot;<br><br>    try:<br>        response = openai.ChatCompletion.create(<br>            model=&quot;gpt-4o&quot;,<br>            messages=[<br>                {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: prompt}<br>            ],<br>            temperature=0.2,<br>        )<br>        return response.choices[0].message.content.strip()<br>    except Exception as e:<br>        return f&quot;Error during LLM call: {str(e)}&quot;</pre><ul><li>app.py: Implements the Microsoft Bot Framework adapter using aiohttp, bridging Teams to the main logic</li></ul><pre># app.py<br>...bunch of set up stuff<br><br>async def on_message_activity(turn_context: TurnContext):<br>    if turn_context.activity.type == ActivityTypes.message:<br>        text = turn_context.activity.text.lower()<br><br>        # --- User existence check ---<br>        user_match = re.search(r&quot;(?:the\s+)?user\s+(\w+)&quot;, text)<br>        if user_match and &quot;exist&quot; in text:<br>            username = user_match.group(1)<br>            print(f&quot;[DEBUG] Checking for users like &#39;{username}&#39;...&quot;)<br>            matches = user_exists_partial(username)<br>            if matches:<br>                reply = f&quot;Found matching user(s) in Snowflake: {&#39;, &#39;.join(matches)}&quot;<br>            else:<br>                reply = f&quot;No users found in Snowflake matching &#39;{username}&#39;&quot;<br>            await turn_context.send_activity(reply)<br>            return<br><br>        # --- Onboarding scenario check ---<br>        if &quot;access&quot; in text and &quot;snowflake&quot; in text or &quot;onboarding&quot; in text:<br>            print(f&quot;[DEBUG] Onboarding condition matched for: &#39;{text}&#39;&quot;)<br>            result = get_onboarding_scenario(text)<br>            print(f&quot;[DEBUG] Wiki result: {result[:100] if result else &#39;None&#39;}&quot;)  # preview<br>            if result:<br>                await turn_context.send_activity(result)<br>                return<br>            else:<br>                reply = (<br>                    &quot;I couldn’t find a matching onboarding scenario.\n&quot;<br>                    &quot;Can you tell me more?\n&quot;<br>                    &quot;- Are you a new user?\n&quot;<br>                    &quot;- Are you requesting PII access?\n&quot;<br>                    &quot;- Is this for a service account or team role?&quot;<br>                )<br>                await turn_context.send_activity(reply)<br>                return<br><br>        # --- Fallback to LLM ---<br>        reply = ask_llm(turn_context.activity.text)<br>        await turn_context.send_activity(reply)<br><br>.. bunch of instantiate stuff like start app, main...<br></pre><ul><li>services/wiki.py: file that gives the LLM bot instructions on where to get the wiki for onboarding. I wanted this to fetch from an actual wiki page, but freemium only went so far…</li></ul><pre>import os<br>import re<br>from difflib import SequenceMatcher<br><br>WIKI_FOLDER = os.path.join(os.getcwd(), &quot;snowflake-onboarding-docs.wiki&quot;)<br><br># Keywords to override fuzzy match if directly mentioned<br>PRIORITY_KEYWORDS = {<br>    &quot;pii&quot;: &quot;pii&quot;,<br>    &quot;service&quot;: &quot;service account&quot;,<br>    &quot;new user&quot;: &quot;new user&quot;,<br>}<br><br>def get_onboarding_scenario(question: str):<br>    print(f&quot;[DEBUG] Searching wiki for onboarding match to: &#39;{question}&#39;&quot;)<br><br>    if not os.path.isdir(WIKI_FOLDER):<br>        print(&quot;[DEBUG] Wiki folder not found:&quot;, WIKI_FOLDER)<br>        return &quot;Onboarding wiki not found :(&quot;<br><br>    candidates = []<br><br>    for filename in os.listdir(WIKI_FOLDER):<br>        if filename.endswith(&quot;.md&quot;):<br>            print(f&quot;[DEBUG] Scanning file: {filename}&quot;)<br>            filepath = os.path.join(WIKI_FOLDER, filename)<br>            with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>                content = f.read()<br><br>            sections = re.split(r&quot;(?m)^##\s+&quot;, content)<br>            for section in sections:<br>                lines = section.strip().splitlines()<br>                if not lines:<br>                    continue<br>                title = lines[0].strip().lower()<br>                full_content = &quot;\n&quot;.join(lines)<br>                if &quot;scenario&quot; in title or &quot;access&quot; in title:<br>                    candidates.append((title, full_content))<br><br>    if not candidates:<br>        print(&quot;[DEBUG] No candidate sections found.&quot;)<br>        return None<br><br>    # Check for exact keyword hits first<br>    for keyword, label in PRIORITY_KEYWORDS.items():<br>        if keyword in question.lower():<br>            for title, content in candidates:<br>                if keyword in title:<br>                    print(f&quot;[DEBUG] Keyword match: &#39;{keyword}&#39; in &#39;{title}&#39;&quot;)<br>                    return content<br><br>    # Fallback to best fuzzy score<br>    best_title, best_content, best_score = None, None, 0<br>    for title, content in candidates:<br>        score = SequenceMatcher(None, question.lower(), title).ratio()<br>        print(f&quot;[DEBUG] Score with &#39;{title}&#39;: {score:.2f}&quot;)<br>        if score &gt; best_score:<br>            best_title = title<br>            best_content = content<br>            best_score = score<br><br>    if best_score &gt;= 0.3:<br>        print(f&quot;[DEBUG] Best fuzzy match: {best_title} with score {best_score:.2f}&quot;)<br>        return best_content<br><br>    print(&quot;[DEBUG] No match above confidence threshold.&quot;)<br>    return None</pre><p>The wiki was just a basic document that looked like this:</p><pre>Welcome to the snowflake-onboarding-docs wiki!<br># Snowflake Access Onboarding Guide<br><br>This document outlines different onboarding scenarios for Snowflake access requests.<br><br>---<br><br>## Scenario 1: New User Needs Access (No Prior User Exists)<br><br>### Steps<br>1. Raise a ticket using the **Snowflake New User Access** template.<br>2. Provide:<br>   - Business justification<br>   - Manager approval<br>   - Desired Snowflake role (e.g., `ANALYST_READ_ONLY`)<br>3. The user will be added to Active Directory and assigned the requested role.<br><br>---<br><br>## Scenario 2: Add Existing User to New Role<br><br>### Steps<br>1. Identify the role you want to grant.<br>2. Raise a ticket with:<br>   - User&#39;s AD ID<br>   - Target role<br>   - Approval from data steward or team lead<br><br>---<br><br>## Scenario 3: Add New User to Existing Group<br><br>### Steps<br>1. Confirm the group exists using `SHOW GRANTS TO USER` in Snowflake.<br>2. Raise a ticket to add the user to that AD group.<br><br>---<br><br>## Scenario 4: Service Account Access<br><br>### Steps<br>1. Provide use case and owner details.<br>2. Request creation of a service account in AD.<br>3. Link the service account to Snowflake role(s).<br><br>---<br><br>## Scenario 5: PII Access Request<br><br>### Steps<br>1. Fill out a Data Privacy Questionnaire.<br>2. Get approval from Legal and Data Governance.<br>3. Raise a ticket referencing approved scope.</pre><p>Setup steps included:</p><ol><li>Registering the OpenAI API key securely</li><li>Writing and testing Snowflake query functions locally</li><li>Building prompt functions and iterating to improve LLM answers</li><li>Creating a minimal Bot Framework app (app.py) that connects the backend to Microsoft Teams emulator</li><li>Running everything locally in a Python virtual environment and testing via Bot Framework Emulator</li></ol><p>By modularizing the logic, it was easier to iterate on Snowflake queries and LLM prompts separately, and then combine them in the bot flow.</p><h3>How things looked running locally</h3><ol><li>Asking the bot about users existing in my Snowflake account</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*LmDwX49lW6C8bet-TYL8EA.jpeg" /></figure><p>2. Asking the bot onboarding steps, it references my wiki above (locally)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*KV-tCdw7RHidySP_nzcpiQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*b3XBLezvcADpF4i-tQXz6w.jpeg" /></figure><p>It does try to add more details to each step, which is interesting.</p><p>3. You do have to be precise (pros and cons) because it does try to pick up keywords and then call the appropriate function. That’s got to do with the logic in the main app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Qrl__NAMCzjcz4tVsO8ygg.jpeg" /><figcaption>i saved this image as bad bot</figcaption></figure><h3>Importance of Prompt Specification</h3><p>At first, the LLM replies included unrelated information, like looking up “KMISRA” on the internet if it didn’t find anything. I got some random Kingdom Ministry of Investments (of Saudi Arabia I think?) definition…</p><p>Once I refined the prompt to focus specifically on the Snowflake environment and not on the internet, the bot stopped returning irrelevant results and gave answers based on my environment. This highlights how critical prompt design is when working with LLMs. The better the prompt aligns with your knowledge domain and expected output style, the more useful and accurate the answers become.</p><h3>Reflections….</h3><p>This thought exercise taught me the importance of the context settings and the fuzzy scoring tweaking, otherwise things break. I may (if I feel like it) see if I can get it to rely entirely on the LLM to context switch, I didn’t like how I had to write a function for finding “user exists”. I’d want the bot to determine if it needs to go to a document, or query my Snowflake account. Vibe coding tells me here this is an excellent use case for RAG and intent routing, so definitely use this as a “baby” RAG model that’s not very smart; this baby be as smart as adult me!</p><p>… and also how this was more effort than just simply answering the user’s question in Teams initially by manually querying the Snowflake account myself &gt;.&lt;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=436d798919cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Key Vault Key Rotation — Snowflake Passwords]]></title>
            <link>https://medium.com/@misrakeshav/azure-key-vault-key-rotation-snowflake-passwords-7f042f72b5d6?source=rss-dbd510e68880------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f042f72b5d6</guid>
            <category><![CDATA[password-rotation]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-functions]]></category>
            <dc:creator><![CDATA[Keshav M.]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 04:06:39 GMT</pubDate>
            <atom:updated>2024-10-01T04:06:39.217Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Key Vault Key Rotation — Snowflake Passwords</h3><p>So a few months ago, there was some noise in the Snowflake sphere of things about account security and the enforcing MFAs on (human) user accounts. One of the concepts that I was thinking around the time was — what about service accounts that are used for programmatic access to your Snowflake instance by your code? And what about password rotations?</p><p>In an enterprise, you normally store service account usernames and passwords in the key vault or a secrets manager in that case of Azure or AWS respectively. You then use these service accounts to move data in and out of Snowflake, or just retrieve it for building dashboards/reports. You don’t want to expose the password to the developers of the app, but rather have them reference the key vault value instead.</p><p>Ok… so far so good, we can simply create a key and reference it in your code by calling the key vault key, and set the same password by logging into Snowflake and setting the password there as a Security Admin or Account Admin.</p><p>BUT what if we want to put a rotation policy on this? We can do that easily in Azure’s Key Vault; once it rotates, someone’s going to have to know that the key’s been rotated (set reminder or wait for code to fail in production… something that NEVER happens) and then manually log into Snowflake and update it.</p><p>I like to code using the philosophy of “If I got hit by a bus on one of my late night walks, things should still work”.</p><p>So here’s what I FINALLY managed to accomplish.</p><ul><li>Store a key in Azure Key Vault, the name of the key is my service user in Snowflake</li><li>Put a rotation policy on the key</li><li>Create an Azure function that triggers when this Key is rotated (in my case when the http function is called) and log into Snowflake, using an elevated account, and alter my service user’s password.</li></ul><p>Because I’m not an Azure developer… and mostly because this took wayyyyy too many months to get working (side rant: Microsoft… why is your python Azure function so extremely difficult to work with to the point I gave up?), I won’t expand on this to be a Key vault trigger function, but rather an Http Azure function. From my understanding, it should be possible to extend this to be triggered by the Key Vault using Event Hub… and possibly retrieve the Key name that triggered the event being the Snowflake service account username.</p><p>I chose to write this all in C# because this was the only language I could get this working in, and I learned C++ in university, so why not? Also because — I couldn’t get the python version of this working at all. The internet is littered with the same error I received and no resolution.</p><p>Also I’d like to acknowledge GPS on YouTube for the major key for me — how to connect Azure KeyVault using Azure functions. This video specifically - <a href="https://www.youtube.com/watch?v=p0zgKoxpu24">https://www.youtube.com/watch?v=p0zgKoxpu24</a></p><h3><strong>Set up</strong></h3><p>Azure Set Up</p><ol><li>In Azure I created a Key Vault for my subscription, and created a key called — SERVUSER1 and generated a key for it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*n7BHgq5L9wdWrNVPDmCeBA.png" /></figure><p>2. I created a user in Snowflake called SERVUSER1 with no password, because I want to set it from the key vault.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLdPB2wyyvBunoH-1w_IPg.png" /></figure><h3>Code</h3><p>You can watch the YouTube video on how to connect Visual Studio Code to your Azure account, as this isn’t intended to be a step by step guide for Azure and Snowflake.</p><p>Once everything’s set up and connected, packages downloaded and installed, you can have a similar local.settings.json as mine below</p><pre>{<br>  &quot;IsEncrypted&quot;: false,<br>  &quot;Values&quot;: {<br>    &quot;AzureWebJobsStorage&quot;: &quot;&quot;,<br>    &quot;FUNCTIONS_WORKER_RUNTIME&quot;: &quot;dotnet&quot;,<br>    &quot;KeyVaultUrl&quot;: &quot;https://&lt;key_vault&gt;.vault.azure.net/&quot;,<br>    &quot;SnowflakeAccount&quot;: &quot;&lt;account&gt;.&lt;region&gt;&quot;,<br>    &quot;SnowflakeUser&quot;:&quot;my elevated snowflake user &quot;,<br>    &quot;SnowflakePassword&quot;:&quot;my password nice try&quot;<br>  }<br>}</pre><p>Yes, for now I kept the user and password in this file locally. If you watch the video above, you can see how to swap these out for Key Vault parameters instead to reference a Key Vault Secret, but for now — I wanted to run things locally.</p><p>My C# function looked like so —</p><pre>public static class RsaKeyFunction<br>{<br>    [FunctionName(&quot;RsaKeyFunction&quot;)]<br>    public static async Task&lt;IActionResult&gt; Run(<br>        [HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, &quot;post&quot;, Route = null)] HttpRequest req,<br>        ILogger log)<br>    {<br>        log.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);<br><br>        string keyVaultUrl = Environment.GetEnvironmentVariable(&quot;KeyVaultUrl&quot;);<br>        string keyName = req.Query[&quot;keyName&quot;]; // Get key name from query string<br><br>        if (string.IsNullOrEmpty(keyName))<br>        {<br>            return new BadRequestObjectResult(&quot;Please pass the keyName in the query string&quot;);<br>        }<br><br>        try<br>        {<br>            var credential = new DefaultAzureCredential();<br>            var keyClient = new KeyClient(new Uri(keyVaultUrl), credential);<br>            var secretClient = new SecretClient(new Uri(keyVaultUrl), credential);<br><br>            // Retrieve the public key<br>            KeyVaultKey key = await keyClient.GetKeyAsync(keyName);<br>            RSA rsa = key.Key.ToRSA();<br>            byte[] publicKeyBytes = rsa.ExportSubjectPublicKeyInfo();<br>            string publicKeyPem = Convert.ToBase64String(publicKeyBytes);<br>            publicKeyPem = $&quot;{publicKeyPem}&quot;;</pre><p>This code basically connects to my KeyVaultUrl provided in my json file, and gets the key associated with keyName from the Azure Key Vault. I did have to be logged into my Azure account from the VS Code application, so that’s why there’s no authentication to that built in here except the DefaultAzureCredential() function.</p><p>What this function does is, once it connects to my Azure Subscription, it goes to my specified key vault, and retrieves the public key for the key I provide the HTTP request.</p><p>It’ll be a value something like — <br>MIIBIjANBgkqhki……</p><p>Now, I connect to Snowflake, using the same approach and I set the password using the below code. I could’ve set this to the service account’s RSA_PUBLIC_KEY and RSA_PUBLIC_KEY_2 values, and done comparisons to see which key needs to be updated, but since there’s no way to log in using this generated public key, this was pointless. So I just set the password to this public key. However, in my screenshots I did start out setting the RSA_PUBLIC_KEY value.</p><pre>// Retrieve Snowflake credentials (username, password, URL) from Key Vault<br>         <br>            string snowflakeUrl = Environment.GetEnvironmentVariable(&quot;SnowflakeAccount&quot;);<br>            string snowflakeUser = Environment.GetEnvironmentVariable(&quot;SnowflakeUser&quot;);<br>            string snowflakePassword = Environment.GetEnvironmentVariable(&quot;SnowflakePassword&quot;); <br><br>            // Connect to Snowflake<br>            using (var connection = new SnowflakeDbConnection())<br>            {<br>                connection.ConnectionString = $&quot;account={snowflakeUrl};user={snowflakeUser};password={snowflakePassword};&quot;;<br><br>                await connection.OpenAsync();<br><br>            // Update the password with the new public key<br>                        string updateQuery = $&quot;ALTER USER {keyName} SET PASSWORD = &#39;{publicKeyPem}&#39;&quot;;<br>                        using (var updateCommand = new SnowflakeDbCommand(connection))<br>                        {<br>                            updateCommand.CommandText = updateQuery;<br>                            await updateCommand.ExecuteNonQueryAsync();<br>                        }<br>                    }<br>                }<br>            }<br><br>            return new OkObjectResult(&quot;RSA public key updated successfully&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            log.LogError($&quot;Error: {ex.Message}&quot;);<br>            return new StatusCodeResult(500); // Internal Server Error<br>        }<br>    }<br>}</pre><p>What this does is that it looks for keyName I provided it in the URL, and sets its password with the public key retrieved from the Key Vault.</p><p>When you run the above code locally, you’ll need to trigger the fetches and the sets. Your execution in the browser will look something like the below image. You can see that the http trigger of this function is waiting for the “service user” name as the value for the keyName parameter in the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*DN2bVckpCorhJNKYlWzMFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDSqX-LHbaZn1-q38GcxuQ.png" /></figure><p>As you can see, my code ran successfully (yay!). The execution took 9 seconds to find the Key Vault key, get its public key value, log into Snowflake, and alter the user. The screenshot is a bit misleading that — I had started out trying to set the RSA_PUBLIC_KEY value, which you can set using the appropriate ALTER commands, however you’d need the private key file to log in, which you can’t get, hence I updated the code in the above block to set the password instead. My code set the RSA_PUBLIC_KEY for my service user, which is why the RSA_PUBLIC_KEY is referenced.</p><p>In Snowflake, I can see my execution in the query history as well. I ran a DESC USER initially once logged in to “ping” my Snowflake account to see that I was fetching the right user before starting to modify the passwords.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqI1kgrF-ZeZfTGuBS1ONQ.png" /></figure><h3>Future Work Statements</h3><p>So I managed to get a Snowflake Service user’s password set, fetching from an Azure Key Vault, to which you can set a rotation policy, using an HTTP trigger.</p><p>In the future, what’s possible is -</p><ul><li>instead of the local.settings.JSON file, you can store your Snowflake account details in the Azure Key Vault Secrets, and retrieve it from there</li><li>Set a rotation policy on the Key itself</li><li>upload this C# code to your Azure Functions App</li><li>Call the C# Azure Function from an Event Hub Trigger to trigger this code for the appropriate service account that triggered this code (Azure Event Trigger function not HTTP Trigger)</li></ul><p>This would hopefully show a way to be able to manage passwords in your Azure Key Vault, and then have it automatically update the password in your Snowflake account, and be parameterized enough that the code triggers for whichever Service User you have, they don’t all need to have synchronized rotations. And all of this will work with minimal human intervention :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f042f72b5d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Jinja2 templates to create tables]]></title>
            <link>https://medium.com/@misrakeshav/using-jinja2-templates-to-create-tables-c1326b3f1c8b?source=rss-dbd510e68880------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1326b3f1c8b</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[create-table]]></category>
            <category><![CDATA[jinja2]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Keshav M.]]></dc:creator>
            <pubDate>Thu, 30 May 2024 21:48:10 GMT</pubDate>
            <atom:updated>2024-05-30T21:48:10.909Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Context</strong></p><p>This came about from a use case of needing to create hundreds of tables in Snowflake, where the orchestration tool was dumping parquet files of the data from a source system containing structured data.</p><p>The architecture did not allow for the orchestration tool to directly connect to Snowflake and put the data there. The dev team would get the table structure from the source system, run several CONCAT statements in order to generate -</p><ol><li>Streams</li><li>Snowpipe definitions</li><li>Tables in a staging database, and tables in the target database</li><li>Views on top of the target database, with tags</li><li>Tasks</li></ol><p>There are quite a few steps here that need to be followed, and so we asked — could we speed this process up, automate it, and free up time for other development? Otherwise creating all the scripts, validating and executing them, and finally testing them end to end would take about a day or two per table, or even longer if the developer is new and doing all this for the first few times!</p><p>The answer was: yes we can … but how simple can we make it for the end user?</p><p>The idea here was to create a JSON template in the source system for a desired table, with all the information needed for the Snowflake objects, and executing stored procedures to create the objects.</p><p>Or your use case could be if you’re starting on your database migration journey into Snowflake.</p><p><strong>Approach</strong></p><p>We’ll generate JSON from the source system, use jinja2 templates, and write procedures to call the JSON file, and the jinja2 template, and create those objects for us</p><p><strong>Solution</strong></p><p>To get started, here’s a sample JSON table definition file that we’ll use —</p><pre>{<br>  &quot;database&quot;: &quot;JINJA2TEST_DB&quot;,<br>  &quot;schema&quot;: &quot;SCHEMA1&quot;,<br>  &quot;table_name&quot;: &quot;MyTable&quot;,<br>  &quot;columns&quot;: [<br>    {&quot;name&quot;: &quot;column1&quot;, &quot;type&quot;: &quot;VARCHAR(255)&quot;},<br>    {&quot;name&quot;: &quot;column2&quot;, &quot;type&quot;: &quot;INT&quot;},<br>    {&quot;name&quot;: &quot;column3&quot;, &quot;type&quot;: &quot;DATE&quot;}<br>  ]<br>}</pre><blockquote>filename: my_table1.json</blockquote><p>from the above JSON we can see that we want to create a table called MyTable in the JINJA2TEST_DB.SCHEMA1, and it contains an array of the columns. You can separate out the column type into a type and a size field too, depending on your needs</p><p>The jinja2 template required some tricks and experimentation to get it working in Snowflake -</p><pre>CREATE TABLE {{ database }}.{{ schema }}.{{ table_name }} ({% for column in columns %} {{ column.name }} {{ column.type }}{% if column.size %}({{ column.size }}){% endif %}{% if column.default %} DEFAULT {{ column.default }}{% endif %}{% if column.not_null %} NOT NULL{% endif %}{% if not loop.last %}\,{% endif %} {% endfor %});</pre><blockquote>filename: create_table_template.jinja2</blockquote><p>It is poorly formatted for a reason, so let’s first make it easy to read and see why-</p><pre>-- create_table_template.jinja2<br>CREATE TABLE {{ database }}.{{ schema }}.{{ table_name }} (<br>{% for column in columns %}<br>    {{ column.name }} {{ column.type }}{% if not loop.last %},{% endif %}<br>{% endfor %}<br>);</pre><p>If you take the above file, stick it into a Snowflake internal stage, and run Python code against it, it’ll fail with errors because:</p><ol><li>the Python code doesn’t like new lines, so we must remove any new lines from the template files</li><li>the “,” in the column array implies to Snowflake that it’s the end of a column, so to escape it, add a backslash — \, . You can see the difference by excluding the backslash and then doing a select $1 on the file in Snowflake; it should truncate where the comma is. This is how the python procedure will see this file.</li></ol><p>Save the file as create_table_template.jinja2 (or any other extension)</p><p>In Snowflake —</p><p>We’re going to create a database, schema, file format, two internal stages, and put the above two files (JSON and jinja2 template), and create a python procedure to use the two to create a table</p><p>Create the database and schema</p><pre>create database if not exists jinja2test_db;<br>create schema if not exists jinja2test_db.myschema1;</pre><p>Create the file format</p><pre>create or replace file format jinja2test_db.myschema1.my_json_format<br>type = &#39;json&#39;<br>strip_outer_array = true;</pre><p>Create the internal stages for the files</p><pre>create or replace stage jinja2test_db.myschema1.JSON_STAGE file_format = my_json_format;<br>create or replace stage jinja2test_db.myschema1.template_stage;</pre><p>As you can see, the template_stage is where we’ll put the template files, which we can secure so end users can’t see them, and control permissions on the JSON_STAGE stage, where the users can place their files.</p><p>The file_format creation and setting was necessary, otherwise if you run a ls on the file, it breaks every line of the JSON into a new line, which causes errors.</p><p>Put the files into the stages</p><pre>PUT file://&lt;local path&gt;\my_table1.json @JSON_STAGE AUTO_COMPRESS=FALSE;<br>PUT file://&lt;local path&gt;\create_table_template.jinja2 @TEMPLATE_STAGE AUTO_COMPRESS=FALSE;</pre><p>Snippets of the python procedure. You will need to ensure you bring in the Jinja2, snowflake-snowpark-python packages, and import the json lib</p><p>This is where the magic happens!</p><pre><br> # Fetch the JSON file content from the stage<br>    json_stage_query = f&quot;SELECT $1 FROM @JSON_STAGE/{json_file_name}&quot;<br>    json_result = session.sql(json_stage_query).collect()[0][0]<br><br> # Ensure the JSON content is properly loaded<br>    try:<br>        table_definition = json.loads(json_result)<br>    except json.JSONDecodeError as e:<br>        return f&quot;Error decoding JSON: {str(e)}\nRaw JSON content: {json_result}&quot;<br>    <br> # Fetch the Jinja2 template from the stage<br>    template_stage_query = &quot;SELECT $1 FROM @template_stage/create_table_template.jinja2&quot;<br>    template_result = session.sql(template_stage_query).collect()[0][0]<br>    template = Template(template_result)<br>    <br> # Render the template with the JSON data<br>    create_table_sql = template.render(<br>        database=table_definition[&#39;database&#39;],<br>        schema=table_definition[&#39;schema&#39;],<br>        table_name=table_definition[&#39;table_name&#39;],<br>        columns=table_definition[&#39;columns&#39;]<br>    )<br>    <br> # If you&#39;d rather spit out the create statement and not execute it then run the below code and comment out the Execute the CREATE TABLE statement and return statements and use the ones below<br> print(f&quot;Generated SQL: {create_table_sql}&quot;)<br>    <br>  return create_table_sql<br> <br></pre><p>The first step in this python procedure is to read the JSON file from the stage that’ll be passed on to the procedure via the json_file_name parameter. This will be the table definition file.</p><p>Then we read in the create_table_template file. You can adjust these stage names based on your created stages.</p><p>We then render the file based on the tags set for our database, schema, table_name, and columns tags from the JSON file.</p><p>If you prefer to see the generated SQL of the CREATE TABLE instead of having the stored procedure execute it, then use the print statement and the corresponding return(), otherwise session.sql will go ahead and execute the create table statement, and give you a nice return of what it did.</p><p>Call the stored procedure</p><pre>call JINJA2TEST_DB.MYSCHEMA1.&lt;sp_name&gt;(&#39;my_table1.json&#39;);</pre><p>And Voilà! Table’s created</p><figure><img alt="MYTABLE created by executing the python code against the JSON file using the jinja2 template" src="https://cdn-images-1.medium.com/max/294/1*2NqO7vyBFgXdNG0V3Z5dUw.jpeg" /></figure><p><strong>Summary</strong></p><p>This approach, using a simple JSON generating script from the source system allowed our developers to bring down their development time into minutes! Imagine going from 100 days (not quite, but still) to create 100 tables and other Snowflake objects in minutes!</p><p><strong>Forward Thinking</strong></p><ol><li>You can extend the above approach to create tasks, pipes, views, etc as well if you just create the appropriate jinja2 template file and call it.</li><li>I intentionally left out the call procedure as Owner/Caller. This would depend on how much freedom you grant to your developers.</li><li>You can adjust the jinja2 template to fit your needs. Maybe you have tags or comments to apply, or default values to set.</li><li>with the upcoming git integration, it may be possible to set up a git integration, store your jinja2 template, and JSON files there, and just called the procedure in Snowflake and really make devops work for you.</li><li>There was an idea to further enhance this by allowing the user to upload a file using Streamlit running on Snowflake, that would get uploaded directly into the JSON stage location, however the file_uploader function is currently not supported by Snowflake (as of May 2024).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1326b3f1c8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>