<?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 Slava Kalashnikov on Medium]]></title>
        <description><![CDATA[Stories by Slava Kalashnikov on Medium]]></description>
        <link>https://medium.com/@xemuliam?source=rss-65db9b1ace56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZEnUp2HqgBRM0vqJ3EKtlg.jpeg</url>
            <title>Stories by Slava Kalashnikov on Medium</title>
            <link>https://medium.com/@xemuliam?source=rss-65db9b1ace56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:31:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xemuliam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to implement BigQuery full-delta data refresh switch using table labels]]></title>
            <link>https://xemuliam.medium.com/how-to-implement-bigquery-full-delta-data-refresh-switch-using-table-labels-38c631b6baf7?source=rss-65db9b1ace56------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c631b6baf7</guid>
            <category><![CDATA[google-big-query]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[bigquery-sql]]></category>
            <category><![CDATA[google-bigquery]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Slava Kalashnikov]]></dc:creator>
            <pubDate>Fri, 19 May 2023 09:02:33 GMT</pubDate>
            <atom:updated>2024-08-24T09:12:11.105Z</atom:updated>
            <content:encoded><![CDATA[<h4>BigQuery table lables and copy API</h4><p>In <a href="https://medium.com/p/71ff978aa9b8">previous article</a> we learned how to work with BigQuery table labels to store and read some table-related metadata. Now it’s a time to apply that knowledge for real-world-like scenario.</p><p>We’re about to implement solution using following requirements:</p><ul><li>scheduled batch job to upsert data into derived table (e.g. dedupe, enrichment or aggregation) from single base table</li><li>normal mode for that job is “delta upsert” (only limited subset of data will be scanned) from base table</li><li>there should be an option how to run/trigger full data refresh for that derived table (ideally it would be to initiate full refresh w/o touching the job code, e.g. from any other query, job or process)</li><li>when full refresh will be requested and performed, our job must switch back to delta refresh mode w/o any additional action</li><li>data in target table must be always available. There should be no situation when old data will be deleted but new data will be put into table only after some time. In case of any error in processing, data mustn’t be jeopardized</li><li>our job is fully compliant with <a href="https://cloud.google.com/bigquery/quotas#multi_statement_query_limits">BigQuery limitations</a> for multi-statement queries (for both delta and full refreshes)</li></ul><p>Sounds more or less familiar, innit? 😉</p><p>Here is <a href="http://console.cloud.google.com/bigquery?ws=!1m5!1m4!4m3!1sbigquery-public-data!2scovid19_geotab_mobility_impact!3sfuel_station_daily_fillups">base table</a> for our mini-project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*3YMez15wb6-o34HbmrqZbw.png" /><figcaption>Table: bigquery-public-data.covid19_geotab_mobility_impact.fuel_station_daily_fillups</figcaption></figure><p>I chose this table from BigQuery public dataset because it is tiny enough to let you taste difference between full and delta refresh but not to lead unexpected costs for data processing.</p><p>Let’s perform simpliest aggregation for above table data + add field to track when each record has been calculated:</p><pre>select `date` fillup_date, vehicle_class,<br>  cast(avg(percent_of_normal_volume) as int) avg_fillup_percent,<br>  current_timestamp snapshot_update_ts<br>from `bigquery-public-data.covid19_geotab_mobility_impact.fuel_station_daily_fillups`<br>group by 1, 2</pre><p>Also let’s define following logic for pseudo delta partitions determination:</p><pre>declare date_arr, src_dates array&lt;date&gt; default null;<br><br>set src_dates = (<br>  select array_agg(distinct `date`)<br>  from `bigquery-public-data.covid19_geotab_mobility_impact.fuel_station_daily_fillups`<br>);<br><br>set date_arr = (<br>  select array_agg(src_dates[ordinal(cast(rand()*array_length(src_dates) as int)+1)])<br>  from unnest(generate_array(1, cast(rand()*4 as int)+1))<br>);</pre><p>As you can see, we use random (from 1 to 5) number of randomly chosen partitons from base table. It doesn’t look like real world algo but I’d rather to use <a href="https://en.wikipedia.org/wiki/KISS_principle">KISS principle</a> to illustrate smth. instead of deep diving into complex delta determination logic for such mini-project.<br>Nevertheless, now we are ready to add one simple filter into our aggregation to ensure we work with several partitions, not with the whole table:</p><pre>declare date_arr, src_dates array&lt;date&gt; default null;<br><br>set src_dates = (<br>  select array_agg(distinct `date`)<br>  from `bigquery-public-data.covid19_geotab_mobility_impact.fuel_station_daily_fillups`<br>);<br><br>set date_arr = (<br>  select array_agg(src_dates[ordinal(cast(rand()*array_length(src_dates) as int)+1)])<br>  from unnest(generate_array(1, cast(rand()*4 as int)+1))<br>);<br><br>select `date` fillup_date, vehicle_class,<br>  cast(avg(percent_of_normal_volume) as int) avg_fillup_percent,<br>  current_timestamp snapshot_update_ts<br>from `bigquery-public-data.covid19_geotab_mobility_impact.fuel_station_daily_fillups`<br>where `date` in unnest(date_arr)<br>group by 1, 2</pre><p>Now I’m going to run both queries (full and delta) and to compare job execution results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpZpBjtxv-kGE5CWjq7_FQ.png" /><figcaption>Jobs’ result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fPMhGXimLGRiGV60mEtew.png" /><figcaption>Jobs’ execution information</figcaption></figure><p>As we can see, our pseudo-delta approach works and let us to emulate few partitions’ processing for each consequent execution, thus we can treat our delta script as working approach to create our scheduled batch job. Certainly we won’t schedule our BigQuery job for this mini-project but we can honestly say that first two requirements for our solution are satisfied.</p><p>And what about full/delta process switching? I’ve created three stored procedures for that (certainly, they use lables 😜).</p><ul><li><a href="https://github.com/xemuliam/misc/blob/master/BigQuery/Delta/ask_full_refresh.sql"><strong><em>ask_full_refresh</em></strong></a> — to request full refresh for certain table. Puts label <em>full-refresh</em> with value <em>true</em> onto particular table</li><li><a href="https://github.com/xemuliam/misc/blob/master/BigQuery/Delta/should_full_refresh.sql"><strong><em>should_full_refresh</em></strong> </a>— to check whether full refresh has been requested or not finished for particular table. Reads label <em>full-refresh </em>and return true if its value is equal to <em>true </em>with writing the label <em>full-refresh-started </em>if it hasn’t been written before</li><li><a href="https://github.com/xemuliam/misc/blob/master/BigQuery/Delta/finish_full_refresh.sql"><strong><em>finish_full_refresh</em></strong> </a>— to finalize full refresh. Reads label <em>full-refresh-started</em> and if its value is equal to <em>true</em> then<em> w</em>ipes off that label and puts current timestamp into label <em>full-refresh</em> to let <strong><em>should_full_refresh</em></strong> procedure to return <em>false.</em></li></ul><p>The main idea behind those procedures was to use as minimum labels as we can and to have simple and clear process where and when to call the procedures.<br>Finally we have three stored procedure and two table labels, named <em>full-refresh</em> and <em>full-refresh-started</em>. Second one is temporary, avalable during full-refresh process. First one is main. The most of time, this label will show us the time when last full refresh has been performed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*97rwYlH7QK079y7aHdGdfw.png" /><figcaption>Time of last full refresh</figcaption></figure><p>Here you can see the logic how to work with above procedures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8d2yo9LcZ19XV4yta0hxVA.png" /><figcaption>Full-delta refresh switching logic. Image by Author</figcaption></figure><p><strong>Green</strong> rectangle is dedicated to our batch job logic, which needs to be applied to target (TGT) table. It contains a code for both (full and delta) types of processing.</p><p><strong>Red </strong>rectangle is aimed to just request full refresh process fot target table. Such procedure call can be done from outside of our batch job, thus we don’t need to change our batch job’s code to perform full or delta refresh.</p><p>From code perspective, the <strong>green</strong> rectangle could look like this:</p><pre>declare is_full_refresh bool default false;<br><br>-- check whether full refresh is requested<br>call `xemuliam-bigquery`.US.should_full_refresh(<br>  table_name_to_work_with,<br>  is_full_refresh<br>);<br><br>if not is_full_refresh then<br>  -------------------------------------<br>  -- delta refresh logic implementation<br>  -------------------------------------<br>  ...<br>  ...<br>  -------------------------------------<br>else<br>  -------------------------------------<br>  -- full refresh logic implementation<br>  -------------------------------------<br>  ...<br>  ...<br>  -------------------------------------<br><br>end if;<br><br>call `xemuliam-bigquery`.US.finish_full_refresh(<br>  table_name_to_work_with<br>);</pre><p>And <strong>red</strong> one is pretty much simple:</p><pre>call `xemuliam-bigquery`.US.ask_full_refresh(<br>  table_name_to_work_with<br>);</pre><p>Now let’s talk a bit about data availability requirements. Perhaps it’s not so noticeable on such small data set like we used for our mini-project. However, what if we imagine huge data volume processing?</p><p>We need to clean-up data from target table (as a whole for full refresh and partially for delta one), then reprocess data from source and put that data back into our target table. It can take some time, right? Moreover, we can be in the situation, when we vanished data from table but consequent reprocessing fails for some reason. Such issue leads unaialability of data for end users of your target table for undefined period of time. Looks not so comprehensive from business perspective, huh?</p><p>Certainly we can use RDBMS-like transactions approach. Moreover, BigQuery announced <a href="https://cloud.google.com/bigquery/docs/release-notes#October_10_2022">multi-statement transactions as globally available</a>.</p><p>However I wanted to show you a little bit different approach.</p><p>For full refresh we will calculate all required stuff into temporary/interim table and then use BigQuery <a href="https://cloud.google.com/bigquery/docs/managing-tables#copy-table">copy API</a> (also avalable as SQL DDL statement) to replace the whole content of our target table by content from temporary/interim one. It copy API works really fast and costs zero. I tested that DDL statement on petabyte table and it took just about one minute to copy all data and metadata! And again: it doesn’t affect bills at all! Your data in target table has only two states: old and new one. There is no period of time when data is unavailable. While COPY satement works, you see old data in your table. After its completion, you see new data momentairily.</p><pre>create or replace temp table your_temp_table as<br>select smth from your_source_table;<br><br>create or replace table your_target_table<br>copy your_temp_table;</pre><p>For delta refresh we will use BigQuery merge DML statement. It allows us to run all its sub-statements at a time. There is no situation when e.g. DELETE or UPDATE part of MERGE has been performed but INSERT doesn’t or vice versa. MERGE is the single SQL statement will be applied or not applied as a whole to the data.</p><pre>merge into your_target_table t<br>using (<br>  select * from your_source_table cross join unnest([true, false]) to_be_inserted <br>) s<br>on t.key_field = s.key_field and t.partition_field in unnest(your_partitions_array) and not to_be_inserted<br>when matched then delete<br>when not matched and to_be_inserted then insert</pre><p>There is no way to use the same rows for different MERGE sub-statements. Thus we use a trick to be able to do that (look at the join unnest statement in source definition). And we need to ensure that <a href="https://cloud.google.com/bigquery/docs/using-dml-with-partitioned-tables#pruning_partitions_when_using_a_merge_statement">partition pruning</a> will be in use for that statement.</p><p>Also please take into account last requirement (look at the beginning of article) for our job. You need to ensure that your job will be compliant with those limits either for delta or full refresh job execution.</p><p>Looks like we covered all our requirements and it’s time to write some code for all that stuff. I’ve already wrote those scripts for you in environment-agnostic style and I’d propose to use them in following way:</p><ol><li>Open <a href="https://console.cloud.google.com/bigquery?sq=472011246175:c7caa17997a340c684fa4e8f43e86493">main script</a></li><li>Inspect it if it is interesting for you</li><li>Change table name in 5th line to whatever you want to work with. Please ensure there is <strong>no partition expiration</strong> on tables in your target dataset, otherwise results could be not so expected</li><li>Run main script as a whole. <strong>Full data refresh</strong> should be in place</li><li>Ensure <strong><em>assert @cond</em></strong> statement has red icon which means that target table doen’t exists and need to be created</li><li>Wait for main script completion</li><li>Review “Bytes processed” column value for statement <strong><em>create or replace temp table fuel_station_daily_fillups_wip</em></strong> in script results pane</li><li>Review the same column value for statement <strong><em>create or replace table … copy</em></strong> and ensure there is 0 bytes</li><li>Open and review the result of scritpt’s last statement. There should be single row containing the array of all dates (equal to source table partition number) from result table</li><li>Open your target table information and see <em>full-refresh</em> label value</li><li>Run the whole main script again. <strong>Delta data refresh</strong> should be in place</li><li>Review “Bytes processed” column value for statement <strong><em>create or replace temp table fuel_station_daily_fillups_wip</em></strong> in script results pane. It should be much lower than in step (7). Partition pruning should work here</li><li>Review the same column value for statement <strong><em>merge into </em></strong>and ensure it is also much lower than in step (7). Partition pruning should work here also</li><li>Open and review the result of scritpt’s last statement. There should be more than one row. Top one is the result of recent execution and it should contain only up to five dates in the array</li><li>Review <em>full-refresh</em> label on your target table and ensure it remains intact</li><li>Repeat items (11) — (15) several times to see that our delta approach works</li><li>Now it’s time to open and inspect <a href="https://console.cloud.google.com/bigquery?sq=472011246175:f6d7e61bc5d640e5aad8032b46ffb1cd">full refresh request script</a></li><li>Change table name in 5th line to name you used for main script</li><li>Run script and ensure it’s completed siccessfully</li><li>Repeat item (10)</li><li>Repeat item (16)</li><li>Repeat item (2) because I’m pretty sure it became interesting for you😝</li></ol><p>My other BigQuery articles:</p><ul><li><a href="https://medium.com/p/71ff978aa9b8">How to work with BigQuery table labels as easy using SQL</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c631b6baf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to work with BigQuery table labels as easy using SQL]]></title>
            <link>https://xemuliam.medium.com/how-to-work-with-bigquery-table-labels-as-easy-using-sql-71ff978aa9b8?source=rss-65db9b1ace56------2</link>
            <guid isPermaLink="false">https://medium.com/p/71ff978aa9b8</guid>
            <category><![CDATA[google-big-query]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[bigquery-sql]]></category>
            <category><![CDATA[google-bigquery]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Slava Kalashnikov]]></dc:creator>
            <pubDate>Tue, 02 May 2023 15:51:19 GMT</pubDate>
            <atom:updated>2023-10-17T16:06:04.365Z</atom:updated>
            <content:encoded><![CDATA[<h4>BigQuery table labels</h4><p>BigQuery is amazing service but let’s not forget about some important limitations. Especially if we need to store some metadata about our data warehouse jobs, their results etc.</p><p>Imagine we have small data warehouse with 64 (yes, binary-like number 😉) batch jobs, need to be run on regular basis, e.g. hourly. If we don’t want to read source tables fully for each run then we need to store somewhere at least beginning time of last batch job execution and use that value to filter out already processed records and avoid unnecessary data reads. Where to store such information? Sounds logical, to have single common table for such purpose, innit? It’ll be containing meta-information for all our batch jobs. So we need to upsert 64 values every hour. Thus our table will be changed 1536 times per day. Not so frequent but let’s look in <a href="https://cloud.google.com/bigquery/quotas#standard_tables">BigQuery documentation</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*sG9saqkE_-6m-5c7Y4pDvw.png" /><figcaption>BigQuery limits</figcaption></figure><p>As you can see, even for our small data warehouse we need to modify table with meta-information 1536 times per day but BigQuery allows only 1500 modifications! Thus approach with single meta-table doesn’t fit our requirements. And what if we have a little bit bigger solution? For example 256 jobs need to be run each 15 minutes. Certainly we can create one meta-table per each job. However, what if we have 500 jobs? 1000 jobs? How to manage all those tables, how to ensure data and metadata consistency? Such approach become much more complex than we expect.</p><p>The idea: BigQuery <a href="https://cloud.google.com/bigquery/docs/adding-labels#adding_table_and_view_labels">table labels</a> can be life saver to store such meta-information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*XDJqD7Bd3HbLfaMD5zpW0Q.png" /><figcaption>Table labels example</figcaption></figure><p>If we use such approach then we store any table-related information in that particular table’s metadata (please bear in mind <a href="https://cloud.google.com/bigquery/docs/labels-intro#requirements">requirements for labels</a>).</p><p>However, if you try to do smth. with labels then you realize soon that out-of-the-box SQL interface to work with table labels is poor. This is why I created several stored procedures to make label-related work much easier. Those procedures are segregated in three different categories:</p><p><strong>Utility</strong></p><ul><li><strong><em>parse_table_name</em> </strong>— properly split given table name into dataset path and table name. Do not work for temp tables’ names</li><li><strong><em>parse_and_validate_table_name </em></strong>— same as above + validatie whether given table exists on particular environment. Works even for temporary tables</li></ul><p><strong>Getters</strong></p><ul><li><strong><em>get_all_table_labels </em></strong>— returns array which cosists of <strong><em>all</em></strong> label names and values from given table. If there is no label associated with given table then empty array will be returned back</li><li><strong><em>get_many_table_labels </em></strong>— same as above but for particular label names. If given label doesn’t exist then procedure won’t return it</li><li><strong><em>get_table_label</em></strong><em> </em>— returns value for particular label from given table. If label doesn’t exist then <strong><em>NULL</em></strong> will be returned back</li></ul><p><strong>Setters</strong></p><ul><li><strong><em>set_table_label </em></strong>— put given value into particular label. If label doesn’t exist then it will be created</li><li><strong><em>set_many_table_labels </em></strong>— same as above for several labels</li><li><strong><em>remove_table_label</em></strong><em> </em>— remove particular label from given table</li></ul><p><strong>All setters work with only given set of lables and do not touch any other table label and/or option.</strong></p><p>Code for procedures is written using “DNRY” principle, e.g. <em>remove_table_label</em> procedure calls<em> set_table_label.</em> And <em>set_table_label</em> procedure calls <em>set_many_table_labels,</em> where the main logic is placed.</p><p>Here is the simple script how to work with procedures. I used US-based <strong><em>poc_us</em></strong> dataset to create table and US-based procedures. Please change it by your own dataset and region (if required)</p><pre>declare label_value string default null;<br><br>create or replace table poc_us.test_table_labels as select 1 col1;<br><br>call `xemuliam-bigquery`.US.set_many_table_labels(&#39;poc_us.test_table_labels&#39;, [<br>  (&#39;label1&#39;, &#39;value1&#39;),<br>  (&#39;bla-bla-label&#39;, &#39;bla-bla-value&#39;)<br>]);<br><br>call `xemuliam-bigquery`.US.get_table_label(<br>  &#39;poc_us.test_table_labels&#39;,<br>  &#39;bla-bla-label&#39;,<br>  label_value<br>);<br>select label_value;</pre><h4>Where to find the code and procedures?</h4><p>Code for those procedures is available on <a href="https://github.com/xemuliam/misc/tree/master/BigQuery/Labels">GitHub</a> and procedures itselves can be found in <strong><em>xemuliam-bigquery</em></strong> project.</p><p><strong>Whereas BigQuery disallows to mix EU and US data and procedures’ calls, I put the same procedures into EU- and US-based datasets</strong>.</p><p>To add above project in your BigQuery project list please proceed for following steps:<br>1. Click ADD button in your BigQuery explorer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*aALujS2FJ_rbM3efLz5kgA.png" /><figcaption>Click ADD</figcaption></figure><p>2. Choose “Star project by name”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*kjAjSQic8Ego3qvDKMXITA.png" /><figcaption>Star project by name</figcaption></figure><p>3. Enter <em>xemuliam-bigquery</em> and click STAR</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*XA4da5LltWT_8LqaGVTCmQ.png" /></figure><p>4. Voila! It’s in your projects list</p><p>Enjoy! 😀</p><p>Additional information can be found in comments</p><p>My other BigQuery articles:</p><ul><li><a href="https://medium.com/p/38c631b6baf7">How to implement BigQuery full-delta data refresh switch using table labels</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71ff978aa9b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>