<?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 Sindre Grindheim on Medium]]></title>
        <description><![CDATA[Stories by Sindre Grindheim on Medium]]></description>
        <link>https://medium.com/@sindre.grindheim?source=rss-42615da57fa3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wUlVj4errk8AmFuwhI70ig.jpeg</url>
            <title>Stories by Sindre Grindheim on Medium</title>
            <link>https://medium.com/@sindre.grindheim?source=rss-42615da57fa3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:16:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sindre.grindheim/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[How to unit test macros in dbt]]></title>
            <link>https://medium.com/glitni/how-to-unit-test-macros-in-dbt-89bdb5de8634?source=rss-42615da57fa3------2</link>
            <guid isPermaLink="false">https://medium.com/p/89bdb5de8634</guid>
            <category><![CDATA[dbt-cloud]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[dbt-core]]></category>
            <category><![CDATA[data-testing]]></category>
            <dc:creator><![CDATA[Sindre Grindheim]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 12:51:51 GMT</pubDate>
            <atom:updated>2024-11-12T12:51:51.150Z</atom:updated>
            <content:encoded><![CDATA[<h4>A suggested framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UOjPmMc1HXcgtuCy" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>tl;dr:</blockquote><blockquote>By using an empty ephemeral model as a source, a validation sql model that selects from the source and applies a macro to given input columns and a unit test definition for the validation model that provides inputs, outputs and overrides, it is possible to use the unit test framework in dbt for macros without any setup or teardown.</blockquote><h4>Background</h4><p>After having worked in the industry for more than 10 years, being able to unit test pieces of data transformations in a simple and effective matter has always been a missing piece of the puzzle.</p><p>In a typical setup, data tests are to varying degrees end to end rather than on a granular logic level. This typically causes issues when the tests reveal errors, as you first have to identify whether the cause was bad source data or actually bugs in the implemented logic.</p><p>As usual in the dbt community, community members started creating packages to support unit testing in various ways early on, which in turn made dbt Labs implement the first built-in framework for unit testing in dbt version 1.8.</p><p>This enabled unit testing of models by specifying dummy values for inputs (ref and source) along with the expected output. This was especially great for verifying models with few inputs, and ideally a few complex calculations that needed to be verified.</p><p>Macros intuitively seem like a natural fit for unit testing, as they themselves are small units of logic that take some input and generate some output. In addition, for all package maintainers, being able to define tests for the macros without too much setup and teardown hassle is useful.</p><p>But for the time being, macros aren’t directly supported and need some sort of testing framework to be tested in isolation.</p><h4><strong>A dbt unit testing framework for macros</strong></h4><p>In order to unit test a macro, we need three things. A source input for each test, a validation model that uses the specific macro, and a unit test definition that defines the input, outputs and overrides.</p><p>One of the core pieces of the framework is being able to have a reusable source model that can be utilized for all unit tests without having to materialize anything. This can be done by using an ephemeral model, due to the following key piece of information:</p><blockquote>If you want to unit test a model that depends on an ephemeral model, you must use format: sql for that input. (<a href="https://docs.getdbt.com/docs/build/unit-tests#unit-testing-a-model-that-depend-on-ephemeral-models">source</a>)</blockquote><p>This enables us to always reuse the same source model while configuring it however we want.</p><p><strong>Step 1</strong>: Create a model calledtest_source.sql with the following content:</p><pre>{{ config(materialized=&#39;ephemeral&#39;) }}  </pre><p><strong>Step 2</strong>: Create validation models for each macro to be tested.</p><p>Each model will select from {{ ref(&#39;test_source.sql&#39;) }}, and then call the macro with required input for the parameters. If the macro simply takes one or more columns as input then they can be defined as usual.</p><p>However, for any jinja variable inputs, the trick is to define the input as variables, since these can be overriden in the unit test definition. No need to define the variables in the .sql file itself, but you must ensure to specify a dummy value as the optional second argument. Otherwise the model will fail during parsing.</p><p>If we assume we’re creating an integration test for the macro macro_nameof the package package_name, then create a file called validate__macro_name.sql:</p><pre>with dummy_source as (<br>    select * from {{ ref(&#39;test_source&#39;) }}<br>)<br>select<br>    {{ package_name.macro_name(&#39;input_column_a&#39;, var(&#39;input_column_list_b&#39;, [])) }} AS OutputColumnName<br>from dummy_source</pre><p>This file can be created in many ways, depending on how we’d like to test the output.</p><p>A variation of the file could look like the following, where we instead test that the macro generates equal output as a given column or sql function:</p><pre>with dummy_source as (<br>    select * from {{ ref(&#39;test_source&#39;) }}<br>)<br>select<br>    Comparison = &quot;{{ package_name.macro_name(&#39;input_column_a&#39;)) }}&quot; AS IsEqual<br>from dummy_source</pre><p><strong>Step 3</strong>: Create validation unit tests</p><p>The final step is creating validation tests for each macro. Here we specify the following pieces of information:</p><ul><li>model: The validation model defined in the previous step</li><li>overrides: If the model takes jinja variable parameters, these can be specified as vars overrides.</li><li>given: The test always uses the test_source model as input, while the rows are specified using format: sql. If more advanced input is required, the input definition can be written in the shape of multiple CTEs.</li><li>expect: Define the expected value in accordance with the definition of the validation model.</li></ul><p>We continue with the same example as above, so we then create a file called validate__macro_name.yml:</p><pre>unit_tests:<br>  - name: validate__macro_name<br>    description: &quot;Unit test that verifies that macro_name behaves as expected.&quot;<br>    model: validate__macro_name<br>    overrides:<br>      vars:<br>        input_column_list_b: [&#39;col1&#39;,&#39;col2&#39;,&#39;col3&#39;]<br>    given:<br>      - input: ref(&#39;test_source&#39;)<br>        format: sql<br>        rows: |<br>          select 1 as col1, 2 as col2, 3 as col3, &#39;test&#39; as input_column_a<br>    expect:<br>      rows:<br>        - {ColumnCount: 2}</pre><p>Like above, the variation of the code could be defined as below, where we have defined some sql function for the comparison value, and expect that the equality output column is true.</p><pre>    given:<br>      - input: ref(&#39;test_source&#39;)<br>        format: sql<br>        rows: |<br>          select 1 as input_column_a, &lt;some_sql_function&gt; as Comparison<br>    expect:<br>      rows:<br>        - {IsEqual: true}</pre><h4>Final remarks</h4><p>And that’s it — we now have a complete test setup for unit testing a macro without having to do any setup or teardown.</p><p>By being creative in the definition of the validation model and unit test, this approach has seemed to work very well for my own dbt package and could hopefully do the same for your project.</p><p>And if dbt at some point implements support for testing macros directly, then it should be relatively simple to rewrite the unit tests accordingly.</p><h4>PS — for dbt package maintainers</h4><ol><li>Combining the unit tests with a local pre-commit hook that is run whenever a macro sql file is added/changed is very helpful for catching bugs early on.</li><li>There seems to be a bug (i.e. definitive room for improvement) in the <a href="https://docs.getdbt.com/guides/building-packages?step=4">suggested method</a> for defining integration tests for a dbt package. The documentation says to use the below definition in the integration_testssub-project. However, this causes an infinite loop of copying the integration_testsfolder again and again.<br>A workaround is creating a script that replaces dbt deps by copying the parent project into the integration_testsproject while excluding the integration_tests folder itself.</li></ol><pre>packages:<br>    - local: ../</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89bdb5de8634" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glitni/how-to-unit-test-macros-in-dbt-89bdb5de8634">How to unit test macros in dbt</a> was originally published in <a href="https://medium.com/glitni">Glitni</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Querying JSON using SQL — A comparison of Synapse, BigQuery, Databricks and Snowflake]]></title>
            <link>https://medium.com/glitni/querying-json-using-sql-a-comparison-of-synapse-bigquery-databricks-and-snowflake-166c096add54?source=rss-42615da57fa3------2</link>
            <guid isPermaLink="false">https://medium.com/p/166c096add54</guid>
            <category><![CDATA[synapse-analytics]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[databricks-sql]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[google-big-query]]></category>
            <dc:creator><![CDATA[Sindre Grindheim]]></dc:creator>
            <pubDate>Mon, 02 May 2022 20:26:44 GMT</pubDate>
            <atom:updated>2023-02-25T10:27:47.545Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>Querying JSON using SQL — A comparison of Synapse, </em>BigQuery, <em>Databricks and Snowflake</em></h3><h4>A practical comparison of schema-on-read support for JSON in <em>popular big data processing engines</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeqIX85Y6fJm9t9dZUJryA.png" /></figure><blockquote>This article was updated on February 25th, 2023, with the support for native JSON types in Google BigQuery.</blockquote><p>Whether you’re building a cloud data warehouse or a data lakehouse, you’re bound to end up with loads of JSON files in your data lake as they’re frequently used for logging data and as output from APIs. Knowing how to analyze these semi structured files quickly using SQL is an essential skill as a data worker.</p><p>However, each of the popular data processing engines have different variations in how their SQL dialect is implemented. This article aims to show a practical comparison of how the same information is extracted using a select few tool, namely Synapse Serverless SQL pool, BigQuery, Databricks SQL and Snowflake.</p><h4>Case</h4><p>In order to have a fair comparison, we will be using the same dataset for all data processing engine. The case is a some store inventory data courtesy of the <a href="https://docs.databricks.com/spark/latest/spark-sql/semi-structured.html#id5">Databricks documentation</a>, although slightly simplified for this article.</p><p>This dataset is selected due to it containing a fair variation of data structures, and contains both maps of maps as well as arrays.</p><p>What we’d like to do is list the owner of the store along with all the books, where we’re interested in the author and title. In addition, should there be any readers then we’d like to output that too, but in a raw, unprocessed form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe8a334b0599069aab2c9b4bec889e4/href">https://medium.com/media/cfe8a334b0599069aab2c9b4bec889e4/href</a></iframe><p>This means that the output should be the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ad0ab280b9407107017039b7da3d63a/href">https://medium.com/media/5ad0ab280b9407107017039b7da3d63a/href</a></iframe><h4>Synapse — T-SQL</h4><p>First out is <a href="https://docs.microsoft.com/en-us/azure/synapse-analytics/sql/on-demand-workspace-overview">Synapse Serverless SQL pool</a>, that comes with every Azure Synapse Analytics workspace and is used to query data residing in data lakes. The SQL dialect is <a href="https://docs.microsoft.com/en-us/azure/synapse-analytics/sql/overview-features">T-SQL</a>, an ANSI compliant dialect of the SQL language used by Microsoft.</p><p>In T-SQL, JSON is not a native data type, and so one must typically use some, or all, of the following functions to extract all the required data elements:</p><ul><li><a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/json-value-transact-sql?view=azure-sqldw-latest">JSON_VALUE</a>: extracts a scalar</li><li><a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/json-query-transact-sql?view=azure-sqldw-latest">JSON_QUERY</a>: extracts on object or array</li><li><a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=azure-sqldw-latest">OPENJSON</a>: parses JSON and returns a rowset</li></ul><p>When combining the above functions and applying them to the raw data we end up with the following code:</p><pre>WITH raw_json AS (<br> SELECT &#39;&lt;full store_inventory.json content&gt;&#39; AS raw<br>)<br>SELECT<br> JSON_VALUE(raw, &#39;$.owner&#39;) AS Owner,<br> JSON_VALUE(value, &#39;$.author&#39;) AS Author,<br> JSON_VALUE(value, &#39;$.title&#39;) AS Title,<br> JSON_QUERY(value, &#39;$.reader&#39;) AS Readers<br>FROM raw_json,<br> OPENJSON(<br>  (SELECT * FROM raw_json), <br>  &#39;$.store.book&#39;<br>)</pre><p>Clearly, this isn’t particularly intuitive if this is the first time you’re using these functions.</p><p>But before we look at how it works in data processing engines that treat JSON as a native data type, let’s look at the <em>current</em> similarities in implementation in BigQuery.</p><h4>Google BigQuery</h4><p><a href="https://cloud.google.com/bigquery">BigQuery</a> is a serverless multicloud data warehouse provided by Google. Historically, the JSON support offered by BigQuery has had a lot of similarities with the T-SQL functions. However, <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/json-data">BigQuery now supports JSON as a native data type</a> and that radically simplifies the use of JSON in BigQuery.</p><p>Due to the now native support, elements are extracted using a dot or bracket notation from fields of the JSON type. There are three methods to create JSON values:</p><ul><li>Create a JSON literal using SQL</li><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#parse_json">parse_json</a>: converts a string to JSON</li><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#to_json">to_json</a>: converts a SQL type to JSON</li></ul><p>In addition, the following functions will come in handy for more advanced use cases:</p><ul><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#unnest_operator">unnest</a>: returns an array as a table with one row per element</li><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#json_query_array">json_query_array</a>: extracts an array and returns it as an ARRAY&lt;JSON&gt; of JSON</li><li><a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#json_value_array">json_value_array</a>: extracts an array of scalar values and returns it as an ARRAY&lt;STRING&gt; of scalar values</li></ul><p>This results in the following for our example:</p><pre>WITH raw_json AS (<br>    SELECT parse_json(&#39;&lt;full store_inventory.json content&gt;&#39;) AS raw<br>)<br>SELECT<br>  raw.owner AS Owner, <br>  book.author AS Author,<br>  book.title AS Title,<br>  book.reader AS Readers<br>FROM <br>  raw_json,<br>  UNNEST(<br>    JSON_QUERY_ARRAY(raw.store.book)<br>  ) AS book</pre><p>As you can see, this is many times easier than the old implementation of JSON support in BigQuery (which is now removed from this article), as well as that of T-SQL.</p><p>The implementation of Databricks SQL and Snowflake are closely related to this modern way of treating JSON as a native type. But since each database has their own variations, some of the functions are different.</p><h4>Databricks SQL</h4><p>Next is <a href="https://databricks.com/product/databricks-sql">Databricks SQL</a>, the technology built by Databricks to do “data warehousing on the lakehouse”. In 2022, Databricks SQL updated to use ANSI standard SQL dialect. JSON is natively supported by Databricks, and the change to ANSI brought improvements to the simplicity of querying JSON data in a modern manner.</p><p>Due to the native support, most elements can be extracted using a natural syntax that uses either a dot notation or a bracket notation. A simple example of both would be raw:store.fruit[0][&#39;type’], in order to get the type of the first fruit (apple). However, for more complex types, the following functions come in handy:</p><ul><li><a href="https://docs.databricks.com/sql/language-manual/functions/from_json.html">from_json</a>: returns a struct value with the provided schema</li><li><a href="https://docs.databricks.com/sql/language-manual/sql-ref-syntax-qry-select-lateral-view.html">lateral view</a>: used in conjunction with explode to fetch complex types and apply them to the original row</li></ul><p>So how would a Databricks implementation of our inventory data look?</p><pre>WITH raw_json AS (<br>  SELECT &#39;&lt;full store_inventory.json content&gt;&#39; AS raw<br>)<br>SELECT<br>  raw:owner AS Owner,<br>  book:author AS Author,<br>  book:title AS Title,<br>  book:reader AS Readers<br>FROM<br>  raw_json<br>LATERAL VIEW EXPLODE(FROM_JSON(raw:store.book, &#39;array&lt;string&gt;&#39;)) AS book</pre><p>This structure is immediately easier to read and understand. And as this is a very simple test case, this simplicity is even more apparent when the complexity increases.</p><p><strong>Side note</strong>: Although the basic JSON functions are simple to use, Databricks needs to know the schema before you can use them. The trick here is knowing that each level in a JSON file is typically either a map or an array, and only using &#39;array&lt;string&gt;&#39; or &#39;map&lt;string,string&gt;&#39; as the schema in the cases when you need to handle the more complex elements with from_json.</p><h4>Snowflake</h4><p>Finally, let’s look at <a href="https://www.snowflake.com/">Snowflake</a>, a data platform powered by an elastic performance engine for “near-unlimited scale”.</p><p>Like Databricks, Snowflake has support for both dot notation and bracket notation when traversing the semi structured data, and they work in the same way.</p><p>However, an important distinction between the two are when element names does not conform to the SQL identifier rules, e.g. when there are spaces in the name. In these cases, you need to use double quotes in Snowflake where you would use a back tick ` in Databricks. An example of this is raw:&quot;zip code&quot;.</p><p>Some other specific useful functions to be aware of are:</p><ul><li><a href="https://docs.snowflake.com/en/sql-reference/functions/parse_json.html">parse_json</a>: interprets a string as a JSON document, returning the native variant value</li><li><a href="https://docs.snowflake.com/en/sql-reference/functions/flatten.html">lateral flatten</a>: flattens compound values into multiple rows</li></ul><p>And applied to our example it becomes:</p><pre>WITH raw_json AS (<br>    SELECT parse_json(&#39;&lt;full store_inventory.json content&gt;&#39;) AS raw<br>)<br>SELECT<br>    raw:owner AS Owner,<br>    value:author AS Author,<br>    value:title AS Title,<br>    value:reader AS Readers<br>FROM <br>    raw_json,<br>    lateral flatten(input =&gt; raw:store.book)</pre><p>As you can see, this is very similar to both the BigQuery and Databricks SQL versions, but with a few variations. First of all, we needed to parse the JSON since it was saved as a string, plus the implementation of flattening is slightly different.</p><h4>Final notes</h4><p>Traditionally, JSON parsing in databases has been slow due it not being native and you had to rely on several cumbersome functions to get exactly what you wanted.</p><p>However, this is changing now in the newer data processing engines, with BigQuery now also having made the leap to the modern approach.</p><p>JSON is finally being treated like a native data type, and is thus easily available not only to SQL experts, but to all data analysts at all levels.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=166c096add54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glitni/querying-json-using-sql-a-comparison-of-synapse-bigquery-databricks-and-snowflake-166c096add54">Querying JSON using SQL — A comparison of Synapse, BigQuery, Databricks and Snowflake</a> was originally published in <a href="https://medium.com/glitni">Glitni</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>