<?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 Luis Lema on Medium]]></title>
        <description><![CDATA[Stories by Luis Lema on Medium]]></description>
        <link>https://medium.com/@lemalcs?source=rss-25a78a149629------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uyK3VOkRAUoEa7FqfF95MQ.png</url>
            <title>Stories by Luis Lema on Medium</title>
            <link>https://medium.com/@lemalcs?source=rss-25a78a149629------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:19:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lemalcs/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[Spinning up the Apache Spark History Server on Windows]]></title>
            <link>https://medium.com/@lemalcs/spinning-up-the-apache-spark-history-server-on-windows-e279bc99d1ea?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/e279bc99d1ea</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[spark-ui]]></category>
            <category><![CDATA[apache-hadoop]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 13:48:02 GMT</pubDate>
            <atom:updated>2026-10-08T13:48:02.833Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>History Server Web UI</strong> bundled with your local Apache Spark installation on Windows is <strong>not ready to use</strong> out of the box, but it’s easy to bring it to <strong>life</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*NQrit6bTgLk-9VRE61Yo9g.png" /></figure><blockquote><em>The History Server Web UI is a </em><strong><em>web application</em></strong><em> that lets you check the </em><strong><em>logs</em></strong><em> of your Apache Spark workflows.</em></blockquote><h3>Intro</h3><p>A few days ago, I was asked to try the <strong>Apache Spark data processing engine</strong> because the team wanted me to command several machines (both powerful and less powerful ones) to transform their data at will.</p><blockquote><em>By the way, Apache Spark lets you </em><strong><em>transform</em></strong><em> data in a </em><strong><em>distributed manner</em></strong><em> (by using many machines). That’s it.</em></blockquote><p><strong>Why Apache Spark?</strong> Well, there are a few reasons:</p><ul><li>Cost: you can use Apache Spark for free.</li><li>Maturity: born in 2010, it’s pretty stable by now.</li><li>A friend of a friend told me they use it, too.</li></ul><p><strong>And what about SQL Server?</strong></p><ul><li>It costs money, and Azure SQL has a free tier, but it has limits.</li><li>It’s older than Apache Spark.</li><li>An acquaintance told me it’s quite reliable, and it is.</li></ul><p><strong>Why was I asked to try Apache Spark?</strong> Sorry, I didn’t ask.</p><h3>Heads up</h3><p>As of this writing, these are the versions I used:</p><ul><li>Windows 11 25H2</li><li>Apache Spark 3.5.8</li></ul><p>So, the steps I’ll describe in this post might not apply in the future. That’s how software works, unfortunately.</p><h3>Install Apache Spark</h3><p><em>(You can skip this section if you already have a working instance of Apache Spark.)</em></p><p>I have to clarify that although Spark is made with love <strong>for Linux</strong> environments, it <strong>also works</strong> on <strong>Windows</strong>.</p><p>Now, let’s go through the steps.</p><h4>1. Download Spark</h4><p>You can get it from the <a href="https://spark.apache.org/downloads.html">Spark website</a>.</p><p>There is <strong>no installer</strong> for Spark (sadly).</p><p>The downloaded file is just a ZIP file that you have to <strong>unzip into any folder</strong> on your machine.</p><h4>2. Download Hadoop libraries</h4><p>Spark is self-sufficient and <strong>does not need Hadoop</strong>, but it does need some of its libraries.</p><p>Download Hadoop from the <a href="https://github.com/steveloughran/winutils">GitHub repository</a>.</p><p>As of now, the latest released version is <strong>2.8.1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sx6WFgtGFW1oUmO1i_-aeA.png" /></figure><p>Copy <strong>winutils.exe</strong> to the bin folder in the Spark ZIP file you downloaded in step 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*nuvavqKm5mW8bm4bb2j38Q.png" /></figure><p>In my case, the Spark folder is:</p><pre>D:\spark-3.5.8-bin-hadoop3</pre><p>So, the bin folder is here:</p><pre>D:\spark-3.5.8-bin-hadoop3\bin</pre><h4>3. Set the environment variable</h4><p>Create this <strong>environment variable</strong>:</p><p>HADOOP_HOME</p><p>With this <strong>value</strong>:</p><p>D:\spark-3.5.8-bin-hadoop3</p><p>You’ll have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CVkn2GMcU_LXjlyMDxHRA.png" /></figure><p>Click <strong>OK</strong> if you’re using the graphical user interface.</p><blockquote><em>You can access the environment variables dialog by going to </em><strong>Start</strong><em> and typing </em><strong>Edit Environment variables for your account.</strong></blockquote><h4>4. Run the Spark engine</h4><p>There are <strong>no .exe files</strong> for Spark on Windows (enthralling).</p><p>You run Spark by executing <strong>the .bat files</strong> located in the bin folder of the ZIP file you downloaded in step 1.</p><p>Now, open a <strong>PowerShell</strong> window, navigate to that bin folder, and run the <strong>spark-shell.cmd</strong> file:</p><pre>cd D:\spark-3.5.8-bin-hadoop3\bin<br>.\spark-shell.cmd</pre><p>You should see this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAqGabdn7tWUYpmfPrZYxA.png" /></figure><p>If the <strong>Spark logo</strong> is drawn in your terminal, then Spark is <strong>alive</strong>!</p><p>Type :quit to exit the Spark shell.</p><blockquote><em>If you noticed, the Spark Web UI address points to </em><strong><em>host.docker.internal</em></strong><em> because </em><strong><em>Docker Desktop</em></strong><em> might be installed on Windows. Otherwise, you’ll see an IP address or the machine name.</em></blockquote><p>If you prefer the ancient <strong>Windows Command Prompt</strong>, use this:</p><pre>cd D:\spark-3.5.8-bin-hadoop3\bin<br>D:<br>spark-shell.cmd</pre><h3>Wake up the Spark History Server</h3><p>Now, let’s run the <strong>Spark History Server</strong> in a browser and behold the beauty of your <strong>Spark workflow executions</strong>.</p><p>Go to your <strong>Spark folder</strong> and open the <strong>spark-defaults.conf</strong> file located in the conf folder. On my machine, it’s here:</p><pre>D:\spark-3.5.8-bin-hadoop3\conf\spark-defaults.conf</pre><p>You will find some <strong>commented lines</strong>, as it’s just a regular <strong>text file</strong>.</p><p>If you want to use the D:/forSpark folder, add this line at the end of the file:</p><pre>spark.history.fs.logDirectory file:///D:/forSpark</pre><blockquote><em>On </em><strong><em>Windows</em></strong><em>, remember to </em><strong><em>replace</em></strong><em> the backslashes () with forward slashes (/).</em></blockquote><p>You can replace D:/forSpark with any other path you wish.</p><p>This is an example of the <strong>spark-defaults.conf</strong> file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCaZm9Vd6BUf0aUk_Ad8wQ.png" /></figure><p><strong>Save</strong> the changes.</p><p>Next, open a PowerShell window in the bin folder of your Spark folder and run:</p><pre>.\spark-class.cmd org.apache.spark.deploy.history.HistoryServer</pre><p>Spark will promptly <strong>spin up a web server</strong> and show you the address it’s listening on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uixpk7E0n4Rz6v6Yj8q96g.png" /></figure><p>I got the address http://host.docker.internal:18080, but you can also use the <strong>loopback address</strong>:</p><pre>http://127.0.0.1:18080/</pre><p>Type the Spark History Server address (URL) into your preferred browser, and you’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*toeqpYzDuLEUw67De3jSuw.png" /></figure><p>And there you go!</p><p>If you enabled <strong>event logs</strong> for your Spark workflows, they will be listed in a <strong>table</strong>, as you can see in the screenshot.</p><p>Just in case, you can <strong>enable</strong> event logs for Spark workflows with these configuration keys:</p><pre>spark.eventLog.enabled true<br>spark.eventLog.dir file:///D:/forSpark</pre><p>Use spark.eventLog.dir to specify the <strong>location </strong>of the logs. It should be the <strong>same </strong>as the location <strong>configured</strong> for the History Server.</p><h3>Summary</h3><p>Apache Spark does not enable the History Server by default.</p><p>But the History Server can be a <strong>valuable tool for debugging</strong> your workflows when they go rogue or when you want to know what the heck is going on <strong>underground</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*G359Ftt7UHfiCS8Dv0Kb3A.png" /><figcaption>I see…</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e279bc99d1ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bulk inserts with mssql-python and SQL Server]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@lemalcs/bulk-inserts-with-mssql-python-and-sql-server-4900036939da?source=rss-25a78a149629------2"><img src="https://cdn-images-1.medium.com/max/1378/1*YFtWAM9Zaj4-4YTFUax2IQ.png" width="1378"></a></p><p class="medium-feed-snippet">The Python package Microsoft made for SQL Server now lets you make bulk inserts!</p><p class="medium-feed-link"><a href="https://medium.com/@lemalcs/bulk-inserts-with-mssql-python-and-sql-server-4900036939da?source=rss-25a78a149629------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@lemalcs/bulk-inserts-with-mssql-python-and-sql-server-4900036939da?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/4900036939da</guid>
            <category><![CDATA[sqlserver2025]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bulk-insert]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 04:43:02 GMT</pubDate>
            <atom:updated>2026-08-22T04:43:02.537Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Splitting a partition function when SQL Server columnstore indexes get
in the way (for SQL Server)]]></title>
            <link>https://medium.com/@lemalcs/splitting-a-partition-function-when-sql-server-columnstore-indexes-get-in-the-way-for-sql-server-8fd4f22d31a2?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd4f22d31a2</guid>
            <category><![CDATA[sqlserver2025]]></category>
            <category><![CDATA[columnstore-index]]></category>
            <category><![CDATA[data-partitioning]]></category>
            <category><![CDATA[rowstore-index]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Tue, 26 May 2026 06:12:02 GMT</pubDate>
            <atom:updated>2026-05-26T06:12:02.584Z</atom:updated>
            <content:encoded><![CDATA[<p>In SQL Server, columnstore indexes <strong>prevent </strong>splitting partition functions when the partition <strong>contains data</strong>.</p><p>Rowstore indexes <strong>do</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ura4WPt3W_-s55TAG9lDQ.png" /></figure><p>This post will focus on handling columnstore indexes.</p><p>I’ll show you how to deal with <strong>columnstore indexes</strong> in turn.</p><h3><strong>The backstory</strong></h3><p><em>(You can skip this section if you’re only interested in the solution) Recently, I tried </em>to <strong>split a partition function </strong>used by both</p><p><strong>rowstore </strong>and <strong>columnstore </strong>tables.</p><p>With a grin on my face, I ran the ALTER PARTITION FUNCTION… and got this error:</p><blockquote><em>SPLIT clause of ALTER PARTITION statement failed because the partition is not empty. Only empty partitions can be split in</em></blockquote><blockquote><em>when a columnstore index exists on the table. Consider an ALTER TABLE SWITCH operation from one of the nonempty</em></blockquote><blockquote><em>partitions on table ‘DaysWithoutCoding’ to a temporary staging table and then re-attempt the ALTER PARTITION SPLIT</em></blockquote><blockquote><em>operation. Once completed, use ALTER TABLE SWITCH to move the staging table partition back to the original source table.</em></blockquote><p>What the he…?</p><p>I considered <strong>dropping and recreating </strong>the columnstore indexes (which would take a <strong>long time</strong>).</p><ul><li><strong>Truncating </strong>the table partition wasn’t possible; I need to keep the data.</li><li><strong>Creating </strong>a new table and renaming the old one, while possible, would upset current users.</li></ul><p>I didn’t like <strong>either </strong>of the above options.</p><p>What else could I do?</p><p>Just before choosing one option, I saw a shed of light in this post.</p><p>Let’s walk through that <strong>solution </strong>now.</p><h3><strong>Preparing the test environment</strong></h3><p><em>(Again, if you want the solution right away, please go to the next section.)</em></p><p>Here is a simple scenario illustrating the split issue with columnstore indexes.</p><p>⚠️</p><p><strong><em>Important: </em></strong><em>You need to use </em><strong><em>SQL Server 2016 or later </em></strong><em>for the test scenario of this post. Earlier versions of SQL Server </em><strong><em>don’t</em></strong></p><p><em>fully support columnstore indexes.</em></p><p>I’ll use SQL Server 2022 and the AdventureWorks2017 database for this demo.</p><p>Run this code in your SQL Server instance:</p><pre>use AdventureWorks2017<br>go<br><br>create partition function myDateRangePF (datetime2(0))  <br>    as range right for values (&#39;2022-10-01&#39;, &#39;2022-11-01&#39;, &#39;2022-12-01&#39;)  <br>go  <br>  <br>create partition scheme myRangePS  <br>    as partition myDateRangePF  <br>    all to (&#39;SECONDARY&#39;)  <br>go  <br>  <br>drop table if exists dbo.DaysWithoutCoding  <br>create table dbo.DaysWithoutCoding<br>(<br>   JournalDate datetime2(0), <br>   Thoughts nvarchar(256)<br>)  <br>on myRangePS (JournalDate)  <br>  <br>  <br>go  <br>  <br>insert into dbo.DaysWithoutCoding (JournalDate, Thoughts)  <br>values  <br>    (&#39;2022-10-15&#39;, &#39;Good day&#39;),  <br>    (&#39;2022-10-20&#39;, &#39;Great day&#39;),  <br>    (&#39;2022-11-10&#39;, &#39;Bad day&#39;),  <br>    (&#39;2022-11-05&#39;, &#39;Nice day&#39;),  <br>    (&#39;2022-12-25&#39;, &#39;Fun day&#39;)  <br>  <br>go </pre><p>Use this query to get the list of tables’ partitions.</p><pre>use AdventureWorks2017<br>go<br><br>SELECT SCHEMA_NAME(t.schema_id) AS SchemaName, t.name AS TableName, i.name AS IndexName,  <br>    p.partition_number AS PartitionNumber, f.name AS PartitionFunctionName, p.rows AS Rows, rv.value AS BoundaryValue,  <br>CASE WHEN ISNULL(rv.value, rv2.value) IS NULL THEN &#39;N/A&#39;  <br>ELSE  <br>    CASE WHEN f.boundary_value_on_right = 0 AND rv2.value IS NULL THEN &#39;&gt;=&#39;  <br>        WHEN f.boundary_value_on_right = 0 THEN &#39;&gt;&#39;  <br>        ELSE &#39;&gt;=&#39;  <br>    END + &#39; &#39; + ISNULL(CONVERT(varchar(64), rv2.value), &#39;Min Value&#39;) + &#39; &#39; +  <br>        CASE f.boundary_value_on_right WHEN 1 THEN &#39;and &lt;&#39;  <br>                ELSE &#39;and &lt;=&#39; END  <br>        + &#39; &#39; + ISNULL(CONVERT(varchar(64), rv.value), &#39;Max Value&#39;)  <br>END AS TextComparison  <br>FROM sys.tables AS t  <br>JOIN sys.indexes AS i  <br>    ON t.object_id = i.object_id  <br>JOIN sys.partitions AS p  <br>    ON i.object_id = p.object_id AND i.index_id = p.index_id  <br>JOIN  sys.partition_schemes AS s  <br>    ON i.data_space_id = s.data_space_id  <br>JOIN sys.partition_functions AS f  <br>    ON s.function_id = f.function_id  <br>LEFT JOIN sys.partition_range_values AS r  <br>    ON f.function_id = r.function_id and r.boundary_id = p.partition_number  <br>LEFT JOIN sys.partition_range_values AS rv  <br>    ON f.function_id = rv.function_id  <br>    AND p.partition_number = rv.boundary_id  <br>LEFT JOIN sys.partition_range_values AS rv2  <br>    ON f.function_id = rv2.function_id  <br>    AND p.partition_number - 1= rv2.boundary_id  <br>WHERE  <br>    t.name = &#39;DaysWithoutCoding&#39;  <br>ORDER BY t.name, p.partition_number;</pre><p>You should have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sn5nrPxboXwP5eAVd-lxgg.png" /></figure><p>The table above shows the <strong>boundaries </strong>of each partition and the <strong>number of rows </strong>in each.</p><h3><strong>Splitting the non-empty partition from the columnstore table</strong></h3><p>You have to perform these steps:</p><ol><li>Create a <strong>partitioned </strong>stage table using the <strong>same partition function </strong>as the original table.</li><li>Create a <strong>columnstore index </strong>in the stage table.</li><li><strong>Switch </strong>out the target partition from the original table to the <strong>stage </strong>table.</li><li><strong>Drop </strong>the columnstore index from the stage table.</li><li><strong>Split </strong>the partition function as needed.</li><li><strong>Recreate </strong>the columnstore index in the stage table.</li><li>Switch the data back from the <strong>stage </strong>table to the <strong>original </strong>table.</li></ol><blockquote><strong>Note for step 5: </strong>When splitting a partition function, you must <strong>specify the filegroup </strong>for the new partition.</blockquote><p>Following the <strong>scenario </strong>of the last section, suppose you want to continue your journal for <strong>2023</strong>.</p><p>Since our partition function, myDateRangePF <strong>doesn’t </strong>have partitions for the year 2023, let’s create partitions for <strong>the first three months of 2023 </strong>with these statements:</p><pre>use AdventureWorks2017<br>go<br><br>ALTER PARTITION FUNCTION myDateRangePF ()  <br>SPLIT RANGE (&#39;2023-01-01&#39;)<br><br>ALTER PARTITION FUNCTION myDateRangePF ()  <br>SPLIT RANGE (&#39;2023-02-01&#39;)<br><br>ALTER PARTITION FUNCTION myDateRangePF ()  <br>SPLIT RANGE (&#39;2023-03-01&#39;)</pre><p>You should get this <strong>error</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQICWj4i7XXH6ZtFY17eHQ.png" /></figure><p>Indeed, SQL Server <strong>doesn’t </strong>allow us to split a partition function when there is <strong>data </strong>in a partition of a table with a <strong>columnstore </strong>index 🫤.</p><p>Now, we are going to fix that with the following code:</p><pre>use AdventureWorks2017<br>go<br><br>/* 1. Create a **partitioned** stage table using the **same partition function** as the original table. */  <br>create table dbo.DaysWithoutCoding_Stage (JournalDate datetime2(0), Thoughts nvarchar(256))  <br>    on myRangePS (JournalDate)  <br>  <br>/* 2. Create a **columnstore index** in the stage table. */  <br>create clustered columnstore index CI_DaysWithoutCoding_Stage on dbo.DaysWithoutCoding_Stage  <br>    ON myRangePS (JournalDate)  <br>  <br>/* 3. Switch out the target partition from the original table to the stage table. */  <br>alter table DaysWithoutCoding  <br>    switch partition 4 to DaysWithoutCoding_Stage partition 4  <br>  <br>/* 4. Drop the columnstore index from the stage table. */  <br>drop index DaysWithoutCoding_Stage.CI_DaysWithoutCoding_Stage  <br>  <br>/* 5. Split the partition function. */  <br>ALTER PARTITION FUNCTION myDateRangePF ()  <br>SPLIT RANGE (&#39;2023-01-01&#39;)  <br>  <br>/* Specify the filegroup for the new partition */  <br>ALTER PARTITION SCHEME myRangePS  <br>NEXT USED &#39;SECONDARY&#39;  <br>ALTER PARTITION FUNCTION myDateRangePF ()  <br>SPLIT RANGE (&#39;2023-02-01&#39;)  <br>  <br>/* Specify the filegroup for the new partition */  <br>ALTER PARTITION SCHEME myRangePS  <br>NEXT USED &#39;SECONDARY&#39;  <br>ALTER PARTITION FUNCTION myDateRangePF ()  <br>SPLIT RANGE (&#39;2023-03-01&#39;)  <br>  <br>/* 6. Recreate the columnstore index in the stage table. */  <br>create clustered columnstore index CI_DaysWithoutCoding_Stage on dbo.DaysWithoutCoding_Stage  <br>    ON myRangePS (JournalDate)  <br>  <br>/* 7. Switch the data back from the stage table to the original table. */  <br>alter table DaysWithoutCoding_Stage  <br>    switch partition 4 to DaysWithoutCoding partition 4</pre><blockquote>The <strong>sixth </strong>step (Recreate the columnstore index) will take time. Apart from that, the other steps execute in <strong>seconds</strong>!. Please be patient.</blockquote><p>Let’s check out the partitions again:</p><p>And there you go!</p><p><strong>Three new </strong>partitions for January, February, and March <strong>2023</strong>.</p><p>This way, you can overcome the <strong>limitation that SQL Server </strong>puts on <strong>splitting </strong>partition functions that are used in <strong>columnstore</strong></p><p>indexes. 😌</p><h3><strong>Summary</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVGyPyQ0QsouDsmX0Lghkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPBVYAFeDjk2kWY1RzroNg.png" /></figure><ul><li>For <strong>rowstore </strong>indexes, splitting partition functions works in <strong>either empty or non-empty </strong>partitions.</li><li>For <strong>columnstore </strong>indexes, splitting partition functions works <strong>only in empty </strong>partitions.</li><li>For <strong>splitting </strong>partition functions used by <strong>columnstore </strong>indexes, except if you are OK with creating a new table or truncating that partition, you should use a <strong>stage table</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_523rvE3K4aDm5FBUco7g.png" /><figcaption>I drew this.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd4f22d31a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Block your read-only users from executing system stored procedures in SQL Server]]></title>
            <link>https://medium.com/@lemalcs/block-your-read-only-users-from-executing-system-stored-procedures-in-sql-server-e851c5ca9c98?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/e851c5ca9c98</guid>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Sat, 02 May 2026 04:10:51 GMT</pubDate>
            <atom:updated>2026-05-02T04:10:51.285Z</atom:updated>
            <content:encoded><![CDATA[<p>If you <strong>grant</strong> your users <strong>read permissions</strong> on the tables of your SQL Server database, they can still <strong>execute</strong> system stored procedures!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udUJNF00O-aA-IYofmlTvQ.png" /></figure><p><strong>Stop them </strong>in their tracks with an error message like this:</p><blockquote>The EXECUTE permission was denied on the object ‘sp_tables’, database ‘mssqlsystemresource’, schema ‘sys’.</blockquote><p>If you planned to grant your users only the <strong>db_datareader</strong> role to avoid this scenario, you’re <strong>wrong</strong> — that role <strong>won’t prevent</strong> them from <strong>executing system stored procedures</strong> such as sp_help or sp_tables.</p><h3>Why users might need to execute system stored procedures</h3><p>Some applications might <strong>want to scrape your database</strong> for <strong>legitimate</strong> reasons, like assisting other applications, for example:</p><ul><li>SQL Editors</li><li>Monitoring tools</li><li>The “next generation” data platform</li></ul><p>These types of applications are often called web spiders 🕷️, robots 🤖, or <strong>agents</strong> 👥.</p><h3>Why block the execution of system stored procedures</h3><p>But there are cases when you <strong>don’t want them</strong> to scrape your database metadata.</p><blockquote><strong><em>Database metadata</em></strong><em> includes: table definitions, stored procedure bodies, function source code, triggers — to name a few.</em></blockquote><p>Some reasons may be:</p><ul><li>Privacy</li><li>Compliance with regulators</li><li>Security concerns</li></ul><p>(Add your reason to the list 🙂)</p><h3>How to block execution</h3><p>Let’s <strong>block </strong>the execution of the sp_tables <strong>system </strong>stored procedure.</p><blockquote><em>I’ve seen applications use </em><em>sp_tables </em><strong><em>behind the scenes </em></strong><em>to get the list of tables when building catalogs or populating a graphical user interface.</em></blockquote><p>Here are the tasks we’ll do:</p><ol><li>Create a <strong>SQL Server login</strong></li><li>Grant the login the db_datareader <strong>role</strong> in the <a href="https://github.com/Microsoft/sql-server-samples/releases/download/adventureworks/AdventureWorks2025.bak">AdventureWorks2025</a> database</li><li>Block the execution of the sp_tables stored procedure</li></ol><p>I’ll use a <strong>SQL Server 2025</strong> instance.</p><h4>1. Create a SQL Server login</h4><p>Log in to your SQL Server instance with a user that can <strong>create</strong> logins.</p><p>Run these statements to create a login:</p><pre>USE master<br>GO<br>CREATE LOGIN weasel WITH PASSWORD=N&#39;your password for the weasel&#39;, CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF<br>GO</pre><h4>2. Grant the db_datareader role</h4><p>Let’s grant the weasel login the db_datareader role with this:</p><pre>USE AdventureWorks2025<br>GO<br>CREATE USER weasel FOR LOGIN weasel<br>GO<br>USE AdventureWorks2025<br>GO<br>ALTER ROLE db_datareader ADD MEMBER weasel<br>GO</pre><p>Every time you <strong>grant</strong> permissions in a database to a login, you <strong>must create a database user</strong> linked to that login.</p><p>The db_datareader role enables the weasel user to read tables but <strong>not modify data</strong> in the AdventureWorks2025 database.</p><h4>3. Block the execution of sp_tables</h4><p>Since the weasel might go rogue tomorrow, we’re going to block the execution of the sp_tables system stored procedure by running this code:</p><pre>USE master<br>GO<br>CREATE USER fortheweasel FOR LOGIN weasel<br>GO<br>USE master<br>GO<br>DENY EXECUTE ON sys.sp_tables TO fortheweasel<br>GO</pre><p>In the above code we <strong>create a user</strong> in the master database that binds to the weasel login.</p><blockquote><em>The user name in the database </em><strong><em>doesn’t</em></strong><em> have to be the </em><strong><em>same</em></strong><em> as the SQL Server login.</em></blockquote><p>Next, we <strong>block execution</strong> of the sp_tables stored procedure using the DENY EXECUTE statement.</p><h3>Testing the execution blocking</h3><p><strong>Log in</strong> to the SQL Server instance using the weasel user name.</p><p>First, test if the weasel can <strong>query</strong> user tables by running:</p><pre>USE AdventureWorks2025<br>GO<br><br>SELECT * FROM Production.BillOfMaterials</pre><figure><img alt="Rows of the table Production.BillOfMaterials." src="https://cdn-images-1.medium.com/max/1024/1*yj5ONnFo7QhNS7bRM-l54A.png" /></figure><p>Great! The user <strong>can</strong> query tables.</p><p>Now, if our weasel dares to execute the sp_tables stored procedure with:</p><pre>USE AdventureWorks2025<br>GO<br><br>EXEC sp_tables</pre><p>They’ll get the following error message:</p><figure><img alt="Message: The EXECUTE permission was denied on the object ‘sp_tables’, database ‘mssqlsystemresource’, schema ‘sys’." src="https://cdn-images-1.medium.com/max/1024/1*6pXN1ikr6e7Nf3TOkdfDuA.png" /></figure><h4>Why the user got the permission denied error</h4><p>The sp_tables system stored procedure lives in an internal database called mssqlsystemresource.</p><blockquote><em>The </em><em>mssqlsystemresource is a database that contains the </em><strong><em>system objects </em></strong><em>SQL Server needs to accomplish tasks like monitoring your instance or viewing user database metadata. You </em><strong><em>can’t access </em></strong><em>this database directly.</em></blockquote><p>But since we <strong>denied execution </strong>of that stored procedure in the <em>Block the execution of sp_tables</em> section using the master database, SQL Server <strong>doesn’t allow</strong> the weasel to execute sp_tables.</p><p>Just what we wanted! 🙃</p><h3>Summary</h3><ul><li>Grant the db_datareader role to users who <strong>only</strong> need to <strong>read data</strong> from the database.</li><li>The db_datareader role <strong>doesn’t prevent</strong> users from executing system stored procedures.</li><li>Use the DENY EXECUTE statement in the master database to <strong>block execution</strong> of system stored procedures.</li><li>You can block <strong>other system stored procedures </strong>like sp_help, sp_helptext, sp_columns, and similar ones.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_fboen7g1mtwoVP9XioCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tmy-LseVUS6EKHEJ2yJqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_RY86Soc4rWKv-GQOYYUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeUMuQs5nubuZFqKr2j5oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZL2lFJlkaeWQQYuVfpbiCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3WhJVIMAC-gUNQR_s4fww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrzhYBzzc4Osvz3IeVmlgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyexFuZHSCgxijW68bRU0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TT-ebXfgAH0BNPa7SU0ZQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vh9IMGlNCc-qnZBPxS3kNw.png" /><figcaption>My hand-drawn images 🙂.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e851c5ca9c98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Call Rust code from SQL Server using CLR functions]]></title>
            <link>https://medium.com/@lemalcs/call-rust-code-from-sql-server-using-clr-functions-edf79ad476d8?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf79ad476d8</guid>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[sqlserver2025]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 03:50:13 GMT</pubDate>
            <atom:updated>2026-02-20T03:50:13.953Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s make SQL Server taste the speed of Rust through the means of <strong>Common Language Runtime (CLR) functions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxowf0HDpJLvHRt_BL05pw.png" /></figure><p>SQL Server <strong>doesn’t support </strong>calling <strong>Rust functions </strong>natively, but we can use CLR functions, which let us do things SQL Server can only dream of 😌.</p><blockquote>CLR functions have been available since S<strong>QL S</strong>erver 2005.</blockquote><p>The <strong>body</strong> of a CLR function is implemented in the <strong>.NET Framework</strong> platform.</p><blockquote>The .NET Framework is a <strong>legacy </strong>platform, replaced by .NET (formerly .NET Core). The former is <strong>supported</strong> by Microsoft but will not evolve further. The latter cannot be used from SQL Server.</blockquote><p>With the introduction covered, let’s dive into coding the solution.</p><h3>Describing the environment we will use</h3><p>First of all, this is my environment:</p><ul><li><strong>Visual Studio </strong>2026 (with the .NET <strong>desktop development </strong>workload)</li><li>SQL Server 2025 <strong>Enterprise Developer</strong></li><li>Windows 11</li></ul><h4>Creating the Rust project</h4><p>Run these commands in the terminal:</p><pre>cargo new rust_for_sqlserver --lib<br>cd rust_for_sqlserver</pre><p>Open the lib.rs file and replace the code with this function:</p><pre>pub fn remove_numbers(the_string: String) -&gt; String {<br>    let mut result = String::new();<br>    for c in the_string.chars() {<br>        if !c.is_numeric() {<br>            result.push(c);<br>        }<br>    }<br><br>    result<br>}<br><br>#[cfg(test)]<br>mod tests {<br>    use super::*;<br><br>    #[test]<br>    fn test_remove_numbers() {<br>        let result = remove_numbers(&quot;abc123&quot;.to_string());<br>        assert_eq!(result, &quot;abc&quot;);<br>    }<br>}</pre><p>I’ve added a <strong>test </strong>function. If you want to run the test, use this command:</p><pre>cargo test test_remove_numbers</pre><p>Now, we need to <strong>compile </strong>this function into a .dll library so it can be used from a <strong>CLR function</strong> written in the .NET Framework.</p><h4>Compile Rust into a dll library</h4><p>Add the [lib] section to the Cargo.toml file:</p><pre>[package]<br>name = &quot;rust_for_sqlserver&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2024&quot;<br><br>[dependencies]<br><br>[lib]<br>crate-type = [&quot;cdylib&quot;]</pre><p>cdylib is a <strong>build configuration option</strong> that tells Rust to export a <strong>C interface</strong> from Rust code.</p><p>Open the lib.rs file and add the following functions to add the <strong>C interfaces</strong>:</p><pre>use std::ffi::{CStr, CString};<br>use std::os::raw::c_char;<br><br>// [...]<br><br><br>#[unsafe(no_mangle)]<br>pub extern &quot;C&quot; fn remove_numbers_c(input: *const c_char) -&gt; *mut c_char {<br>    if input.is_null() {<br>        return std::ptr::null_mut();<br>    }<br><br>    let c_str = unsafe { CStr::from_ptr(input) };<br>    let input_str = match c_str.to_str() {<br>        Ok(s) =&gt; s,<br>        Err(_) =&gt; return std::ptr::null_mut(),<br>    };<br>    let result = remove_numbers(input_str.to_string());<br>    match CString::new(result) {<br>        Ok(c_string) =&gt; c_string.into_raw(),<br>        Err(_) =&gt; std::ptr::null_mut(),<br>    }<br>}<br><br>#[unsafe(no_mangle)]<br>pub extern &quot;C&quot; fn free_string(s: *mut c_char) {<br>    if !s.is_null() {<br>        unsafe {<br>            let _ = CString::from_raw(s);<br>        }<br>    }<br>}</pre><p>This code manages <strong>strings </strong>and frees memory to avoid <strong>leaks</strong>.</p><p>The procedure to <strong>call </strong>the free_string function from the .NET project will be described later.</p><p>Run this command to create the .dll file for Windows:</p><pre>cargo build --release --target x86_64-pc-windows-msvc</pre><p>Note that I’m targeting the <strong>x64 </strong>platform; this is important because the CLR function <strong>must also target</strong> x64.</p><p>The above command should create the .dll file in the target folder of your <strong>Rust project</strong>, for example:</p><pre>c:\rust_for_sqlserver\target\x86_64-pc-windows-msvc\release\draft_rust_for_sqlserver.dll</pre><p>On my machine, the library looks like this:</p><figure><img alt="The file explorer shows the rust_for_sqlserver.dll file on Windows." src="https://cdn-images-1.medium.com/max/443/1*2jf4ch34z5DbNcWxoboUog.png" /></figure><p>With the Rust library ready, it’s time to focus on the SQL Server <strong>integration</strong>.</p><h4>Create a .NET library project</h4><p>Open <strong>Visual Studio</strong> (2026) and create a <strong>Class Library (.NET Framework)</strong> project by going to the <strong>File &gt; New &gt; Project &gt; Solution…</strong> menu.</p><figure><img alt="Create new project dialog in Visual Studio 2026." src="https://cdn-images-1.medium.com/max/888/1*qYnhNOIeclwwxN1mLMvBHQ.png" /></figure><p>Click <strong>Next</strong>.</p><p>In the <strong>Configure your new project</strong>, set these values:</p><ul><li><strong>Project name</strong>: SSFunction</li><li><strong>Framework</strong>: .NET Framework 4.7.2</li></ul><figure><img alt="Configure your new project dialog in Visual Studio 2026." src="https://cdn-images-1.medium.com/max/890/1*GnpvMdmSETEBR5jW2DUlrQ.png" /></figure><p>Leave the other fields with their <strong>default </strong>values.</p><blockquote>You can target <strong>other .NET Framework versions if SQL Server supports them and they’re installed</strong>.</blockquote><p>Add the FunctionDefinitions.cs file and replace the code with this:</p><pre>using System;<br>using System.Runtime.InteropServices;<br>using Microsoft.SqlServer.Server;<br><br>namespace SSFunction<br>{<br>    public class FunctionDefinitions<br>    {<br>        [DllImport(@&quot;C:\rust_for_sqlserver\target\x86_64-pc-windows-msvc\release\rust_for_sqlserver.dll&quot;)]<br>        internal static extern IntPtr remove_numbers_c(string input);<br><br>        [SqlFunction(DataAccess = DataAccessKind.Read)]<br>        public static string RemoveNumbersWithRust2(string input)<br>        {<br>            if (input == null)<br>            {<br>                return null;<br>            }<br>            string result = remove_numbers_c(input);<br>            return result;<br>        }<br>    }<br>}</pre><p>The DllImport lets us execute <strong>native code</strong> from a .dll file.</p><p>Ensure that the DllImport parameter points to the <strong>full path </strong>of the Rust library ( .dll ).</p><p>Press Ctrl+B to <strong>compile </strong>the project.</p><p>In the <strong>project </strong>folder, you’ll find the bin\Debug folder, where the <strong>.NET library</strong> file called SSFunction.dll is located:</p><figure><img alt="SSFunction.dll compiled .NET library file." src="https://cdn-images-1.medium.com/max/345/1*bIGsEzkaJj-fdDh2H8qChQ.png" /></figure><p>We will <strong>upload</strong> the .dll file to SQL Server later.</p><h4>Security considerations for .NET assemblies</h4><p>Since we are executing <strong>native code </strong>(rust_for_sqlserver.dll file) from a .NET library SSFunction.dll file, SQL Server requires that the .NET library be a <strong>trusted assembly</strong>.</p><p>That’s because who knows what <strong>nasty code</strong> 😈 you are intending execute from a <strong>native library</strong>.</p><blockquote>Microsoft made SQL Server 2017 and <strong>later versions </strong>paranoid enough to mark .NET assemblies UNSAFE by <strong>default</strong>.</blockquote><p>You have two options to make SQL Server trust your <strong>.NET assembly</strong>:</p><ol><li><strong>Set</strong> the <a href="https://learn.microsoft.com/en-us/sql/relational-databases/security/trustworthy-database-property?view=sql-server-ver17">TRUSTWORTHY</a> database property to <strong>ON</strong>.</li><li><a href="https://learn.microsoft.com/en-us/dotnet/standard/assembly/sign-strong-name">Sign your .NET assembly</a> to give it a <strong>unique identity</strong>.</li></ol><blockquote>Allow any <strong>non-signed </strong>.NET assembly by using the <a href="https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sys-sp-add-trusted-assembly-transact-sql?view=sql-server-ver17">sys.sp_add_trusted_assembly</a> .</blockquote><p>The first option (TRUSTWORTHY ) is <strong>not recommended</strong> as it leaves your database open to <strong>malicious attacks</strong>.</p><p>I’ll go with the second option because it is the one <strong>Microsoft recommends</strong>.</p><blockquote><strong>Signing</strong> .NET assemblies <strong>prevents collisions </strong>when multiple assemblies have the <strong>same</strong> file name.</blockquote><h4>Signing the .NET assembly (library)</h4><p>As mentioned in the last section, we are going to <strong>sign </strong>our .NET library.</p><p>In Visual Studio, go to the menu <strong>Project &gt; SSFunction Properties</strong>.</p><p>Click in the <strong>Signing</strong> section, and check the <strong>Sign the assembly box</strong>. Expand the list from the <strong>Choose a strong name key file field</strong>, and select the <strong>&lt;New…&gt;</strong> item.</p><figure><img alt="Signing section in the Properties page of the SSFunction project." src="https://cdn-images-1.medium.com/max/902/1*jqjSnIYzTmPXkkgYNAMM5w.png" /></figure><p>In the <strong>Create Strong Name Key</strong> dialog, type a name in the <strong>Key file name</strong> field:</p><figure><img alt="Create Strong Name Key dialog for signing a .NET library." src="https://cdn-images-1.medium.com/max/440/1*g-haoxeBAxpEcOeKcv5bNw.png" /></figure><p>I will call the file ssfunctionkey.snk , feel free to choose <strong>another </strong>name.</p><p><strong>Uncheck</strong> the <strong>Protect my key file with a password</strong> option (you can also add a password if you wish).</p><p>Leave the other fields with their <strong>default </strong>values and click OK.</p><p>Visual Studio will <strong>create </strong>a file called ssfunctionskey.snk in the <strong>root </strong>of the project:</p><figure><img alt="ssfunctionskey.snk key file for the SSFunction project." src="https://cdn-images-1.medium.com/max/354/1*EiQFdU1EK3hC5WJlETlGYA.png" /></figure><p><strong>Compile</strong> the project again with Ctrl+B .</p><h4>Enabling the CLR in the SQL Server</h4><p><strong>Check </strong>if you have CLR enabled in SQL Server:</p><pre>SELECT name,<br>       value,<br>       value_in_use<br>FROM sys.configurations<br>WHERE<br>    name = &#39;clr enabled&#39;</pre><p>Next are the meanings of the value results:</p><ul><li>0: CLR is <strong>not </strong>enabled</li><li>1: CLR is <strong>enabled</strong></li></ul><p>If CLR is <strong>not</strong> enabled, run this code:</p><pre>sp_configure &#39;show advanced options&#39;, 1<br>GO<br>RECONFIGURE<br>GO<br>sp_configure &#39;clr enabled&#39;, 1<br>GO<br>RECONFIGURE<br>GO</pre><blockquote>Make sure your login to SQL Server has ALTER SETTINGS <strong>server-level permission</strong> to change or enable CLR.</blockquote><h4>Uploading the .NET library to SQL Server</h4><p>Time for some SQL Server bureaucracy to <strong>upload </strong>the SSFunction.dll file.</p><p>I’ll use an <strong>existing database </strong>called Household .</p><p>First and foremost, <strong>log</strong> in to SQL Server with an account that has the CONTROL <strong>permission</strong> in the master database.</p><p>Run the following code:</p><pre>USE master<br>GO<br>DROP MASTER KEY<br>CREATE MASTER KEY<br>    ENCRYPTION BY PASSWORD = &#39;25600you_should_not_share__this_password!&#39;;<br>GO<br><br>ALTER MASTER KEY<br>    ADD ENCRYPTION BY SERVICE MASTER KEY;<br>GO</pre><p><strong>Replace </strong>the value 25600you_should_not_share__this_password! with your own password.</p><p>Next, we need to create an <strong>asymmetric key </strong>and a <strong>login </strong>for the .NET assembly; use this code:</p><pre>USE master<br>GO<br>DROP LOGIN SSFunctionLogin<br>DROP ASYMMETRIC KEY SSFunctionKey<br>CREATE ASYMMETRIC KEY SSFunctionKey<br>    FROM EXECUTABLE FILE = &#39;C:\SSFunction\SSFunction\bin\Debug\SSFunction.dll&#39;;<br><br>GO<br>CREATE LOGIN SSFunctionLogin FROM ASYMMETRIC KEY SSFunctionKey;<br>GO<br>GRANT UNSAFE ASSEMBLY TO SSFunctionLogin;<br>GO</pre><p>Recall to enter the <strong>complete path</strong> where the SSFunction.dll file is located.</p><p>Don’t worry about the SSFunctionLogin login; you <strong>won’t use it</strong> to log into SQL Server, nor use it from your application.</p><p>Now we are ready to <strong>upload </strong>the .NET library to <strong>SQL Server</strong>.</p><p><strong>Switch </strong>to the database from which you want to call the <strong>Rust function</strong>, in my case, it’s the Household database:</p><pre>USE Household<br>GO<br><br>DROP FUNCTION IF EXISTS dbo.RemoveNumbersWithRust<br>DROP ASSEMBLY IF EXISTS SSFunctionAssembly<br>CREATE ASSEMBLY SSFunctionAssembly<br>    FROM &#39;C:\SSFunction\SSFunction\bin\Debug\SSFunction.dll&#39;<br>    WITH PERMISSION_SET = UNSAFE;<br>GO<br><br><br>DROP FUNCTION IF EXISTS dbo.RemoveNumbersWithRust<br>GO<br>CREATE FUNCTION dbo.RemoveNumbersWithRust(@input NVARCHAR(MAX))<br>    RETURNS NVARCHAR(MAX)<br>AS<br>    EXTERNAL NAME SSFunctionAssembly.[SSFunction.FunctionDefinitions].RemoveNumbersWithRust<br>GO</pre><p>Ensure the path to the SSFunction.dll file <strong>matches </strong>the one used previously for the asymmetric key setup.</p><h4>Call the Rust function from SQL Server</h4><p>Here comes the funny part.</p><p>If you followed the steps so far, <strong>run </strong>this statement in your SQL Server database:</p><pre>USE Household<br>GO<br><br>SELECT dbo.RemoveNumbersWithRust(N&#39;The leading prime numbers are: 1, 2, 3, 5&#39;) AS result;<br>GO</pre><p>You should get something like this:</p><figure><img alt="Result of calling the Rust function from a SQL Server database." src="https://cdn-images-1.medium.com/max/479/1*kP_2K3WgyuRBx0x_nFQTzg.png" /></figure><p>Now <strong>Rust </strong>is at your spell! 🙂</p><h4>What if you need to change your .NET library? Here’s what to do</h4><p>Good question. You have to <strong>apply any change </strong>you want to the .NET library and <strong>upload it again </strong>to SQL Server.</p><p>Let’s modify our SSFunction.dll library.</p><p>Do you remember the free_string Rust function we added in an earlier section?</p><p>Well, this function <strong>frees </strong>the memory that <strong>Rust allocated </strong>for the string we are sending from SQL Server.</p><p>You have to <strong>free</strong> that memory into the <strong>.NET library</strong>.</p><p>Open the FunctionDefinitions.cs file and modify the code:</p><pre>using System;<br>using System.Runtime.InteropServices;<br>using Microsoft.SqlServer.Server;<br><br>namespace SSFunction<br>{<br>    public class FunctionDefinitions<br>    {<br>        [DllImport(@&quot;C:\rust_for_sqlserver\target\x86_64-pc-windows-msvc\release\rust_for_sqlserver.dll&quot;)]<br>        internal static extern IntPtr remove_numbers_c(string input);<br><br>        [DllImport(@&quot;C:\rust_for_sqlserver\target\x86_64-pc-windows-msvc\release\rust_for_sqlserver.dll&quot;)]<br>        internal static extern void free_string(IntPtr ptr);<br><br>        [SqlFunction(DataAccess = DataAccessKind.Read)]<br>        public static string RemoveNumbersWithRust(string input)<br>        {<br>            if (input == null)<br>            {<br>                return null;<br>            }<br><br>            IntPtr ptr = remove_numbers_c(input);<br>            if (ptr == IntPtr.Zero)<br>            {<br>                return null;<br>            }<br><br>            try<br>            {<br>                string result = Marshal.PtrToStringAnsi(ptr);<br>                return result;<br>            }<br>            finally<br>            {<br>                free_string(ptr); // Call this here to free the memory<br>            }<br>        }<br>    }<br>}</pre><p><strong>Compile </strong>the .NET project with Ctrl+B .</p><p>Go to SQL Server and run this statement:</p><pre>USE Household<br>GO<br>/* The ALTER ASSEMBLY statement will fail if the .dll file has not changes since it was created or last altered. */<br>ALTER ASSEMBLY SSFunctionAssembly<br>    FROM &#39;C:\SSFunction\SSFunction\bin\Debug\SSFunction.dll&#39;<br>    WITH PERMISSION_SET = UNSAFE;<br><br>GO</pre><p>Test the dbo.RemoveNumbersWithRust function in SQL Server, and it should work:</p><figure><img alt="Result of calling the Rust function (the one that frees memory) from a SQL Server database." src="https://cdn-images-1.medium.com/max/1024/1*Wk5TeWa2vSI5vFS-26bWTA.png" /></figure><p>When you need to <strong>alter </strong>an assembly in SQL Server, consider <strong>keeping</strong> method signatures. <a href="https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-assembly-transact-sql?view=sql-server-ver17#remarks">Find the complete list of restrictions in this documentation.</a></p><p>By the way, if you want to <strong>modify </strong>the <strong>Rust code</strong>, you only have to <strong>apply your change</strong> and <strong>build </strong>the project to get the updated rust_for_sqlserver.dll file.</p><h3>Wrapping up</h3><ul><li>One approach to <strong>calling Rust code </strong>from SQL Server is to use <strong>CLR functions</strong> from the .NET Framework.</li><li>The .NET Framework (C# code) acts as an <strong>intermediary</strong> between SQL Server and Rust.</li><li>You have to <strong>upload</strong> your .NET library (which contains the CLR functions) to <strong>SQL Server</strong>.</li></ul><p><a href="https://github.com/lemalcs/sql-server-tastes-rust">Find the whole project in GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsvr6d5l8UDtbvYYDIaC3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shvSZjn4y9FdpOlqcwGr6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3toGQY5HTQF2Dfa-jXpEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XdNcJ_48XB0An2XmL7oXAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viot0Pdn5ux5tDtc5L-UnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZi4gUWTERuLqU_r-vh0Xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXChUdgrHxuqIyXzS0K9Tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*Cog7nCI0gQ6c-YjIuyjRqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*kk4Muwg3Tr9fuo9kfTnF6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGIDzoDBZDkx7q_PAHBkYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0ZDe8aWBkCDzax465nSZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMCijL1tZja8FwPwGsJTTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8EhMqAG5_aAQW2eSanG4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xWvSaj0SGPwRjIg3Dh0mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*DiAW1_0KI5ajlxeLcd6buw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*wKtIT6ZpyAn9-gS9nCKPsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ao8keBXXXknHWHzxf6zJHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVLP-QnfzM6IRfcugR3Vog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPMAejaywsuidhYMLKPZJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qxxs8CjwdyxlxcI4r7Xuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*UvbGrSOe293aIxbvHob7aw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*BuEKzJzd9scy_NvQjWSpWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKtWfR9a5Vt1QB3JucVZEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*U1XR3aNOtPz3hW6JeX5aIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzzib4VVRgtpwQ_5LERRrw.png" /></figure><p><em>Do you want to know how the story continues in the </em><strong><em>obfuscated panels</em></strong><em>?</em></p><p><em>Let me know in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf79ad476d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft just did a Python driver for SQL Server, but don’t get too excited]]></title>
            <link>https://medium.com/@lemalcs/microsoft-just-did-a-python-driver-for-sql-server-but-dont-get-too-excited-ae113c623061?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae113c623061</guid>
            <category><![CDATA[sqlserver2025]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 05:02:16 GMT</pubDate>
            <atom:updated>2025-12-23T05:02:16.539Z</atom:updated>
            <content:encoded><![CDATA[<p>With the launch of <strong>SQL Server 2025</strong>, Microsoft also launched the <strong>Python driver</strong> for SQL Server: <em>mssql-python</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qN4OIXJr9GERdPK78aQNVg.png" /></figure><p>Before mssql-python, we had to depend on some community drivers, such as:</p><ul><li><a href="https://pypi.org/project/pyodbc/">pyobc</a></li><li><a href="https://pypi.org/project/python-tds/">pytds</a></li><li><a href="https://pypi.org/project/pymssql/">pymssql</a></li><li>Other pys…</li></ul><p>Now, we have a Python driver <strong>supported by Microsoft</strong>, which we expect will fill the <a href="https://medium.com/@lemalcs/pymssql-vs-pytds-for-bulk-inserts-with-python-and-sql-server-de0773e2645a">gaps left by third-party SQL Server drivers</a>.</p><p>Although mssql-python is in an <strong>early stage</strong>, I hope this evolves to the degree that <strong>Microsoft.SqlClient</strong> .NET library currently is. (Don’t disappoint me, Microsoft.)</p><h3>Creating the Python project</h3><p>Let’s create a Python project to connect to SQL Server, <strong>the Microsoft way</strong>.</p><p>Run these commands in your favorite terminal:</p><pre>mkdir python_sticks_with_sqlserver<br>cd python_sticks_with_sqlserver<br>python -m venv .mvenv</pre><p><em>(Feel free to name the project folder without your own name)</em></p><p><strong>Activate</strong> the virtual environment.<br>On Windows:</p><pre>.mvenv\Scripts\Activate.bat</pre><p>On macOS and Linux:</p><pre>source .mvenv/Scripts/activate</pre><p>This will be a project with tests, so I’ll install the pytest package with:</p><pre>pip install -U pytest</pre><h3>Installing the Python driver for SQL Server</h3><p>For Windows, run this command:</p><pre>pip install mssql-python</pre><p>For other platforms, refer to the <a href="https://github.com/microsoft/mssql-python?tab=readme-ov-file#installation">mssql-python README file in GitHub</a>.</p><p>Now, I’m going to <strong>connect</strong> to a SQL Server instance running on <strong>my machine</strong>:</p><p>Create a file called mssqlpy.py and write this header:</p><pre># mssqlpy.py<br>import mssql_python<br><br>def test_connect_to_bare_sql_server():<br>    connection_string = &quot;SERVER=localhost\\sql2025ed;DATABASE=master;Trusted_Connection=yes;Encrypt=yes;TrustServerCertificate=yes&quot;<br>    connection = mssql_python.connect(connection_string)<br><br>    cursor = connection.cursor()<br>    cursor.execute(&quot;select count(1) from sys.all_objects&quot;)<br>    rows = cursor.fetchall()<br>    rows_number = rows[0][0]<br><br>    print(f&quot;Number of rows in sys.all_objects: {rows_number}&quot;)<br><br>    assert rows_number &gt; 0</pre><p>The function test_connect_to_bare_sql_server does these:</p><ul><li><strong>Connect </strong>to an SQL Server instance called sql2025ed</li><li><strong>Count </strong>the number of rows in the sys.all_objects table</li><li><strong>Check </strong>whether the mentioned table has more than zero rows.</li></ul><p>Run the test with:</p><pre>pytest mssqlpy.py::test_connect_to_bare_sql_server -s</pre><p>The -s variable <strong>shows</strong> the result of print functions.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8G82s1qo4IjxROG3WMc9w.png" /></figure><h3>Chores to do in SQL Server</h3><p>Next are some common tasks you would need to do with SQL Server, such as:</p><ul><li><strong>Create </strong>tables</li><li><strong>Insert </strong>rows</li><li>Execute <strong>stored procedures</strong></li><li>Execute <strong>functions</strong></li></ul><p>To stop annoying you with <strong>creating</strong> the connection string for <strong>each</strong> of the tasks above, I’ll create a function that will <strong>open a connection</strong> for you:</p><p>Add this code to the mssqlpy.py file:</p><pre># mssqlpy.py<br><br># [...]<br>import pytest<br><br>@pytest.fixture()<br>def db_connection():<br>    connection_string = &quot;SERVER=localhost\\sql2025ed;DATABASE=Household;Trusted_Connection=yes;Encrypt=yes;TrustServerCertificate=yes&quot;<br>    connection = mssql_python.connect(connection_string)<br>    return connection</pre><p>By the way, the following is the code to create the test database:</p><pre>USE master<br>GO<br><br>create database Household</pre><h4>Create tables</h4><pre># mssqlpy.py<br><br># [...]<br><br>def test_create_table(db_connection):<br>    statement=&quot;&quot;&quot;<br>drop table if exists dbo.Chores<br>create table dbo.Chores<br>(<br>    Id int,<br>    Title nvarchar(256),<br>    DueBy date,<br>    IsComplete bit<br>)<br>&quot;&quot;&quot;<br>    cursor=db_connection.cursor()<br>    cursor.execute(statement)<br><br>    cursor.execute(&quot;select count(1) from sys.tables where name=&#39;Chores&#39;&quot;)<br>    rows=cursor.fetchone()<br><br>    assert rows[0]==1</pre><p>Run with:</p><pre>pytest mssqlpy.py::test_create_table</pre><h4>Insert row</h4><pre># mssqlpy.py<br><br># [...]<br><br>def test_insert_and_query_data(db_connection):<br>    insert_statement=&quot;&quot;&quot;<br>insert into dbo.Chores (Id, Title, DueBy, IsComplete) <br>values(?, ?, ?, ?)<br>&quot;&quot;&quot;<br>    cursor=db_connection.cursor()<br>    cursor.execute(insert_statement,<br>                   (<br>                       1,<br>                       &quot;Take out the trash&quot;,<br>                       &quot;2025-09-16&quot;,<br>                       0<br>                   ))<br>    <br>    cursor.execute(&quot;select Title, DueBy, IsComplete from dbo.Chores where Id=?&quot;, (1,))<br>    <br>    row=cursor.fetchone()<br>    cursor.commit()<br><br>    assert row[0]==&quot;Take out the trash&quot;<br>    assert str(row[1])==&quot;2025-09-16&quot;<br>    assert row[2]==0</pre><p>Command to run test:</p><pre>pytest mssqlpy.py::test_insert_and_query_data</pre><h4>Execute stored procedures</h4><pre># mssqlpy.py<br><br>def test_execute_stored_procedure(db_connection):<br><br>    &quot;&quot;&quot; <br>    /* Source code for stored procedure */<br>    create proc dbo.save_chore<br>            @Title nvarchar(256),<br>            @DueBy date,<br>            @IsComplete bit,<br>            @NewId int output<br>    as<br>        begin<br>            select @NewId=count(1)+1 from dbo.Chores<br><br>            insert dbo.Chores(Id, Title, DueBy, IsComplete)<br>            values(@NewId,@Title,@DueBy,@IsComplete)<br>        end<br>    &quot;&quot;&quot;<br><br>    statement=&quot;&quot;&quot;<br>set nocount on<br>declare @new_id int<br>exec dbo.save_chore @Title=?, @DueBy=?, @IsComplete=?, @NewId=@new_id output<br>select @new_id<br>&quot;&quot;&quot;<br><br>    params=(<br>        &quot;Mow the lawn&quot;,<br>        &quot;2025-09-20&quot;,<br>        0<br>    )<br>    cursor=db_connection.cursor()<br>    cursor.execute(statement, params)<br>    rows=cursor.fetchall()<br>    for row in rows:<br>        new_id=row[0]<br>        break<br>    cursor.commit()<br><br>    assert new_id is not None</pre><p>Test with:</p><pre>pytest mssqlpy.py::test_execute_stored_procedure</pre><h4>Execute functions</h4><pre># mssqlpy.py<br><br>def test_execute_function(db_connection):<br><br>    &quot;&quot;&quot; <br>    /* Source code for function */<br>create function dbo.translate_to_emoji(@word nvarchar(32))<br>returns nvarchar(32)<br>as<br>    begin<br>        if @word = &#39;dog&#39;<br>            return N&#39;🐕&#39;<br><br>        if @word = &#39;dishes&#39;<br>            return N&#39;🍽️&#39;<br><br>        if @word = &#39;laundry&#39;<br>            return N&#39;👕&#39;<br><br>        if @word = &#39;bathroom&#39;<br>            return N&#39;🚽&#39;<br><br>        if @word = &#39;car&#39;<br>            return N&#39;🛻&#39;<br><br>        return @word<br>    end<br>    &quot;&quot;&quot;<br><br>    statement=&quot;select dbo.translate_to_emoji(?)&quot;<br>    cursor=db_connection.cursor()<br>    cursor.execute(statement, (&quot;dog&quot;,))<br><br>    row=cursor.fetchone()<br>    emoji=None<br>    while row:<br>        emoji=row[0]<br>        break<br><br>    assert emoji==&quot;🐕&quot;</pre><p>Execute test with:</p><pre>pytest mssqlpy.py::test_execute_function</pre><h3>What a serious SQL Server driver must have</h3><p>To <strong>recognize</strong> a database <strong>made with love</strong> for a database engine (SQL Server in this case), it <strong>must support bulk inserts</strong>.</p><blockquote><em>Generic drivers like </em><strong><em>pyodbc</em></strong><em> don’t support it.</em></blockquote><blockquote>Sadly, as of this writing, mssql-python <strong>does not support true bulk inserts</strong>. 😕</blockquote><p>But you can insert multiple rows with the executemany function, which I describe next.</p><h4>Doing FAKE bulk inserts with mssql-python</h4><p>Add the test_bulk_insert and get_chores functions:</p><pre># mssqlpy.py<br><br># [...]<br><br>def get_chores():<br>    chores_for_everyday=[<br>        (2, &quot;Wash the dishes&quot;, &quot;2025-09-17&quot;, 0),<br>        (3, &quot;Do the laundry&quot;, &quot;2025-09-18&quot;, 0),<br>        (4, &quot;Clean the bathroom&quot;, &quot;2025-09-19&quot;, 0),<br>        (5, &quot;Wash the car&quot;, &quot;2025-09-21&quot;, 0)<br>    ]<br><br>    all_chores=[]<br><br>    for id in range(0,100000):<br>        all_chores.append((<br>            id+1,<br>            chores_for_everyday[id % len(chores_for_everyday)][1],<br>            &quot;2025-12-31&quot;,<br>            0<br>        ))<br><br>    return all_chores<br><br>def test_fake_bulk_insert(db_connection):<br>    statement=&quot;&quot;&quot;<br>insert into dbo.Chores (Id, Title, DueBy, IsComplete) <br>values(?, ?, ?, ?)&quot;&quot;&quot;<br><br>    cursor=db_connection.cursor()<br>    chores= get_chores()<br>    cursor.executemany(statement,chores)<br>    cursor.commit()<br>    print(f&quot;Inserted {len(chores)} rows.&quot;)<br><br>    cursor.execute(&quot;select count(1) from dbo.Chores&quot;)<br>    row=cursor.fetchone()<br><br>    assert row[0]&gt;=100000</pre><p>Run the test with</p><pre>pytest mssqlpy.py::test_fake_bulk_insert</pre><p>Python side result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKDeXesG725j_q13j9MjLg.png" /></figure><p>SQL Server side result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*liWrEECXcN-U0RvNEfQzYg.png" /></figure><p>Why is the executemany function a fake bulk insert? 🤔</p><p>It inserts every row in a <strong>single transaction</strong> using the slow INSERT INTO statement.</p><p>If we check the <a href="https://learn.microsoft.com/en-us/sql/relational-databases/extended-events/quick-start-extended-events-in-sql-server?view=sql-server-ver17">extended events</a> in SQL Server, we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bm6eiyNsTinkWnzQJkGnxQ.png" /></figure><p>As you can see, there are <strong>tons</strong> of statements for the 100000 rows we inserted earlier from the Python script.</p><p>A true bulk insert uses the insert bulk statement.</p><h3>Summary</h3><ul><li>The mssql-python driver could be considered a <strong>complete Python driver</strong> for SQL Server.</li><li>As of now, the mssql-python does <strong>not</strong> support <strong>bulk inserts</strong>.</li><li>And, for enterprises, mssql-python is supported by <strong>Microsoft</strong>, so you have the <strong>peace of mind</strong> of knowing who to go to for complaints 😌.</li></ul><p>The completed project is on <a href="https://github.com/lemalcs/python_sticks_with_sqlserver">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QG55tN6gR_sHgRgFOnhFBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sfu25SH_wNs69dit0M3g3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDCvl5WiFoVS71srdrrHnA.png" /><figcaption>Do you want to see what is in this panel?</figcaption></figure><p><em>PS: If bulk inserts are already implemented for the </em><em>mssql-python driver, please leave a comment down below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae113c623061" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the scope of variables can screw up your SQL Server scripts]]></title>
            <link>https://medium.com/@lemalcs/how-the-scope-of-variables-can-screw-up-your-sql-server-scripts-cd407eccde60?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd407eccde60</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql-server-agent]]></category>
            <category><![CDATA[transact-sql]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 05:58:45 GMT</pubDate>
            <atom:updated>2025-12-13T05:58:45.510Z</atom:updated>
            <content:encoded><![CDATA[<p>If you <strong>overlook </strong>how SQL Server manages <strong>variables</strong>, your code may not work as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NsXWpAKg4456e4-vd4rMw.png" /></figure><p>For example, I ran into an<strong> error</strong> message when <strong>creating</strong> jobs with <strong>Transact-SQL</strong>:</p><blockquote><em>Cannot add, update, or delete a job (or its steps or schedules) that originated from an MSX server.</em></blockquote><p>I’ll describe the <strong>non-intuitive</strong> handling of <strong>variable scope </strong>in SQL Server.</p><p>Stay alert to SQL Server’s quirks!</p><h3>I wanted to create jobs with code</h3><p>You can create jobs using a graphical user interface (<strong>GUI</strong>) or SQL code (<strong>Transact-SQL</strong>). I went with the latter option.</p><p>I used this code:</p><pre>declare @jobs_number int=5,<br>  @n int=1,<br>  @the_job_name nvarchar(36)<br><br>while @n&lt;=@jobs_number<br>begin<br> DECLARE @jobId BINARY(16)<br><br> set @the_job_name=concat(N&#39;Print_table_count_&#39;,@n)<br> EXEC  msdb.dbo.sp_add_job @job_name=@the_job_name, <br>   @enabled=1, <br>   @notify_level_eventlog=0, <br>   @notify_level_email=2, <br>   @notify_level_page=2, <br>   @delete_level=0, <br>   @description=N&#39;Print the number of tables in the master database.&#39;, <br>   @category_name=N&#39;[Uncategorized (Local)]&#39;, <br>   @owner_login_name=N&#39;localhost\me&#39;, @job_id = @jobId OUTPUT<br> select @jobId as job_Id<br><br> EXEC msdb.dbo.sp_add_jobserver @job_name=@the_job_name, @server_name = N&#39;localhost\SQL2022D&#39;<br><br> EXEC msdb.dbo.sp_add_jobstep @job_name=@the_job_name, @step_name=N&#39;Count tables&#39;, <br>   @step_id=1, <br>   @cmdexec_success_code=0, <br>   @on_success_action=1, <br>   @on_fail_action=2, <br>   @retry_attempts=0, <br>   @retry_interval=0, <br>   @os_run_priority=0, @subsystem=N&#39;TSQL&#39;, <br>   @command=N&#39;declare @table_count int <br> select @table_count= count(1) from sys.tables<br> print cast(@table_count as nvarchar(10))&#39;, <br>   @database_name=N&#39;master&#39;, <br>   @flags=0<br><br> EXEC msdb.dbo.sp_update_job @job_name=@the_job_name, <br>   @enabled=1, <br>   @start_step_id=1, <br>   @notify_level_eventlog=0, <br>   @notify_level_email=2, <br>   @notify_level_page=2, <br>   @delete_level=0, <br>   @description=N&#39;Print the number of tables in the master database.&#39;, <br>   @category_name=N&#39;[Uncategorized (Local)]&#39;, <br>   @owner_login_name=N&#39;localhost\me&#39;, <br>   @notify_email_operator_name=N&#39;&#39;, <br>   @notify_page_operator_name=N&#39;&#39;<br><br> set @n+=1<br>end</pre><p>The code does something simple:</p><ul><li><strong>Create</strong> 5 jobs for SQL Server Agent.</li><li>Each job <strong>prints</strong> the number of tables in the master database.</li></ul><p>The code above is useful if you need to create <strong>several jobs</strong> quickly.</p><p>Consider how challenging it would be to create <strong>5000 jobs</strong> using only the dialog interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*IadCHtL-M5qzg1P3bZjwmA.png" /></figure><p>Although you can create <strong>every job in this case without a single line of code</strong>, I don’t recommend it.</p><h3>The error I got was because of variable scope</h3><p>When I executed the <strong>script</strong> of the last section, I got this error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*pCrkb5xKvnVY6GoxggK1dA.png" /></figure><p>The failure happened in the msdb.dbo.sp_add_job system stored procedure, because in the <strong>second iteration,</strong> the script sent the <strong>value from the first iteration</strong> into the @jobId variable!</p><p>For example, @jobId had this value in the <strong>first </strong>iteration:</p><pre>0xBA0C6391470E704BBA2EE1E7A0E3BE06</pre><p>In the <strong>second </strong>iteration, @jobId retained the <strong>same </strong>value.</p><p>That means that SQL Server <strong>didn’t create the variable again</strong> when executing this line:</p><pre>-- [...]<br> DECLARE @jobId BINARY(16)<br><br>-- [...] </pre><p>Why is that? 🤔</p><h3>How SQL Server manages variable scopes</h3><p>In the SQL Server world, variable scope is either the <strong>batch</strong> or a <strong>stored procedure</strong>.</p><p>Let’s look at a simple example of this.</p><p>Consider the next code:</p><pre>declare @count int=1<br><br>while @count&lt;3<br>begin<br> /* the @attempt variable is created once regardless of the number of iterations */<br> declare @attempt int <br> <br> print concat(&#39;Iteration &#39;,@count,&#39;: &#39;,cast(@attempt as varchar(11)))<br> <br> set @attempt=1 <br><br> set @count+=1<br>end<br><br>print cast(@attempt as varchar(11)) </pre><p>Result:</p><pre>Iteration 1: <br>Iteration 2: 1<br>1</pre><p>In the <strong>first </strong>iteration, @attempt is NULL.<br>In the <strong>second </strong>iteration, @attempt has the value 1.</p><p>In languages like Rust, Python, or C#, the variable @attempt would be <strong>recreated </strong>in every iteration.</p><p>But in SQL Server, the variable @attempt is created <strong>once</strong>! <strong>regardless</strong> of the times you use the declare statement.</p><p>Notice that it’s <strong>correct</strong> to use the @attempt <strong>outside </strong>the while statement 😀.</p><h3>How to fix the code, taking into account the scope of variables</h3><p>Now that you know <strong>how variable scope works</strong>, we can modify our code to create jobs.</p><p>We have to ensure that the @jobId variable is set to NULL before calling the sp_add_jog stored procedure, like this:</p><pre>-- [...]<br> DECLARE @jobId BINARY(16)<br> <br> set @jobId=NULL /* Add this statement */<br><br> set @the_job_name=concat(N&#39;Print_table_count_&#39;,@n)<br> EXEC  msdb.dbo.sp_add_job @job_name=@the_job_name, <br>   @enabled=1, <br>   @notify_level_eventlog=0, <br>   @notify_level_email=2, <br>   @notify_level_page=2, <br>   @delete_level=0, <br>   @description=N&#39;Print the number of tables in the master database.&#39;, <br>   @category_name=N&#39;[Uncategorized (Local)]&#39;, <br>   @owner_login_name=N&#39;localhost\me&#39;, @job_id = @jobId OUTPUT<br> select @jobId as job_Id<br>-- [...]</pre><p>Run the fixed code, and SQL Server should <strong>create</strong> all the jobs (5 jobs in this example).</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*MAvynj_3hYx8mZiSI7_O6A.png" /></figure><h3>Conclusion</h3><ul><li>Speaking of SQL Server rules, the <strong>scope</strong> of a variable is the <strong>batch</strong> or the <strong>stored procedure</strong>.</li><li>You <strong>cannot</strong> create a variable that was already created in a <strong>previous statement</strong>.</li><li>If you use a <strong>loop</strong>, you <strong>cannot</strong> create a variable that was created in a <strong>past iteration</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j65pefRzttfK4yZ2tI9vBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGk5XPLqcmgmwEhdTBh0mA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8J1CKBJa0s_UG7-C5D-91w.png" /><figcaption>Can you guess what is going on in the panel?</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd407eccde60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting Rust to Azure SQL Without Losing Your Mind]]></title>
            <link>https://medium.com/@lemalcs/connecting-rust-to-azure-sql-without-losing-your-mind-33ea2863bc86?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ea2863bc86</guid>
            <category><![CDATA[azure-sql-database]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[tiberius-rust]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 17:55:49 GMT</pubDate>
            <atom:updated>2025-11-22T17:55:49.123Z</atom:updated>
            <content:encoded><![CDATA[<p>How to use Rust, Tokio, and Tiberius to connect to Azure SQL Database.</p><p>Of course, you can use <strong>Rust</strong> to <strong>connect</strong> to the SQL Server living up there in the sky: <strong>Azure SQL</strong>.</p><figure><img alt="The developer is trying to connect a Rust application to Azure SQL, but it’ll cost money." src="https://cdn-images-1.medium.com/max/919/1*ODjzRGFmVDyeTQakUHqmFw.png" /></figure><p>Let’s get our hands dirty.</p><p>What we will need:</p><ul><li>Rust toolchain</li><li><strong>Tiberius</strong> crate</li><li>The <strong>Tokio</strong> runtime</li><li>An Azure SQL instance</li></ul><p>These are the versions I’m going to use for this project.</p><p>Command:</p><pre>cargo tree --depth 1</pre><p>Output:</p><pre>|-- anyhow v1.0.100<br>|-- azure_core v0.29.1<br>|   [build-dependencies]<br>|-- azure_identity v0.29.0<br>|-- tiberius v0.12.3<br>|-- tokio v1.48.0<br>`-- tokio-util v0.7.16</pre><h3>Creating the project</h3><p>Make sure you have the <strong>Rust toolchain</strong> installed on your machine.</p><p>Run this in the terminal:</p><pre>cargo new tiberius_picks_azure_sql --lib</pre><p>Add this to your Cargo.toml file:</p><pre>// Cargo.toml  <br><br>// [...]<br>  <br>[dependencies]  <br>tiberius = &quot;0.12.3&quot;  <br>tokio={version = &quot;1.47.1&quot;,features = [&quot;rt-multi-thread&quot;,&quot;net&quot;,&quot;macros&quot;]}  <br>tokio-util = {version = &quot;0.7.16&quot;, features = [&quot;compat&quot;]}  <br>anyhow=&quot;1.0.100&quot; </pre><blockquote>The <strong>anyhow</strong> crate lets us add <strong>useful context to our errors</strong> and frees us from using the dyn keyword to create <strong>Error</strong> instances. Some people spit dynamic code out when they taste it😀.</blockquote><h3><strong>Testing the Azure SQL stuff</strong></h3><p>Let’s connect to Azure SQL the <strong>traditional way</strong>: by using a <strong>username</strong> and <strong>password</strong>.</p><h4><strong>Connecting with username and password</strong></h4><ol><li>Create the connection.rs file in the src folder.</li><li>Add this code to the file you just created:</li></ol><pre>// connection.rs<br><br>use tiberius::{AuthMethod, Client, Config};  <br>use tokio::net::TcpStream;  <br>use tokio_util::compat::{Compat, TokioAsyncWriteCompatExt};  <br>  <br>pub async fn connect_to_azure_sql_database_with_password() -&gt; anyhow::Result&lt;Client&lt;Compat&lt;TcpStream&gt;&gt;&gt; {  <br>    let mut config=Config::new();  <br>    config.authentication(AuthMethod::sql_server(&quot;theadmin&quot;,&quot;YOUR_FOREVER_SECRET_PASSWORD&quot;));  <br>    config.host(&quot;rainforest.database.windows.net&quot;);  <br>    config.port(1433);  <br>    config.database(&quot;nestdb&quot;);  <br>    config.trust_cert();  <br>  <br>    let tcp = TcpStream::connect(config.get_addr()).await?;  <br>    tcp.set_nodelay(true)?;  <br>  <br>    let mut client = Client::connect(config, tcp.compat_write()).await?;  <br>    println!(&quot;Connected to database&quot;);  <br>  <br>    Ok(client)  <br>}</pre><p><strong>Replace</strong> the placeholder YOUR_FOREVER_SECRET_PASSWORD with your password.</p><p>3. Open the lib.rs file and replace its contents with:</p><pre>// lib.rs<br><br>mod connection;  <br>  <br>#[cfg(test)]  <br>mod tests {  <br>    use super::*;  <br>  <br>    #[tokio::test]  <br>    async fn test_connection_to_azure_sql_with_password() {  <br>        let conn = connection::connect_to_azure_sql_database_with_password().await;  <br>  <br>        // In case of failure, uncomment this line to see the error details  <br>        //dbg!(&amp;conn);  <br>        assert!(conn.is_ok());  <br>    }<br>}</pre><p>4. Run the test:</p><pre>cargo test test_connection_to_azure_sql_with_password -- --show-output</pre><p>If all is right, you should get this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*PjbdeiL5M4glnA2abfZxZQ.png" /></figure><p>If the test fails, <strong>retry the connection</strong>, because Azure SQL goes to <strong>sleep</strong> 😴 when there are <strong>no active</strong> connections for some time.</p><p>It takes a few <strong>seconds</strong> for Azure SQL to <strong>wake up</strong> and serve you.</p><p>Now, what about <strong>other authentication methods</strong> for Azure SQL?</p><p>I’m going to describe them in order.</p><h4><strong>How to connect using Windows authentication</strong></h4><p>Sadly, Azure SQL <strong>does not support</strong> Windows Authentication.</p><p>I’m using an <a href="https://azure.microsoft.com/en-us/products/azure-sql/database"><strong>Azure SQL Database</strong></a> instance, which is the <strong>only</strong> Azure SQL offering available in the <strong>free tier</strong>.</p><p>However, you <strong>can</strong> use Windows Authentication with <a href="https://azure.microsoft.com/en-us/products/azure-sql/managed-instance"><strong>Azure SQL Managed Instance</strong></a> — another flavor of Azure SQL.</p><blockquote>Azure SQL Managed Instance <strong>costs money</strong>, so I’ll cover that in a future post.</blockquote><h4><strong>I prefer Microsoft Entra</strong></h4><p>At the time of writing, the <a href="https://github.com/prisma/tiberius"><strong>Tiberius</strong></a> crate <strong>does support</strong> authentication with <strong>Microsoft Entra</strong> <strong>user</strong> accounts (also known as user principals).</p><blockquote><strong>User accounts</strong> in Microsoft Entra are <strong>different</strong> from <strong>application accounts</strong> — the former is for humans, the latter is for applications.</blockquote><p>Take a look at this <a href="https://github.com/prisma/tiberius/issues/175">GitHub discussion</a>.</p><p>If you must use Microsoft Entra you have to <strong>register an application</strong>, which I describe next.</p><h3><strong>How do I connect with a Microsoft Entra identity?</strong></h3><p>You’ll need to:</p><ol><li>Set up a <strong>Microsoft Entra administrator</strong> for your Azure SQL instance</li><li>Assign an <strong>identity</strong> to Azure SQL</li><li>Register a Microsoft Entra <strong>application</strong></li><li>Create a <strong>secret</strong> for the application</li><li>Create a <strong>user</strong> in Azure SQL for the service principal</li><li>Connect to Azure SQL from <strong>Rust</strong>!</li></ol><blockquote>A <strong>managed identity</strong> is a password-less service principal. This identity <strong>frees you up</strong> from the management of <strong>credentials</strong>.</blockquote><h4>1. Set up a Microsoft Entra administrator for your Azure SQL instance</h4><p>In the <a href="https://portal.azure.com/#view/HubsExtension/ServiceMenuBlade/~/AllResources/extension/SqlAzureExtension/menuId/AzureSqlHub/itemId/SingleDatabase"><strong>Azure SQL</strong></a> page, go to <strong>Azure SQL Database &gt; SQL Logical Servers</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*hnp508gU8eBzu3I-QuIP8Q.png" /></figure><p>Select your <strong>logical server</strong>; in my case, it’s <strong>rainforest</strong>.</p><p>In the section <strong>Settings/Microsoft Entra ID</strong>, click <strong>Set admin</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-585CIMRr9s1lCXYdpm7Gw.png" /></figure><p>Select a <strong>Microsoft Entra user</strong> that you want to be the <strong>administrator</strong> of Azure SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*KHAO5mzUgSZd0xOf5LhvYg.png" /></figure><p>I selected the <em>operator</em> user.</p><p>Click <strong>Save</strong>.</p><p>The admin name should appear with a <strong>green check</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0uWk-ZH1UXjBMzqIhmH5g.png" /></figure><h4>2. Assign an identity to Azure SQL</h4><p>For the Microsoft Entra authentication to work, you <strong>must give a system identity</strong> to your Azure SQL instance.</p><p>In the <a href="https://portal.azure.com/#view/HubsExtension/ServiceMenuBlade/~/AllResources/extension/SqlAzureExtension/menuId/AzureSqlHub/itemId/SingleDatabase"><strong>Azure SQL</strong></a> page, select your <strong>Azure SQL</strong> instance.</p><p>Go to the section <strong>Security/Identity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmL3ZIHnBZt27FcfLPXZBQ.png" /></figure><p>Select <strong>On</strong> for Status radio button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSn14tqeFl_OUWhLib_HpA.png" /></figure><p>Click <strong>Save</strong>.</p><h4>3. Register a Microsoft Entra Application</h4><p>A Microsoft Entra Application enables an application (like Rust) <strong>to secure</strong> <strong>access to Azure resources</strong>, such as Azure SQL.</p><blockquote><a href="https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app#register-an-application"><em>Application registration</em></a><em> ensures the </em><strong><em>security</em></strong><em> and privacy of users, applications, and data.</em></blockquote><p>Let’s register our <strong>Rust</strong> application in Azure.</p><p>Go to the <a href="https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Overview">Microsoft Entra ID</a> page.</p><p>Open the section <strong>Manage/App registrations</strong>, and click <strong>New Registration</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Uouil0Koa0i1Sk1nTyw0oQ.png" /></figure><p>Enter a <strong>name</strong> for your Rust application and select the following option in the <strong>Supported account types</strong>:</p><p><em>Account in the organizational directory only (Default Directory only — Single tenant)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*OuDVlzxyufUTNNV9pmodag.png" /></figure><p>We are only going to use our application from the <strong>current tenant</strong>.</p><p>Click <strong>Register</strong>.</p><p>You will be forwarded to an <strong>Overview</strong> page for the application you just registered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*u2moWmFY-aiHR0uE9oSh1g.png" /></figure><h4>4. Create a secret for the application</h4><p>Now we need to create a <strong>secret</strong> that our Rust application will use to <strong>get a token</strong> from Microsoft Entra.</p><p>This enables <strong>authentication</strong> for Rust in Microsoft Entra.</p><p>Later, we will use this <strong>token to access</strong> the Azure SQL instance.</p><p>Go to the <a href="https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/RegisteredApps">Microsfot Entra ID/App registrations</a> section and <strong>select</strong> the App you registered from the list <strong>All applications</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJMI9qiXzUzjnAYDjlBPZQ.png" /></figure><p>Click in the <strong>Client credentials</strong> link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNBYnGdmznnt9Et-N9jpfQ.png" /></figure><p>In the <strong>Certificates &amp; secrets</strong>, go to the <strong>Client secrets</strong> tab and click on <strong>New client secret</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*WYbBNHG70uQs75HW6TSPtw.png" /></figure><p>In the <strong>Add a client secret</strong> panel, fill in the <strong>Descriptions</strong> and <strong>Expires fields</strong>.</p><p>I entered these values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ibbJextFbThv3pHdvhj84A.png" /></figure><p>Click <strong>Add</strong>.</p><p>⚠️<strong>Warning</strong></p><p>When the <strong>details</strong> page of your secret appears, <strong>copy the Value field</strong> <strong>of the secret</strong> because it’s the <strong>only time</strong> that Azure will allow you to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rL0MtFhnpTN3tOxYAdhEg.png" /></figure><h4>5. Create a user in Azure SQL for the Application</h4><p>Connect to your Azure SQL database with a <strong>Microsoft Entra user</strong>.</p><p>You can use the <strong>Azure SQL administrator</strong> you set in the <em>Set up a Microsoft Entra administrator for your Azure SQL instance</em> section.</p><p>Grab the <strong>application name</strong> you created in <a href="https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/RegisteredApps">Microsoft Entra</a>. Find the name in the <strong>Display name</strong> field from the <strong>Overview</strong> page as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*1-eCP9Bve3dSVofMC_irow.png" /></figure><p>Then, run this query in the <strong>database</strong> that your application will access.</p><pre>use nestdb <br>go<br><br>CREATE USER rustrocks FROM EXTERNAL PROVIDER;</pre><p>In my case:</p><ul><li>My database is <strong>nestdb</strong>.</li><li>My application is rustrocks.</li></ul><h4>6. Connect to Azure SQL</h4><p>In the Cargo.toml file, add these crates in the [dependencies] section:</p><pre># Cargo.toml<br><br># [...]<br><br>[dependencies]<br># [...]<br>azure_identity = &quot;0.29.0&quot;  <br>azure_core = &quot;0.29.0&quot;</pre><p>Then, add this code to the connection.rs file:</p><pre>// connection.rs<br><br>// [...]<br><br>use std::env;  <br>use azure_identity::ClientSecretCredential;  <br>use azure_core::credentials::{Secret, TokenCredential, TokenRequestOptions};<br><br>// [...]<br><br>pub async fn connet_to_azure_sql_with_microsoft_entra() -&gt; anyhow::Result&lt;Client&lt;Compat&lt;TcpStream&gt;&gt;&gt; {  <br>    let client_id = env::var(&quot;CLIENT_ID&quot;).expect(&quot;CLIENT_ID is missing&quot;);  <br>    let client_secret = env::var(&quot;CLIENT_SECRET&quot;).expect(&quot;CLIENT_SECRET is missing&quot;);  <br>    let tenant_id = env::var(&quot;TENANT_ID&quot;).expect(&quot;TENANT_ID is missing&quot;);  <br>  <br>    let credential = ClientSecretCredential::new(  <br>        tenant_id.as_str(),  <br>        client_id,  <br>        Secret::new(client_secret),  <br>        Default::default(),  <br>    )?;  <br>      <br>    let token_response = credential.get_token(&amp;[&quot;https://database.windows.net/.default&quot;], Some(TokenRequestOptions::default())).await?;  <br>    let access_token = token_response.token.secret();  <br>  <br>    let mut config = Config::new();  <br>    config.authentication(AuthMethod::AADToken(access_token.to_string()));  <br>    config.host(&quot;rainforest.database.windows.net&quot;);  <br>    config.port(1433);  <br>    config.database(&quot;nestdb&quot;);  <br>    config.trust_cert();  <br>  <br>    let tcp = TcpStream::connect(config.get_addr()).await?;  <br>    tcp.set_nodelay(true)?;  <br>  <br>    let client = Client::connect(config, tcp.compat_write()).await?;  <br>    println!(&quot;Connected to database with Azure AD token&quot;);  <br>  <br>    Ok(client)  <br>}</pre><p>I’m storing the Application credentials in <strong>environment variables</strong>, but you can use other approaches.</p><p>The <strong>Powershell</strong> commands to set the <strong>environment variables</strong> are:</p><pre>$env:CLIENT_ID = &quot;your-client-id-value&quot;<br>$env:CLIENT_SECRET = &quot;your-client-secret-value&quot;<br>$env:TENANT_ID = &quot;your-tenant-id-value&quot;</pre><p>Do you use other OS? Please follow the <strong>appropriate methods</strong> to create your <strong>environment variables</strong> 🙂.</p><p>In the lib.rs file, add the test function:</p><pre>// lib.rs<br><br>// [...]<br><br>#[cfg(test)]<br>mod tests {<br>    use super::*;<br><br>    // [...]<br><br>    #[tokio::test]<br>    async fn test_connection_to_azure_sql_with_valid_credentials() {<br>        let conn = connection::connet_to_azure_sql_with_microsoft_entra().await;<br><br>        // In case of failure, uncomment this line to see the error details<br>        dbg!(&amp;conn);<br><br>        assert!(conn.is_ok());<br>    }<br>}</pre><p>Run the test with:</p><pre>cargo t test_connection_to_azure_sql_with_valid_credentials -- --show-output</pre><p>You should get this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6lB3It4mBY9exL4SyDttg.png" /></figure><p>Otherwise, if you have an error like this:</p><pre>[src\lib.rs:36:9] &amp;conn = Err(<br>    Server(<br>        TokenError {<br>            code: 40613,<br>            state: 1,<br>            class: 20,<br>            message: &quot;Database &#39;nestdb&#39; on server &#39;rainforest.database.windows.net&#39; is not currently available.  Please retry the connection later.  If the problem persists, contact customer support, and provide them the session tracing ID of &#39;{C66D54B7-A2D1-4034-AC45-13C01241A5C8}&#39;.&quot;,<br>            server: &quot;rainforest.database.windows.net&quot;,<br>            procedure: &quot;&quot;,<br>            line: 0,<br>        },<br>    ),<br>)</pre><blockquote><em>If you get the message: </em>“Database ‘database_name’ on server ‘server_name’ is not currently available”<em>, please </em><strong><em>retry</em></strong><em> the connection.</em></blockquote><p>It could mean that the Azure instance was <strong>sleeping</strong> and needs time to <strong>wake up</strong>.</p><p><strong>Retry</strong> the connection, and it should work now.</p><h3>Summary</h3><p>I hope someday <strong>Microsoft</strong> builds a SQL Server <strong>driver</strong> <strong>for</strong> <strong>Rust</strong> made with <strong>love</strong> for Rustaceans 🦀.</p><p>Meanwhile, you can use <strong>Tiberius</strong> to access your Azure SQL database from <strong>Rust</strong>.</p><p>The complete project is on <a href="https://github.com/lemalcs/tiberius_picks_azure_sql">GitHub</a>.</p><p>By the way, here is how to <a href="https://medium.com/@lemalcs/connect-rust-and-the-tokio-runtime-to-sql-server-b6da66abc8b5">run queries with Rust and SQL Server</a>.</p><figure><img alt="Obfuscated panel, the story continues…" src="https://cdn-images-1.medium.com/max/1022/1*QZwO8JcKZTgqcV8JnCOYdg.png" /></figure><p><strong><em>Do you want to see what’s in the obfuscated panel? Let me know in the comments.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ea2863bc86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft Entra ID Yeets Me Out, And Azure SQL Backs It Up.]]></title>
            <link>https://medium.com/@lemalcs/microsoft-entra-id-yeets-me-out-and-azure-sql-backs-it-up-a44517f41976?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/a44517f41976</guid>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[sql-server-ssms]]></category>
            <category><![CDATA[azure-sql-database]]></category>
            <category><![CDATA[visual-studio-2026]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 04:45:25 GMT</pubDate>
            <atom:updated>2025-11-18T04:45:25.576Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a story of how I <strong>regained </strong>access to my Azure SQL database from <strong>SSMS</strong>.</p><p>When <strong>logging in</strong> to your <strong>Azure SQL instance</strong> from SQL Server Management Studio, the connection might get <strong>denied</strong> — even if you’re the <strong>almighty owner</strong> of your Azure subscription.</p><figure><img alt="A cartoon of our hero walking toward a sign labeled “Azure SQL” but being stopped by a triangular character labeled “Entra” holding a stop sign." src="https://cdn-images-1.medium.com/max/951/1*JPtpBwHxiHwP9zo6ZRSDvQ.png" /></figure><p>Let’s find out why… and how to fix it.</p><blockquote><strong><em>Important:</em></strong><em><br>This issue happened in SQL Server Management Studio </em><strong><em>version 20</em></strong><em>. Newer versions may have already </em><strong><em>fixed the login problem</em></strong><em> with Azure SQL databases.</em></blockquote><p>I used this version of SSMS:</p><figure><img alt="SQL Server Management Studio “About” window listing version information for SSMS 20.2.30.0 and related components." src="https://cdn-images-1.medium.com/max/478/1*TWP9hFGPM7dXxZMkaZcmQg.png" /></figure><h3>Prelude to the Azure error message</h3><p>I launched SQL Server Management Studio (SSMS) to log in to my <a href="https://medium.com/@lemalcs/create-your-free-azure-sql-database-6917a1b9a42d"><strong>old free Azure SQL database</strong></a>.</p><p>Here’s what I did:</p><ol><li>Filled in the required fields in the <strong>Connect</strong> dialog.</li><li>Clicked <strong>Sign in</strong> — nothing special here.</li></ol><figure><img alt="SQL Server Management Studio “New Firewall Rule” window showing the message that the client IP does not have access to the server, with a button to sign in to Azure and fields to add the current IP address." src="https://cdn-images-1.medium.com/max/336/1*ah1eYzZBMzmbudpYsCzhQg.png" /></figure><p>3. Entered my <strong>credentials</strong> on the Azure login page.</p><figure><img alt="Microsoft login page prompting the user to enter their password for the selected account during the Azure sign-in process." src="https://cdn-images-1.medium.com/max/888/1*ZtASJyjhhKfOaFHaQSKLSQ.png" /></figure><p>4. Clicked <strong>Next</strong>.</p><figure><img alt="Azure login dialog showing the error “Selected user account does not exist in tenant ‘Microsoft Services’” when attempting to sign in. The message indicates the account cannot access the application and must be added as an external user." src="https://cdn-images-1.medium.com/max/815/1*0U2f5CNz3RQ-bGTLJiJbNw.png" /></figure><blockquote><em>Selected user account does not exist in tenant ‘Microsoft Services’…<br></em>The account needs to be added as an external user in the tenant first. Please use a different account.</blockquote><p>What the heck? 🤨</p><p>I checked the Azure SQL database <strong>properties</strong>, and something strange appeared:</p><figure><img alt="Azure SQL database Overview page showing the Authentication method incorrectly set to “Unknown,” highlighted with a red arrow." src="https://cdn-images-1.medium.com/max/394/1*yPoXdRFzqzEIzl-NMGmk3A.png" /></figure><p>The authentication method was set to <strong>Unknown</strong> — even though I had configured it for <strong>SQL Authentication</strong>.</p><figure><img alt="Azure portal screenshot of an SQL database’s Overview page showing the Authentication method set to SQL and the SQL admin account name." src="https://cdn-images-1.medium.com/max/380/1*M0EQzCn8zu1LX7y585ht9w.png" /></figure><p>Something felt <strong>fishy</strong>.</p><h3>What actually happened</h3><p>My Azure SQL database was <strong>fine</strong>. The problem was SSMS.</p><p>A couple of days earlier, I had <strong>updated my Azure account password</strong>, which <strong>invalidated SSMS’s cached credentials</strong>.</p><p>So SSMS asked me to sign in again — but for some reason, it <strong>kept rejecting</strong> my updated credentials, and the browser kept showing that same Azure error message.</p><h3>Who was denying access?</h3><p>It was <strong>Microsoft Entra ID</strong> — the identity system responsible for authenticating Azure users and authorizing access to Azure resources.</p><p>In this case, the resource was my <strong>Azure SQL database</strong>.</p><h3>How I fixed it</h3><p>I managed to fix everything by logging in to my Azure SQL database through <strong>Visual Studio Insiders 2026</strong>! 😀</p><p>Visual Studio revealed what SSMS failed to show:<br>I simply needed to <strong>re-enter my credentials</strong> properly.</p><p>Here’s what I followed:</p><ol><li>Opened the <strong>Azure portal</strong> and navigated to my <strong>Azure SQL database</strong> page.</li><li>In <strong>Overview</strong>, clicked <strong>Connect with</strong>, then selected <strong>Visual Studio</strong>.</li></ol><figure><img alt="Azure SQL database Overview page showing the “Connect with” dropdown menu, with “Visual Studio” highlighted as a connection option." src="https://cdn-images-1.medium.com/max/1024/1*YwtduBfTIvtlUn9MUITffg.png" /></figure><p>3. Clicked <strong>Open in Visual Studio</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NKe7yHBy4u8nK2ftn9xhg.png" /></figure><blockquote><em>You need </em><a href="https://visualstudio.microsoft.com/downloads/"><em>Visual Studio</em></a><em> installed on your machine.</em></blockquote><p>4. Visual Studio opened with the SQL <strong>Connect</strong> dialog.</p><figure><img alt="Visual Studio SQL Server connection window showing server name, SQL Server Authentication mode, username and password fields, and the target database name." src="https://cdn-images-1.medium.com/max/486/1*yeqPNixAs7kExor48WZr_A.png" /></figure><p><strong><em>Tip: </em></strong>If the portal doesn’t launch VS, open Visual Studio manually → <strong>View → SQL Server Object Explorer → Add SQL Server</strong>.</p><p>5. Clicked <strong>Connect</strong>.</p><p>6. Visual Studio prompted me to <strong>add my IP</strong> to the Azure SQL firewall.</p><figure><img alt="SQL Server Management Studio dialog prompting to create a new firewall rule, with a warning icon and a “Re-enter your credentials” link highlighted by a red arrow." src="https://cdn-images-1.medium.com/max/376/1*0ZKjZDQfSdmPVNyS00l-1Q.png" /></figure><p>7. Noticed the <strong>Re-enter your credentials</strong> link — <em>this</em> was the real clue. !</p><figure><img alt="Microsoft login screen showing two account options: a Work or School account and a Personal Microsoft account, prompting the user to choose which one to sign in with." src="https://cdn-images-1.medium.com/max/650/1*DKJmzthPlcF8Ne5jsWaIAw.png" /></figure><p>8. Clicked it and chose the proper Azure account (one with valid permissions).</p><figure><img alt="Visual Studio SQL Server Object Explorer displaying a connected Azure SQL Server instance with the target database highlighted." src="https://cdn-images-1.medium.com/max/632/1*LxlI8JnITu2downffBwTHg.png" /></figure><p>9. After signing in again, <strong>access was restored</strong>! 🎉</p><p>Some <a href="https://sqlpal.blogspot.com/2025/01/How%20to%20clear%20the%20SSMS%20cache.html">folks recommend</a> clearing the <a href="https://learn.microsoft.com/en-us/ssms/troubleshoot/ssms-troubleshoot?view=sql-server-ver16#clear-ssms-cache-files">SSMS cache</a>, but that <strong>didn’t</strong> solve the issue for me.</p><h3>About the “fishy” authentication setting</h3><p>Remember how the authentication showed as <strong>Unknown</strong> in the Azure portal?</p><figure><img alt="Azure SQL database Overview page displaying the Authentication method set to “SQL,” with a green arrow pointing to the correct setting." src="https://cdn-images-1.medium.com/max/824/1*ng35A9Fvn3C4n-HIMb9frg.png" /></figure><p>After successfully signing in through Visual Studio, it changed back to <strong>SQL Authentication</strong> — the correct value.</p><p>Good to see Azure fixing itself. 😄</p><h3>Summary</h3><p>As of this writing, SQL Server Management Studio (version 20) <strong>doesn’t properly refresh stale Azure credentials</strong>, which can cause login issues with Azure SQL databases.</p><p>Your current options are:</p><ul><li>Use <strong>Visual Studio</strong> (Windows only)</li><li>Use <strong>Visual Studio Code</strong></li><li><strong>Update</strong> SSMS</li><li><strong>Factory-reset</strong> your machine (only as a last resort)</li></ul><figure><img alt="In the first panel, our hero walks toward a road where an Entra character stands holding a red STOP sign, blocking the path to a sign that reads “Azure SQL.” The hero looks confused and holds a shirt with the SSMS logo. In the second panel, the hero takes off the shirt and tosses it aside. In the third panel, the hero now holds a purple shirt with a Visual Studio logo on it. In the fourth panel, the Entra character switches to a green GO sign. Last panel is pixelated." src="https://cdn-images-1.medium.com/max/1024/1*wNq6hs8MGXmmHLfpxcDBFQ.png" /></figure><p><em>Would you like to see what’s in the pixelated frame? I’ll leave that as an exercise for you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a44517f41976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Python App Timed Out Because Timeout = 0 Means Absolutely Nothing (Thanks ODBC!)]]></title>
            <link>https://medium.com/@lemalcs/my-python-app-timed-out-because-timeout-0-means-absolutely-nothing-thanks-odbc-831e8a75d16b?source=rss-25a78a149629------2</link>
            <guid isPermaLink="false">https://medium.com/p/831e8a75d16b</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[timeouterror]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[pyodbc]]></category>
            <dc:creator><![CDATA[Luis Lema]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 19:16:27 GMT</pubDate>
            <atom:updated>2025-11-08T19:18:06.116Z</atom:updated>
            <content:encoded><![CDATA[<p>I tried to make my python app wait forever for SQL Server. ODBC said no.</p><p>Setting the <strong>timeout</strong> value in an ODBC driver for SQL Server is not apparent at first sight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waBKuRoOXDAKwtoYyZUbvw.png" /></figure><p>Luckily, there <em>is</em> a way to solve this.</p><h3>What I tried</h3><p>When I was connecting a Python application to SQL Server using the ODBC driver, I ran into a <strong>timeout error</strong> even after doing this:</p><ul><li>Added the Timeout = 0 <strong>keyword</strong> to the connection string</li><li>Set the connection.timeout = 0 <strong>property</strong> in the driver</li></ul><blockquote><em>The zero (0) value means: </em><strong><em>wait forever</em></strong></blockquote><p><strong>Neither</strong> of them worked!…</p><p>After devouring the <a href="https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#connect"><strong>pyodbc documentation</strong></a>, I found this <strong>discouraging</strong> statement:</p><blockquote><em>“…this </em><strong><em>timeout</em></strong><em> functionality is implemented by the database driver, </em><strong><em>not pyodbc</em></strong><em>, and </em><strong><em>not all drivers support this</em></strong><em>.” 😕</em></blockquote><p>I know my SQL Server instance can get sluggish as hell sometimes, but it ultimately <strong>responds</strong> (my .NET apps worked flawlessly).</p><p>For my use case:</p><ul><li>Waiting is <strong>worth it</strong></li><li>Rewriting the Python script is <strong>not feasible</strong> due to time constraints</li></ul><p>As you can see, this <strong>timeout issue</strong> was turning into a real pain in the rear, so I want to share the solution I came up with.</p><p>(The solution was right under my nose 😛 — more on that later.)</p><p>Enough ranting, let’s get to it.</p><h3>Creating the Python project</h3><p>By the way, the <strong>pyodbc</strong> library uses the <strong>ODBC driver</strong> installed on the system.</p><p>In my case I’m using the <strong>ODBC Driver 17 for SQL Server</strong>.</p><p>First, let’s set up the project.</p><p>Run this in the command line:</p><pre>mkdir python_odbc_for_sql_server<br>cd python_odbc_for_sql_server<br>python -m venv .mvenv</pre><p>I’m using <strong>Windows </strong>for this project, so I <strong>activate </strong>the virtual environment with:</p><pre>.mvenv\Scripts\activate.bat</pre><blockquote>I didn’t use <strong>PowerShell</strong> because some folks are <strong>not allowed</strong> to use it. I’m sorry for them.</blockquote><p>If you’re a <strong>macOS</strong> or <strong>Linux</strong> user, run this:</p><pre>source .mvenv/scripts/activate</pre><p>Install <strong>pyodbc</strong>:</p><pre>pip install pyodbc</pre><blockquote>I’m using pyodbc version <strong>5.3.0</strong>.</blockquote><h3>Connecting Python to SQL Server</h3><p>Create the main.py file and add this code:</p><pre>from pyodbc import connect<br><br>def main():<br>    connection = connect(&quot;Driver={ODBC Driver 17 for SQL Server};Server=localhost\\sql2022d;Database=AdventureWorks2017;TrustServerCertificate=yes;Authentication=SPI&quot;)<br>    <br>    query = &quot;select count(1) as number_rows from Production.BillOfMaterials&quot;<br>    <br>    cursor = connection.cursor()<br>    cursor.execute(query)<br>    <br>    rows = cursor.fetchone()<br>    print(f&quot;Number of rows: {rows.number_rows}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>That code does the following:</p><ul><li>Connects to the <strong>sql2022d</strong> instance</li><li>Uses the <strong>AdventureWorks2017</strong> database</li><li>Uses <strong>Windows authentication</strong></li><li><strong>Counts</strong> the number of rows in Production.BillOfMaterials</li></ul><p>Run it:</p><pre>python main.py</pre><p>If your SQL Server instance is <strong>healthy</strong>, the Python script should run <strong>flawlessly</strong>:</p><figure><img alt="Number of rows returned by SQL Server." src="https://cdn-images-1.medium.com/max/1024/1*fo2eeqyrkHdvVhEhGZrYgw.png" /></figure><p>Now let’s <strong>break</strong> the code on purpose.</p><h4>Getting the timeout issue</h4><p>We are going to <strong>simulate</strong> a dog-slow SQL Server instance by <strong>stopping the service</strong>.</p><p>On <strong>Windows</strong>, use the <strong>Services</strong> console to start/stop SQL Server:</p><figure><img alt="The Windows Services console showing the SQL Server service." src="https://cdn-images-1.medium.com/max/599/1*p9Gf0kfyqdpJ-p5hyl6fVA.png" /></figure><p>Click <strong>Stop</strong>.</p><p>(In my case, I stop the <em>SQL2022D</em> instance.)</p><p>Then run main.py.</p><p><strong>Wait</strong> about 15 seconds and you should see this beautiful <strong>error message</strong>:</p><figure><img alt="Python script throwing a timeout error when connecting to SQL Server using the ODBC driver." src="https://cdn-images-1.medium.com/max/1024/1*UyP2rEkX6rwYibCeZ2mWwg.png" /></figure><blockquote>Login timeout expired (0)</blockquote><p>Yay! That’s exactly what we wanted.</p><h4>Fixing the timeout issue</h4><p>Set the timeout <strong>parameter</strong> of the connect function.</p><p>main.py should look like this:</p><pre>from pyodbc import connect<br><br>def main():<br>    connection = connect(<br>        &quot;Driver={ODBC Driver 17 for SQL Server};Server=localhost\\sql2022d;Database=AdventureWorks2017;Trusted_Connection=yes;TrustServerCertificate=yes&quot;,<br>        timeout=30  # wait for 30 seconds<br>    )<br><br>    query = &quot;select count(1) as number_rows from Production.BillOfMaterials&quot;<br><br>    cursor = connection.cursor()<br>    cursor.execute(query)<br>    <br>    rows = cursor.fetchone()<br>    print(f&quot;Number of rows: {rows.number_rows}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>The value of timeout is in <strong>seconds</strong>.</p><p>So the code will <strong>wait 30 seconds</strong> before throwing a timeout error.</p><p>Rerun it.</p><p><strong>After</strong> 30 seconds, you should get the <strong>same error</strong> as before.</p><p>In the screenshot below, the Python script fails at around <strong>31.16 seconds</strong>:</p><figure><img alt="Timeout after waiting 30 seconds when connecting to SQL Server." src="https://cdn-images-1.medium.com/max/1024/1*WnYCw-bM2hoP0TUXYEdNLg.png" /></figure><p>That’s it — now you can change the timeout to any value that works for you.</p><p><strong>Curiosity:</strong> if you start the SQL Server instance <strong>while</strong> the script is running, it will <strong>fail immediately</strong> afterward. That’s how it works 🙂‍↕️.</p><h3>Why my attempts failed</h3><h4>❌ Why Timeout in the connection string doesn&#39;t work</h4><p>As of today, the ODBC driver for SQL Server <strong>does not support</strong> a timeout keyword in the <strong>connection string</strong>.</p><p>However, you <em>can</em> set the ODBC attribute <strong>SQL_ATTR_LOGIN_TIMEOUT</strong>.</p><p>More on this <a href="https://github.com/mkleehammer/pyodbc/issues/106">here</a>.</p><h4>❌ Why connection.timeout = 0 doesn’t work</h4><p>If you write:</p><pre>connection = connect(&quot;Driver={ODBC Driver 17 for SQL Server};Server=localhost\\sql2022d;Database=AdventureWorks2017;Trusted_Connection=yes;TrustServerCertificate=yes&quot;)<br>connection.timeout = 0</pre><p>The value set in connection.timeout = 0 is <strong>ignored</strong>.</p><blockquote><em>In this example, </em><em>connection is a </em><em>pyodbc.Connection object.</em></blockquote><p>You <strong>must</strong> set the timeout parameter of the connect() function as shown earlier.</p><h3>Conclusion</h3><p>The ODBC driver for SQL Server <strong>does not</strong> support a timeout keyword in the connection string.</p><p>Find the <a href="https://github.com/lemalcs/python_odbc_for_sql_server">completed project in GitHub</a>.</p><p>However, these SQL Server drivers <strong>do</strong> support a <strong>timeout </strong>keyword in the connection string:</p><ul><li>ADO.NET</li><li>OLE DB</li></ul><p>Sometimes connection strings and drivers for databases are a <strong>chaos</strong>, so you have to <strong>tune into</strong> where your feet are stepping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7TPqJjf9StsF9pyZtcmzA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831e8a75d16b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>