<?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 Alan Vainsencher on Medium]]></title>
        <description><![CDATA[Stories by Alan Vainsencher on Medium]]></description>
        <link>https://medium.com/@alanvain?source=rss-e4e9518d36fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*It4ljVNrLXMvkUrTE9xIfw.png</url>
            <title>Stories by Alan Vainsencher on Medium</title>
            <link>https://medium.com/@alanvain?source=rss-e4e9518d36fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:20:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alanvain/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[Clean up your BigQuery instance. Delete old tables with BigQuery Cleaner]]></title>
            <link>https://alanvain.medium.com/clean-up-your-bigquery-instance-delete-old-tables-with-bigquery-cleaner-550536fe8f91?source=rss-e4e9518d36fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/550536fe8f91</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Alan Vainsencher]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 08:54:45 GMT</pubDate>
            <atom:updated>2026-01-12T08:54:45.277Z</atom:updated>
            <content:encoded><![CDATA[<p>BigQuery is an incredible tool for data warehousing, but it’s easy for projects to become cluttered. Over time, experimental tables, temporary datasets, and old backups start piling up. This isn’t just a matter of “tidiness” — stray tables can lead to confusion for your team and unnecessary storage costs for your organization.</p><p>That’s why I built BigQuery Cleaner, a powerful, developer-friendly CLI tool designed to automate the process of identifying and cleaning up unused BigQuery tables.</p><h4>The Problem: The “Ghost Table” Syndrome</h4><p>We’ve all been there: you look at a dataset and see temp_table_v1, temp_table_v2_final, and analysis_backup_2023. You’re 90% sure they aren’t being used, but the fear of breaking a production dashboard or a critical query keeps you from hitting “Delete.”<br>Manual cleanup is tedious:<br>1. Checking table metadata for creation dates.<br>2. Scanning INFORMATION_SCHEMA.JOBS to see if anyone has actually queried the table recently.<br>3. Calculating the potential storage savings.</p><p>BigQuery Cleaner does all of this for you in seconds.</p><h4>How It Works: Smart Detection</h4><p>BigQuery Cleaner doesn’t just look at when a table was created. Its core power lies in Detection Logic. It scans your project’s INFORMATION_SCHEMA.JOBS to find tables that:<br>• Were created more than N days ago.<br>• Have not been referenced in any query within that same window.</p><p>This gives you a data-driven way to identify truly “dead” tables.</p><h4>Key Features</h4><ul><li>Unused Table Detection: Leverages BigQuery’s own audit logs to find unreferenced data.</li><li>Storage Insights: See exactly how much space you’re reclaiming. The tool provides per-dataset and grand total summaries in beautiful, sortable tables.</li><li>️ Safe Renaming (Dry-Run First!): Instead of jumping straight to deletion, the tool encourages a “Soft Delete” workflow. It renames unused tables with a suffix (e.g., _renamed_20241225). If nothing breaks after a week, you’re safe to delete.</li><li>Easy Revert: Made a mistake? The revert-renamed-tables command lets you undo a rename operation instantly.</li><li>Dataset Cleanup: Easily remove empty datasets that no longer contain any tables or views.</li><li>Configurable: Use a cleaner.toml file to save your project defaults, exclusions, and lookback windows.</li></ul><h4>Quick Start</h4><pre># Install the tool<br>uv tool install bigquery-cleaner<br><br># Find unused tables older than 60 days<br>bigquery-cleaner list-unused-tables --project your-gcp-project --all-datasets --days 60</pre><p>The output is a beautiful terminal table (thanks to the Rich library) showing you exactly what’s old and how much storage it’s taking up.</p><h4>Common Workflow</h4><p>The recommended way to use BigQuery Cleaner is a three-step dance:<br>1. Identify: Run list-unused-tables to see the state of your project.<br>2. Rename: Run rename-old-tables (with — dry-run first!) to mark tables for deletion.<br>3. Delete: After a “cooling-off” period, use delete-tables with your chosen suffix to permanently free up space.</p><h4>Technical Highlights</h4><p>Under the hood, BigQuery Cleaner is built with modern Python tools:<br>• uv: For lightning-fast dependency management and installation.<br>• Typer: To provide a robust and intuitive CLI interface.<br>• Rich: For beautiful terminal output, including progress bars and formatted tables.</p><h4>Conclusion</h4><p>Managing BigQuery at scale doesn’t have to be a manual chore. With BigQuery Cleaner, you can turn cleanup from a “someday” task into a regular, automated part of your data engineering workflow.<br><br>GitHub: <a href="https://github.com/elvainch/bigquery-cleaner">https://github.com/elvainch/bigquery-cleaner</a><br>Pypi: <a href="https://pypi.org/project/bigquery-cleaner/">https://pypi.org/project/bigquery-cleaner/</a></p><p>Happy cleaning! 🧹</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=550536fe8f91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2 — Migrating Your Existing BigQuery Views to Dataform]]></title>
            <link>https://alanvain.medium.com/part-2-migrating-your-existing-bigquery-views-to-dataform-6cbc407b061a?source=rss-e4e9518d36fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cbc407b061a</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[bigquery-views]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alan Vainsencher]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 08:15:02 GMT</pubDate>
            <atom:updated>2025-12-07T08:15:02.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2 — Migrating Your Existing BigQuery Views to Dataform</h3><p>In <a href="https://medium.com/@alanvain/version-control-your-bigquery-views-with-dataform-a1d52e2e4df8">Part 1</a>, I showed how to manage BigQuery views using Dataform and get version control, reproducibility, and daily validation. That structure works perfectly for new projects — but most teams already have dozens or hundreds of views created manually in the BigQuery UI.</p><p>Those legacy views are usually unversioned, inconsistent, and impossible to reproduce in another environment. Before adopting Dataform fully, you need to migrate them.</p><h3>The Problem With Legacy UI-Created Views</h3><ul><li>No version control</li><li>No reproducibility</li><li>No clear ownership</li><li>No way to validate that a change didn’t break downstream logic</li></ul><p>When you move to Dataform, these views become the main blocker: rewriting each one manually is tedious and error-prone.</p><h3>The Migration Approach</h3><p>To automate the process, I built an open-source tool that extracts all existing BigQuery views and converts them into Dataform-compatible .sqlx files with the correct structure and tagging.</p><p>📦 PyPI: <a href="https://pypi.org/project/dataform-view-migrator/">https://pypi.org/project/dataform-view-migrator/</a><br> 💻 GitHub: <a href="https://github.com/elvainch/dataform-view-migrator">https://github.com/elvainch/dataform-view-migrator</a></p><p>The tool:</p><ul><li>Scans your BigQuery project</li><li>Finds all existing views</li><li>Extracts their SQL definitions</li><li>Generates Dataform-ready .sqlx files</li><li>Creates the folder structure you saw in Part 1</li><li>Adds a consistent config section with tags like &quot;views&quot;</li></ul><p>This gives you a complete, version-controlled representation of your legacy view layer within minutes.</p><h3>How to Use It</h3><p>Usage is intentionally simple — install the package and run it against your project.<br> All details and flags are in the README file.</p><p>The important part is the outcome:<br><strong>You end up with a Dataform project where every BigQuery view is now version-controlled, reproducible, and deployable using your Airflow DAG from Part 1.</strong></p><h3>What This Enables</h3><p>Once migrated:</p><ul><li>All views live in Git</li><li>Airflow recreates them daily, catching any breakage early</li><li>Teams stop editing SQL in the UI</li><li>You have a single, unified source of truth for your entire view layer</li></ul><p>This closes the gap between your “old world” of unmanaged views and your new Dataform workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cbc407b061a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Version control your Bigquery views with Dataform]]></title>
            <link>https://alanvain.medium.com/version-control-your-bigquery-views-with-dataform-a1d52e2e4df8?source=rss-e4e9518d36fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1d52e2e4df8</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Alan Vainsencher]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 08:31:10 GMT</pubDate>
            <atom:updated>2025-12-07T08:16:13.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>The environment</h3><p>If you’re working on GCP, chances are BigQuery is at the center of your data stack. Your team might strive to keep everything tidy and maintainable — but real life happens. A data analyst asks for a dataset they needed <em>yesterday</em>, you write a quick query, hand over the results, and everyone moves on.</p><p>A week later, they need it again. And again. Eventually you create a view, share it with the analyst, and the problem seems solved.</p><h3>The problem</h3><p>Fast-forward a year. Requirements have changed, the original data engineer has left the company, the analyst has moved on, and suddenly someone has to update that view.</p><p>You open BigQuery’s UI, edit the view definition directly, and consider the job done.</p><p>A few days pass. People start reporting incorrect numbers. That seemingly harmless CASE WHEN change didn’t account for an edge case, and now dashboards and reports are wrong. You need to revert to the previous version of the view.</p><p>You go back to BigQuery… and realize there <em>is no</em> previous version. BigQuery does <strong>not</strong> keep version history for views.</p><h3>The Solution</h3><p>Use version control. Use Git.</p><p>That part isn’t groundbreaking — but the implementation can vary. The classic approach is to store all your CREATE VIEW statements in a repository. This works, but what I’m presenting here is cleaner and more modular.</p><p>It uses <strong>Dataform</strong>, a dbt-like framework built specifically for BigQuery.</p><h3>The Implementation</h3><p>This article isn’t about setting up Dataform from scratch — Google’s documentation covers that well. Instead, the focus here is on how to structure all your BigQuery view definitions inside Dataform, and then run a daily Airflow DAG that compiles and deploys them.</p><p>This gives you version control out of the box, along with a predictable, repeatable deployment process.</p><h3>Project Structure</h3><p>Inside your Dataform project, create a views/ folder under definitions/.<br>For each BigQuery dataset, create a subfolder with the same dataset name.<br>Inside each dataset folder, place one file per view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRoBPWMYDKsOY8d_UUILoA.png" /><figcaption>Your dataform setup should look like this</figcaption></figure><p>The key convention: in each view file’s config, include a tag with “views” or whatever word you choose.</p><p>This allows Airflow to selectively run only the view-creation workflow.</p><p>Once your views are defined, simply commit, push, and merge as you would with any other repository.</p><h3>The airflow dag</h3><p>Now that the repo contains all your view definitions, you need a way to create (or recreate) the views in BigQuery. We’ll use an Airflow DAG scheduled to run daily — though any cadence works.</p><p>Here’s a complete example:</p><pre>from datetime import datetime<br>from airflow import DAG<br>import logging<br>from airflow.providers.google.cloud.operators.dataform import (DataformCreateWorkflowInvocationOperator,<br>                                                               DataformCreateCompilationResultOperator)<br>from airflow.operators.python import PythonOperator<br>from airflow.models import Variable<br><br><br>default_args = {<br>    &#39;owner&#39;: &#39;YOURNAME&#39;,<br>    &#39;gcp_conn_id&#39;: &#39;your_bq_connection&#39;,<br>    &#39;use_legacy_sql&#39;: False,<br>    &#39;catchup&#39;: False,<br>    &#39;start_date&#39;: datetime(2025, 11, 10)<br>}<br><br><br>with ((DAG(<br>        dag_id=&#39;create_bq_views_dataform&#39;,<br>        default_args=default_args,<br>        description=&#39;View creation through dataform&#39;,<br>        schedule_interval=&#39;0 4 * * *&#39;,<br>        catchup=False,<br>        max_active_runs=1<br>))) as dag:<br><br><br>    <br>    creates_dataform_compilation_result = DataformCreateCompilationResultOperator(<br>        task_id=&quot;creates_dataform_compilation_result&quot;,<br>        project_id=&quot;{{YOUR_GCP_PROJECT}}&quot;,<br>        region=&quot;{{YOUR_DATAFORM_LOCATION}}&quot;,<br>        dag=dag,<br>        repository_id=&quot;{{YOUR_DATAFORM_REPO}}&quot;, -- as defined in Dataform UI<br>        compilation_result={<br>            &quot;git_commitish&quot;: &quot;main&quot;,  -- Your git branch you want to compile to<br>            &quot;code_compilation_config&quot;: {<br>                &quot;default_database&quot;: &quot;{{YOUR_GCP_PROJECT}}&quot;<br>            }<br>        }<br>    )<br><br>    creates_dataform_workflow_invocation = DataformCreateWorkflowInvocationOperator(<br>        task_id=&#39;creates_dataform_workflow&#39;,<br>        project_id=&quot;{{YOUR_GCP_PROJECT}}&quot;,<br>        region=&quot;{{YOUR_DATAFORM_LOCATION}}&quot;,<br>        dag=dag,<br>        repository_id=&quot;{{YOUR_DATAFORM_REPO}}&quot;,<br>        workflow_invocation={<br>            &quot;compilation_result&quot;: &quot;{{ task_instance.xcom_pull(&#39;creates_dataform_compilation_result&#39;)[&#39;name&#39;] }}&quot;,<br>            &quot;invocation_config&quot;: {&quot;included_tags&quot;: [&quot;views&quot;]}<br>        }<br><br>    )<br><br>    creates_dataform_compilation_result &gt;&gt; creates_dataform_workflow_invocation</pre><p>In case of failures of the dag, you can troubleshoot and see the logs in the Workflow Execution Logs in the dataform UI.</p><h3>What You Achieve With This Setup</h3><p>By defining your BigQuery views in Dataform and deploying them via Airflow, you unlock several benefits:</p><ul><li><strong>Full version control</strong> — every view definition lives in Git.</li><li><strong>A single source of truth</strong> — no mysterious UI-edited view definitions.</li><li><strong>Daily validation</strong> — if a base table changes (e.g., a removed field), the workflow fails early.</li><li><strong>Repeatability</strong> — environments can be recreated reliably and consistently.</li></ul><h3>Part 2</h3><p><a href="https://medium.com/@alanvain/part-2-migrating-your-existing-bigquery-views-to-dataform-6cbc407b061a">In part 2</a>, I’ll show how to migrate your existing manually-created BigQuery views into this Dataform-managed structure — without breaking dependencies or downstream dashboards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1d52e2e4df8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install python package from GCP artifact registry in docker]]></title>
            <link>https://alanvain.medium.com/install-python-package-from-gcp-artifact-registry-in-docker-bc31c117b1af?source=rss-e4e9518d36fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc31c117b1af</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[artifact-registry]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alan Vainsencher]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 07:35:20 GMT</pubDate>
            <atom:updated>2025-01-28T07:35:20.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Install Python Packages from GCP Artifact Registry in Docker file</h3><p>Back up article in : <a href="https://dev.to/alancher/how-to-install-python-packages-from-gcp-artifact-registry-in-docker-file-20a7">docker artifact registry</a></p><p>You’ve developed an awesome python package for internal use at your company. You want to publish it so your colleagues can start using it. Since the package is for internal use, publishing it on PyPI (the official Python package registry) isn’t an option. Instead, because your company uses GCP, the natural choice is Artifact Registry.</p><p>Publishing the package to the registry is straightforward, as the documentation explains.</p><h4>Packaging the Library</h4><p>I’m using <strong>Poetry</strong> for packaging the library. Here are some commands you’ll use:</p><pre>poetry source add --priority=supplemental gcp_registry https://{LOCATION}-python.pkg.dev/{REPO}/{PACKAGE}/<br>poetry publish --no-interaction --build --repository gcp_registry</pre><p>Once you’ve published your package to Artifact Registry, you can make it available as a dependency for other projects.</p><h4>Installing the Package</h4><p>To install the package in your local machine, create a requirements_private.txt file:</p><pre>--index-url https://{LOCATION}-python.pkg.dev/{REPO}/{PACKAGE}/simple/<br>--extra-index-url https://pypi.org/simple<br>{YOUR_PACKAGE_NAME}</pre><p>Then, install the package with:</p><pre> pip install keyring <br> pip install keyrings.google-artifactregistry-auth<br> pip install -r /opt/requirements_private.txt</pre><p>The <strong>keyring</strong> packages handle Artifact Registry authentication. Ensure your Application Default Credentials (ADC) are set before proceeding.</p><h4>Docker Challenges</h4><p>When running the app in Docker, you face additional challenges:</p><ul><li>You don’t want to copy sensitive information, such as your service account file, into the Docker image.</li><li>You still need to authenticate with Artifact Registry.</li></ul><p>The solution is simple but not well-documented. It took me days to figure this out, so I want to save your time and help you implement it in minutes.</p><h3>The Solution</h3><ol><li>Pass the GOOGLE_APPLICATION_CREDENTIALS environment variable during the Docker build, pointing to the <strong>path</strong> of the service account file (not the file content itself).</li><li>Mount the service account file as a secret at the path specified by GOOGLE_APPLICATION_CREDENTIALS.</li><li>Perform all operations, including installing keyring packages and private dependencies, in the same RUN statement. <strong>It is important to be in the same </strong><strong>RUNstatement since the mount of the file lives only within that context.</strong></li><li>Make sure you have the mode with proper permissions so the file can be read.</li></ol><h3>Dockerfile Example</h3><p>Here’s how your Dockerfile should look:</p><pre>ARG GOOGLE_APPLICATION_CREDENTIALS<br><br>COPY requirements_private.txt /opt/requirements_private.txt<br><br>RUN --mount=type=secret,id=creds,target=/opt/mykey.json,mode=0444 \<br>     pip install keyring &amp;&amp; \<br>     pip install keyrings.google-artifactregistry-auth &amp;&amp; \<br>     pip install -r /opt/requirements_private.txt<br><br>COPY requirements.txt /opt/requirements.txt<br>RUN pip install -r /opt/requirements.txt</pre><p>The requirements_private.txt still the same.</p><pre>--index-url https://{LOCATION}-python.pkg.dev/{REPO}/{PACKAGE}/simple/<br>--extra-index-url https://pypi.org/simple<br>{YOUR_PACKAGE_NAME}</pre><p>As you see you can have multiple requirements files. In my case the requirements.txt file is for the packages that are hosted in the public registry of pypi.</p><p>And then your docker_compose.yml file</p><pre>services:<br>  app:<br>    build:<br>      context: .<br>      args:<br>        - GOOGLE_APPLICATION_CREDENTIALS=/opt/mykey.json<br>      secrets:<br>        - creds<br><br>secrets:<br>  creds:<br>    file: &quot;C:/your/local/host/path/to/google_service_account.json&quot;</pre><p>And then you can just run for building</p><pre>docker compose build </pre><p>Hope this article helps you with the integration with artifact registry and docker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc31c117b1af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow DAG cross dependency, custom sensing DAG execution.]]></title>
            <link>https://alanvain.medium.com/airflow-dag-cross-dependency-custom-sensing-dag-execution-a7a58018fe3d?source=rss-e4e9518d36fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7a58018fe3d</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Alan Vainsencher]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 16:08:40 GMT</pubDate>
            <atom:updated>2022-06-28T11:18:06.354Z</atom:updated>
            <content:encoded><![CDATA[<p>As shared in my previous post, at my company we have most of our services on Google Cloud Platform. As part of the data engineering department, we of course use Airflow. More specifically, we use the GCP-hosted version called cloud composer.</p><p>As we, data engineers, develop and deploy our DAGs, the data scientists need a way to know when they can execute their DAGs. Their DAGs are dependent on our DAGs. In this article, I will focus on sensing other DAG execution status. In other words, we needed a way for a DAG B to know what is the execution status of DAG A.</p><p>When I was assigned this task I did what all of us would have done: google it. For such a common scenario, there must already be an implemented proved solution. And in fact, there was. There is a native airflow operator called ExternalTaskSensor. The problem with it is that, honestly, sometimes I could make it work but sometimes I couldn’t. But most importantly - it was not flexible enough for our needs.</p><p>We, data engineers, have DAGs that run multiple times a day. And data scientists needed their DAGs to check whether the first, second, last or specific execution of the day was executed successfully or failed. In addition to that, in their DAGs, they needed to take a different flow according to the state of our DAG execution. So we implemented a custom sensor operator and here is the code with the explanations.</p><p>The airflow/cloud composer versions that the code was tested are the following ones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*MUnSJP5PLo8635FBxff-Sg.png" /></figure><p>Yes, old versions. I haven’t tried the code in the newer versions, but it should work, maybe with some changes.</p><p>First, we have our main_dag(DAG A), the one that is running and the other dag is dependent on it (DAG B). Main_dag does not depend on any other dag, and it is the one that is watched on to check whether it has finished or not.<br>This example code of the dag will always succeed because there is only few echos and sleep, here you would need to replace the code of your real dag that is watched on.</p><pre>#main_dag.py DAG A<br>from datetime import datetime, timedelta<br>from airflow import DAG<br>from airflow.utils.dates import days_ago<br><br><em># Operators; we need this to operate!<br></em>from airflow.operators.bash_operator import BashOperator<br><br><em># These args will get passed on to each operator<br># You can override them on a per-task basis during operator initialization<br></em>default_args = {<br>    <strong>&#39;owner&#39;</strong>: <strong>&#39;airflow&#39;</strong>,<br>    <strong>&#39;depends_on_past&#39;</strong>: False,<br>    <strong>&#39;email&#39;</strong>: [<strong>&#39;airflow@example.com&#39;</strong>],<br>    <strong>&#39;email_on_failure&#39;</strong>: False,<br>    <strong>&#39;email_on_retry&#39;</strong>: False,<br>    <strong>&#39;retries&#39;</strong>: 0<br>}<br>dag = DAG(<br>    dag_id=<strong>&#39;primary_dag&#39;</strong>,<br>    default_args=default_args,<br>    description=<strong>&#39;A simple tutorial DAG&#39;</strong>,<br>    schedule_interval=timedelta(minutes=2),<br>    start_date=days_ago(1),<br>    tags=[<strong>&#39;example&#39;</strong>],<br>    catchup=False,<br>    max_active_runs=1<br>)<br><br><br>t1 = BashOperator(<br>    task_id=<strong>&#39;before_sleep&#39;</strong>,<br>    depends_on_past=False,<br>    bash_command=<strong>&#39;echo &quot;Running before sleep&quot;&#39;</strong>,<br>    retries=3,<br>    dag=dag<br>)<br><br>t2 = BashOperator(<br>    task_id=<strong>&#39;sleep&#39;</strong>,<br>    depends_on_past=False,<br>    bash_command=<strong>&#39;sleep 5&#39;</strong>,<br>    retries=3,<br>    dag=dag<br>)<br><br>t3 = BashOperator(<br>    task_id=<strong>&#39;after_sleep&#39;</strong>,<br>    depends_on_past=False,<br>    bash_command=<strong>&#39;echo &quot;Its running after sleep&quot;&#39;</strong>,<br>    retries=3,<br>    dag=dag<br>)<br><br>t1 &gt;&gt; t2 &gt;&gt; t3</pre><p>Then we have the Dag or Dags that watch the main_dag and check whether it finished.<br>It would look like this. If the sensing successes then take one path, if fails take the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*qLlqe_Ki17mz3nFTBmHUfg.png" /></figure><pre>from airflow import DAG<br>from dagstatussensor import DagStatusSensor<br><br>from airflow.utils.dates import days_ago<br>from airflow.operators.python_operator import BranchPythonOperator<br>from airflow.operators.dummy_operator import DummyOperator<br><br><em><br></em>default_args = {<br>    <strong>&#39;owner&#39;</strong>: <strong>&#39;airflow&#39;</strong>,<br>    <strong>&#39;depends_on_past&#39;</strong>: False,<br>    <strong>&#39;email&#39;</strong>: [<strong>&#39;airflow@example.com&#39;</strong>],<br>    <strong>&#39;email_on_failure&#39;</strong>: False,<br>    <strong>&#39;email_on_retry&#39;</strong>: False,<br>    <strong>&#39;retries&#39;</strong>: 0<br>}<br>dag = DAG(<br>    dag_id=<strong>&#39;external_sensor_testing&#39;</strong>,<br>    default_args=default_args,<br>    description=<strong>&#39;A simple tutorial DAG&#39;</strong>,<br>    schedule_interval=<strong>&quot;*/2 * * * *&quot;</strong>,<br>    start_date=days_ago(1),<br>    tags=[<strong>&#39;example&#39;</strong>],<br>    catchup=False,<br>    max_active_runs=1<br>)<br><br>def what_status(**kwargs):<br>    return kwargs[<strong>&#39;ti&#39;</strong>].xcom_pull(dag_id=<strong>&quot;external_sensor_testing&quot;</strong>, key=<strong>&#39;status&#39;</strong>)<br><br>t1 = DagStatusSensor(<br>    task_id=<strong>&#39;task_sensor&#39;</strong>,<br>    status_to_check =<strong>&#39;success&#39;</strong>,<br>    dag_name=<strong>&quot;primary_dag&quot;</strong>,<br>    dag=dag,<br>    run_to_check=0,<br>    timeout=40,<br>    do_xcom_push=True,<br>    poke_interval=20,<br>    soft_fail=False<br>)<br><br>t2 = BranchPythonOperator(<br>    task_id=<strong>&#39;branching&#39;</strong>,<br>    python_callable=what_status,<br>    provide_context=True,<br>    trigger_rule=<strong>&#39;all_done&#39;</strong>,<br>    dag=dag)<br><br>op = DummyOperator(task_id=<strong>&#39;successful&#39;</strong>, dag=dag,trigger_rule=<strong>&#39;all_done&#39;</strong>)<br>op2 = DummyOperator(task_id=<strong>&#39;failure&#39;</strong>, dag=dag,trigger_rule=<strong>&#39;all_done&#39;</strong>)<br><br>t1 &gt;&gt; t2<br>t2 &gt;&gt; op<br>t2 &gt;&gt; op2</pre><p>The watcher dag it starts with a DagStatusSensor. Hey, but what is that?<br>It is a custom implementation of a sensor that basically is the implementation that pokes the execution of any other dag. And the code is here.</p><pre>from airflow.operators.sensors import BaseSensorOperator<br>from airflow.utils.decorators import apply_defaults<br>from datetime import datetime<br>from typing import List, Optional, Union<br>from airflow.models.dagrun import DagRun<br>from airflow.utils import timezone<br>from airflow.utils.db import provide_session<br>from sqlalchemy.orm.session import Session<br>from time import sleep<br>from airflow.exceptions import AirflowSensorTimeout, AirflowSkipException<br><br><br><strong>&quot;&quot;&quot; <br>This sensor is for checking the status of dag. If its success then only it will return true or mark <br>as completed so next task will get execute.<br>In case dag is failed it will raise an airflow exception as failed.<br>params:<br>dag_name: pass the dag_id for your dag<br>status_to_check: pass &#39;success&#39; if you want sensor to return true for this.<br>for e.g. <br>dag_status_sensor = DagStatusSensor(dag_name=&#39;test_dag&#39;,status_to_check=&#39;success&#39;,task_id=&#39;dag_status_sensor&#39;,poke_interval=30,timeout=1800,dag=dag)<br>&quot;&quot;&quot;<br><br></strong>class DagStatusSensor(BaseSensorOperator):<br><br>    @apply_defaults<br>    def __init__(self,dag_name,status_to_check, run_to_check=0,*args,**kwargs):<br>        self.dag_name = dag_name<br>        self.status_to_check = status_to_check<br>        self.run_to_check = run_to_check<br><br>        super(DagStatusSensor,self).__init__(*args,**kwargs)<br><br>    def poke (self,context):<br><br>        task_instance = context[<strong>&#39;task_instance&#39;</strong>]<br>        start = timezone.make_aware(datetime.now().replace(hour=0,minute=0,second=0, microsecond=0))<br>        end = timezone.make_aware(datetime.now().replace(hour=23,minute=59,second=59, microsecond=0))<br>        daggies = MyDagRun.find(dag_id=self.dag_name, execution_start_date=start, execution_end_date=end)<br><br>        if(daggies):<br>            length = len(daggies)<br>            if(length&gt;0):<br>                if daggies[self.run_to_check].state == self.status_to_check:<br>                    task_instance.xcom_push(<strong>&quot;status&quot;</strong>, <strong>&quot;successful&quot;</strong>)<br>                    return True<br>                elif daggies[self.run_to_check].state == <strong>&quot;failed&quot;</strong>:<br>                    task_instance.xcom_push(<strong>&quot;status&quot;</strong>, <strong>&quot;failure&quot;</strong>)<br>                    return False<br>                else:<em>#if state is running or else. After timeout will raise exception<br>                    </em>task_instance.xcom_push(<strong>&quot;status&quot;</strong>, <strong>&quot;failure&quot;</strong>)<br>                    return False<br>            else:<em>#if no runs of sensed dag, after timeout will raise exception and fail<br>                </em>task_instance.xcom_push(<strong>&quot;status&quot;</strong>, <strong>&quot;failure&quot;</strong>)<br>                return False<br>        else:<br>            task_instance.xcom_push(<strong>&quot;status&quot;</strong>, <strong>&quot;failure&quot;</strong>)<br>            return False<br><br>    def execute(self, context):<br>        started_at = timezone.utcnow()<br>        while not self.poke(context):<br>            if (timezone.utcnow() - started_at).total_seconds() &gt; self.timeout:<br>                <em># If sensor is in soft fail mode but will be retried then<br>                # give it a chance and fail with timeout.<br>                # This gives the ability to set up non-blocking AND soft-fail sensors.<br>                </em>if self.soft_fail and not context[<strong>&#39;ti&#39;</strong>].is_eligible_to_retry():<br>                    raise AirflowSkipException(<strong>&#39;Snap. Time is OUT.&#39;</strong>)<br>                else:<br>                    raise AirflowSensorTimeout(<strong>&#39;Snap. Time is OUT.&#39;</strong>)<br>            sleep(self.poke_interval)<br>        self.log.info(<strong>&quot;Success criteria met. Exiting.&quot;</strong>)<br><br><br>class MyDagRun(DagRun):<br><br>    @staticmethod<br>    @provide_session<br>    def find(<br>        dag_id: Optional[Union[str, List[str]]] = None,<br>        run_id: Optional[str] = None,<br>        execution_date: Optional[datetime] = None,<br>        state: Optional[str] = None,<br>        external_trigger: Optional[bool] = None,<br>        no_backfills: bool = False,<br>        session: Session = None,<br>        execution_start_date: Optional[datetime] = None,<br>        execution_end_date: Optional[datetime] = None,<br>    ) -&gt; List[DagRun]:<br><br>        DR = MyDagRun<br><br>        qry = session.query(DR)<br>        dag_ids = [dag_id] if isinstance(dag_id, str) else dag_id<br>        if dag_ids:<br>            qry = qry.filter(DR.dag_id.in_(dag_ids))<br>        if run_id:<br>            qry = qry.filter(DR.run_id == run_id)<br>        if execution_date:<br>            if isinstance(execution_date, list):<br>                qry = qry.filter(DR.execution_date.in_(execution_date))<br>            else:<br>                qry = qry.filter(DR.execution_date == execution_date)<br>        if execution_start_date and execution_end_date:<br>            qry = qry.filter(DR.execution_date.between(execution_start_date, execution_end_date))<br>        elif execution_start_date:<br>            qry = qry.filter(DR.execution_date &gt;= execution_start_date)<br>        elif execution_end_date:<br>            qry = qry.filter(DR.execution_date &lt;= execution_end_date)<br>        if state:<br>            qry = qry.filter(DR.state == state)<br>        if external_trigger is not None:<br>            qry = qry.filter(DR.external_trigger == external_trigger)<br>        if no_backfills:<br>            <em># in order to prevent a circular dependency<br>            </em>from airflow.jobs import BackfillJob<br>            qry = qry.filter(DR.run_id.notlike(BackfillJob.ID_PREFIX + <strong>&#39;%&#39;</strong>))<br><br>        return qry.order_by(DR.execution_date).all()</pre><p>A few comments to clarify what is going on here:</p><ul><li>status_to_check is the status of the main_dag that you want to check. Usually, you’d want to check if it succeeded but sometimes you’d want to know if it failed, or know other statuses. So here you define it.</li><li>run_to_check is the run of the day that you want to check its status. It could be the first run of the day, second…or last. 0 is as the first, 1 as second and -1 as last. As any python list.</li><li>For an explanation of what MyDagRun is please check <a href="https://stackoverflow.com/questions/66418106/airflow-find-dag-run-of-specific-dag-id-by-execution-date-without-time">this stackoverflow</a> question and why is it needed.</li></ul><p>And where to put all these files?</p><p>Each airflow instance has a bucket in Google Cloud storage.<br>The dags go in the dag folder, and the dagstatussensor.py goes in the <a href="https://cloud.google.com/composer/docs/concepts/plugins">plugins</a> folder.</p><p>Entire project on <a href="https://github.com/elvainch/custom-airflow-crossdag-sensor">github</a> for better readability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7a58018fe3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update BigQuery columns description from Google Spreadsheet]]></title>
            <link>https://medium.com/playamp/update-bigquery-columns-description-from-google-spreadsheet-45a6bc82b87?source=rss-e4e9518d36fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/45a6bc82b87</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alan Vainsencher]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 16:42:07 GMT</pubDate>
            <atom:updated>2022-06-28T11:18:03.245Z</atom:updated>
            <content:encoded><![CDATA[<p>At my company, we heavily rely on Google Cloud. Specifically for datawarehousing we use BigQuery. With thousands of tables in it, we need to do a good job in keeping metadata tidy and clean.</p><p>In order to do this, our product data team has different Google spreadsheets so they can manage the column description for every field of every table. Product don’t have direct access or permissions to edit directly on BigQuery, so they do it in a spreadsheet like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*C5mAjy9Le0ZpKPMtYpQntQ.png" /><figcaption>The schema is completely made up for this article. Don’t try to find any logic in it :)</figcaption></figure><p>With this spreadsheet, we have processes working in the background that update BigQuery columns description with the data we have in the spreadsheets. These processes use many python libraries Google provides in order to communicate with their products and some other open source libraries as well.</p><p>First, we need some methods to talk to the Google spreadsheet and retrieve the fields and their descriptions. We use the library <a href="https://gspread.readthedocs.io/en/latest/">gspread</a>.</p><pre>import gspread<br>from oauth2client.service_account import ServiceAccountCredentials</pre><pre>class GoogleSheetHandler():<br>    def __init__(self): <br>        self.gc = gspread.authorize(ServiceAccountCredentials.from_json_keyfile_name(&quot;c://PATH_TO_YOUR_SECRET/credentials.json&quot;,  [&#39;<a href="https://spreadsheets.google.com/feeds&#39;">https://spreadsheets.google.com/feeds&#39;</a>,<br>             &#39;<a href="https://www.googleapis.com/auth/drive&#39;">https://www.googleapis.com/auth/drive&#39;</a>]))</pre><pre>    def get_spread_sheet(self,spread_sheet_id,worksheet):<br>        self.spread_sheet = self.gc.open_by_key(spread_sheet_id)<br>        self.worksheet = self.spread_sheet.worksheet(worksheet)</pre><pre>    def get_all_values_by_col(self,col_id):<br>        return self.worksheet.col_values(col_id)</pre><p>Make sure you give read permissions in the spreadsheet to the user that is on your credentials.json.</p><p>Then we have two helper functions and a main one to update the fields. The tricky and fun part here is that this main function is recursive, so it supports any level of nested Record types BigQuery provides.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93fdebe176765b379b9f585848d0405b/href">https://medium.com/media/93fdebe176765b379b9f585848d0405b/href</a></iframe><p>We have a BigQuery table like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcD61oNARAPd2OaYtpkAQg.png" /></figure><p>and calling this function:</p><pre>update_description_columns_bqtable_from_gsheet(project, dataset,table_name,&quot;YOUR_SPREADSHEET_ID&quot;,&quot;YOUR_WORKSHEEET_NAME&quot;,1,4)</pre><p>then we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s43mlhw9HSfBuuv26DBvQ.png" /></figure><p>Please make sure your fields in the spreadsheet are with the same case as of the columns in BigQuery. While writing this article, I had done the mistake of putting different cases, and of course it didn’t work :)</p><p>Happy bigquerying :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45a6bc82b87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/playamp/update-bigquery-columns-description-from-google-spreadsheet-45a6bc82b87">Update BigQuery columns description from Google Spreadsheet</a> was originally published in <a href="https://medium.com/playamp">Playamp-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>