<?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[datashift.eu - Medium]]></title>
        <description><![CDATA[Data engineering blogs - Medium]]></description>
        <link>https://medium.com/datashift-eu?source=rss----fe7ff9b94a85---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>datashift.eu - Medium</title>
            <link>https://medium.com/datashift-eu?source=rss----fe7ff9b94a85---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:53:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/datashift-eu" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SQLFluff and dbt: Enforcing SQL Quality at Scale]]></title>
            <link>https://medium.com/datashift-eu/sqlfluff-and-dbt-enforcing-sql-quality-at-scale-c633bc1e33e7?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/c633bc1e33e7</guid>
            <category><![CDATA[sqlfluff]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[De Lee Liam]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 07:44:24 GMT</pubDate>
            <atom:updated>2025-12-03T07:44:22.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever had the feeling your team was spending a lot of time commenting standards on merge requests, there were no clear standards in your SQL code, or you found your SQL hard to read? Instead of just writing code and playing with your data?</p><p><strong>Then this is the blog post for you!</strong></p><p>We will touch the following points:</p><ol><li>Explaining SQLFluff</li><li>How to install SQLFluff</li><li>How to use SQLFluff</li><li>Some basic configs</li></ol><h3>Explaining SQLFluff</h3><p><a href="https://docs.sqlfluff.com/en/stable/">SQLFluff</a> is an open source SQL linter and formatter that helps teams write clean, consistent, and standards-compliant SQL. It checks your queries against configurable rules — catching things like inconsistent casing, missing commas, or improper indentation — before they ever make it into your codebase.</p><p>Think of it as <a href="https://prettier.io/docs/"><strong>Prettier</strong></a><strong> or </strong><a href="https://eslint.org/docs/latest/use/core-concepts/"><strong>ESLint</strong></a><strong>, but for SQL! </strong>It doesn’t just enforce style, it helps you maintain quality and readability across a growing SQL codebase.</p><p>SQLFluff <a href="https://docs.sqlfluff.com/en/stable/reference/dialects.html">supports many SQL dialects</a> (like BigQuery, Snowflake, Redshift, and Databricks), also works perfect together with <a href="https://docs.getdbt.com/docs/cloud/dbt-cloud-ide/lint-format#lint">dbt</a> and integrates seamlessly into your workflow — whether that’s through your IDE, CI/CD pipeline, or pre-commit hooks.</p><p>By automating SQL reviews, teams can spend less time nitpicking syntax and more time focusing on what really matters: <strong>data accuracy and performance</strong>.</p><h3>How to install SQLFluff</h3><p>Have a look at this git repo with an example of how to install SQLFluff with dbt and DuckDB for an easy setup.</p><p><a href="https://github.com/datashift-eu/sqlfluff-basic-setup">https://github.com/datashift-eu/sqlfluff-basic-setup</a></p><p>This can all be changed to your own environment and use case of course.</p><h3>How to use SQLFluff</h3><p>In SQLFluff there are 2 main options you can use to format your files:</p><p>sqlfluff lint: This will lint your file(s) and gives you back all breaches found compared to the .sqlfluff config file. Based on this list you can work out what needs to be changed in your file.</p><pre>sqlfluff lint path/to/your_file.sql</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRzrsHUwuBaMA-dVea5l3Q.png" /><figcaption>result example of sqlfluff lint</figcaption></figure><p>sqlfluff fix: This will try and fix all the breaches found by the lint. Not all breaches can be automatically fixed, so always do a lint after to make sure everything is working, and fix non auto fixable linting yourself.</p><pre>sqlfluff fix path/to/your_file.sql</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEv9JkEK-OdP7KGJ1e_8dQ.png" /><figcaption>result example of sqlfluff fix</figcaption></figure><h3>Some basic configs</h3><p>For all the configs possible I would direct you to the <a href="https://docs.sqlfluff.com/en/stable/reference/rules.html">SQLFluff docs</a>.</p><p>For this example we have some basic configs:</p><ol><li>we disabled <a href="https://docs.sqlfluff.com/en/stable/reference/rules.html#rule-structure.column_order">rule L034</a>: since we used some unions (in our own project) and needed to have exactly the same ordering.</li><li>tab_space_size = 4: this indicates that tabs should always be 4 spaces.</li><li>capitalisation_policy = lower: this indicates that select, from and so on should be lower case</li><li>line_position = leading under [sqlfluff:layout:type:comma]: indicating that we want the comma at the start of the line.</li><li>and many more!</li></ol><p>All those options we have selected in our .sqlfluff file can always be changed to your own preference or your team’s needs.</p><p>If you enjoy a clean codebase as much as we do, why not turn this energy into impact at Datashift? <a href="https://www.datashift.eu/jobs">Check out our vacancies</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c633bc1e33e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/sqlfluff-and-dbt-enforcing-sql-quality-at-scale-c633bc1e33e7">SQLFluff and dbt: Enforcing SQL Quality at Scale</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitLab CI/CD: Pipelines for Python and Terraform in AWS]]></title>
            <link>https://medium.com/datashift-eu/gitlab-ci-cd-pipelines-for-python-and-terraform-in-aws-579ed25713bd?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/579ed25713bd</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Pieter Coremans]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 18:50:44 GMT</pubDate>
            <atom:updated>2025-09-17T18:50:44.237Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An introduction to configuring GitLab CI/CD through the .gitlab-ci.yml file.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3Zp88qodEZQ6gw0EjTv5g.png" /></figure><p><a href="https://www.atlassian.com/continuous-delivery/principles/continuous-integration-vs-delivery-vs-deployment">CI/CD</a> (Continuous Integration / Continuous Delivery/Deployment) pipelines are essential for data engineers in today’s modern data landscape. These pipelines automate testing and deployment processes, thereby minimizing manual errors and freeing up valuable development time. Additionally, they provide alerting and graphical representation of pipeline states and their history.</p><p>When selecting a tool for CI/CD, there are several options available. In this post, I will explain how I utilize GitLab CI/CD for both Python code running on AWS Lambda and Terraform code for AWS resources. The Python code will be containerized and stored in Amazon Elastic Container Registry (ECR).</p><h3>CI/CD variables</h3><p>To enable your pipeline to access the necessary cloud resources, you must configure specific variables, such as AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to authenticate with AWS. To prevent these variables from being exposed during runtime, GitLab allows you to specify them either <a href="https://docs.gitlab.com/user/group/">at the group level</a> (where they will be inherited by child projects) or directly at the project level. To configure these variables, navigate to <strong>Settings</strong> -&gt; <strong>CI/CD</strong> -&gt; <strong>Variables</strong>. Once specified, you can utilize them in subsequent steps. Ensure you uncheck the “Protected variable” flag if you need to use a variable for a non-protected branch, such as a feature branch where you intend to run unit tests or create a merge request.</p><h3>Python repo</h3><p>For example, below is a simple project containing Python code for a function nth_workday, which calculates the workday of the month. The project also includes unit tests in the tests/ folder, Poetry files containing the project’s dependencies, and a Dockerfile for creating the Docker image during the deployment stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8F4kLuT1B_Q6WHx_mDXxA.png" /><figcaption>GitLab Python project root directory</figcaption></figure><h4>.gitlab-ci.yml</h4><p>At its core, all the logic for the pipeline is written in a .gitlab-ci.yml file located at the root of the GitLab project. Unlike AWS CodePipeline, where the pipeline <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-view-console.html#pipelines-settings-console">is a fixed resource</a> with multiple executions triggered by new events, GitLab CI/CD operates differently. In GitLab CI/CD, there is only an ephemeral pipeline that is triggered by a new event which exists solely for the duration of its execution. This means that we do not need to set up or maintain any infrastructure. This single file is the entry point for all configuration, making it more convenient to handle. Additionally, the pipeline configuration resides alongside the rest of your code.</p><p>At the top of the yaml file, there are 3 important sections.</p><ul><li><strong>variables</strong>: This section allows you to create variables to be used throughout the file. Using the CI/CD variables defined earlier, you can access these with the $-notation and create new variables.</li><li><strong>.standard-rules</strong>: This powerful feature defines when the pipeline should be triggered. In these rules, I have specified that the pipeline should start both when a commit is made to the main branch and when a merge request is created. You can later override these rules if you wish to use different criteria.</li><li><strong>stages</strong>: This section defines the stages that will be encountered during the pipeline configuration and in which order they should be executed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iI2N-wnsYOWBWt3jB7tB5w.png" /><figcaption>variables, .standard-rules and stages</figcaption></figure><h4>Test stage</h4><p>Following these sections comes the bulk of the configuration: jobs. Jobs describe the specific actions to perform and the stage to which each job belongs. Jobs are categorized according to their stage, and only when all jobs of a particular stage have been successfully completed does the execution of the next stage commence.</p><p>Below is an example of a test job. I specify the stage to which the job should belong, the image to use, and the commands to run before executing the tests, followed by the tests themselves. Using the extends keyword, I instruct GitLab to apply the standard rules defined earlier, as I want to run the tests both when a new merge request is created and when a new Docker image is deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iczXuyQVapAesuMcu1bU8w.png" /><figcaption>Python run-tests job</figcaption></figure><h4>Build stage</h4><p>The build-image job is structurally similar to the run-tests job; however, it should only execute on a commit to the main branch. Therefore, the rules keyword is used with the appropriate conditional. Since we are running Docker commands within a Docker image, we need to add the docker:dind service, which stands for “<a href="https://docs.gitlab.com/ci/docker/using_docker_build/#use-docker-in-docker">Docker-in-Docker</a>”. In the before_script, we log in to ECR and pull the latest image. This step is not mandatory but it accelerates the process by requiring only the upload of the image layers that have changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oigh0HnfRxjLV6E-_3dAQQ.png" /><figcaption>Python build-image job</figcaption></figure><p>This is a simple example of a pipeline, as there is only one job per stage and at most two stages. When a pipeline starts, you can navigate to the <strong>Build</strong> -&gt; <strong>Pipelines</strong> section to view a visual representation of the triggered pipeline. You can then click on the job of interest to see the console output, along with statistics about the job and links to related jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnNSv1MJrifwjzIt5adPmw.png" /><figcaption>Python merge request pipeline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ET7LRZRP7cCUE_diC1SZjQ.png" /><figcaption>Python main branch pipeline</figcaption></figure><h3>Terraform repo</h3><p>For Terraform, the setup differs slightly. In this case, a Dockerfile is not required. However, we do have different environments and will utilize templates to make the CI/CD pipeline modular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MpIvGg7pjqvAuw-tEZjxw.png" /><figcaption>GitLab Terraform project root directory</figcaption></figure><h4>.gitlab-ci.yml</h4><p>In the .gitlab-ci.yml file, we can specify the default image to use, the standard rules, and the stages, similar to the Python example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0QnzmZk42mWF87nzDHa9w.png" /><figcaption>Terraform .gitlab-ci.yml file</figcaption></figure><h4>Template</h4><p>In addition to the .gitlab-ci.yml file, we now have a terraform-run-template.yml file located in the templates/ folder. This time, we can use the include keyword in the .gitlab-ci.yml file to import the template file and provide input values, which will populate the specified parameters at the top of the template file. These values can then be accessed using the $[[ inputs.&lt;parameter_name&gt; ]] syntax. Utilizing templates in this manner reduces the amount of code to write and lowers the likelihood of typos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wdqd3D0IRa8yWPOs3pvOYA.png" /><figcaption>Terraform plan stage</figcaption></figure><p>Also, note the use of the <a href="https://docs.gitlab.com/ci/jobs/job_artifacts/">artifacts</a> keyword here. This is necessary to output the Terraform plan, which will be applied in the Terraform apply step later in the pipeline, the rest of which is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdWbgj9HjGfsPQV2VeUiTg.png" /><figcaption>Approve and Terraform apply stages</figcaption></figure><p>Ultimately, by incorporating a manual approval step and a Terraform apply step, the final pipeline resembles the image below. First, the Terraform plan job in the development stage will run, and only after approval will the changes be applied. If the development stage succeeds, the same process will occur for the production stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urSuGpy6ie4VBUbXagN55A.png" /><figcaption>Terraform pipeline</figcaption></figure><p>And with that, we’re running in production 🚀</p><p>If you enjoy learning about the technical side of DevOps, why not turn your curiosity into impact at Datashift? <a href="https://www.datashift.eu/jobs">Check out our vacancies</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=579ed25713bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/gitlab-ci-cd-pipelines-for-python-and-terraform-in-aws-579ed25713bd">GitLab CI/CD: Pipelines for Python and Terraform in AWS</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[dbt to DataHub: A practical guide to metadata ingestion]]></title>
            <link>https://medium.com/datashift-eu/dbt-to-datahub-a-practical-guide-to-metadata-ingestion-7bc15d56c72a?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/7bc15d56c72a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[datahub]]></category>
            <category><![CDATA[data-governance]]></category>
            <dc:creator><![CDATA[Alp]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 16:05:00 GMT</pubDate>
            <atom:updated>2025-04-21T16:25:13.848Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A hands-on tutorial on building dbt models on a Postgres database, ingesting the resulting dbt metadata into DataHub.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYdkdYON976j6k-m6swvrw.png" /></figure><p>As a tool for building, testing, and deploying data transformations, dbt needs little introduction. A core feature of dbt is its ability to infer relationships between models. It writes this and other metadata, like model documentation and test results, to internal artifacts in <a href="https://docs.getdbt.com/reference/artifacts/dbt-artifacts">well-documented</a> json formats. Beyond dbt itself, these artifacts can be a valuable data source for integration with other tools, such as metadata platforms like <a href="https://datahubproject.io/">DataHub</a>. These platforms enable use cases like unified data lineage views across systems or support for operational data governance.</p><p>In this post, we’ll show how to integrate dbt metadata with DataHub. It’s a hands-on tutorial that comes with a <a href="https://github.com/datashift-eu/dbt-datahub-tutorial">companion repository</a>. If you feel like following along and writing the dbt models yourself, the tutorial branch is your starting point. If you prefer to just run the project, use the main branch instead.</p><h3>Systems up</h3><p>To get started, install the project dependencies. We’re using the <a href="https://datahubproject.io/docs/cli/#sources">DataHub CLI with the dbt plugin</a>.</p><pre>poetry install</pre><p>Next, start DataHub locally using the <a href="https://datahubproject.io/docs/quickstart/#start-datahub">Docker quickstart</a>. It’s a simple way to get everything running with no extra setup.</p><pre>poetry run datahub docker quickstart</pre><p>dbt needs a database to work with. We’ll use a local Postgres instance running in a container.</p><pre>docker compose up -d</pre><p>The tutorial branch includes a skeleton dbt project. Once Postgres is running, you can test your dbt setup.</p><pre>docker compose run --rm dbt debug</pre><p>No errors? Good to go.</p><h3>The dbt project</h3><p>Before you can start building models, install the dbt dependencies. We’re using dbt-utils, which includes, among other things, helpful data tests like the one we are using in this example, accepted_range (<a href="https://github.com/dbt-labs/dbt-utils?tab=readme-ov-file#accepted_range-source">readme</a>).</p><pre>docker compose run --rm dbt deps</pre><p>Since we don’t have a real data source, we’ll use dbt seed to load some sample data. This data is included in the repository as a csv file. It represents shipment data with details like sender, recipient, and weight.</p><pre>tracking_id,sender,recipient,shipment_type,weight_kg,origin,destination,delivery_date<br>TRK376593,Zalando,CUST1388,Large Parcel,9.58,Brussels,Paris,2025–02–25<br>TRK351882,Coolblue,CUST4823,Large Parcel,4.18,Amsterdam,Rotterdam,2025–02–25<br>TRK422924,Bol.com,CUST5988,Small Parcel,8.27,Antwerp,Lille,2025–02–26</pre><p>To be able to properly seed this data, add a <a href="https://docs.getdbt.com/reference/seed-configs">seed configuration</a>. Note how we are including explicit data types here, as dbt would have inferred a float type for weight_kg, which is not a great way to represent weights in this context.</p><pre># seeds/_seeds.yml<br><br>version: 2<br>seeds:<br>  - name: delivered_shipments<br>    config:<br>      schema: sample_data<br>      column_types:<br>        tracking_id: text<br>        sender: text<br>        recipient: text<br>        shipment_type: text<br>        weight_kg: numeric(5, 2)<br>        origin: text<br>        destination: text<br>        delivery_date: date</pre><p>Structurally, this is a very simple dbt project. It has a staging and a mart layer, each with one model. We are setting this up in a pragmatic way, based on the <a href="https://docs.getdbt.com/best-practices/how-we-structure/1-guide-overview">dbt best practice</a> for how to structure a dbt project.</p><p>Start by creating a staging model that selects all columns from the seeded data.</p><pre>-- staging/stg_delivered_shipments.sql<br><br>select<br>    tracking_id,<br>    sender,<br>    recipient,<br>    shipment_type,<br>    weight_kg,<br>    origin,<br>    destination,<br>    delivery_date<br>from<br>    {{ ref(&#39;delivered_shipments&#39;) }}</pre><p>Next, add a <a href="https://docs.getdbt.com/reference/model-configs">model configuration</a> for this staging model. This includes metadata that will later be visible in DataHub. You can fill in ownership and glossary info as you like, although that will also impact how you will configure ingestion into DataHub later. See the file <a href="https://github.com/datashift-eu/dbt-datahub-tutorial/blob/main/dbt/models/staging/_models.yml">in the repository</a> for a full worked example.</p><pre># staging/_models.yml<br><br>version: 2<br>models:<br>  - name: stg_delivered_shipments<br>    description: <br>    meta:<br>      business_owner: <br>      data_steward: <br>      technical_owner: <br>      terms_list: <br>    columns:<br>      - name: tracking_id<br>        data_type: text<br>        description: Unique tracking identifier associated with each shipment<br>        data_tests:<br>          - unique<br>          - not_null</pre><p>Note how we are using dbt’s meta fields to enrich our model metadata. This config will be picked up by DataHub through <a href="https://datahubproject.io/docs/generated/ingestion/sources/dbt/#dbt-meta-automated-mappings">automated mappings</a>. We’ll return to this topic when we configure the DataHub <a href="https://datahubproject.io/docs/metadata-ingestion/recipe_overview/">ingestion recipe</a> below.</p><p>You can now add a mart model that aggregates shipments by sender.</p><pre>-- marts/shipments_by_sender.sql<br><br>select<br>    sender,<br>    count(tracking_id) as shipments,<br>    round(avg(weight_kg), 2) as avg_weight<br>from <br>    {{ ref(&#39;stg_delivered_shipments&#39;) }}<br>group by<br>    sender</pre><p>Finally, add a model configuration for this mart model as well.</p><pre># marts/_models.yml<br><br>version: 2<br>models:<br>  - name: shipments_by_sender<br>    description: Aggregated shipment data grouped by sender<br>    meta:<br>      terms_list: Shipment,Sender<br>    columns:<br>      - name: sender<br>        data_type: text<br>        description: Company shipping the package<br>      - name: shipments<br>        data_type: integer<br>        description: Total number of shipments sent by the company<br>      - name: avg_weight<br>        data_type: numeric<br>        description: Average weight of shipments sent by the company, in kilograms</pre><p>Now that the dbt models are ready, we can generate the dbt documentation using dbt docs. This creates the catalog.json file, part of the metadata that you will soon ingest into DataHub.</p><pre>docker compose run --rm dbt docs generate</pre><p>After that, run the full dbt pipeline with dbt build. This handles seeding the data, running the models, and running the tests. It writes additional metadata to the manifest.json and run_results.json files.</p><pre>docker compose run --rm dbt build</pre><h3>Ingestion into DataHub</h3><p>With all the artifacts in place, you’re now ready to configure and run metadata ingestion into DataHub. This is done through a DataHub <a href="https://datahubproject.io/docs/generated/ingestion/sources/dbt/#starter-recipe">recipe file</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0oa2ZcWRbxrBSiHImRDkA.png" /><figcaption>High-level architecture</figcaption></figure><p>Below are a few key things about the config used in this project. See the file <a href="https://github.com/datashift-eu/dbt-datahub-tutorial/blob/main/datahub/recipe.yml">in the repository</a> for a full worked example.</p><p>1. test_warnings_are_errors: True — In our example, we’ve set all dbt tests to have warn severity, to prevent test failures from <a href="https://docs.getdbt.com/reference/commands/build#details">skipping downstream models</a>. <a href="https://datahubproject.io/docs/generated/ingestion/sources/dbt/#config-details">This setting</a> then helps surface test warnings as failures in DataHub, without stopping the dbt build.</p><p>2. meta_mapping— As mentioned above, we’re using dbt’s meta fields to define ownership and glossary terms. <a href="https://datahubproject.io/docs/generated/ingestion/sources/dbt/#dbt-meta-automated-mappings">This configuration</a> tells DataHub how to map the keys under meta to actual metadata entries.</p><pre># datahub/recipe.yml<br><br>meta_mapping:<br>  business_owner:<br>    match: .*<br>    operation: add_owner<br>    config:<br>      owner_type: user<br>      owner_category: BUSINESS_OWNER<br>  data_steward:<br>    match: .*<br>    operation: add_owner<br>    config:<br>      owner_type: user<br>      owner_category: DATA_STEWARD<br>  technical_owner:<br>    match: .*<br>    operation: add_owner<br>    config:<br>      owner_type: user<br>      owner_category: TECHNICAL_OWNER<br>  terms_list:<br>    match: .*<br>    operation: add_terms<br>    config:<br>      separator: &#39;,&#39;</pre><p>3. sink— Since we’re running everything locally, the <a href="https://datahubproject.io/docs/metadata-ingestion/sink_docs/datahub#quickstart-recipe">sink</a> is set to datahub-rest, pointing to the local DataHub instance.</p><pre># datahub/recipe.yml<br><br>sink:<br>  type: datahub-rest<br>  config:<br>    server: http://localhost:8080</pre><p>To ingest the dbt metadata into DataHub, run the ingest <a href="https://datahubproject.io/docs/cli/#ingest">command</a> from the DataHub CLI.</p><pre>poetry run datahub ingest -c datahub/recipe.yml</pre><h3>The result</h3><p>Navigate to DataHub running at <a href="http://localhost:9002/">http://localhost:9002</a> and <a href="https://datahubproject.io/docs/quickstart/#sign-in">sign in</a> with the default credentials (username: <em>datahub</em>, password: <em>datahub</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH6ioONE-mCFJ762JYQPgw.png" /></figure><p>Let’s walk through some of what we have realized here.</p><h4>Ownership and glossary terms</h4><p>Ownership and glossary terms from the dbt meta fields are now visible in DataHub. This helps document who’s responsible for the data and what key terms mean in the business context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzupVsdBUGiqdX1ui1g8yA.png" /></figure><h4>Test results</h4><p>You can see the results of your dbt tests, including any failures. This makes it easier to monitor data quality directly in DataHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzKjQ1d9AmH8md4xjc-rkg.png" /></figure><h4>Lineage</h4><p>DataHub (much like the dbt docs site itself) shows how data flows from seed to staging to mart models in a column-level lineage view. In itself this may not seem like much, though if you were ingesting metadata from other systems into DataHub (like your dashboarding tool, for example) and integrating those into the same view, this can get quite powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0O8pFIYqm6oHjWeDxmIyDA.png" /></figure><p>If you enjoy diving into challenges like these, why not turn your skills into impact at Datashift? <a href="https://www.datashift.eu/jobs?categories=data-science-engineering,data-governance">Check out our vacancies</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bc15d56c72a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/dbt-to-datahub-a-practical-guide-to-metadata-ingestion-7bc15d56c72a">dbt to DataHub: A practical guide to metadata ingestion</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracing data lineage from notebooks into Microsoft Purview]]></title>
            <link>https://medium.com/datashift-eu/tracing-data-lineage-from-notebooks-into-microsoft-purview-a35ff09f183b?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/a35ff09f183b</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[microsoft-purview]]></category>
            <dc:creator><![CDATA[Senne Vanstraelen]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 11:12:59 GMT</pubDate>
            <atom:updated>2025-02-05T11:50:13.467Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://learn.microsoft.com/en-us/purview/">Microsoft Purview</a> has a variety of robust lineage capabilities right out of the box. We recently faced a situation at a client where we did, however, need a custom solution.</p><p><em>This post is a technical deep dive into some of the topics covered in an earlier Datashift blog, </em><a href="https://www.datashift.eu/blog/when-data-governance-meets-data-engineering-optimizing-microsoft-purview-with-sparklin-for-automate"><em>When Data Governance Meets Data Engineering: Optimizing Microsoft Purview with SparkLin for Automated Lineage</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M38KYyGdKfgENxL0Bgr0gg.png" /></figure><p>In this post, we’ll show how to trace data lineage from notebooks in Spark environments into Purview, using OpenLineage and Sparklin. The aim is to discuss how we implemented this solution and how we encountered some unexpected things along the way, so it might be useful for teams working on similar lineage extraction projects.</p><p>For a technical introduction to the tools we are using, see:</p><ul><li><a href="https://openlineage.io/docs/integrations/spark/main_concept/">The main concepts</a> of OpenLineage’s Spark integration</li><li>An overview of the <a href="https://techcommunity.microsoft.com/blog/microsoft-security-blog/end-to-end-data-lineage-from-spark-big-data-environment/3721358">Data Lineage solution</a> on the Microsoft Security Blog</li><li>The README of the <a href="https://github.com/wjohnson/pyapacheatlas">PyApacheAtlas repository</a></li></ul><h3>Considerations for using the Data Lineage solution</h3><p>As we’ll see in more detail below, OpenLineage emits events in JSON format. The first step in processing these is to capture and store the events relevant to our use case. For that we use a service written in Python, <a href="https://github.com/microsoft/DataLineage/tree/main/sparklin/HttpTriggerFuncApp/HttpTriggerFunction">adapted</a> from the Sparklin component of an open source solution called <a href="https://github.com/microsoft/DataLineage/tree/main">Data Lineage</a> in Microsoft’s GitHub organization. However, the Data Lineage repository isn’t actively maintained as of posting this blog, with the last commit dating back to December 2023 and several open PRs with no activity. Teams planning to implement this solution in production environments should thus fork and commit to maintaining the code themselves, as we did, with the possibility of eventually contributing improvements back to the open source community.</p><h3>Architecture overview</h3><p>OpenLineage’s approach for lineage extraction from notebooks <a href="https://openlineage.io/docs/integrations/spark/">depends on Spark</a>, through an implementation of the SparkListener interface. Here, we’re using it in Azure Synapse Analytics, but the same concepts apply to other Spark-based platforms such as Azure Databricks and Fabric. This is quite relevant as Fabric further strengthens its position as Microsoft’s flagship analytics platform, meaning, teams could migrate to Fabric without any changes to the core implementation of this lineage setup.</p><p>Everything starts with the <a href="https://mvnrepository.com/artifact/io.openlineage/openlineage-spark">OpenLineage Spark integration</a> running on a <strong>Spark Cluster</strong>. OpenLineage’s JSON events are picked up by the <strong>JSON Receiver</strong> service, written in Python and running in Azure Functions.<strong> </strong>For every event coming from OpenLineage, the JSON Receiver checks events against a predefined list of Spark SQL operations, writing only events pertaining to these operations to <strong>Blob Storage</strong> for further processing, as well as to <strong>Table Storage</strong> for driving the execution of the <strong>JSON Parser</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25286ca18bbba3dac883d6e04632019c/href">https://medium.com/media/25286ca18bbba3dac883d6e04632019c/href</a></iframe><p>For every object written to Blob Storage, the JSON Parser service is triggered, which, like the JSON Receiver, is written in Python and running in Azure Functions. The JSON parser uses the <a href="https://wjohnson.github.io/pyapacheatlas-docs/latest/">PyApacheAtlas package</a> to read the lineage-related events from the JSON files stored in Blob Storage and then register them as metadata entities in Purview, as well as storing them in Table Storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36cddt5GXJx92-C0LENSSA.png" /><figcaption>End-to-end architecture overview of the solution</figcaption></figure><h3>Handling lineage in Purview via the Atlas API</h3><p><a href="https://learn.microsoft.com/en-us/purview/legacy/how-to-purview-custom-lineage-api-user-guide">Building custom lineage in Purview</a> requires using the Atlas API, which follows the Apache Atlas standards. As mentioned above, the JSON parser service uses the PyApacheAtlas package to that end. More specifically, it creates metadata <a href="https://wjohnson.github.io/pyapacheatlas-docs/latest/core/api/pyapacheatlas.core.entity.AtlasEntity.html#pyapacheatlas-core-entity-atlasentity">entities</a> for each source and sink table with the correct attributes, along with a <a href="https://wjohnson.github.io/pyapacheatlas-docs/latest/core/api/pyapacheatlas.core.entity.AtlasProcess.html#pyapacheatlas-core-entity-atlasprocess">process entity</a> that links them. This process entity is key for establishing table-level lineage and can also incorporate column-level lineage where applicable. However, some modifications are needed for optimal integration with Purview.</p><p>If objects already exist — typically from an automated scan of the data environment — the parser, by default, may create duplicate entities instead of linking to existing ones. Purview assigns both a UUID and a string-based unique identifier called the qualified name to objects. To prevent duplication, the parser must use the same qualified name as Purview. This alignment requires some manual changes to the code to match the architecture of the Data Lake. The best way to test this is by trial and error, and by looking at the different inputs coming from the JSON files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/361c47c95d546359ae9cac34387e8cb5/href">https://medium.com/media/361c47c95d546359ae9cac34387e8cb5/href</a></iframe><p>Another challenge is that the default process type used in the parser does not support column lineage effectively. To address this, the azure_synapse_operation process type should be used, as it enables column-level lineage tracking. These modifications, while necessary, introduce an ongoing maintenance requirement — ensuring that any updates to the parser continue to align with Purview’s metadata model.</p><h3>Tutorial: sending lineage events to Purview</h3><p>In this tutorial, we will walk through how to send lineage events from JSON data to Purview using the pyapacheatlas package. The example code defines and uploads metadata entities representing data lineage, including tables (source and sink) and a process entity that links them while incorporating column-level lineage.</p><h4>1. Install dependencies</h4><p>Before running the script, ensure you have installed pyapacheatlas. You can install it using pip.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb030f773dd703aa60beef5116ade794/href">https://medium.com/media/cb030f773dd703aa60beef5116ade794/href</a></iframe><h4>2. Authenticate with Purview</h4><p>To interact with Purview, we need to authenticate using <strong>Azure Service Principal Authentication</strong>. Replace the following values with your own Azure credentials:</p><ul><li><strong>Tenant ID</strong>: Your Azure Active Directory (AAD) tenant ID.</li><li><strong>Client ID</strong>: The application (service principal) ID.</li><li><strong>Client Secret</strong>: The secret key associated with the service principal.</li><li><strong>Purview Account Name</strong>: The name of your Purview account.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adca1db61d4a81916de5f9dcfe948993/href">https://medium.com/media/adca1db61d4a81916de5f9dcfe948993/href</a></iframe><p>📌 <strong>Security Note</strong>: Never hardcode sensitive credentials in your script. Use environment variables or Azure Key Vault.</p><h4>3. Define metadata entities (source and sink tables)</h4><p>Now, we define three <strong>AtlasEntity</strong> objects:</p><ul><li>Two <strong>input (source) tables</strong>: customer and address</li><li>One <strong>output (sink) table</strong>: customer_master</li></ul><p>Each entity has:</p><ul><li>✅ A <strong>name</strong> (human-readable name)</li><li>✅ A <strong>type name</strong> (azure_datalake_gen2_resource_set)</li><li>✅ A <strong>qualified name</strong> (a unique identifier in Purview)</li><li>✅ A <strong>GUID</strong> (temporary unique ID for the session)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/354833eb177fac6eae148bdd0b7ce35d/href">https://medium.com/media/354833eb177fac6eae148bdd0b7ce35d/href</a></iframe><p>📌 <strong>Why is the GUID negative? </strong>Negative GUIDs are used as placeholders during batch uploads. Purview assigns real GUIDs once uploaded.</p><h4>4. Define column-level lineage</h4><p>To track column transformations between tables, we use a <strong>column mapping structure</strong>.</p><p>This structure contains:</p><ul><li><strong>DatasetMapping</strong> (maps input tables to the output table)</li><li><strong>ColumnMapping</strong> (maps specific columns from input to output)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/325677b27e4a09a25c58cc41596ee729/href">https://medium.com/media/325677b27e4a09a25c58cc41596ee729/href</a></iframe><h4>5. Define the process entity (linking the tables)</h4><p>A <a href="https://wjohnson.github.io/pyapacheatlas-docs/latest/core/api/pyapacheatlas.core.entity.AtlasProcess.html?highlight=process">Process Entity</a> represents the transformation logic applied to input tables to create the output table.</p><ul><li>The <strong>process type</strong> used here is azure_synapse_operation because it supports column-level lineage.</li><li>The <strong>inputs</strong> and <strong>outputs</strong> link the tables together.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca2467cd721c68ae9d5a3dc6407b5ab/href">https://medium.com/media/5ca2467cd721c68ae9d5a3dc6407b5ab/href</a></iframe><p>We then attach the column mapping information to this process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de8c0767338dc622032e7536e6963706/href">https://medium.com/media/de8c0767338dc622032e7536e6963706/href</a></iframe><h4>6. Upload the entities to Purview</h4><p>Finally, we upload all entities (<strong>source tables</strong>, <strong>sink table</strong>, and <strong>process</strong>) in a single batch using client.upload_entities().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adcae72109c5c2261a5b84eaef6cc0ac/href">https://medium.com/media/adcae72109c5c2261a5b84eaef6cc0ac/href</a></iframe><p>📌 <strong>Why batch upload? </strong>Uploading all related entities in one call ensures they are linked correctly in Purview.</p><h4>7. Verify lineage in Purview</h4><p>Once the script runs successfully, check <strong>Microsoft Purview Studio</strong>:</p><ol><li>Navigate to <strong>Data Map</strong> → <strong>Browse Assets</strong></li><li>Search for customer_master (sink table)</li><li>Click on <strong>Lineage View</strong> to see the transformation from customer and address</li><li>Expand column details to verify column-level lineage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frB0ml4VcYJt0Emhnlz9OQ.png" /><figcaption>The final result in Purview</figcaption></figure><h3>Conclusion</h3><p>In this post, we showed how to trace data lineage from notebooks into Purview using <a href="https://openlineage.io/">OpenLineage</a> and <a href="https://github.com/microsoft/DataLineage/tree/main/sparklin">Sparklin</a>. We demonstrated the process of capturing and storing lineage events emitted by OpenLineage, and how these events are processed and eventually registered as metadata entities in Purview using the <a href="https://github.com/wjohnson/pyapacheatlas">PyApacheAtlas</a> package.</p><p>We went over the architecture of the solution, which involves as its main components the <a href="https://openlineage.io/docs/integrations/spark/main_concept/">OpenLineage Spark integration</a>, and a JSON Receiver and JSON Parser service running in Azure Functions.</p><p>Importantly, we discussed the challenge of maintainability when working with open source projects. Given that the Data Lineage repository is not actively maintained as of posting this blog, teams should be prepared to fork and maintain the code themselves, making necessary modifications to ensure compatibility with their specific data environments and in alignment with Purview’s metadata model.</p><p>If you enjoy diving into challenges like these, why not turn your skills into impact at Datashift? <a href="https://www.datashift.eu/jobs?categories=business-analytics,data-governance">Check out our vacancies</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a35ff09f183b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/tracing-data-lineage-from-notebooks-into-microsoft-purview-a35ff09f183b">Tracing data lineage from notebooks into Microsoft Purview</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable Customer Data Platform on AWS]]></title>
            <link>https://medium.com/datashift-eu/building-a-scalable-customer-data-platform-on-aws-7b883ce4fb08?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/7b883ce4fb08</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Alp]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 13:09:03 GMT</pubDate>
            <atom:updated>2024-11-27T13:12:00.759Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven world, effectively managing customer data is crucial for businesses to succeed. Especially in a business managing millions of customer records, with a need to ensure data privacy, respect customer consent preferences, and provide quick access to customer insights for marketing and analytics.</p><p>With AWS, you can build a scalable, secure, and cost-effective platform to handle customer identities, consent, and data export operations. In this blog, we’ll walk through the process of setting up a customer data platform using CloudFormation for infrastructure as code and Go for serverless functions.</p><h3>Overview of the Architecture</h3><p>This architecture leverages the following AWS services to build a robust customer data platform that can handle customer identities, consent, and data export operations efficiently and securely:</p><ul><li>API Gateway: Manages and secures API requests.</li><li>Lambda: Provides serverless compute power for customer data processing tasks, including retrieving, updating, creating, and deleting customer identities and consent records.</li><li>DynamoDB: A fully managed NoSQL database for storing customer data.</li><li>EventBridge: For scheduling automated tasks like data exports.</li><li>S3: Stores exported customer data as files , enabling integration with analytics tools or other data sources.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqk8Mw7WhOxdD5whB6_OVg.png" /><figcaption>a simple diagram to help visualize how these components interact</figcaption></figure><h3>Infrastructure as Code with CloudFormation</h3><p>Using CloudFormation, we define our infrastructure as code (IaC), ensuring consistent, repeatable deployments. This allows us to easily deploy the same resources in the same way in development and production. Here’s a breakdown of each key component in the CloudFormation template.</p><h4>1. API Gateway and IAM Roles</h4><p>The ExampleApi resource in the CloudFormation template sets up an API Gateway that handles RESTful APIs for customer data operations. The configuration secures API access with IAM roles, ensuring that only authorized entities can invoke the endpoints.</p><pre>ExampleApi:<br>  Type: AWS::Serverless::Api<br>  Properties:<br>    DefinitionBody:<br>      Fn::Transform:<br>        Name: AWS::Include<br>        Parameters:<br>          Location: api-definition.yaml<br>    StageName: production<br>    Auth:<br>      DefaultAuthorizer: AWS_IAM<br>    ResourcePolicy:<br>      CustomStatements:<br>        - Effect: Allow<br>          Action: execute-api:Invoke<br>          Resource:<br>            - execute-api/Prod/GET/examples<br>          Principal: <br>            AWS: !Ref ApiInvokeRoles</pre><p>This setup provides a secure API layer, where only specific IAM roles can access the API endpoints. Tip: Monitor API Gateway request quotas, especially for high-traffic applications, to avoid throttling.</p><h4>2. Lambda Functions in Go</h4><p>At the heart of our platform are Lambda functions written in Go, handling customer identity and consent CRUD operations and interacting with DynamoDB. By using Go and the ARM64 architecture, we achieve both high efficiency and low operational costs.</p><p>Identity Management Lambda Functions:</p><ul><li>IdentityGetFunction: Retrieves customer identity data.</li><li>IdentityPatchFunction: Updates existing customer identity data.</li><li>IdentityPostFunction: Creates a new customer identity.</li><li>IdentityDeleteFunction: Deletes customer identity data.</li></ul><p>Consent Management Lambda Functions:</p><ul><li>ConsentGetFunction: Retrieves customer consent data.</li><li>ConsentPatchFunction: Updates customer consent records.</li></ul><p>Here’s an example of how one of these functions is defined:</p><pre>IdentityGetFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    Architectures:<br>      - arm64<br>    Handler: bootstrap<br>    Runtime: provided.al2023<br>    Tracing: Active<br>    CodeUri: .<br>    Environment:<br>      Variables:<br>        EXAMPLE_TABLE: !Ref ExampleTable<br>    Policies:<br>      - DynamoDBReadPolicy:<br>          TableName: !Ref ExampleTable<br>    Events:<br>      IdentityGet:<br>        Type: Api<br>        Properties:<br>          Path: /identity/{id}<br>          Method: get<br>          RestApiId: !Ref ExampleApi</pre><pre>func HandleGetRequest(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {<br>    initLambdaExecutionEnv(ctx)<br>    if initErr != nil {<br>        slog.Error(&quot;failed to initialize Lambda execution environment&quot;, &quot;error&quot;, initErr)<br>        return createErrorResponse(500, &quot;Internal server error.&quot;), nil<br>    }<br><br>    // Without a valid customer id in the request, we cannot get the<br>    // identity from the database.<br>    reqDataId, err := validateRequestId(req.PathParameters[&quot;id&quot;], isInt, isUUID)<br>    if err != nil {<br>        slog.Error(&quot;failed to validate request&quot;, &quot;error&quot;, err, &quot;request&quot;, req)<br>        return createErrorResponse(400, &quot;The id should be an integer or a uuid.&quot;), nil<br>    }<br><br>    identityKey, err := buildIdentityKey(reqDataId)<br>    if err != nil {<br>        slog.Error(&quot;failed to build identity key&quot;, &quot;error&quot;, err, &quot;request&quot;, req)<br>        return createErrorResponse(500, &quot;Internal server error.&quot;), nil<br>    }<br><br>    dbItemOutput, err := db.Client.GetItem(ctx, &amp;dynamodb.GetItemInput{<br>        TableName: aws.String(db.TableNames.Customer),<br>        Key:       identityKey,<br>    })<br>    if err != nil {<br>        slog.Error(&quot;failed to get identity from database&quot;, &quot;error&quot;, err, &quot;request&quot;, req)<br>        return createErrorResponse(500, &quot;Internal server error.&quot;), nil<br>    }<br>    if len(dbItemOutput.Item) == 0 {<br>        err := fmt.Errorf(&quot;identity not found&quot;)<br>        slog.Error(&quot;failed to get identity from database&quot;, &quot;error&quot;, err, &quot;request&quot;, req)<br>        return createErrorResponse(404, &quot;Identity not found.&quot;), nil<br>    }<br><br>    var identity Identity<br>    err = attributevalue.UnmarshalMap(dbItemOutput.Item, &amp;identity)<br>    if err != nil {<br>        slog.Error(&quot;failed to unmarshal identity&quot;, &quot;error&quot;, err, &quot;request&quot;, req)<br>        return createErrorResponse(500, &quot;Internal server error.&quot;), nil<br>    }<br><br>    resBody, err := json.Marshal(identity)<br>    if err != nil {<br>        slog.Error(&quot;failed to marshal API response&quot;, &quot;error&quot;, err, &quot;request&quot;, req, &quot;identity&quot;, identity)<br>        return createErrorResponse(500, &quot;Internal server error.&quot;), nil<br>    }<br><br>    res := events.APIGatewayProxyResponse{<br>        StatusCode: 200,<br>        Body:       string(resBody),<br>    }<br>    return res, nil<br>}</pre><h4>3. DynamoDB Tables</h4><p>DynamoDB is used to store customer identity data and email mappings, defined in the CloudFormation template as follows:</p><ul><li>CustomerTable: Stores customer identity data with id as the partition key.</li><li>EmailMapTable: Maps customer emails to their corresponding IDs using emailHash as the partition key.</li></ul><p>Both tables are set to use on-demand billing, which automatically adjusts capacity based on traffic, and point-in-time recovery is enabled to protect against accidental data loss.</p><pre>CustomerTable:<br>  Type: AWS::DynamoDB::Table<br>  Properties:<br>    AttributeDefinitions:<br>      - AttributeName: id<br>        AttributeType: S<br>    KeySchema:<br>      - AttributeName: id<br>        KeyType: HASH<br>    BillingMode: PAY_PER_REQUEST<br>    PointInTimeRecoverySpecification:<br>      PointInTimeRecoveryEnabled: true</pre><h4>4. Scheduled Data Exports with S3 and EventBridge</h4><p>Our platform includes daily exports of customer data to S3 for external integration or analytics. A scheduled Lambda function, triggered by an EventBridge rule, performs this export.</p><pre>ExportToS3Function:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    Architectures:<br>      - arm64<br>    Handler: bootstrap<br>    Runtime: provided.al2023<br>    CodeUri: ../export/<br>    MemorySize: 1536<br>    Timeout: 300<br>    Environment:<br>      Variables:<br>        S3_BUCKET_NAME: !Ref DataExportBucket<br>        DYNAMODB_TABLE_ARN: !GetAtt CustomerTable.Arn<br>    Policies:<br>      - Statement:<br>          - Effect: Allow<br>            Action:<br>              - dynamodb:ExportTableToPointInTime<br>            Resource: !GetAtt CustomerTable.Arn<br>          - Effect: Allow<br>            Action:<br>              - s3:PutObject<br>              - s3:AbortMultipartUpload<br>              - s3:PutObjectAcl<br>            Resource: !Sub &quot;${DataExportBucket.Arn}/*&quot;<br>    Metadata:<br>      BuildMethod: makefile</pre><p>This function allows flexible, reliable data backups, with EventBridge managing the schedule. The solution can easily adapt to other triggers, making it versatile and scalable.</p><h3>Conclusion</h3><p>This architecture is designed to scale with your needs, providing a strong foundation for managing customer data securely and efficiently.</p><p>By leveraging AWS services like Lambda, DynamoDB, S3, and EventBridge, along with the power of CloudFormation, you can build a robust customer data platform that is both scalable and cost-effective. Golang, used for the Lambda functions, provides high performance for handling backend processes, making it a great choice for a data-intensive application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZg-P64JZoJ-DNjUzJoEwQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b883ce4fb08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/building-a-scalable-customer-data-platform-on-aws-7b883ce4fb08">Building a Scalable Customer Data Platform on AWS</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a serverless web portal in AWS]]></title>
            <link>https://medium.com/datashift-eu/how-to-build-a-serverless-web-portal-in-aws-9ac9c2066b81?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ac9c2066b81</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Pieter Coremans]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 13:05:12 GMT</pubDate>
            <atom:updated>2024-07-10T08:42:05.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leveraging dbt documentation for data lineage, debugging, and communication</h4><p>Recently, we introduced dbt (data build tool) at one of our clients and discovered the value of dbt docs. These auto generated docs provide a clear data lineage, which is incredibly useful for debugging and communication.</p><p>These docs are in HTML and JSON format that work together to give you a nice interactable image. This image is suitable for rendering in a browser but not easily shareable via tools like Confluence or Teams. To address this, we decided to create a web portal where these files could be hosted securely. Additionally, we included other HTML documentation, creating a centralized repository accessible through a landing page with links to various subfolders. This approach ensures that authorized team members can access the information conveniently.</p><h4>Let’s get started: Amazon S3 and Cloudfront</h4><p>Firstly, let’s discuss where we obtain the dbt docs. These docs are generated by running the “dbt docs generate” command. To streamline this process, we added it to the end of your CI/CD pipeline whenever a new feature branch merges into the main branch. Once generated, you can store these files in an S3 bucket. Since they are static files, this simple hosting solution suffices.</p><p>Now, let’s address the need for a domain pointing to the bucket, allowing secure access over HTTPS without delving into the technical intricacies. For this purpose, we can leverage CloudFront, Amazon Web Services’ content delivery network (CDN). With CloudFront in place, we have a straightforward way to access the dbt docs centrally. Sounds easy, right?</p><p>However, there’s one crucial aspect missing: authentication. We don’t want these files to be publicly accessible; only authorized individuals should have access. Fortunately, AWS offers solutions for this as well, albeit with some nuances.</p><h4>Amazon Cognito</h4><p>AWS provides a service called Amazon Cognito, which theoretically allows us to add authentication to our solution. Cognito offers a user-friendly login screen and handles password management. Here’s how it works. We create a Cognito User Pool and add all the authorized users who should have access to the web portal. When users are added, they receive an email with a temporary password. Upon their first login through the Cognito UI, they’ll be prompted to change this password. However, implementing Cognito to meet our specific needs isn’t straightforward. We can’t simply link Cognito with CloudFront and expect everything to work seamlessly out of the box. Instead, we need to incorporate custom logic using Lambda functions, API Gateway, and DynamoDB as secondary services in the background. While the official documentation might not provide a clear path, I found a helpful <a href="https://codesmith.ch/blog/2019-11-05-cogcf-barrier/">blog post</a> that explains how to achieve this integration. Even though it’s a bit outdated, I used it as a foundation to build upon.</p><p>In the following section, I’ll delve into how all these services work together to achieve the desired solution.</p><h4>The solution: how it works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*pdPEGVwJpkgG5rrPWOFtEg.png" /></figure><p><strong>Diagram Overview:</strong></p><p>The diagram illustrates the integration of key services — S3, CloudFront, and Cognito — within a system. These services act as the core components, while additional elements serve as the “glue” that enables seamless interaction.</p><p><strong><em>Initial Access:</em></strong></p><p>A user accesses the CloudFront domain. Since no specific path is provided, the default path directs the user to the Session Checker Lambda function. The Session Checker verifies whether a session cookie exists. If no cookie is found (e.g., during the first visit or after cookie expiration), the user is prompted to log in.</p><p><strong><em>Authentication Process:</em></strong></p><p>The CloudFront domain is called again, this time with the _identity/login path. This redirects the user to the Session Manager Lambda function via API Gateway. The Session Manager further redirects the user to the Cognito UI for email and password-based sign-in. Upon successful authentication, a session is created and stored in a DynamoDB table.</p><p><strong><em>Final Steps:</em></strong></p><p>The user is redirected to the CloudFront domain once more, now using the _identity/auth path along with additional authentication details. API Gateway invokes the Session Manager Lambda, which validates the authentication details. Finally, the user is redirected to the S3 Static site, granting access to the web portal.</p><p><strong><em>Subsequent Visits:</em></strong></p><p>As long as the session cookie remains valid, the user is directly redirected to the S3 site without needing to log in again.</p><p>This flow ensures secure access and efficient communication between the services</p><h4>Conclusion</h4><p>This integrated solution offers robust security through Cognito, allowing users to authenticate securely using email and password. Meanwhile, CloudFront acts as a global CDN, optimizing performance by distributing content efficiently. With S3 serving as scalable storage for static assets, the hosting solution remains cost-effective. Users interact seamlessly with the CloudFront domain, unaware of the underlying complexity. Transparent redirection between services ensures a smooth experience during login and subsequent visits. Additionally, session data is stored centrally in DynamoDB, enabling efficient monitoring and analysis. In summary, this architecture optimizes security, performance, and user experience, making it an excellent choice for web applications.</p><p><a href="http://www.datashift.eu/contact">If you have a similar use case and require assistance with the setup, feel free to reach out.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-MfqNL7X2_ZXtvCxYt-Qg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac9c2066b81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/how-to-build-a-serverless-web-portal-in-aws-9ac9c2066b81">How to build a serverless web portal in AWS</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Databricks-IDE Romance]]></title>
            <link>https://medium.com/datashift-eu/the-databricks-ide-romance-f0faec74c522?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/f0faec74c522</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ide]]></category>
            <dc:creator><![CDATA[Stefanie Turelinckx]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 07:59:20 GMT</pubDate>
            <atom:updated>2024-06-12T07:59:20.540Z</atom:updated>
            <content:encoded><![CDATA[<p>What if you want to leverage the power of a Databricks cluster while enjoying the development experience in your beloved IDE, instead of the Databricks workspace? Well, for all the IDE lovers there is something called Databricks Connect.</p><p>In this blog post we will introduce you to Databricks Connect and show you step by step how to set it up.</p><h3>Introduction</h3><p>Databricks Connect allows you to connect your IDE to a Databricks cluster so that Spark code is run on the remote Databricks cluster instead of in the local Spark session. Check out <a href="https://docs.databricks.com/en/dev-tools/databricks-connect/index.html#what-is-databricks-connect">What is Databricks Connect?</a> for more information.</p><p>Unfortunately, it is not possible to connect to every Databricks cluster. The workspace and cluster must meet certain requirements and settings before Databricks Connect can connect to a cluster:</p><ul><li>Your Databricks workspace must be enabled for Unity Catalog.</li><li>Your Databricks cluster must have Databricks Runtime 13.3 LTS or higher installed.</li><li>Your Databricks cluster must use a cluster access mode of Assigned or Shared.</li><li>Your version of Databricks Connect must be at or lower than the Databricks Runtime version running on your Databricks cluster.</li></ul><h3>Step-by-step guide</h3><p>Now it is time to get your hands dirty. By following these steps you can set up Databricks Connect yourself. Please note that we are using Azure Databricks and PyCharm to demonstrate the use of Databricks Connect.</p><h4>1. Infrastructure</h4><p>First of all, you need to set up the necessary resources. In this guide, we will use <a href="https://developer.hashicorp.com/terraform?product_intent=terraform">Terraform</a> to create the resources needed to set up Databricks Connect.</p><h4>1.1. Terraform necessities</h4><p>Before we start declaring the resources, let us define some required Terraform elements:</p><ul><li><strong>Terraform input variable</strong>: <a href="https://developer.hashicorp.com/terraform/language/values/variables">Terraform input variables</a> allow you to parametrize your Terraform modules which makes your modules composable and reusable. We define a prefix that will be used in the name of each resource.</li><li><strong>Terraform local value</strong>: A local value is used to set an env local value based on the currently selected Terraform workspace.</li><li><strong>Terraform data source</strong>: The data source refers to the Azure resource group where we will deploy our Azure resources that we define later.</li><li><strong>Terraform providers</strong>: Our configuration requires specific Terraform providers, so you need to declare them so Terraform can install and use them.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/251ba86a3d50240138509fad609ffcc6/href">https://medium.com/media/251ba86a3d50240138509fad609ffcc6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/476d05f58c7190c33026f321b7001798/href">https://medium.com/media/476d05f58c7190c33026f321b7001798/href</a></iframe><h4>1.2. Azure Databricks</h4><p>To use Databricks Connect you obviously need a number of Databricks resources. As mentioned earlier, we decided to use Azure Databricks. We have deployed the following Azure Databricks resources:</p><ul><li>Databricks Workspace</li><li>Databricks Unity Catalog Metastore</li><li>Databricks Cluster</li></ul><p>You can add the below declarations to your main.tf script and apply the execution plan so that the resources are created.</p><p>Please note that you must be an Azure Databricks account administrator to create a Databricks unity catalog metastore. More information can be found <a href="https://learn.microsoft.com/en-us/azure/databricks/admin/#--what-are-account-admins">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27fc2242efd2dfad427f647bf6ca174c/href">https://medium.com/media/27fc2242efd2dfad427f647bf6ca174c/href</a></iframe><h4>2. Local config</h4><p>You must set up an authentication method before you can connect to a Databricks workspace locally. In this tutorial we use a Databricks personal access token. How to set up such a token and the required local configuration can be found <a href="https://docs.databricks.com/en/dev-tools/cli/authentication.html#id1">here</a>.</p><p>After the configuration, a corresponding configuration profile is added to your .databrickscfg file. Please note that we gave our profile the name &#39;DATASHIFT-SANDBOX&#39; .</p><h4>3. PySpark project</h4><p>Now let us develop a small, simple PySpark project to demonstrate Databricks Connect.</p><h4>3.1. Python virtual environment</h4><p>We first set up a Python virtual environment containing the necessary packages to use Databricks Connect. We use <a href="https://python-poetry.org/">Poetry</a> for this and our toml-file is defined as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/738b3e1c79269f0e76bd3e44673af436/href">https://medium.com/media/738b3e1c79269f0e76bd3e44673af436/href</a></iframe><p>Once installed, you can point your Python interpreter in your IDE to the created virtual environment.</p><h4>3.2. PySpark job</h4><p>Finally, you can develop a PySpark job in your IDE and run it on the earlier created Databricks cluster. We made a simple PySpark job to demonstrate.</p><p>Note that how to establish the Spark session depends on whether the job is running locally or directly in Databricks. That is why we created a functionality to build the Spark session depending on this. The functionality uses an environment variable to operate. In the Terraform code you can see that this environment variable is set in the Databricks cluster (resource &quot;databricks_cluster&quot; &quot;dc&quot;).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24bbfc0deadfae2550123070d4b16bc4/href">https://medium.com/media/24bbfc0deadfae2550123070d4b16bc4/href</a></iframe><h4>4. Demo</h4><p>The video below shows you what happens when you run the PySpark job in the PyCharm IDE and the behavior of the job when run in Databricks itself.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F956531742%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F956531742&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1868212369-9d00c6074ddd068c50303d59e8524cd9013bed2c13778f667454796a42189409-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/32fa64122d8523e963b03957d7baef06/href">https://medium.com/media/32fa64122d8523e963b03957d7baef06/href</a></iframe><h3>Need more detail?</h3><p>Interested in the ins and outs of Databricks and what this technology can do for your organization? <a href="https://www.datashift.eu/contact">Get in touch with us</a> and we will be happy to discuss in more detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ol3eqQHszaVYeMpOIqH-cw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0faec74c522" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/the-databricks-ide-romance-f0faec74c522">The Databricks-IDE Romance</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One simple trick that will make your dbt table setup future proof]]></title>
            <link>https://medium.com/datashift-eu/one-simple-trick-that-will-make-your-dbt-table-setup-future-proof-112abef6e184?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/112abef6e184</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[dbt-labs]]></category>
            <category><![CDATA[macro]]></category>
            <dc:creator><![CDATA[De Lee Liam]]></dc:creator>
            <pubDate>Mon, 27 May 2024 08:49:37 GMT</pubDate>
            <atom:updated>2024-05-27T08:49:37.622Z</atom:updated>
            <content:encoded><![CDATA[<p>Did you ever need a new table created on a daily basis, with today’s date in its table name? We are convinced that such a table can be a great addition to your dbt setup.</p><p>If you stick with one table and keep inserting large amounts of data on a daily basis, you are bound to run into some problems in the near future. After a while, the proportions of that one table can take on gigantic measures and there will come a time querying becomes challenging or impossible. It is time to say goodbye to that one ever growing table!</p><p>Now we have convinced you of the need, we have quite a simple solution to future proof your table structures.</p><p>dbt itself in the back also uses macros to generate for instance the name of your table called <a href="https://docs.getdbt.com/docs/build/custom-aliases#generate_alias_name"><em>generate_alias_name</em></a>. This macro we can then overwrite to our own needs so we can choose the names of the tables/views at run time as shown below:</p><pre>{% macro generate_alias_name(custom_alias_name=none, node=none) -%}<br><br>    {% if node.name.startswith(&#39;stg_&#39;) or node.name.startswith(&#39;int_&#39;) or node.name.endswith(&#39;_hist&#39;) %}<br>        {{ return(node.name) }}<br>    {% else %}<br>        {{ return(node.name ~ &quot;&quot; ~ var(&quot;year&quot;) ~ &quot;&quot; ~ var(&quot;loadingoperation&quot;)) }}<br>    {% endif %}<br><br>{%- endmacro %}</pre><p>This macro has some needed code that we cannot avoid. This is the first line of code “{% macro generate_alias_name(custom_alias_name=none, node=none) -%}”. This code we keep the same in this example.</p><p>The next lines are a simple if else statement:</p><ol><li>where we check if the model name (= table/ view name) starts with specific values since for those we did not want to change the table name.</li><li>In the else statement we then return the existing model name (= table/ view name) and then add values using the var() syntax which will be delivered with the<em> dbt run -- vars ‘{“year”: “2023”, “loadingoperation”: 2}’</em></li></ol><p>This code can be changed to whatever code you want. You can even add another macro to run some tests on your input vars for instance, or make it a lot more complicated according to your needs.</p><p>If you follow this advice, you will never end up with a humongous and unqueryable table!</p><p>Enjoy coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_Xk8QpElXFuWXWlz6zQXBw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=112abef6e184" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/one-simple-trick-that-will-make-your-dbt-table-setup-future-proof-112abef6e184">One simple trick that will make your dbt table setup future proof</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How dbt Contracts can make your output more robust]]></title>
            <link>https://medium.com/datashift-eu/how-can-dbt-contracts-make-your-output-more-robust-c19fba9a42e1?source=rss----fe7ff9b94a85---4</link>
            <guid isPermaLink="false">https://medium.com/p/c19fba9a42e1</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[dbt-labs]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[De Lee Liam]]></dc:creator>
            <pubDate>Fri, 03 May 2024 07:30:57 GMT</pubDate>
            <atom:updated>2024-05-03T07:43:44.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCoguTvXSTryc89ODhKnfQ.png" /></figure><p>Dbt makes life easier for all data engineers, from novices to seasoned SQL engineers. It is a tool that can structure SQL code in a clear manner, enhancing collaboration and boosting efficiency. But even in dbt, from time to time, it can go sideways.</p><p>It’s a true nuisance when your dbt data model fails… Or even worse it runs on production, but the source changes the datatype of a column or adds a new column, and eventually crashes your code down the line.</p><p>We have a straightforward solution: this problem can be easily resolved with using dbt Model Contracts.</p><h3>What can it do?</h3><p>dbt Model Contracts is a great way to test your output models against a predefined “contract”. These contracts are a list of predefined columns with datatypes that will be checked at build time. This means that if the output of your dbt run pipeline does not match the contracts predefined column names and datatypes, the data will not be written to the database!</p><p>This makes it a very strong tool to use in an environment where change happens a lot. Also these these checks will give piece of mind when building pipelines and running tests to make sure the end-users get the correct data.</p><h3>How do we use it?</h3><p><em>A prerequisite before you can get started with the code below is to have at least dbt version 1.5</em></p><p>It is a simple as adding a .yml file in your output folder with the same name as your model.sql. (this is done for readability and containing your sql and yml files close to each other in the editor) It contains a little boilerplate but the most import field to fill in are the ‘name:’ and ‘data_type:’ Since those will be used to check with the output of your model that everything is buil as expected.</p><pre>models:<br>  - name: school<br>    columns:<br>      - name: school_number<br>        data_type: int<br>      - name: school_name<br>        data_type: string</pre><p>This can also be put into one big yml file for instance schema.yml. this is great at the start but might become very big and harder to manage once you start creating a couple of output models.</p><pre>models:<br>  - name: school<br>    config:<br>      contract:<br>        enforced: true<br>    columns:<br>      - name: school_number<br>        data_type: int<br>      - name: school_name<br>        data_type: varchar<br>  - name: pupils<br>    config:<br>      contract:<br>        enforced: true<br>     columns:<br>      - name: pupil_number<br>        data_type: int<br>      - name: pupil_name<br>        data_type: varchar<br>        </pre><p>You can also add more constraints like that it cannot be null or that a field has to be greater then 0 and so on. But that is more info for another blog post.</p><p>You can also add the ‘contract: enforce: true’ out of the specific schema files and put them in your dbt_project.yml file. This has the added benefit that it cannot be forgotten in the contract file itself. You have to put the following code under your output models folder name.</p><pre>+contract:<br>  enforced: true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*6Vb3-yo38vc-vD_JDxt_VA.jpeg" /></figure><p>This means that it will run all found contracts in that specified folder and enforces them to have a 100% match. If this is not the case it will fail the build and not write any output to your tables.</p><p>When you execute a dbt run in the root of your project where these contracts are residing you can get two results:</p><ol><li>Just a success, this means that the build, executions and contract checks where a success and your tables have been populated.</li><li>An error has occurred: This means that the build did not succeed. This can be because of a error in your code or because the output data did not match the contract. Here it is very easy to see what the issue is and how you can solve this. For instance in the error below you can see that in the contract postcode_id needs to be an INTEGER but the output of the DBT model returns an VARCHAR.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*-nkoMZO_fUhlRErbEWm5RA.jpeg" /></figure><p>You now have successfully set up the dbt Contracts in your dbt project, congratulations!</p><p>Do you want to read even more about dbt or other technologies?<a href="https://www.datashift.eu/blog?utm_source=Medium&amp;utm_medium=dbt&amp;utm_campaign=dbt"> Have a look at the blogs on the website Datashift.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c19fba9a42e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datashift-eu/how-can-dbt-contracts-make-your-output-more-robust-c19fba9a42e1">How dbt Contracts can make your output more robust</a> was originally published in <a href="https://medium.com/datashift-eu">datashift.eu</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>