<?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 Jagdish Wagh on Medium]]></title>
        <description><![CDATA[Stories by Jagdish Wagh on Medium]]></description>
        <link>https://medium.com/@jagdishmwagh?source=rss-6877b8587c85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GKSPhstS1MbW1xSJ</url>
            <title>Stories by Jagdish Wagh on Medium</title>
            <link>https://medium.com/@jagdishmwagh?source=rss-6877b8587c85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:32:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jagdishmwagh/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[Structuring Azure Infrastructure with Terraform — A Modular, Environment-Aware Approach]]></title>
            <link>https://medium.com/@jagdishmwagh/structuring-azure-infrastructure-with-terraform-a-modular-environment-aware-approach-c8de80c0ec35?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8de80c0ec35</guid>
            <category><![CDATA[hashicorp]]></category>
            <category><![CDATA[azure-infrastructure]]></category>
            <category><![CDATA[infra-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Sat, 30 May 2026 15:46:00 GMT</pubDate>
            <atom:updated>2026-05-30T15:46:00.522Z</atom:updated>
            <content:encoded><![CDATA[<h4>Infrastructure teams often face the same dilemma: start simple and refactor later, or invest in structure upfront and move slower at first. After managing Azure resources through a series of brittle, monolithic Terraform configurations, we chose the latter — and it paid off.</h4><p>In this post, we walk through the directory layout, provider configuration, remote state setup, and module design we use to manage our Data platform across <strong>development</strong> and <strong>production</strong> environments on Azure. The patterns are straightforward, but the reasoning behind each choice matters.</p><p><strong>Why structure matters in Terraform</strong></p><p>Terraform makes it easy to get started, and equally easy to end up with a 2,000-line main.tf that no one dares touch. Shared state, environment-specific drift, and tangled provider configs are the natural enemies of scale.</p><p>Our solution is a layered folder structure where environments are isolated, shared logic lives in modules, and variables enforce discipline at every boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNGwRhLS6bUbF1roJH3LDw.png" /></figure><h3>The directory layout</h3><p>Everything lives under a top-level terraform/ directory. Each environment gets its own folder; reusable logic goes into shared modules.</p><p>terraform/<br> ├── shared/<br> │ └── modules/<br> │<br> ├── dev/<br> │ ├── main.tf<br> │ ├── variables.tf<br> │ └── dev.tfvars<br> │<br> ├── prod/<br> │ ├── main.tf<br> │ ├── variables.tf<br> │ └── prod.tfvars</p><h3>Key Design Principles</h3><ul><li><strong>Reusability</strong> → Common logic is placed in shared/modules</li><li><strong>Environment isolation</strong> → Each environment has its own configuration</li><li><strong>Scalability</strong> → Easy to extend for new regions or teams</li><li><strong>Governance</strong> → Standardized tagging and naming conventions</li></ul><h3>Terraform Module Setup</h3><p>To ensure reusability and consistency, we organize our infrastructure using <strong>modular Terraform design</strong>.<br> All reusable components are placed under the shared/modules directory, allowing multiple teams and environments to use the same standardized logic.</p><p>Each module is designed to represent a <strong>specific resource or service</strong> (e.g., Resource Group, Storage, Key Vault), making the infrastructure easy to scale and maintain.</p><h4>Modelule Structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*q7MeOBAl5j77s5VHfYtKgQ.png" /><figcaption>Module Structure</figcaption></figure><h4>Resource Group Module</h4><pre>resource &quot;azurerm_resource_group&quot; &quot;resource_group&quot; {<br> name = var.resource_group_name<br> location = var.location<br> tags = var.tags<br>}</pre><h3>Configuring providers and remote state</h3><p>The main.tf in each environment handles three responsibilities: pinning provider versions, configuring the Azure backend, and wiring up module calls. Here is the dev configuration:</p><pre>terraform {<br>  required_providers = {<br>    azurerm = {<br>      source  = &quot;hashicorp/azurerm&quot;<br>      version = &quot;~&gt; 3.42&quot;<br>    }<br>    databricks = {<br>      source  = &quot;databricks/databricks&quot;<br>      version = &quot;~&gt; 1.0&quot;<br>    }<br>    azuread = {<br>      source  = &quot;hashicorp/azuread&quot;<br>      version = &quot;~&gt; 2.0&quot;<br>    }<br>  }<br><br>  backend &quot;azurerm&quot; {<br>    resource_group_name  = var.resource_group_name<br>    storage_account_name = var.storage_account_name<br>    container_name       = var.container_name<br>    key                  = var.file_path<br>  }<br>}<br><br>provider &quot;azurerm&quot; {<br>  features {}<br>}<br><br>provider &quot;azuread&quot; {<br>  tenant_id = var.tenant_id<br>}</pre><p>Notice that the backend uses variables rather than hardcoded values. This is intentional — it lets each environment point to its own Azure Storage container without changing the code, only the *.tfvars file.</p><blockquote>Why pin provider versions? Terraform providers release frequently, and minor bumps can introduce breaking changes. Using version constraints like ~&gt; 3.42 allows patch updates while guarding against unexpected major changes in shared pipelines.</blockquote><h3>Calling shared modules — the security resource group</h3><p>With providers and backend in place, the real work begins: calling modules. Here is how we provision the security resource group in the dev environment, applying a rich set of governance tags through Terraform’s merge() function:</p><p>dev/main.tf — security resource group moduleHCL</p><pre>module &quot;resource_group_security&quot; {<br>  source = &quot;./shared/modules/resource_group&quot;<br><br>  resource_group_name = &quot;rg-dp-security-${var.environment}-weu-01&quot;<br>  location            = var.location<br><br>  tags = merge(var.tags, {<br>    ApplicationName  = &quot;DataPlatform-AI&quot;<br>    BusinessUnit     = &quot;DataPlatform&quot;<br>    CostCenter       = &quot;DL-XX-001&quot;<br>    WorkType         = &quot;INFRA&quot;<br>    ServiceCategory  = &quot;Security&quot;<br>    BillingOwner     = &quot;DataEngineering&quot;<br>    Confidentiality  = &quot;Internal&quot;<br>    Criticality      = &quot;High&quot;<br>    CreatedBy        = &quot;Terraform&quot;<br>    ExpirationDate   = &quot;None&quot;<br>    Description      = &quot;Security resources: NSG, Private Endpoints, Routing&quot;<br>  })<br>}</pre><p>The naming convention rg-dp-security-${var.environment}-weu-01 dynamically resolves to rg-dp-security-dev-weu-01 in development and rg-dp-security-prod-weu-01 in production — with identical module code.</p><h4>Why Tagging Matters</h4><p>In a multi-team and multi-environment setup, tagging is not just metadata — it is critical for:</p><ul><li><strong>Cost tracking and chargeback</strong></li><li><strong>Resource ownership identification</strong></li><li><strong>Security and compliance classification</strong></li><li><strong>Operational governance</strong></li></ul><h4><strong>Terraform Exuection Commond</strong></h4><p>1terraform init — wire up providers and backend</p><p>Downloads providers, initialises the remote backend, and resolves module sources. Run this once per environment, and again whenever providers or modules change.</p><p>2 terraform plan — inspect changes before they happen</p><p>Compares your configuration against real Azure state and produces a diff. Nothing changes in Azure — this is read-only. Always save the plan output for apply.</p><p>3terraform apply — execute with explicit approval Applies the</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8de80c0ec35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Transactions and Snapshot Isolation in Microsoft Fabric Warehouses]]></title>
            <link>https://medium.com/@jagdishmwagh/understanding-transactions-and-snapshot-isolation-in-microsoft-fabric-warehouses-dddd91b5bf54?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/dddd91b5bf54</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 10:23:03 GMT</pubDate>
            <atom:updated>2025-07-14T11:13:32.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4QkwAc0vMz8eHolokITn8A.png" /><figcaption><strong>Fabric Warehouse Isolation Details</strong></figcaption></figure><p>As Microsoft Fabric continues to gain traction in the data community, many professionals are transitioning from traditional SQL Server environments to this new, unified analytics platform. While the Fabric Warehouse brings several innovations, it also retains many familiar concepts from SQL Server — like transactions, isolation levels, and ACID compliance — but with a Fabric-native twist.</p><p>In this article, we’ll explore how transactions work in Fabric Warehouses, how snapshot isolation differs from SQL Server, and how these mechanics impact real-world scenarios like reading, updating, and inserting data.</p><h4><strong>Transactions &amp; ACID Principles in Fabric</strong></h4><p>Before diving into Fabric-specific behavior, let’s revisit the basics.</p><p>What is a Database Transaction?<br>A transaction is a logical unit of work that encapsulates one or more SQL operations — either reading or modifying data. Transactions in SQL are initiated using:</p><pre>BEGIN TRANSACTION;<br><br> - Your SQL operations<br><br>COMMIT TRANSACTION;</pre><p>If something goes wrong mid-way, you can use:</p><pre>ROLLBACK TRANSACTION;</pre><p>This ensures that all operations succeed or none do, maintaining consistency.</p><p><strong>ACID Explained<br></strong>Fabric adheres to the ACID principles, just like SQL Server:</p><ul><li><strong>Atomicity</strong>: All operations succeed or none do.</li><li><strong>Consistency</strong>: Ensures the database adheres to its rules post-transaction.</li><li><strong>Isolation</strong>: Transactions do not interfere with each other.</li><li><strong>Durability</strong>: Once committed, changes persist even after a crash.</li></ul><h4><strong>Snapshot Isolation: The Default in Fabric Warehouses</strong></h4><p>Fabric Warehouses use <strong>Snapshot Isolation</strong> as the <strong>only</strong> concurrency model. Unlike SQL Server, where you can choose from multiple levels (e.g., READ COMMITTED, SERIALIZABLE, etc.), Fabric simplifies this with a default optimistic model.</p><h4>What is Snapshot Isolation?</h4><p>Under Snapshot Isolation:</p><ul><li>Reads always return a consistent snapshot of the data as it existed at the beginning of the transaction.</li><li>Writes are evaluated at commit time, and only the first writer wins.</li></ul><p>This model enables high concurrency, which is especially beneficial for analytics and reporting scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wsQD_P9A9qSa5Ee_Zky-Q.png" /></figure><p><strong>Practical Demo: Transaction-Controlled Reads</strong></p><pre>- Setup<br>CREATE SCHEMA demo;<br>DROP TABLE IF EXISTS demo.D_Article;<br>DROP TABLE IF EXISTS demo.F_Sales;<br><br><br>CREATE TABLE demo.D_Article (<br> ArticleKey INT,<br> ArticleID VARCHAR(10),<br> ArticleName VARCHAR(50)<br>);<br><br>CREATE TABLE demo.F_Sales (<br> ArticleKey INT,<br> salesCount INT,<br> salesAmount DECIMAL(6,2)<br>);<br>INSERT INTO demo.D_Article VALUES<br>(11, &#39;S0S68&#39;, &#39;HP 14&#39;),<br>(12, &#39;DE54678&#39;, &#39;Dell&#39;),<br>(13, &#39;TP9734&#39;, &#39;ThinkPad&#39;);<br><br>INSERT INTO demo.F_Sales VALUES<br>(11, 1, 11.99), (11, 2, 24.98),<br>(12, 1, 56.99), (12, 3, 23.97),<br>(13, 1, 34.99), (13, 1, 1299.00);</pre><p>Now, let’s run a SELECT twice inside a transaction with a delay:</p><pre>BEGIN TRANSACTION;<br><br>SELECT D.ArticleName, SUM(F.salesCount) AS TotalSalesCount, SUM(F.salesAmount) AS TotalSalesAmount<br>FROM demo.F_Sales F<br>JOIN demo.D_Article D ON D.ArticleKey = F.ArticleKey<br>GROUP BY D.ArticleName;<br><br>WAITFOR DELAY &#39;00:00:30&#39;;<br><br>SELECT D.ArticleName, SUM(F.salesCount) AS TotalSalesCount, SUM(F.salesAmount) AS TotalSalesAmount<br>FROM demo.F_Sales F<br>JOIN demo.D_Article D ON D.ArticleKey = F.ArticleKey<br>GROUP BY D.ArticleName;<br><br>COMMIT TRANSACTION;</pre><p>Now open a <strong>new query window</strong> and run this update <em>during</em> the delay:</p><pre>UPDATE demo.F_Sales<br>SET salesAmount = salesCount * 599.99<br>WHERE ArticleKey = 11;</pre><p><strong>Observation</strong>: Both SELECTs within the transaction return the same data — proving Snapshot Isolation gives you a consistent, unchanging view of the data throughout the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*_YjidWQfuoPEKFYyg79-aw.png" /><figcaption><strong>Result-1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*a2wzfVL_c6zww0uBMLisrw.png" /><figcaption><strong>Result-1</strong></figcaption></figure><p>Running a SELECT again will return the new TotalSalesAmount from the UPDATE statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*JYSpnLW97HHDncQf2SKKSg.png" /><figcaption>Select After Update</figcaption></figure><h4>Update Conflicts: First Commit Wins</h4><p>With updates, Snapshot Isolation follows a strict <strong>“first committer wins”</strong> approach. If two transactions update the same table simultaneously, only the one that commits first will succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bONY-iGaPXz353sq7FDVbQ.png" /><figcaption>Update With Timeline</figcaption></figure><p>Demo: Conflicting Updates</p><pre>- Transaction 1 (long-running)<br>BEGIN TRANSACTION;<br><br>UPDATE demo.D_Article<br>SET ArticleName = &#39;Nokia Windows Phone&#39;<br>WHERE ArticleID = &#39;DE54678&#39;;<br><br>WAITFOR DELAY &#39;00:00:30&#39;;<br><br>COMMIT TRANSACTION;</pre><p>Now run this <strong>immediately</strong> in a new window:</p><pre>UPDATE demo.D_Article<br>SET ArticleName = &#39;MacBook&#39;<br>WHERE ArticleID = &#39;DE54678&#39;;</pre><p><strong>Expected</strong>: The second update will <strong>fail</strong> with:</p><p>Msg 15806: Snapshot isolation transaction aborted due to update conflict.</p><h4><strong>Insert Behavior: No Conflicts, Just New Files</strong></h4><p>Inserts in Fabric are conflict-free by design. Each insert operation generates a new Parquet file, meaning concurrent inserts don’t interfere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6k2jou55FPJxzwUrhMCScA.png" /><figcaption>Insert With Timeline</figcaption></figure><p>Demo: Parallel Inserts</p><pre>- Window 1<br>BEGIN TRANSACTION;<br>INSERT INTO demo.D_Article VALUES (14, &#39;Z48734&#39;, &#39;Lenovo&#39;);<br>WAITFOR DELAY &#39;00:00:30&#39;;<br>COMMIT TRANSACTION;<br>- Window 2 (immediately after)<br>INSERT INTO demo.D_Article VALUES (15, &#39;Q82374&#39;, &#39;Gaming Mouse&#39;);</pre><p><strong>Result</strong>: Both inserts succeed independently. This is ideal for high-throughput ingestion pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*EvHbBoz3TdfSc9Gen25XFg.png" /><figcaption>Insert Result No Conflict</figcaption></figure><h3>Deleting Data</h3><p>DELETE operations in Fabric Warehouses follow the same <strong>Snapshot Isolation</strong> rules as UPDATEs. This means that if one transaction initiates a DELETE and another concurrent transaction modifies (or deletes) rows from the same table and commits first, the original DELETE transaction will <strong>fail and be rolled back</strong>.</p><p>In simple terms, it’s still <strong>“first committer wins.”</strong> Even if the rows being deleted are different, Fabric Warehouses prevent <strong>any</strong> concurrent write operations on the same table from succeeding together.</p><p>Understanding this behavior is essential when designing data pipelines or scheduling background processes that perform data cleanup or archival tasks.</p><h4>Demonstrating DELETE Conflicts</h4><p>Run the following block in one query window to simulate a long-running DELETE operation:</p><pre>--begin a transaction to delete a record and wait while another delete is run<br>BEGIN TRANSACTION<br>    <br>    --run delete<br>    DELETE FROM demo.D_Article<br>    WHERE ArticleKey = 14;<br><br>    -wait while other statement is run<br>    WAITFOR DELAY &#39;00:00:30&#39;;<br><br>COMMIT TRANSACTION;</pre><p><strong>While that SQL is running</strong>, open a second query window and execute the following <strong>immediately</strong>:</p><pre>--run an immediate delete<br>DELETE FROM DW.DimProducts<br>WHERE ProductKey = 5;</pre><h4>Expected Behavior</h4><p>You’ll likely encounter an error in one of the transactions, indicating a <strong>snapshot isolation conflict</strong>. The transaction that <strong>commits first</strong> will succeed, and the other will be <strong>rolled back automatically</strong>.</p><p>This showcases how Fabric ensures data consistency and prevents conflicting modifications — even across rows that aren’t identical — by locking at the <strong>table level</strong> rather than the row level.</p><h3>Monitoring Locks</h3><p>Understanding and tracking table-level locks can be essential — especially when diagnosing performance issues or dealing with unexpected transaction conflicts.</p><p>To monitor the locks placed on tables within the Warehouse, you can query the sys.dm_tran_locks dynamic management view (DMV). This DMV provides details about lock types, associated resources, and the session or transaction responsible.</p><p>For easier integration with reporting tools like Power BI, it’s helpful to encapsulate this logic into a view. Below is a sample implementation that includes a helper function and a view for lock tracking:</p><pre>--get user function<br>CREATE FUNCTION dbo.getuser <br>(<br>@sessionid AS INT<br>)<br>RETURNS TABLE<br>AS<br>RETURN<br>SELECT login_name FROM sys.dm_exec_sessions WHERE session_id=@sessionid;<br>GO<br><br>--create lock view<br>CREATE OR ALTER VIEW dbo.vwSysDMTranLocks<br>AS<br>SELECT<br>    DB_NAME(resource_database_id) AS DatabaseName,<br>    OBJECT_NAME(resource_associated_entity_id) AS ObjectName,<br>    resource_type,<br>    CASE request_mode<br>        WHEN &#39;IX&#39; THEN &#39;Intent Exclusive&#39;<br>        WHEN &#39;Sch-S&#39; THEN &#39;Schema Stability&#39;<br>        WHEN &#39;Sch-M&#39; THEN &#39;Schema Modification&#39;<br>        WHEN &#39;S&#39; THEN &#39;Shared&#39;<br>        WHEN &#39;U&#39; THEN &#39;Update&#39;<br>        WHEN &#39;X&#39; THEN &#39;Exclusive&#39; <br>        WHEN &#39;IS&#39; THEN &#39;Intent Shared&#39; <br>        WHEN &#39;IU&#39; THEN &#39;Intent Update&#39; <br>        WHEN &#39;IX&#39; THEN &#39;Intent Exclusive&#39;<br>        WHEN &#39;SIU&#39; THEN &#39;Shared Intent Update&#39; <br>        WHEN &#39;SIX&#39; THEN &#39;Shared Intent Exclusive&#39; <br>        WHEN &#39;UIX&#39; THEN &#39;Update Intent Exclusive&#39;<br>        ELSE request_mode<br>    END AS LockRequestModeDesc,<br>    request_mode,<br>    request_type,<br>    request_status,<br>    request_reference_count,<br>    request_session_id,<br>    resource_associated_entity_id,<br>    getuser.login_name <br>FROM sys.dm_tran_locks<br>CROSS APPLY dbo.getuser(request_session_id) as getuser</pre><h3>Final Thoughts</h3><p>Fabric Warehouses’ use of Snapshot Isolation offers a powerful yet simplified concurrency model, optimized for analytical workloads. While familiar transaction principles apply, some key differences — especially around update conflicts — must be understood when designing solutions or migrating from SQL Server.</p><h3>Key Takeaways:</h3><ul><li>Fabric Warehouses only support <strong>Snapshot Isolation</strong>.</li><li>Reads are stable and consistent during transactions.</li><li>Updates follow a <strong>first-committer-wins</strong> strategy.</li><li>Inserts are <strong>conflict-free</strong>, ideal for high-concurrency environments.</li></ul><p>References:<br><a href="https://learn.microsoft.com/en-us/fabric/data-warehouse/transactions">Transactions in Warehouse Tables — Microsoft Fabric | Microsoft Learn</a><br><a href="https://docs.delta.io/0.4.0/delta-concurrency.html">Concurrency Control — Delta Lake Documentation</a><br><a href="https://www.sqlservercentral.com/articles/lock-scenarios-using-sys-dm_tran_locks">Lock Scenarios Using sys.dm_tran_locks — SQLServerCentral</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dddd91b5bf54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Data to Azure Data Lake Gen2 with Databricks: Parquet and CSV Done Right!]]></title>
            <link>https://medium.com/@jagdishmwagh/writing-data-to-azure-data-lake-gen2-with-databricks-parquet-and-csv-done-right-813a42b82233?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/813a42b82233</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Wed, 28 May 2025 18:56:50 GMT</pubDate>
            <atom:updated>2025-07-14T11:07:14.447Z</atom:updated>
            <content:encoded><![CDATA[<p>As a data engineer, we often need to write structured data to cloud storage in standard formats like <strong>Parquet</strong> and <strong>CSV</strong>. While this is common, many tutorials skip over one important aspect: <strong>security</strong>.</p><p>In this post, you’ll learn how to:</p><ul><li>Write Parquet and CSV files to <strong>Azure Data Lake Storage Gen2</strong></li><li>Configure secure access using <strong>Azure Key Vault-backed secret scopes</strong></li><li>Avoid common pitfalls with .save() and file formats</li></ul><p>Let’s say you want to save a simple Spark DataFrame into both <strong>Parquet</strong> and <strong>CSV</strong> formats on <strong>Azure Data Lake Gen2</strong>, and read it back for validation.</p><h3>📌 Prerequisites</h3><ul><li>Azure Databricks workspace</li><li>Azure Data Lake Storage Gen2 account</li><li>Azure Key Vault with a <strong>storage key</strong> stored securely</li><li>Databricks secret scope linked to the Key Vault</li></ul><h3>🛡️ Step 1: Securely Access Storage Account Key from Key Vault.</h3><h4>Never hardcode secrets in notebooks. Instead, retrieve them from a secret scope linked to Azure Key Vault:</h4><pre># Access storage key securely from Databricks secret scope<br>storage_account_name = &quot;dlstestdev01&quot;<br>container_name = &quot;your-container&quot;<br># Fetch the access key securely<br>storage_account_key = dbutils.secrets.get(scope=&quot;kv-scope&quot;, key=&quot;adls-key&quot;)<br># Set Spark config<br>spark.conf.set(<br> f&quot;fs.azure.account.key.{storage_account_name}.dfs.core.windows.net&quot;,<br> storage_account_key<br>)</pre><p>💡 Replace kv-scope with your actual Databricks secret scope and adls-key with the name of the key stored in Key Vault.</p><h3>Step 2: Create Sample DataFrame</h3><pre>data = [(&quot;A&quot;, 1), (&quot;B&quot;, 2), (&quot;C&quot;, 3)]<br>columns = [&quot;letter&quot;, &quot;number&quot;]<br>pos_df = spark.createDataFrame(data, columns)<br>pos_df.show()<br>Step 3: Write to Parquet and CSV on ADLS Gen2</pre><pre>parquet_folder_path = &quot;demo/parquet-output&quot;<br>csv_folder_path = &quot;demo/csv-output&quot;<br>parquet_location = f&quot;abfss://{container_name}@{storage_account_name}.dfs.core.windows.net/{parquet_folder_path}&quot;<br>csv_location = f&quot;abfss://{container_name}@{storage_account_name}.dfs.core.windows.net/{csv_folder_path}&quot;</pre><h4>Save as Parquet</h4><pre>pos_df.write \<br> .format(&quot;parquet&quot;) \<br> .mode(&quot;overwrite&quot;) \<br> .save(parquet_location)</pre><h4>Save as CSV</h4><pre>pos_df.write \<br> .format(&quot;csv&quot;) \<br> .option(&quot;header&quot;, True) \<br> .mode(&quot;overwrite&quot;) \<br> .save(csv_location)</pre><h3>Step 4: Read CSV Back for Validation</h3><pre>df_read = spark.read \<br> .format(&quot;csv&quot;) \<br> .option(&quot;header&quot;, True) \<br> .load(csv_location)<br>df_read.show()p</pre><ul><li>🔒 Security First: Use Azure Key Vault-backed secret scopes. Never hardcode sensitive values.</li><li>💾 Use abfss:// paths for ADLS Gen2, not wasbs://.</li><li>🧹 Use .mode(&quot;overwrite&quot;) carefully to avoid accidental data loss.</li><li>🧠 Validate after write to ensure correctness.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=813a42b82233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ingesting Emails from Outlook 365 to Azure Blob Storage using Databricks]]></title>
            <link>https://medium.com/@jagdishmwagh/ingesting-emails-from-outlook-365-to-azure-blob-storage-using-databricks-1d79809d2c3f?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d79809d2c3f</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Mon, 12 May 2025 20:43:04 GMT</pubDate>
            <atom:updated>2025-07-14T11:11:10.443Z</atom:updated>
            <content:encoded><![CDATA[<p>We aim to:</p><ul><li>Extract emails from specific folders (e.g., <em>Inbox/AI</em>, <em>Inbox/R&amp;D</em>) in multiple users’ mailboxes.</li><li>Load this data in JSON format into <strong>Azure Blob Storage</strong>, partitioned by year/month/day.</li><li>Track last-modified timestamps using watermarking for <strong>incremental ingestion</strong>.</li></ul><p>High-Level Architecture</p><blockquote>M365 Outlook ➡ Microsoft Graph API ➡ Databricks Notebook ➡ Azure Blob Storage (Raw Layer)</blockquote><ol><li>🔐 Set Up Azure AD App Registration</li></ol><ul><li>Create a <strong>Service Principal</strong> in <strong>Azure Entra ID</strong> (Azure AD).</li><li>Assign Mail.Read or Mail.ReadBasic API permission (application-level).</li><li>Generate <strong>Client ID</strong> and <strong>Client Secret</strong>.</li></ul><p>2. 🔑 Store Secrets in Azure Key Vault</p><p>Use Databricks Secret Scope to securely access credentials:</p><pre>scope=&quot;kv-test-01&quot;, key=&quot;test-m365-email-export-client-id&quot;<br>scope=&quot;kv-test-01&quot;, key=&quot;test-m365-email-export-client-secret-key&quot;<br>scope=&quot;kv-test-01&quot;, key=&quot;test-dlstest01-connection-string-dev-01&quot;</pre><p>3. Email Mapping Configuration Table</p><p>We created a config table to dynamically loop through users and folders:</p><pre>CREATE TABLE catalog_email.config.email_mapping (<br> user_email STRING,<br> container_folder_name STRING,<br> folder_name STRING,<br> sub_folder_name STRING,<br> load_date TIMESTAMP<br>) USING delta<br>LOCATION &#39;abfss://config@dlstest01.dfs.core.windows.net/email/mapping&#39;;<br><br>INSERT INTO catalog_email.config.email_mapping VALUES<br>(&#39;test.test@greenland-cap.com&#39;,&#39;email/test-test&#39;,&#39;Inbox/AI&#39;,&#39;AI&#39;,current_timestamp()),<br>(&#39;test.test@greenland-cap.com&#39;,&#39;email/test-test&#39;,&#39;Inbox/R&amp;D&#39;,&#39;R&amp;D&#39;,current_timestamp());</pre><p>4. 🕒 Watermark Table for Incremental Loads</p><p>To avoid duplicate exports, we maintain the last exported timestamp:</p><pre>CREATE TABLE catalog_email.config.watermark (<br> user_email STRING,<br> container_folder_name STRING,<br> folder_name STRING,<br> sub_folder_name STRING,<br> last_modified_date STRING<br>) USING delta<br>LOCATION &#39;abfss://config@dlstest01.dfs.core.windows.net/email/watermark&#39;;</pre><p>5. 📦 Python Libraries and Installation</p><pre>pip install msal</pre><p>6. Databricks Email Extraction Logic</p><p>This notebook:</p><ul><li>Authenticates using msal and ConfidentialClientApplication</li><li>Reads configuration from Delta tables</li><li>Uses Microsoft Graph API to recursively locate folders</li><li>Downloads new messages only (using last-modified filters)</li><li>Uploads flattened JSON to Azure Blob Storage</li></ul><p>Core features:</p><ul><li>Recursive folder traversal</li><li>Robust error handling</li><li>Watermark update logic</li><li>Partitioned blob structure (year/month/day)</li></ul><p>Sample Output Structure in Blob Storage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*N7lk1Xo7WgzMuttsd6CuDw.png" /></figure><p>Each JSON contains fields like subject, from, to, bodyPreview, and full HTML content.</p><h3>Deployment Consideration</h3><p>Before production deployment:</p><ul><li>Parameterize email filters and folder mappings</li><li>Introduce logging and email alerts for failures</li><li>Enable email attachment processing (if needed)</li><li>Secure audit logging of watermark updates</li></ul><p><strong>Databricks Notebook</strong></p><pre>import os<br>import json<br>import requests<br>from datetime import datetime<br>from msal import ConfidentialClientApplication<br>from azure.storage.blob import BlobServiceClient<br>from pyspark.sql import Row<br>from pyspark.sql.functions import to_timestamp<br><br># === CONFIGURATION ===<br>TENANT_ID = &#39;XXXXXXXXXXXXXXXXXXXXXXXXXX&#39;<br>CLIENT_ID = cluster = dbutils.secrets.get(scope=&quot;kv-test-01&quot;, key=&quot;test-m365-email-export-client-id&quot;)<br>CLIENT_SECRET = cluster = dbutils.secrets.get(scope=&quot;kv-test-01&quot;, key=&quot;test-m365-email-export-client-secret-key&quot;)<br>STORAGE_CONN_STR = cluster = dbutils.secrets.get(scope=&quot;kv-test-01&quot;, key=&quot;test-dlsgtest01-connection-string-dev-01&quot;)<br>CONTAINER_NAME = &#39;raw&#39;<br><br># === GET EMAIL MAPPING CONFIG ===<br>def get_email_mapping():<br> df = spark.sql(f&#39;&#39;&#39;<br> SELECT user_email, container_folder_name, folder_name, sub_folder_name<br> FROM catalog_email.config.email_mapping<br> &#39;&#39;&#39;)<br> return df.collect()<br><br># === AUTH TOKEN ===<br>def get_graph_token():<br> app = ConfidentialClientApplication(<br> client_id=CLIENT_ID,<br> authority=f&quot;https://login.microsoftonline.com/{TENANT_ID}&quot;,<br> client_credential=CLIENT_SECRET<br> )<br><br> result = app.acquire_token_for_client(scopes=[&quot;https://graph.microsoft.com/.default&quot;])<br> if &quot;access_token&quot; in result:<br> return result[&quot;access_token&quot;]<br> else:<br> raise Exception(f&quot;Failed to acquire token: {result}&quot;)<br><br># === RECURSIVE FOLDER LOOKUP ===<br>def get_folder_id(user_email, folder_name):<br> token = get_graph_token()<br> headers = {&#39;Authorization&#39;: f&#39;Bearer {token}&#39;}<br># Split the folder path into parts (e.g., Inbox/AI -&gt; [&#39;Inbox&#39;, &#39;AI&#39;])<br> parts = folder_name.strip(&#39;/&#39;).split(&#39;/&#39;)<br> current_folder_id = &quot;&quot; # Start from root or Inbox<br><br>for i, part in enumerate(parts):<br> if i == 0:<br> # First level: use special name like &quot;Inbox&quot;<br> url = f&quot;https://graph.microsoft.com/v1.0/users/{user_email}/mailFolders/{part}&quot;<br> else:<br> # Nested: childFolders under the previous folder ID<br> url = f&quot;https://graph.microsoft.com/v1.0/users/{user_email}/mailFolders/{current_folder_id}/childFolders&quot;<br>res = requests.get(url, headers=headers)<br> if res.status_code != 200:<br> raise Exception(f&quot;Failed to get folder &#39;{part}&#39;: {res.status_code} - {res.text}&quot;)<br>data = res.json()<br> if i == 0:<br> # First level folder (Inbox)<br> current_folder_id = data[&#39;id&#39;]<br> else:<br> # Search for the matching subfolder<br> found = next((f for f in data[&#39;value&#39;] if f[&#39;displayName&#39;].lower() == part.lower()), None)<br> if not found:<br> raise Exception(f&quot;Subfolder &#39;{part}&#39; not found under parent ID &#39;{current_folder_id}&#39;&quot;)<br> current_folder_id = found[&#39;id&#39;]<br>return current_folder_id<br><br># === FLATTEN EMAIL ===<br>def flatten_email(email):<br> return {<br> &#39;id&#39;: email.get(&#39;id&#39;),<br> &#39;subject&#39;: email.get(&#39;subject&#39;),<br> &#39;from&#39;: email.get(&#39;from&#39;, {}).get(&#39;emailAddress&#39;, {}).get(&#39;address&#39;),<br> &#39;to&#39;: [t[&#39;emailAddress&#39;][&#39;address&#39;] for t in email.get(&#39;toRecipients&#39;, [])],<br> &#39;receivedDateTime&#39;: email.get(&#39;receivedDateTime&#39;),<br> &#39;importance&#39;: email.get(&#39;importance&#39;),<br> &#39;hasAttachments&#39;: email.get(&#39;hasAttachments&#39;),<br> &#39;bodyPreview&#39;: email.get(&#39;bodyPreview&#39;),<br> &#39;bodyContent&#39;: email.get(&#39;body&#39;, {}).get(&#39;content&#39;)<br> }<br><br># === UPLOAD TO BLOB STORAGE ===<br>def upload_to_blob(container_folder_name, sub_folder,blob_client, email_json):<br> dt = datetime.strptime(email_json[&#39;receivedDateTime&#39;], &quot;%Y-%m-%dT%H:%M:%SZ&quot;)<br> blob_path = f&quot;{container_folder_name}/{sub_folder}/year={dt.year}/month={dt.month:02d}/day={dt.day:02d}/{email_json[&#39;id&#39;]}.json&quot;<br> blob_client.upload_blob(blob_path, json.dumps(email_json, indent=2), overwrite=True)<br><br># === LOAD LAST EXPORT TIMES FROM WATERMARK ===<br>def load_last_export_times():<br> df = spark.sql(f&#39;&#39;&#39;<br> SELECT user_email, container_folder_name, folder_name, sub_folder_name, CAST(last_modified_date as timestamp) AS last_modified_date<br> FROM catalog_email.config.email_watermark<br> &#39;&#39;&#39;)<br> watermark = {}<br> for row in df.collect():<br> key = f&quot;{row[&#39;user_email&#39;]}_{row[&#39;folder_name&#39;]}&quot;<br> last_modified_date = row[&#39;last_modified_date&#39;]<br><br> # Ensure last_modified_date is a datetime object<br> if isinstance(last_modified_date, str):<br> last_modified_date = datetime.strptime(last_modified_date, &quot;%Y-%m-%dT%H:%M:%SZ&quot;)<br> watermark[key] = last_modified_date<br> return watermark<br><br># === UPDATE WATERMARK TABLE ===<br>def update_watermark(user_email, container_folder_name, folder_name, sub_folder_name, last_modified_date):<br> print(f&quot;📝 Updating watermark for {user_email} | {folder_name} =&gt; {last_modified_date}&quot;)<br> row = Row(<br> user_email=user_email,<br> container_folder_name=container_folder_name,<br> folder_name=folder_name,<br> sub_folder_name=sub_folder_name,<br> last_modified_date=last_modified_date<br> )<br> df = spark.createDataFrame([row])<br><br>spark.sql(&quot;&quot;&quot;<br> CREATE TABLE IF NOT EXISTS catalog_email.config.email_watermark (<br> user_email STRING,<br> container_folder_name STRING,<br> folder_name STRING,<br> sub_folder_name STRING,<br> last_modified_date TIMESTAMP<br> ) USING DELTA<br> &quot;&quot;&quot;)<br><br>df.createOrReplaceTempView(&quot;temp_watermark&quot;)<br>spark.sql(&quot;&quot;&quot;<br> MERGE INTO catalog_email.config.email_watermark AS target<br> USING temp_watermark AS source<br> ON target.user_email = source.user_email AND target.folder_name = source.folder_name<br> WHEN MATCHED THEN UPDATE SET<br> target.last_modified_date = source.last_modified_date,<br> target.container_folder_name = source.container_folder_name,<br> target.sub_folder_name = source.sub_folder_name<br> WHEN NOT MATCHED THEN INSERT *<br> &quot;&quot;&quot;)<br><br># === EXPORT EMAILS FOR USER AND FOLDER ===<br>def export_inbox_for_user(user_email, container_folder_name, sub_folder,folder_id, last_export_time):<br> token = get_graph_token()<br> headers = {&#39;Authorization&#39;: f&#39;Bearer {token}&#39;}<br><br># If last_export_time is a string, convert it to datetime<br> if isinstance(last_export_time, str):<br> last_export_time = datetime.strptime(last_export_time, &quot;%Y-%m-%dT%H:%M:%SZ&quot;)<br><br># Convert datetime to ISO 8601 string format for the filter<br> if last_export_time:<br> iso_time = last_export_time.strftime(&quot;%Y-%m-%dT%H:%M:%SZ&quot;)<br> url = f&quot;https://graph.microsoft.com/v1.0/users/{user_email}/mailFolders/{folder_id}/messages?$top=50&amp;$filter=receivedDateTime ge {iso_time}&quot;<br> print(f&quot;🔍 Filtering emails received after: {iso_time}&quot;)<br> else:<br> url = f&quot;https://graph.microsoft.com/v1.0/users/{user_email}/mailFolders/{folder_id}/messages?$top=50&quot;<br> print(&quot;🔍 No last export time found. Exporting all emails.&quot;)<br><br># Continue with the email extraction process<br> blob_service_client = BlobServiceClient.from_connection_string(STORAGE_CONN_STR)<br> container_client = blob_service_client.get_container_client(CONTAINER_NAME)<br> if not container_client.exists():<br> container_client.create_container()<br>print(f&quot;📤 Exporting emails from user &#39;{user_email}&#39;…&quot;)<br> count = 0<br> all_received_times = []<br>while url:<br> res = requests.get(url, headers=headers)<br> if res.status_code != 200:<br> raise Exception(f&quot;Graph API error: {res.status_code} - {res.text}&quot;)<br> data = res.json()<br>for email in data.get(&#39;value&#39;, []):<br> email_json = flatten_email(email)<br> upload_to_blob(container_folder_name,sub_folder, container_client, email_json)<br> all_received_times.append(email_json[&#39;receivedDateTime&#39;])<br> count += 1<br>url = data.get(&#39;@odata.nextLink&#39;)<br>print(f&quot;✅ Export completed. Total emails exported: {count}&quot;)<br> return max(all_received_times) if all_received_times else last_export_time<br><br># === MAIN CONTROLLER ===<br>def export_emails():<br> last_export_times = load_last_export_times()<br> email_configs = get_email_mapping()<br>for config in email_configs:<br> user_email = config[&#39;user_email&#39;]<br> folder_name = config[&#39;folder_name&#39;]<br> sub_folder = config[&#39;sub_folder_name&#39;]<br> container_folder_name = config[&#39;container_folder_name&#39;]<br> folder_key = f&quot;{user_email}_{folder_name}&quot;<br> last_export_time = last_export_times.get(folder_key, None)<br>try:<br> folder_id = get_folder_id(user_email, folder_name)<br> latest_export_time = export_inbox_for_user(user_email, container_folder_name, sub_folder,folder_id, last_export_time)<br> update_watermark(user_email, container_folder_name, folder_name, sub_folder, latest_export_time)<br> except Exception as e:<br> print(f&quot;❌ Failed to export for {user_email} - {folder_name}: {e}&quot;)<br><br><br># === EXECUTE SCRIPT ===<br>if __name__ == &quot;__main__&quot;:<br> export_emails()</pre><h3>Conclusion</h3><p>This notebook-based approach makes it seamless to bring in <strong>unstructured email data</strong> from M365 into your <strong>modern data lake</strong> architecture. This data can then power <strong>NLP models, topic modeling, anomaly detection</strong>, and other downstream AI pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d79809d2c3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks Table Migration Across Catalogs and Environments Using Deep Clone]]></title>
            <link>https://medium.com/@jagdishmwagh/databricks-table-migration-across-catalogs-and-environments-using-deep-clone-2439b677230b?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/2439b677230b</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 20:49:04 GMT</pubDate>
            <atom:updated>2025-04-28T20:49:04.023Z</atom:updated>
            <content:encoded><![CDATA[<p>Migrating data assets across environments (like <strong>Dev → Prod</strong>) or catalogs in <strong>Azure Databricks</strong> can be tedious, especially when dealing with multiple managed tables.<br> In this blog, I’ll show you a streamlined way to <strong>deep clone tables</strong> from one catalog to another and <strong>drop all tables</strong> if needed — using Databricks’ <strong>system tables</strong> and <strong>PySpark</strong>!</p><p>Why Use Deep Clone for Migration?</p><ul><li><strong>Fast</strong>: It creates copies of tables almost instantly using Delta Lake’s metadata optimizations.</li><li><strong>Space Efficient</strong>: Only changed data is copied physically.</li><li><strong>Safe</strong>: You can easily recreate your environment without affecting your original tables.</li></ul><p>Step 1: Query All Managed Tables From Source Catalog</p><p>First, we query system.information_schema.tables to retrieve the list of all <strong>managed</strong> tables under the source catalog.</p><blockquote>from pyspark.sql import DataFrame<br>from pyspark.sql.functions import regexp_replace<br>from pyspark.sql import lit</blockquote><blockquote>query = “””<br>SELECT <br> table_catalog,<br> table_schema,<br> table_name,<br> concat(table_catalog, ‘.’, table_schema, ‘.’, table_name) as full_table_name,<br> substring(storage_sub_directory, 1, 7) as tgt_location_path1,<br> substring(storage_sub_directory, 8, 300) as tgt_location_path2<br>FROM system.information_schema.tables<br>WHERE table_catalog = ‘sales_dev’ AND table_type = ‘MANAGED’<br>“””</blockquote><blockquote># Execute the query<br>data = spark.sql(query)</blockquote><p>Step 2: Deep Clone Each Table to Target Catalog</p><p>Once we have the table list, we loop through and <strong>clone</strong> each table into the <strong>target catalog</strong> (sales_prod.sales in this case).</p><blockquote># Fetch and print all results<br>results = data.collect()</blockquote><blockquote>for row in results:<br> # Check if the table exists<br> check_table_exists_query = f”””<br> SHOW TABLES IN {row.table_catalog}.{row.table_schema} LIKE ‘{row.table_name}’<br> “””<br> exists_df = spark.sql(check_table_exists_query)</blockquote><blockquote>if exists_df.count() &gt; 0:<br> # If exists, perform deep clone<br> clone_query = f”””<br> CREATE TABLE IF NOT EXISTS sales_prod.sales.{row.table_name}<br> CLONE {row.full_table_name}<br> “””<br> clone_result = spark.sql(clone_query)<br> display(clone_result)<br> else:<br> print(f”Table {row.table_name} does not exist. Skipping clone operation.”)</blockquote><p>✅ This ensures <strong>only existing tables</strong> are cloned, avoiding unnecessary errors.</p><p>Step 3: (Optional) Drop All Tables in a Catalog</p><p>Sometimes you need to <strong>clear</strong> a schema before re-migrating (e.g., fresh Prod environment).<br> Here’s how to <strong>drop all tables and views</strong> programmatically from a catalog and schema.</p><blockquote># Define catalog and schema<br>catalog_name = “sales_prod”<br>schema_name = “sales”</blockquote><blockquote># Query all tables and views<br>objects = spark.sql(f”””<br> SELECT table_catalog,<br> table_schema,<br> table_name,<br> table_type,<br> concat(table_catalog, ‘.’, table_schema, ‘.’, table_name) as full_table_name<br> FROM system.information_schema.tables<br> WHERE table_catalog = ‘{catalog_name}’ AND table_schema = ‘{schema_name}’<br>“””)</blockquote><blockquote># Drop each table or view<br>for obj in objects.collect():<br> full_object_name = obj[‘full_table_name’]</blockquote><blockquote>if obj[‘table_type’] == ‘VIEW’:<br> print(f”Dropping view: {full_object_name}”)<br> spark.sql(f”DROP VIEW IF EXISTS {full_object_name}”)</blockquote><blockquote>if obj[‘table_type’] == ‘MANAGED’:<br> print(f”Dropping table: {full_object_name}”)<br> spark.sql(f”DROP TABLE IF EXISTS {full_object_name}”)</blockquote><blockquote>print(f”✅ All tables and views dropped from catalog ‘{catalog_name}’, schema ‘{schema_name}’.”)</blockquote><h3>📋 Key Points to Remember</h3><ul><li><strong>system.information_schema.tables</strong> gives a universal view of tables, including type (MANAGED, VIEW, etc.).</li><li><strong>Deep Clone</strong> can clone large datasets quickly without moving all the data immediately.</li><li>Always validate using <strong>SHOW TABLES</strong> before cloning or dropping.</li><li>Use <strong>DROP VIEW</strong> and <strong>DROP TABLE</strong> separately based on object type.</li></ul><p>🌟 Conclusion</p><p>Databricks’ built-in capabilities like <strong>Deep Clone</strong> and <strong>Information Schema</strong> make <strong>environment migrations</strong> much easier and safer.<br> With a few simple PySpark scripts, you can automate migration and cleanup, saving hours of manual work!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2439b677230b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering: General Python Notebook Exception Handling]]></title>
            <link>https://medium.com/@jagdishmwagh/data-engineering-general-python-notebook-exception-handling-dc96c94369e3?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc96c94369e3</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 10:52:38 GMT</pubDate>
            <atom:updated>2025-03-28T10:52:38.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>I am working with <strong>Databricks</strong> and <strong>Fabric</strong> notebooks and have learned some important aspects of <strong>exception handling</strong> in Python. Implementing proper error handling ensures that notebooks fail with <strong>clear and standardized error messages</strong>, making it easier to identify and debug issues.</p><p>To simplify this process, I decided to document <strong>common exceptions</strong> in one central place so that others can easily implement them in their <strong>data processing Python notebooks</strong>.</p><h3>🔧 1. File Handling &amp; Data Ingestion</h3><h3>Scenarios:</h3><ul><li>File not found</li><li>Incorrect schema or malformed records</li><li>Unsupported file format</li><li>Empty file</li></ul><h3>Exceptions to Handle:</h3><blockquote>FileNotFoundError<br>ValueError<br>pyspark.sql.utils.AnalysisException<br>pyspark.sql.utils.ParseException</blockquote><h3>Example:</h3><blockquote>try:<br> df = spark.read.csv(“/mnt/data/input.csv”, header=True)<br>except FileNotFoundError:<br> print(“File not found.”)<br>except ValueError as ve:<br> print(f”Schema mismatch or parsing error: {ve}”)</blockquote><h3>🔄 2. Data Transformation Errors</h3><h4>Scenarios:</h4><ul><li>Null values where not expected</li><li>Type mismatch</li><li>Division by zero</li><li>UDF errors</li></ul><h4>Exceptions to Handle:</h4><blockquote>TypeError<br>ZeroDivisionError<br>ValueError<br>pyspark.sql.utils.AnalysisException</blockquote><h4>Example:</h4><blockquote>try:<br> df = df.withColumn(“ratio”, df[“total”] / df[“count”])<br>except ZeroDivisionError:<br> print(“Division by zero encountered.”)</blockquote><h3>📊 3. Schema &amp; Metadata Mismatch</h3><h4>Scenarios:</h4><ul><li>Schema of input data doesn’t match expected</li><li>Column missing or renamed</li><li>Data quality rules failing</li></ul><h4>Exceptions to Handle:</h4><blockquote>KeyError<br>AttributeError<br>pyspark.sql.utils.AnalysisException</blockquote><h3>🔌 4. Database &amp; External Connection Failures</h3><h4>Scenarios:</h4><ul><li>JDBC connection failures</li><li>Credentials missing/invalid</li><li>Timeout errors</li></ul><h4>Exceptions to Handle:</h4><blockquote>py4j.protocol.Py4JJavaError<br>ConnectionError<br>TimeoutError</blockquote><h4>Example:</h4><blockquote>try:<br> jdbc_url = “jdbc:sqlserver://host:port;database=dbname”<br> df.write.jdbc(jdbc_url, “tablename”, mode=”append”, properties=props)<br>except py4j.protocol.Py4JJavaError as je:<br> print(f”JDBC operation failed: {je}”)</blockquote><h3>☁️ 5. Cloud Storage/ADLS/S3 Access Issues</h3><h4>Scenarios:</h4><ul><li>Access denied to blob storage or S3</li><li>Expired SAS token</li><li>Mount point issues</li></ul><h4>Exceptions to Handle:</h4><blockquote>PermissionError<br>OSError</blockquote><h3>🗃️ 6. Writing/Saving Data</h3><h4>Scenarios:</h4><ul><li>Write to non-existing directory</li><li>Overwriting protected data</li><li>Unsupported write format</li></ul><h4>Exceptions to Handle:</h4><blockquote>OSError<br>PermissionError<br>pyspark.sql.utils.AnalysisException</blockquote><h3>📦 7. Job Dependency &amp; Runtime Errors</h3><h4>Scenarios:</h4><ul><li>Notebook called from another notebook fails</li><li>Incorrect import or missing library</li><li>Version mismatch</li></ul><h4>Exceptions to Handle:</h4><blockquote>ImportError<br>ModuleNotFoundError<br>RuntimeError</blockquote><h3>📜 8. JSON/CSV/Parquet Parsing Errors</h3><h4>Scenarios:</h4><ul><li>Malformed records</li><li>Encoding issues</li><li>Invalid structure</li></ul><h4>Exceptions to Handle:</h4><blockquote>UnicodeDecodeError<br>json.decoder.JSONDecodeError<br>ValueError</blockquote><h3>📈 9. Logging and Notification Failures</h3><h3>Scenarios:</h3><ul><li>Logging system unreachable</li><li>Alerting system (like email/slack/Teams) failure</li></ul><h4>Exceptions to Handle:</h4><blockquote>ConnectionError<br>TimeoutError<br>smtplib.SMTPException</blockquote><h3>✅ Best Practices</h3><ul><li>Use try-except-finally blocks around key pipeline steps</li><li>Implement custom exception classes if needed</li><li>Add logging in each exception block (logger.error)</li><li>Send alerts for critical failures (email/Teams)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc96c94369e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Delete Delta Files From Fabric Lakehouse]]></title>
            <link>https://medium.com/@jagdishmwagh/how-delete-delta-files-from-fabric-2d733ef310c0?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d733ef310c0</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 09:18:32 GMT</pubDate>
            <atom:updated>2025-03-28T09:19:34.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>While dropping a table in Microsoft Fabric, we sometimes notice that Delta files are not completely removed. This can cause issues when recreating the table, as the location may still contain old metadata or non-Delta files.</p><p>To resolve this, we first list the files in the target folder location, identify any remaining Delta files, and then perform the necessary actions to delete them. Once the location is clean, we proceed with recreating the table to ensure a fresh and error-free setup.</p><p>In <strong>Microsoft Fabric Lakehouse</strong>, dbutils is not supported like in Databricks. Instead, you should use <strong>Fabric-specific APIs</strong> to manage files.</p><h4>Error Message:</h4><blockquote>Fabric gettting this error while dropping and recreating rable| AnalysisException: [DELTA_CREATE_TABLE_WITH_NON_EMPTY_LOCATION] Cannot create table (‘lh_gold.t_dim_customer&#39;). The associated location (&#39;abfss://7eaf3bc1-2d0c-43d9-bcbf-12b1195cb9a5@onelake.dfs.fabric.microsoft.com/cd923083-448c-43a9-bc86-94cfc95a7bc8/Tables/t_dim_customer&#39;) is not empty and also not a Delta table.</blockquote><p>Follow below steps to perform delta file deletion process.</p><p>1. Check if the Location Contains Files</p><p>from pyspark.sql.functions import col</p><blockquote>files = mssparkutils.fs.ls(“abfss://<a href="/service/mailto:7eaf3bc1-2d0c-43d9-bcbf-12b1195cb9a5@onelake.dfs.fabric.microsoft.com">7eaf3bc1–2d0c-43d9-bcbf-12b1195cb9a5@onelake.dfs.fabric.microsoft.com</a>/cd923083–448c-43a9-bc86–94cfc95a7bc8/Tables/t_dim_customer”)<br>display(files)</blockquote><p>2. Delete Non-Delta Files (If Any)</p><blockquote>mssparkutils.fs.rm(“abfss://<a href="/service/mailto:7eaf3bc1-2d0c-43d9-bcbf-12b1195cb9a5@onelake.dfs.fabric.microsoft.com">7eaf3bc1–2d0c-43d9-bcbf-12b1195cb9a5@onelake.dfs.fabric.microsoft.com</a>/cd923083–448c-43a9-bc86–94cfc95a7bc8/Tables/t_fact_day_sales”, recurse=True)</blockquote><p>3. Drop the Table Before Recreating</p><blockquote>DROP TABLE IF EXISTS lh_gold.t_fact_day_sales;</blockquote><h4><strong>4. Create the Table Again Using Delta Format</strong></h4><blockquote>CREATE TABLE lh_gold.t_fact_day_sales<br>USING DELTA<br>LOCATION ‘abfss://<a href="/service/mailto:7eaf3bc1-2d0c-43d9-bcbf-12b1195cb9a5@onelake.dfs.fabric.microsoft.com">7eaf3bc1–2d0c-43d9-bcbf-12b1195cb9a5@onelake.dfs.fabric.microsoft.com</a>/cd923083–448c-43a9-bc86–94cfc95a7bc8/Tables/t_fact_day_sales’;</blockquote><h3>Alternative: Delete the Folder Manually</h3><p>If you are unable to delete files programmatically, try these options:</p><ul><li><strong>OneLake Explorer</strong> → Navigate to Tables/t_fact_day_sales and delete the folder.</li><li><strong>Azure Storage Explorer</strong> → Connect to the Fabric OneLake storage and manually delete the folder.</li></ul><p>Once the folder is clean, retry the table creation.</p><p>Note: External table we can easily apply alternative way to drop the folder but when we are working with managed table then we have to use fabric api as above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d733ef310c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and Managing Secret Scopes in Azure Databricks]]></title>
            <link>https://medium.com/@jagdishmwagh/creating-and-managing-secret-scopes-in-azure-databricks-63d8eccd33cd?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/63d8eccd33cd</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 22:12:54 GMT</pubDate>
            <atom:updated>2025-03-25T22:17:06.219Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Secrets management is a crucial aspect of securing sensitive information like database credentials, API keys, and tokens in Azure Databricks. Azure Databricks provides a built-in mechanism to store and manage secrets using <strong>Databricks Secret Scopes</strong>. This article walks you through creating, managing, and accessing secrets securely within Azure Databricks.</p><h4>Why Use Secret Scopes in Databricks?</h4><ul><li><strong>Security</strong>: Prevents hardcoding sensitive information in notebooks.</li><li><strong>Access Control</strong>: Provides fine-grained permissions using Databricks ACLs.</li><li><strong>Integration</strong>: Seamless integration with Azure Key Vault and Databricks-backed storage.</li></ul><h4>Types of Secret Scopes in Databricks</h4><ol><li><strong>Databricks-Backed</strong>: Managed directly within Databricks using the CLI.</li><li><strong>Azure Key Vault-Backed</strong>: Uses Azure Key Vault to store secrets securely.</li></ol><h4>Creating a Databricks-Backed Secret Scope</h4><h4>Step 1: Install Databricks CLI</h4><p>Ensure you have the Databricks CLI installed on your local machine. If not, install it using:</p><blockquote>pip install databricks-cli</blockquote><h4>Step 2: Authenticate to Azure Databricks</h4><p>Authenticate the CLI with your Azure Databricks workspace:</p><blockquote>databricks configure — host https://&lt;databricks-instance&gt; — token</blockquote><p>Enter your Databricks token when prompted.</p><h4>Step 3: Create a Secret Scope</h4><p>Run the following command to create a new secret scope:</p><blockquote>databricks secrets create-scope — scope &lt;scope-name&gt;</blockquote><p>For example:</p><blockquote>databricks secrets create-scope — scope my-secret-scope</blockquote><h4>Step 4: Add a Secret to the Scope</h4><p>To add a secret (e.g., a database password), use:</p><blockquote>databricks secrets put — scope my-secret-scope — key db-password</blockquote><p>You’ll be prompted to enter the secret value securely.</p><h4>Step 5: Retrieve and Use Secrets in Notebooks</h4><p>To retrieve a stored secret in a notebook:</p><blockquote>password = dbutils.secrets.get(scope=”my-secret-scope”, key=”db-password”)<br>print(password) # Avoid printing secrets in production!</blockquote><h4>Managing Secret Scopes</h4><h4>List Secret Scopes</h4><blockquote>databricks secrets list-scopes</blockquote><h4>List Secrets in a Scope</h4><p>databricks secrets list — scope my-secret-scope</p><h4>Delete a Secret</h4><p>databricks secrets delete — scope my-secret-scope — key db-password</p><h4>Delete a Secret Scope</h4><p>databricks secrets delete-scope — scope my-secret-scope</p><h4>Create an Azure Key Vault-backed secret scope</h4><ol><li>Go to databricks workspace and create URL and Run new in window:</li></ol><blockquote>https://&lt;databricks-instance&gt;#secrets/createScope</blockquote><blockquote>This URL is case sensitive. For example, scope in createScope must use an uppercase S).</blockquote><p>Below window will open automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*a0EoJF_BhHvZ5nPeDmmSoQ.png" /></figure><p>2. Enter the name of the secret scope. Secret scope names are case insensitive.</p><p>3. In Manage Principal select Creator or All workspace users to specify which users have the MANAGE permission on the secret scope.</p><p>4. Enter the DNS Name (for example, https://databrickskv.vault.azure.net/) and Resource ID, for example:</p><blockquote>/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/databricks-rg/providers/Microsoft.KeyVault/vaults/databricksKV</blockquote><p>These properties are available from the Settings &gt; Properties tab of an Azure Key Vault in your Azure portal.</p><p>5. Click Create.</p><h3>Conclusion</h3><p>Secret Scopes in Azure Databricks provide a secure and efficient way to manage sensitive credentials. By leveraging Databricks-backed or Azure Key Vault-backed scopes, organizations can ensure robust security practices while integrating with various services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63d8eccd33cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mounting Azure Data Lake Storage in Azure Databricks Using a Service Principal]]></title>
            <link>https://medium.com/@jagdishmwagh/mounting-azure-data-lake-storage-in-azure-databricks-using-a-service-principal-611e742caadb?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/611e742caadb</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 21:43:07 GMT</pubDate>
            <atom:updated>2025-03-25T21:43:07.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Mounting Azure Data Lake Storage (ADLS) in Azure Databricks allows seamless access to your data using standard file APIs. Using a <strong>Service Principal</strong> for authentication enhances security by eliminating the need to store credentials in notebooks. This blog post will guide you through the steps to mount ADLS in Azure Databricks using a Service Principal.</p><h3>Prerequisites</h3><p>Before proceeding, ensure you have:</p><ul><li>An <strong>Azure Subscription</strong> with an <strong>Azure Data Lake Storage (Gen2)</strong> account.</li><li>An <strong>Azure Databricks Workspace</strong>.</li><li>A <strong>Service Principal</strong> with access to the ADLS account.</li></ul><h3>Step 1: Create a Service Principal in Azure Active Directory (AAD)</h3><ol><li>Navigate to <strong>Azure Portal</strong> → <strong>Azure Active Directory</strong> → <strong>App registrations</strong>.</li><li>Click on <strong>+ New registration</strong>.</li><li>Provide a name (e.g., spn-databricks-mount) and choose an appropriate account type.</li><li>Click <strong>Register</strong>.</li><li>Note down the <strong>Application (client) ID</strong> and <strong>Directory (tenant) ID</strong>.</li><li>Navigate to <strong>Certificates &amp; secrets</strong> → <strong>Client secrets</strong> → <strong>+ New client secret</strong>.</li><li>Set the expiration duration and copy the <strong>client secret value</strong>.</li></ol><h3>Step 2: Assign Storage Permissions to the Service Principal</h3><ol><li>Navigate to <strong>Azure Storage Account</strong> → <strong>Access control (IAM)</strong>.</li><li>Click <strong>+ Add role assignment</strong>.</li><li>Select <strong>Storage Blob Data Contributor</strong> (or <strong>Storage Blob Data Reader</strong> for read-only access).</li><li>Assign it to your <strong>Service Principal</strong>.</li></ol><h3>Step 3: Mount ADLS in Databricks</h3><ol><li>Open <strong>Azure Databricks</strong> and launch a new <strong>Notebook</strong>.</li><li>Define the authentication credentials:</li><li>Client id and Client Secret access from azure keyvault scope. follow my article for setting up azure keyvault scope. here using scope kv-smaple-dev-01.</li></ol><blockquote>client_id = dbutils.secrets.get(scope=”kv-smaple-dev-01&quot;, key=”spn-test-client-key”)<br>client_secret= dbutils.secrets.get(scope=”kv-smaple-dev-01&quot;, key=”spn-test-secret-key”)</blockquote><blockquote>tenant_id = “&lt;your-tenant-id&gt;”<br>storage_account_name = “&lt;your-storage-account&gt;”<br>container_name = “&lt;your-container-name&gt;”<br>mount_point = f”/mnt/{container_name}”</blockquote><p>3. Configure the OAuth authentication:</p><blockquote><em>configs = {<br> “fs.azure.account.auth.type”: “OAuth”,<br> “fs.azure.account.oauth.provider.type”: “org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider”,<br> “fs.azure.account.oauth2.client.id”: client_id,<br> “fs.azure.account.oauth2.client.secret”: client_secret,<br> “fs.azure.account.oauth2.client.endpoint”: f”</em><a href="https://login.microsoftonline.com/%7Btenant_id%7D/oauth2/token"><em>https://login.microsoftonline.com/{tenant_id}/oauth2/token</em></a><em>&quot;<br>}</em></blockquote><p>4. Mount the storage account:</p><blockquote>try:<br> dbutils.fs.mount(<br> source=f”abfss://{container_name}@{storage_account_name}.dfs.core.windows.net/”,<br> mount_point=mount_point,<br> extra_configs=configs<br> )<br> print(f”Mounted at {mount_point}”)<br>except Exception as e:<br> print(f”Already mounted or error: {str(e)}”)</blockquote><p>5. Verify the mount:</p><blockquote>display(dbutils.fs.ls(mount_point))</blockquote><h3>Step 4: Read and Write Data</h3><p>To <strong>read a CSV file</strong>:</p><blockquote>df = spark.read.csv(f”{mount_point}/data/sample.csv”, header=True)<br>df.show()</blockquote><p>To <strong>write a DataFrame to ADLS</strong>:</p><blockquote>df.write.mode(“overwrite”).parquet(f”{mount_point}/output”)</blockquote><h3>Step 5: Unmount (if needed)</h3><p>If you need to unmount the storage, run:</p><blockquote>dbutils.fs.unmount(mount_point)</blockquote><h3>Conclusion</h3><p>Mounting ADLS in Databricks using a <strong>Service Principal</strong> is a secure and scalable approach. This method avoids storing secrets in notebooks and enables fine-grained access control. By following these steps, you can efficiently integrate your ADLS storage with Databricks for seamless data processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=611e742caadb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Microsoft Fabric Capacity Resume and Pause using Azure Automation Account]]></title>
            <link>https://medium.com/@jagdishmwagh/automating-microsoft-fabric-capacity-resume-and-pause-using-azure-automation-account-f89290dfcd57?source=rss-6877b8587c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/f89290dfcd57</guid>
            <dc:creator><![CDATA[Jagdish Wagh]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 14:02:37 GMT</pubDate>
            <atom:updated>2025-03-23T14:02:37.196Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Managing Microsoft Fabric capacity efficiently can significantly impact cost savings. By automating the start and stop operations based on usage patterns, you can optimize resource utilization and reduce unnecessary expenses. In this guide, we’ll walk through setting up a PowerShell runbook in Azure Automation to achieve this automation.</p><h3>Prerequisites</h3><p>Before we begin, make sure you have:</p><ul><li>An Azure subscription with permissions to create Azure Automation resources.</li><li>Knowledge of the Resource ID for your Microsoft Fabric capacity.</li><li>Basic understanding of PowerShell scripting and Azure Automation concepts.</li></ul><h3>Step 1: Setting Up Azure Automation Account</h3><ol><li><strong>Create an Automation Account</strong>: Navigate to the Azure portal, create a new Automation Account, and configure it with the necessary modules and permissions.</li></ol><h3>Step 2: Creating PowerShell Runbook</h3><ol><li><strong>Define Parameters</strong>: Create a PowerShell runbook with parameters for ResourceID and operation (resume or suspend).</li></ol><blockquote>Param(<br> [string]$ResourceID,<br> [string]$operation<br>)</blockquote><p><strong>2. Connect to Azure Account</strong>: Use Connect-AzAccount cmdlet to authenticate with Azure</p><blockquote>Connect-AzAccount -Identity</blockquote><p><strong>3. Acquire Access Token</strong>: Obtain an access token to authenticate API requests.</p><blockquote>$tokenObject = Get-AzAccessToken -ResourceUrl “<a href="https://management.azure.com/">https://management.azure.com/</a>&quot;<br>$token = $tokenObject.Token</blockquote><p><strong>4. Construct API URL</strong>: Build the URL for the REST API call based on the ResourceID and operation.</p><blockquote>$url = “<a href="https://management.azure.com$resourceid/$operation">https://management.azure.com$ResourceID/$operation</a>&quot; + “?api-version=2022–07–01-preview”</blockquote><p><strong>5. Set Headers and Invoke API</strong>: Define headers with authentication token and make the API call.</p><blockquote>$headers = @{<br> ‘Content-Type’ = ‘application/json’<br> ‘Authorization’ = “Bearer $token”<br>}<br>$response = Invoke-RestMethod -Uri $url -Method Post -Headers $headers</blockquote><p><strong>6. Output Result</strong>: Optionally, handle and log the response from the API call.</p><h3>Step 3: Testing and Execution</h3><ol><li><strong>Test the Runbook</strong>: Use the Azure portal to test the runbook with sample parameters to ensure it executes correctly.</li><li><strong>Schedule Automation</strong>: Set up schedules in Azure Automation to run the runbook during specified times (e.g., weekdays from 8 AM to 5 PM).</li></ol><h3>Conclusion</h3><p>Automating Microsoft Fabric capacity management through Azure Automation enables efficient resource utilization and cost savings. By following these steps, you can tailor the automation to your organization’s specific usage patterns and operational needs.</p><h3>Further Enhancements</h3><ul><li><strong>Error Handling</strong>: Implement robust error handling and logging to monitor runbook executions.</li><li><strong>Integration</strong>: Explore integrating with Azure Monitor or other monitoring solutions for proactive management.</li></ul><p><strong>Code Repository<br></strong><a href="https://github.com/jagdish0909/microsoft-fabric-resume-pause/tree/main">microsoft-fabric-resume-pause</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f89290dfcd57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>