<?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 Alex Feldman on Medium]]></title>
        <description><![CDATA[Stories by Alex Feldman on Medium]]></description>
        <link>https://medium.com/@alex-feldman?source=rss-df0ac233814a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HF2S1Ocgtvy7c15DtJ49QA.png</url>
            <title>Stories by Alex Feldman on Medium</title>
            <link>https://medium.com/@alex-feldman?source=rss-df0ac233814a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:51:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex-feldman/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 Execute Dataform Workflows with Parameters from Cloud Run Functions]]></title>
            <link>https://medium.com/google-cloud/how-to-execute-dataform-workflows-with-parameters-from-cloud-run-functions-c161f9a4b22b?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c161f9a4b22b</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 02:41:47 GMT</pubDate>
            <atom:updated>2024-09-25T02:41:47.538Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How to Execute Dataform Workflows with Parameters from Cloud Run Function</strong></h3><p>In the last article, “<a href="https://medium.com/@alex-feldman/how-to-trigger-the-dataform-workflow-execution-from-cloud-functions-94408502716f?source=your_stories_page-------------------------------------">How to trigger the Dataform workflow execution from Cloud Functions</a>,”[1] we discussed how to trigger the previously configured Dataform workflow from the Cloud Functions (Cloud Run Function, for now). This article considers more options for executing the Dataform workflow using Python code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WMgVEtnGtAeFl5TK" /><figcaption>Photo by <a href="https://unsplash.com/@cbarbalis?utm_source=medium&amp;utm_medium=referral">Chris Barbalis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This article assumes readers are familiar with Cloud Run Functions and basic Dataform concepts.</em></p><p>Let’s have a data pipeline that generates a JSON file and uploads it to GCS using a Cloud Run Function. The next step is to process the file further in Dataform. We should trigger the Dataform workflow execution from the Cloud Run Function and send the file path as a parameter.</p><p>In the previous article, we discussed the Dataform code cycle[2], which involves multiple steps to execute the workflow after creating and saving the action’s code to Git.</p><p>1. Create the release configuration based on the Git branch.<br>2. Create the release compilation based on the release configuration.<br>3. Create the workflow configuration based on the release compilation.<br>4. Run the workflow configuration execution by creating the workflow invocation.</p><p>The previous article focused on step 4, executing a workflow using the workflow configuration name where the workflow configuration runs the previously compiled action code by creating the workflow invocation.</p><p>Now, to update the action code before execution, we need to add a new variable value to be used in the action queries. This can be achieved by using compilation variables in the release configuration[3]. The Dataform API enables us to combine the four steps into two by merging steps 1 with 2 and steps 3 with 4.</p><h3>Defining the parameter variable</h3><p>First, open the dataform.json file in the development workspace and add the new variable to be used as the parameter.</p><pre>{<br>  &quot;defaultSchema&quot;: &quot;dataform&quot;,<br>  &quot;assertionSchema&quot;: &quot;df_assertions&quot;,<br>  &quot;warehouse&quot;: &quot;bigquery&quot;,<br>  &quot;defaultDatabase&quot;: &quot;my_project&quot;,<br>  &quot;defaultLocation&quot;: &quot;us-east1&quot;,<br>    &quot;vars&quot;: {<br>    &quot;inbound_json_file_path&quot;: &quot;gs://my_bucket/test_file_for_dev_env.json&quot;<br>  }  <br>}</pre><p>We can add any variable value in the development workspace. For example, we can specify the path for a test file that will only be used when we execute an action in the development workspace. Since we use the main configuration file to declare the variable, it’s essential to use a clear variable name (Oh, it’s a pity that the JSON format does not support comments).</p><h3>Dataform action code</h3><p>Next, we write the action code.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  tags: [&quot;load_file_from_gcs&quot;],<br>  protected: true<br>}<br><br>pre_operations {<br><br>IF LENGTH(&#39;${dataform.projectConfig.vars.inbound_json_file_path}&#39;) &gt; 1 THEN<br><br>  LOAD DATA INTO TEMP TABLE loaded_data_table<br>  FROM FILES (<br>    format = &#39;JSON&#39;,<br>    uris = [&quot;${dataform.projectConfig.vars.inbound_json_file_path}&quot;]);<br><br>ELSE RETURN;<br><br>END IF;<br><br>}<br><br>SELECT CURRENT_TIMESTAMP as created_at, <br>&quot;${dataform.projectConfig.vars.inbound_json_file_path}&quot; as file_path,<br>TO_JSON_STRING(a, true) as json_data<br>FROM loaded_data_table a</pre><p>In the config block, we have the incremental table type to add every new file data. The action tag is load_file_from_gcs. We will use it in the calling code. The protected option is to protect us from losing data.</p><p>In the pre-operations block, we use the IF-ELSE construction to check if the inbound_json_file_path value is valid. If it is valid, the LOAD statement is executed. Otherwise, the action execution is stopped by the RETURN operator. The LOAD statement loads data from the JSON file with the defined variable path into a temporary table.</p><p>In the SELECT statement, the loaded data from the temp table is inserted into the json_data field, along with the addition of the creation timestamp and the file path as extra columns.</p><h3>Function code</h3><p>Let’s consider the Cloud Run Function code. We aim to call the Dataform workflow execution, sending the JSON file path as the parameter.</p><pre>from google.cloud import dataform_v1beta1<br><br>df_client = dataform_v1beta1.DataformClient()<br><br><br>def create_compilation_result(repo_uri, git_branch, params):<br><br>    # Initialize request argument(s)<br>    compilation_result = dataform_v1beta1.CompilationResult()<br>    compilation_result.git_commitish = git_branch<br>    compilation_result.code_compilation_config.vars = params<br><br>    # Add compilation overrides if needed<br>    # compilation_result.code_compilation_config.schema_suffix = &quot;prod&quot;<br>   <br>    request = dataform_v1beta1.CreateCompilationResultRequest(<br>        parent=repo_uri,<br>        compilation_result=compilation_result,<br>    )<br><br>    response = df_client.create_compilation_result(request=request)<br>   <br>    return response.name<br><br><br>def create_workflow_invocation(repo_uri, compilation_name, tag_list):<br><br>    workflow_invocation = dataform_v1beta1.types.WorkflowInvocation(<br>        compilation_result=compilation_name<br>    )<br>    workflow_invocation.invocation_config.included_tags = tag_list<br><br>    request = dataform_v1beta1.CreateWorkflowInvocationRequest(<br>        parent=repo_uri,<br>        workflow_invocation=workflow_invocation<br>    )<br><br>    response = df_client.create_workflow_invocation(request=request)<br><br>    return 0<br><br>def main():<br>    gcp_project = &#39;my_project&#39;<br>    location = &#39;us-east1&#39;<br>    repo_name = &#39;my_repo_name&#39;<br><br>    repo_uri = f&#39;projects/{gcp_project}/locations/{location}/repositories/{repo_name}&#39; <br>    <br>    git_branch = &#39;my_branch&#39;<br><br>    params = {<br>              &quot;json_file_path&quot;: &quot;gs://my_bucket/my_file.json&quot;<br>    }<br><br>    tag_list = [&#39;load_file_from_gcs&#39;]<br><br>    compilation_name = create_compilation_result(repo_uri, git_branch, params)<br>     <br>    create_workflow_invocation(repo_uri, compilation_name, tag_list)<br>     <br>    return 0</pre><p>In the main function, we start by setting the values of the gcp_project, location, and repo_name variables and then use them to compose the repo_uri. After that, we set the git_branch value and create the params object, which includes the json_file_path value. It&#39;s important to note that you should add any other compilation variables (e.g., environment) to the params object if you use them.</p><p>Next, we call the create_compilation_result function using the repo_uri, git_branch, and params as function arguments. Let&#39;s take a closer look at the code for the create_compilation_result function. It begins by initializing a compilation_result object using the <a href="https://cloud.google.com/python/docs/reference/dataform/latest/google.cloud.dataform_v1beta1.types.CodeCompilationConfig?hl=en">CompilationResult</a> class[4]. If we refer to the class description via the provided <a href="https://cloud.google.com/python/docs/reference/dataform/latest/google.cloud.dataform_v1beta1.types.CodeCompilationConfig?hl=en">link</a>, we can observe that in addition to the standard method of creating a compilation based on the release configuration, it allows us to directly utilize compilation parameters through the git_commitish and code_compilation_config class attributes. The git_commitish is set to the value of git_branch. The code_compilation_config.vars is then filled with the params. If you are using compilation overrides (e.g., schema_suffix), you can also include them according to the <a href="http://codecompilationconfig/">CodeCompilationConfig</a> specification. A request is generated, linking the repo_uri and the initialized compilation_result. Once the request is sent, it returns the name of the created compilation result (response.name).</p><p>In the next step, we call the create_workflow_invocation function with the repo_uri, compilation_name, and tag_list arguments. This function initializes a workflow_invocation object from the <a href="https://cloud.google.com/python/docs/reference/dataform/latest/google.cloud.dataform_v1beta1.types.WorkflowInvocation?hl=en">WorkflowInvocation</a> class[5]. The compilation_result attribute of the WorkflowInvocation is set to the value of compilation_name. The included_tags field of the <a href="https://cloud.google.com/python/docs/reference/dataform/latest/google.cloud.dataform_v1beta1.types.InvocationConfig?hl=en">invocation_config</a> is then populated with tag_list. A request object is created with the repo_uri as the parent and the initialized workflow_invocation object. The request is sent to make the workflow invocation.</p><p>After we run the Cloud Run Function, we can see the Dataform job execution in the Workflow Execution Logs tab.</p><h3>Summarizing</h3><p>In this article, we have discussed how to use Python code to dynamically trigger Dataform workflow executions with parameters. By utilizing the Dataform API, we can integrate with systems like Cloud Run Functions and pass parameters to be processed during workflow execution. As Dataform continues to evolve, expect new features and optimizations to further improve this workflow execution process.</p><p>Thanks for reading.</p><h3>Related Links</h3><ul><li>[1] Medium. Alex Feldman, <a href="https://medium.com/@alex-feldman/how-to-trigger-the-dataform-workflow-execution-from-cloud-functions-94408502716f?source=your_stories_page-------------------------------------">How to trigger the Dataform workflow execution from Cloud Functions</a>.</li><li>[2] Google Cloud Docs, <a href="https://cloud.google.com/dataform/docs/code-lifecycle">Introduction to code lifecycle in Dataform</a>.</li><li>[3] Google Cloud Docs. Dataform, <a href="https://cloud.google.com/dataform/docs/release-configurations?hl=en#release-configuration-details">View details of a release configuration</a></li><li>[4] Google Cloud Docs. Dataform, <a href="https://cloud.google.com/python/docs/reference/dataform/latest/google.cloud.dataform_v1beta1.types.CodeCompilationConfig?hl=en">Class CodeCompilationConfig</a></li><li>[5] Google Cloud Docs. Dataform, <a href="https://cloud.google.com/python/docs/reference/dataform/latest/google.cloud.dataform_v1beta1.types.WorkflowInvocation?hl=en">Class WorkflowInvocation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c161f9a4b22b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/how-to-execute-dataform-workflows-with-parameters-from-cloud-run-functions-c161f9a4b22b">How to Execute Dataform Workflows with Parameters from Cloud Run Functions</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</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 trigger the Dataform workflow execution from Cloud Functions]]></title>
            <link>https://medium.com/@alex-feldman/how-to-trigger-the-dataform-workflow-execution-from-cloud-functions-94408502716f?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/94408502716f</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 16:22:36 GMT</pubDate>
            <atom:updated>2024-07-20T16:22:36.756Z</atom:updated>
            <content:encoded><![CDATA[<p>Apart from SQL development, Dataform is also an orchestration tool. That allows us to execute our data pipeline by scheduling the workflow executions. But what if we need to trigger the workflow configuration from another Google Cloud service?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WzuXvFPn8ar04BC2" /><figcaption>Photo by <a href="https://unsplash.com/@waldemarbrandt67w?utm_source=medium&amp;utm_medium=referral">Waldemar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article will discuss initiating the execution of the Dataform workflow from Cloud Functions. When can it be helpful? For instance, if a data pipeline processes new files in GCS using Cloud Functions, and we need to continue processing the data in Dataform.</p><blockquote>This article assumes readers are familiar with Cloud Functions and basic Dataform concepts[1] and know how to create a Dataform repository, configure the development workspace, develop actions, and create the release configuration and compilation.</blockquote><p>The Dataform code cycle[2] includes several steps to run the workflow execution after we create the action’s code and save it to GitHub.</p><ol><li>Creating the release configuration based on the Git branch [3].</li><li>Creating the release compilation based on the release configuration.</li><li>Creating the workflow configuration based on the release compilation.</li><li>Finally, the workflow configuration execution is done by creating the workflow invocation.</li></ol><p>All these steps can be completed using the Dataform UI (BigQuery console) or other ways, including the Python client library [4] or Dataform API [5].</p><p>The good news is that if we want to run the workflow execution using the Python code, we do not need to complete all these steps in our script. Instead, we can use the first three in the Dataform UI and only the last one using the Python code.</p><h3>Workflow configuration creating</h3><p>So, if we have already created the release configuration and compilation in Dataform, we must configure the workflow for outside-triggered execution.</p><p>On the Releases and Scheduling tab in the workflow configuration section, click the CREATE button. Set the configuration name, select the release configuration, and choose actions to be executed by name or tag. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*c89mR-jwQ8sJWP8_oIy3hg.png" /><figcaption>Creating the workflow configuration</figcaption></figure><p>We do not need to fill out the frequency field. If necessary, configure other execution options. Click CREATE. The new configuration will appear in the workflow configuration section with an empty Cron Schedule field.</p><h3>Cloud Function using the client library</h3><p>Next, we need to create the Cloud Function. The code can look like this.</p><pre>from google.cloud import dataform_v1beta1<br><br>df_client = dataform_v1beta1.DataformClient()<br><br>def run_workflow(project, location, repo_name, workflow_config_name):<br><br>    repo_uri = f&#39;projects/{project}/locations/{location}/repositories/{repo_name}&#39;<br>    workflow_config = f&#39;projects/{project}/locations/{location}/repositories/{repo_name}/workflowConfigs/{workflow_config_name}&#39;<br><br>    request = dataform_v1beta1.CreateWorkflowInvocationRequest(<br>        parent=repo_uri,<br>        workflow_invocation=dataform_v1beta1.types.WorkflowInvocation(<br>            workflow_config=workflow_config<br>        )<br>    )<br><br>    response = df_client.create_workflow_invocation(request=request)<br>    name = response.name<br>    return name<br><br><br>def main():<br>    gcp_project = &#39;my-project&#39;<br>    location = &#39;us-east1&#39;<br>    repo_name = &#39;my-repo-name&#39;<br>    workflow_config_name = &#39;my_workflow_api_execution&#39;<br><br>    run_workflow(gcp_project, location, repo_name, workflow_config_name)<br>    <br>    return 0</pre><p>Let’s describe the code above.</p><p>First, we imported the dataform_v1beta1 module from the Google Cloud client library. Next, we created an instance of the DataformClient, which allows us to interact with the Dataform API.</p><p>In the next step, we defined the main function, which acts as the entry point for the script. We set up the workflow parameters, including the Google Cloud project, location, repository name, and workflow configuration name. Then, we called the run_workflow function, which has the specified parameters to run the workflow.</p><p>Next, we defined the run_workflow function. The run_workflow function takes four parameters: project, location, repo_name, and workflow_config_name. We constructed repository and workflow configuration URIs, made a CreateWorkflowInvocationRequest object, and set the parent to the repository URI. Then, we specified the workflow_config in a WorkflowInvocation object.</p><p>Next, we called the create_workflow_invocation method and passed the request object created in the previous step. We stored the response in the response variable and extracted the workflow invocation&#39;s name, which contains its unique identifier.</p><p>If we prefer not to use the client library, we can utilize the Dataform API with an HTTP request-based approach.</p><h3>Cloud Function using Dataform API HTTP request</h3><p>The code can look like this for the Dataform API HTTP request-based approach.</p><pre>import google.auth<br>from google.auth.transport.requests import Request<br>from googleapiclient.discovery import build<br><br>def create_workflow_invocation(project_id, location, repository, workflow_config):<br><br>    credentials, project = google.auth.default()<br>    credentials.refresh(Request())<br><br>    service = build(&#39;dataform&#39;, &#39;v1beta1&#39;, credentials=credentials)<br><br>    parent = f&#39;projects/{project_id}/locations/{location}/repositories/{repository}&#39;<br><br>    request_body = {<br>        &#39;workflowConfig&#39;: f&#39;projects/{project_id}/locations/{location}/repositories/{repository}/workflowConfigs/{workflow_config}&#39;<br>    }<br><br>    response = service.projects().locations().repositories().workflowInvocations().create(parent=parent, body=request_body).execute()<br><br>    return response<br><br><br>def main ()    <br>    gcp_project = &#39;my-project&#39;<br>    location = &#39;us-east1&#39;<br>    repo_name = &#39;my-repo-name&#39;<br>    workflow_config_name = &#39;my_workflow_api_execution&#39;<br>    <br>    result = create_workflow_invocation(gcp_project, location, repo_name, workflow_config_name)<br></pre><p>In the import and authentication section, we imported libraries from Google Cloud for authentication and API interaction. The default credentials are obtained using google.auth.default() and refreshed using the Request() method to ensure they are up to date.</p><p>In the next step, we defined the main function, which acts as the entry point for the script. We set up the workflow parameters, including the Google Cloud project, location, repository name, and workflow configuration name. Then, we called the create_workflow_invocation function with the specified parameters to run the workflow.</p><p>In the create_workflow_invocation function, we initialized the Dataform service using the build function and refreshed credentials. We constructed the parent URI for the repository using the provided project ID, location, and repository name.</p><p>Next, we created a request body containing the workflow configuration URI, which was constructed using the provided project ID, location, repository name, and workflow configuration name.</p><p>We called the create method [7] on the workflowInvocations resource of the Dataform service, passing the parent URI and request body. The response from this API call is executed and stored in the response variable. It contains details about the workflow invocation created.</p><p>After deploying one of the functions, we can use it as the Dataform workflow execution trigger.</p><h3>Summarizing</h3><p>Triggering Dataform workflow execution from Cloud Functions expands the flexibility of managing and orchestrating your data pipelines within Google Cloud. Whether processing new files in GCS or responding to other cloud events, integrating Cloud Functions with Dataform allows seamless and efficient execution of data workflows. By utilizing either the Google Cloud client library or the Dataform API, you can easily initiate workflow configurations and invocations programmatically, ensuring your data pipelines remain responsive and robust.</p><h3>Related Links</h3><ul><li>[1] Google Cloud Docs, <a href="https://cloud.google.com/dataform/docs/features">Overview of Dataform features</a>.</li><li>[2] Google Cloud Docs, <a href="https://cloud.google.com/dataform/docs/code-lifecycle">Introduction to code lifecycle in Dataform</a>.</li><li>[3] Google Cloud Docs, <a href="https://cloud.google.com/dataform/docs/release-configurations?hl=en">Create a release configuration</a>.</li><li>[4] Google Cloud Docs, <a href="https://cloud.google.com/python/docs/reference/dataform/0.2.2/google.cloud.dataform_v1beta1.services.dataform.DataformClient?hl=en#google_cloud_dataform_v1beta1_services_dataform_DataformClient_create_workflow_invocation">Dataform client (Python)</a>.</li><li>[5] Google Cloud Docs, <a href="https://cloud.google.com/dataform/reference/rest?hl=en">Dataform API</a>.</li><li>[6] Google Cloud Docs, <a href="https://cloud.google.com/dataform/reference/rest/v1beta1/projects.locations.repositories.workflowInvocations/create">Dataform API, workflowInvocations.create method</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94408502716f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with variables in Dataform]]></title>
            <link>https://medium.com/@alex-feldman/working-with-variables-in-dataform-59f2d6745f9d?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/59f2d6745f9d</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 17:42:27 GMT</pubDate>
            <atom:updated>2024-11-14T15:18:57.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QpFtW3bilIspTAnZ" /><figcaption>Photo by <a href="https://unsplash.com/@tumbao1949?utm_source=medium&amp;utm_medium=referral">James Wainscoat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Variables make a developer’s life easier. They store values and allow us to reuse them during development. Dataform enables us to use GoogleSQL, JavaScript, and special compilation variables.</p><h3>GoogleSQL variables</h3><p>The GoogleSQL procedural language allows us to define and reuse variables in multi-statement queries [1]. To define variables, we use the DECLARE statement. The optional DEFAULT clause specifies the default value. If it’s omitted, it is equal to NULL. The SET statement assigns the variable values. Next, we can use this variable in the query.</p><pre>DECLARE d DATE DEFAULT CARRENT_DATE();<br><br>SET d = CARRENT_DATE() - 1;<br><br>SELECT d as date_value</pre><p>DECLARE and SET operations are performed during the query execution. We can use the calculation results to set the variable value. We can declare and use variables only in one query. However, we can create a UDF function to share values between queries instead.</p><h3>Dataform JS variables</h3><p>Dataform allows us to use JavaScript variables or functions in action code [2]. In this article, our focus will be on variables.</p><p>JS variables are declared using the const keyword in the js block.</p><pre>js { <br>  const VARIABLE_NAME = VARIABLE_VALUE;<br>  module.exports = { VARIABLE_NAME };<br>}</pre><p>The JS variables support various data types, but their use as the Dataform variables is limited by the SQL code&#39;s processing capability. Dataform variables can accept integer, float, boolean, DateTime, string scalar values, and JS functions. The string value can also be an SQL code snippet. An array is considered valid if all elements have the same type.</p><pre>config { type: &quot;view&quot; }<br><br>js {<br><br>    const int_value = 4;<br><br>    const float_value = 5.5;<br><br>    const bool_value = true;<br><br>    const string_value = &quot;hey there&quot;;<br><br>    // Using SQL code snippet<br>    const previous_date = `CURRENT_DATE()-1`;<br><br>    // Using JS function<br>    const this_year = new Date().getFullYear();<br><br>    // Array is wrapped up with backquotes. Use the extra variable inside.<br>    const array_value = `[&quot;one&quot;, &quot;two&quot;, &quot;${string_value}&quot;, &quot;three&quot;]`<br><br>    // JSON is wrapped up with backquotes<br>    const json_value = `{&quot;first_name&quot;: &quot;John&quot;, &quot;last_name&quot;: &quot;Snow&quot;}`<br><br>    // Array JSON elements are wrapped up with double quotes<br>    const json_array = `[<br>        &quot;{&#39;first_name&#39;: &#39;John&#39;, &#39;last_name&#39;: &#39;Snow&#39;}&quot;,<br>        &quot;{&#39;first_name&#39;: &#39;Alex&#39;, &#39;last_name&#39;: &#39;Feldman&#39;}&quot;<br>    ]`<br><br>    module.exports = {<br>      int_value, float_value, bool_value, previous_date, <br>      this_year, array_value<br>  };<br>}<br><br>SELECT ${int_value} as int_value, <br>${float_value} as float_value, <br>${bool_value} as bool_value, <br>&#39;${string_value}&#39; as string_value, -- Add extra quotes<br>${previous_date} as previous_date, <br>${this_year} as this_year,<br>&#39;${json_value}&#39; as json_value, -- Add extra quotes<br>${array_value} as array_value, <br>${json_array} as json_array</pre><p>When declaring variables, it is essential to use quotes for string and array values. This is also relevant for JavaScript objects because GoogleSQL can only process the JSON-like string directly. We can use different quotes, such as single, double, or triple quotes, backquotes, or their combinations. However, since the string variable values are inserted in SQL code without quotes, it is necessary to add extra quotes when we call them (For example, SELECT ‘${string_value}’).</p><p>JavaScript supports the null value to represent an empty value in SQL code. An array can not have a null value.</p><p>Compiled action code.</p><pre>SELECT 4 as int_value, <br>5.5 as float_value, <br>true as bool_value, <br>&#39;hey there&#39; as string_value, <br>CURRENT_DATE()-1 as previous_date, <br>2024 as this_year,<br><br>[&quot;one&quot;, &quot;two&quot;, &quot;hey there&quot;, &quot;three&quot;] as array_value, <br><br>&#39;{&quot;first_name&quot;: &quot;John&quot;, &quot;last_name&quot;: &quot;Snow&quot;}&#39; as json_value,<br><br>[<br>        &quot;{&#39;first_name&#39;: &#39;John&#39;, &#39;last_name&#39;: &#39;Snow&#39;}&quot;,<br>        &quot;{&#39;first_name&#39;: &#39;Alex&#39;, &#39;last_name&#39;: &#39;Feldman&#39;}&quot;<br>    ] as json_array</pre><p>Query result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*aeqzEGk2S_dczfpVFJPFhg.png" /><figcaption>Query result</figcaption></figure><p>The main advantage of JavaScript over GoogleSQL variables is that they can be used across different actions in the repository. We can declare JS variables in any .sqlx or .js file and make them accessible in another file using the &quot;require” function.</p><pre>config { type: &quot;view&quot; }<br><br>js {<br>   const { my_var } = require(&quot;definitions/path/to/declared/variable.sqlx&quot;);<br>}<br><br>SELECT ${my_var} as var_value</pre><p>Dataform has provided a special includes/ directory as a location for global variables and functions.</p><pre>  // filename is includes/constants.js<br>  const date = `CURRENT_DATE()`;<br>  module.exports = { date };</pre><p>If the variable is declared inside the includes directory, we can access it without the js block.</p><pre>config { type: &quot;view&quot; }<br><br>SELECT ${constants.date} as date_value</pre><h3>Dataform compilation variables</h3><p>Dataform supports compilation variables that can be used as environment variables [3]. We can define specific JS variable values for each development workspace and release configuration. This functionality helps us to configure different environments and alter the behavior of actions depending on the environment in which the code is executed.</p><p>We can define the compilation variable in the dataform.json file for the development workspace.</p><pre>{<br>  &quot;defaultSchema&quot;: &quot;dataform&quot;,<br>  &quot;assertionSchema&quot;: &quot;df_assertions&quot;,<br>  &quot;warehouse&quot;: &quot;bigquery&quot;,<br>  &quot;defaultDatabase&quot;: &quot;my-project-development&quot;,<br>  &quot;defaultLocation&quot;: &quot;us-east1&quot;<br>  &quot;vars&quot;: {<br>      &quot;df_environment&quot;: &quot;development&quot;<br>  }  <br>}</pre><p>We defined the df_environment variable with the development value.</p><p>We can add the compilation variable during the release configuration creation for the release configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*-Q3h3wRh9Swb9XhiGIz-JQ.png" /><figcaption>Adding the compilation variable during the release configuration creation</figcaption></figure><p>To utilize the compilation variable in the action code, the when JS function can be employed.</p><pre>config { type: &quot;view&quot; }<br><br>SELECT ${when(<br>              dataform.projectConfig.vars.df_environment === &quot;production&quot;,<br>                 `&quot;This is the production&quot; as value`, <br>                 `&quot;This is the development&quot; as value`<br>        )};</pre><p>When the action is executed in the development workspace, &quot;This is the development&quot; will be displayed. If the production release configuration is used, &quot;This is the production&quot; will be present.</p><p>For more information about compilation variables and configuring environments in Dataform, please refer to my article &quot;Configuring Data Pipeline Environments in Dataform [4].&quot;</p><h3>Using variables in actions</h3><p>Let’s consider an example of the use of variables. Our organization collaborates with agencies to attract customers. Each agency has unique fee conditions. We need to create customer rosters per agency, calculate fees, and store the results in CSV format. We will configure a JSON file to store the fee conditions for each agency and the JS file to load it. We will develop the operations-type action, using procedural language to create a loop that processes data for each agency and exports it to Google Cloud Storage as a CSV file.</p><p>Let’s create the JSON file with the condition parameters (agency_fee.json).</p><pre>[<br>    {<br>        &quot;agency&quot;: &quot;First broker agency&quot;,<br>        &quot;fee&quot;: &quot;0.2&quot;,<br>        &quot;file_prefix&quot;: &quot;first_broker&quot;<br>    },<br>    {<br>        &quot;agency&quot;: &quot;Simple marketing&quot;,<br>        &quot;fee&quot;: &quot;0.1&quot;,<br>        &quot;file_prefix&quot;: &quot;simple_mark&quot;<br>    },<br>    {<br>        &quot;agency&quot;: &quot;Best customers&quot;,<br>        &quot;fee&quot;: &quot;0.15&quot;,<br>        &quot;file_prefix&quot;: &quot;best_cust&quot;<br>    }<br>]</pre><p>Next, let’s create the config .js file that loads the JSON file and makes it readable in the SQL code.</p><pre>// Agency fee parameters<br><br>const agency_fee_json = require(&quot;definitions/my_folder/agency_fee.json&quot;)<br><br>const agency_fee_dict = agency_fee_json.map(item =&gt; `&#39;&#39;&#39;${JSON.stringify(item)}&#39;&#39;&#39;`);<br><br>module.exports = {<br>      agency_fee_dict<br>  };</pre><p>The agency_fee_dict variable is a dictionary that includes three parameters: agency—an agency name, fee—a percent of the sales amount, and file_prefix—a prefix for the result CSV file name.</p><p>Source table with our customers, agencies they were attracted to, and the sale amount looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*ABFmIJxrygesy8g1Hvrr2A.png" /><figcaption>Source table</figcaption></figure><p>The action code.</p><pre>config {<br>  type: &quot;operations&quot;, <br>  schema: &quot;customer_agency_rosters&quot;<br>}<br><br>js {<br>   const { agency_fee_dict } = require(&quot;definitions/customer_agency_rosters/customer_agency_rosters_config.js&quot;);<br>}<br><br>DECLARE _agency STRING;<br>DECLARE _fee STRING;<br>DECLARE _file_prefix STRING;<br>DECLARE _iter_item INT64 DEFAULT 1;<br>DECLARE bucket STRING DEFAULT ${when(<br>                               dataform.projectConfig.vars.df_environment === &quot;production&quot;,<br>                                 `&#39;gs://bucket_prod/&#39;;`,<br>                                 `&#39;gs://bucket_dev/&#39;;`<br>                                   )}<br><br>WHILE _iter_item &lt;= (ARRAY_LENGTH( [${agency_fee_dict}] )) DO<br><br>  SET _agency = JSON_EXTRACT_SCALAR ( [${agency_fee_dict}] [SAFE_ORDINAL(_iter_item)], &#39;$.agency&#39;);<br>  SET _fee = JSON_EXTRACT_SCALAR ( [${agency_fee_dict}] [SAFE_ORDINAL(_iter_item)], &#39;$.fee&#39;);<br>  SET _file_prefix = JSON_EXTRACT_SCALAR ( [${agency_fee_dict}] [SAFE_ORDINAL(_iter_item)], &#39;$.file_prefix&#39;);<br><br>  EXECUTE IMMEDIATE &quot;&quot;&quot;<br>  EXPORT DATA<br>    OPTIONS (<br>      uri = &#39;&quot;&quot;&quot; || bucket  || _file_prefix || &#39;_*.csv&#39;  &quot;&quot;&quot;&#39;,<br>      format = &#39;CSV&#39;,<br>      overwrite = true,<br>      header = true<br>)<br>AS (<br>  SELECT *, sale_amount * CAST( &#39;&quot;&quot;&quot; || _fee || &quot;&quot;&quot;&#39;  as FLOAT64) as fee_amount<br>  FROM ${ref(&#39;customer_table&#39;)}<br>  WHERE agency = &#39;&quot;&quot;&quot; || _agency  || &quot;&quot;&quot;&#39;<br>    )<br>&quot;&quot;&quot;;<br><br>SET _iter_item = _iter_item + 1;<br>END WHILE;<br><br></pre><p>Let’s consider the code step by step.</p><p>The config block includes the operationals type action and the dataset&#39;s name in the schema field.</p><p>Next, we declared the GoogleSQL variables using DECLARE. The _agency, _fee, and _file_prefix will store their current values in the loop. The _iter_item is responsible for the loop iteration. The bucket variable defines the bucket name using the when function and the compilation variable df_environment.</p><p>The WHILE, SET _iter_item, and END WHILE statements form a loop. The loop continues until the value of _iter_item reaches the array&#39;s length.</p><p>In the loop body, we extract specific JSON fields using the JSON_EXTRACT_SCALAR function and save them in the current value variable as _agency, _fee, and _file_prefix.</p><p>The EXPORT DATA statement [5] fetches data from the source table for each agency, computes the fee amount using the current fee value, and then exports the result to GCS in CSV format. The EXECUTE IMMEDIATE function assists in creating the statement string. Using concatenation operators ||, we inserted the bucket, _file_prefix, and _agency variables into the string.</p><p>After the action execution, three CSV files will be created on the GCS bucket, with names according to the file prefix.</p><h3>Summary</h3><p>Using Dataform variables- whether GoogleSQL, JavaScript, or compilation variables — boosts our data pipeline’s flexibility and efficiency. GoogleSQL variables help with dynamic queries, JS variables are great for reusability across actions, and compilation variables allow us to customize settings for different environments. These tools help us write cleaner, more adaptable code, making it easier to handle complex data operations.</p><p>Thank you for taking the time to read this.</p><h3>Related Links</h3><ul><li>[1] Google, <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language">Procedural language</a>.</li><li>[2] Google, <a href="https://cloud.google.com/dataform/docs/reuse-code-includes">Reuse variables and functions with includes in Dataform</a>.</li><li>[3] Google, <a href="https://cloud.google.com/dataform/docs/code-lifecycle#workspace-overrides">Ways to configure Dataform compilation</a>.</li><li>[4] Medium, <a href="https://medium.com/google-cloud/configuring-data-pipeline-environments-in-dataform-f06359ff634c">Alex Feldman. Configuring Data Pipeline Environments in Dataform</a>.</li><li>[5] Google, <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/other-statements#export_to_gcs">Export and load statements in GoogleSQL</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59f2d6745f9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Data Pipeline Environments in Dataform]]></title>
            <link>https://medium.com/google-cloud/configuring-data-pipeline-environments-in-dataform-f06359ff634c?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f06359ff634c</guid>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 01:08:00 GMT</pubDate>
            <atom:updated>2024-04-25T01:08:00.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lxbc4rML4ni01CqS" /><figcaption>Photo by <a href="https://unsplash.com/@noaa?utm_source=medium&amp;utm_medium=referral">NOAA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Two great features of Dataform enable us to manage code versions and configure separate environments. These features are Git integration and overriding default compilation settings.</p><p>This article considers options for separating development, production, and other required data pipeline environments inside the Google Cloud Platform. Environment, in this case, means separated data sources, compiled code that provides data transformation, and the data pipeline output. We will discuss data pipelines constructed using SQL code and connected GCP services. The code we create for the data pipeline should be the same for all environments. We only need the GitHub pull requests to transfer code between environments.</p><h3>Dataform development environment configuration</h3><p>Dataform supports working in different workspaces, possibly overriding the default compilation setting. This feature allows us to separate compilation results for development, QA, and production in BigQuery.</p><p>We can configure workspace compilation overrides in the repository settings after <a href="https://cloud.google.com/dataform/docs/quickstart-dev-environments#create-repository">creating the Dataform repository</a>. These compilation override settings will be applied only for manual executions during the development process, that is, the development environment. Let’s look at the settings (SETTING tab → Workspace compilation overrides → EDIT button)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*yhiVvLLIZJblukqNCEqVwA.png" /><figcaption>Workspace compilation overrides → EDIT.</figcaption></figure><ul><li><strong>Google Cloud Project.</strong> We can use another Google Cloud project as a place where tables will materialize after execution. For example, my-project-development.</li><li><strong>Schema suffix</strong>. We can use the BigQuery schema (dataset) suffix. For example, _development. For this case, the destination dataset will be my_dataset_development. Instead of a static suffix, we can use the workspace name (the branch name in terms of GitHub) using ${workspaseName} value. It can be helpful if several developers work on the same project. For example, for the alex branch, the dataset name is my_dataset_alex.</li><li><strong>Table prefix</strong>. We can add a prefix to table names. For example, development_total_amount or alex_total_amount using ${workspaseName}.</li></ul><p>We can use one of the options or their combination.</p><h3>Dataform production and QA environment configuration</h3><p>To configure the production or QA environment, first, we need to <a href="https://cloud.google.com/dataform/docs/connect-repository">connect to a remote GitHub repository</a> (it can also be GitLab or Bitbucket) to record changes, manage file versions, and pull requests. To do so, we must authenticate a remote repository through HTTPS or SSH.</p><p><em>If you plan to use GitHub actions (as we consider below), I recommend including the workflow scope option when </em><a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic"><em>creating the personal access token</em></a><em> on GitHub, as it is not included by default.</em></p><p>When configuring the Git connection settings, we define the default branch name. For example, main for production or qa for QA environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*lB9J-Rk3XgNsNZDhLiAK4Q.png" /></figure><p>The default branch is a GitHub branch containing finished and approved code after a pull request. This branch will serve as a source for the production (or QA) environment compiling code. Overriding the default compilation setting for the default branch configures the Dataform production (QA) environment. The <a href="https://cloud.google.com/dataform/docs/code-lifecycle#release-configurations">Dataform code life cycle</a> supposes these overrides settings during the<a href="https://cloud.google.com/dataform/docs/code-lifecycle#release-configurations"> release configuration creation</a>. The same options as for a repository can be used here by replacing the GCP project, adding the schema (dataset) suffix, or the table prefix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*9IWLrnfQQ6Xp-8BIrTu30w.png" /><figcaption>Create a release configuration form.</figcaption></figure><p>Besides that, we can add compilation variables. We will consider an example below.</p><p>The decision to use specific compilation override options depends on various factors, such as the number of developers working on it, whether other GCP services are included in data pipelines, whether mock data sources are used for development and testing, and who is responsible for testing.</p><p>Let’s look at the environment element’s relationships if we use the schema (dataset) suffix overriding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*HFvPv-EU6FdReV7eqde2mQ.png" /><figcaption>Environments configured on schema (dataset) suffix overriding.</figcaption></figure><p>When we develop code in the Dataform development workspace, the automatically compiled code materializes the tables in the BigQuery my_dataset_development dataset. The _development suffix is configured in the development workspace settings. Once we have finished coding, we commit the code to the GitHub development branch and then submit a pull request to the QA branch.</p><p>To compile code for the QA environment, we need to create a QA release configuration where we define the _qa suffix. Once the code is compiled and executed, the tables will be materialized in the my_dataset_qa dataset in BigQuery.</p><p>After merging the QA pull request into the production branch, we can compile and execute the production environment code to materialize the table in the my_dataset_production dataset.</p><h3>Mock and production data sources</h3><p>One of the requirements for environment separation is using the same code for any environment. But what if we use one data source when we develop and test it and another when it works in production? A way to provide it is by using project compilation overrides. The fact that the project overrides affects not only the destination tables but also the source table, which can be used to configure mock data sources for the development environment and actual data sources for the production version.</p><p>When we declare the data source in Dataform, we can or cannot use the database parameter in the config block. For example, the source table is always queried from the production project in the following case:</p><pre>config {<br>      type: &quot;declaration&quot;,<br>      database: &quot;my-project-production&quot;,<br>      schema: &quot;my_source_dataset&quot;,<br>      name: &quot;my_source_table&quot;,<br>    }</pre><p>But here, the source table project is dependent on the override settings:</p><pre>config {<br>      type: &quot;declaration&quot;,<br>      schema: &quot;my_source_dataset&quot;,<br>      name: &quot;my_source_table&quot;,<br>    }</pre><p>If we have BigQuery table sources in the production project, we can create the same named tables with mock data in the development project and use them in the development environment. Or if we have two Cloud SQL databases, one for QA and another for production, we can create BigQuery views with the same name in both projects using different external connections. The Dataform source declaration uses identical code, but the output data depends on the Dataform project&#39;s override settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*0Mw-c3FL2ytmSD3Ki5BOiQ.png" /><figcaption>The same Dataform code for both environments with different results.</figcaption></figure><p>For data sources where we can’t create the same name resources in different projects, such as GCS buckets and external connections, we can use compilation variables and $when contractions.</p><h3>Define environments using compilation variables</h3><p>Let’s return to the Create release configuration form and add the df_environment compilation variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*waxPY6FNCCzOaiYj84QmAw.png" /><figcaption>Adding the compilation variable</figcaption></figure><p>For example, we have a task to export data to the GCS bucket. Unfortunately, GCP does not allow the creation of buckets with the same name across different projects within the same organization. To distinguish between production and development buckets, let&#39;s name the buckets output_prod and output_dev, respectively. The Dataform action code can look like this.</p><pre>config {<br>  type: &quot;operations&quot;,<br>  schema: &quot;my_dataset&quot;<br>}<br><br><br>DECLARE bucket_uri STRING;<br><br>SET bucket_uri =  ${when(<br>                    dataform.projectConfig.vars.df_environment === &quot;production&quot;,<br>                       `&quot;gs://output_prod/file.csv&quot;`, <br>                       `&quot;gs://output_dev/file.csv&quot;`<br>                    )};<br><br>EXECUTE IMMEDIATE &quot;&quot;&quot;<br>EXPORT DATA<br>  OPTIONS (<br>    uri = &#39;&quot;&quot;&quot; || bucket_uri || &quot;&quot;&quot;&#39;,<br>    format = &#39;CSV&#39;,<br>    overwrite = true<br>)<br>AS (<br>  SELECT *<br>  FROM ${ref(&#39;source_table&#39;)}<br>    )<br>&quot;&quot;&quot;;</pre><p>If the df_environment variable equals production, the destination bucket is output_prod; otherwise, output_dev. If you want to define a variable in the current project explicitly, add its value to the dataform.json file.</p><pre>{<br>  &quot;defaultSchema&quot;: &quot;dataform&quot;,<br>  &quot;assertionSchema&quot;: &quot;df_assertions&quot;,<br>  &quot;warehouse&quot;: &quot;bigquery&quot;,<br>  &quot;defaultDatabase&quot;: &quot;my-project-development&quot;,<br>  &quot;defaultLocation&quot;: &quot;us-east1&quot;<br>  &quot;vars&quot;: {<br>      &quot;df_environment&quot;: &quot;development&quot;<br>  }  <br>}</pre><p>Another example. If we need to create a BigQuery remote function in different GCP projects that trigger different Cloud functions depending on the environment (look at <a href="https://medium.com/@alex-feldman/bigquery-and-cloud-functions-integration-by-using-remote-function-to-create-cost-effective-pipelines-c1b96c98f453">my article</a> for further information on BigQuery remote functions), we can use the default project settings stored in the dataform.json file. Set the defaultDatabase value in the $when construction.</p><pre>config {<br>  type: &quot;operations&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  hasOutput: true<br>}<br><br>DECLARE connection_id STRING;<br>DECLARE endpoint_id STRING;<br><br>${when(<br>     dataform.projectConfig.defaultDatabase === &quot;my-project-production&quot;,<br>        // setting for the production project<br>        `SET connection_id = &#39;my-project-production.us-east1.cloud_func_connection&#39;;<br>         SET endpoint_id = &#39;https://us-east1-my-project-production.cloudfunctions.net/my_function&#39;;`, <br>        // setting for the development project<br>        `SET connection_id = &#39;my-project-development.us-east1.cloud_func_connection_dev&#39;;<br>         SET endpoint_id = &#39;https://us-east1-my-project-development.cloudfunctions.net/my_function&#39;;`<br>  )}<br><br><br>EXECUTE IMMEDIATE &quot;&quot;&quot;<br>CREATE FUNCTION IF NOT EXISTS ${self()}() RETURNS STRING<br>REMOTE WITH CONNECTION `&quot;&quot;&quot;|| connection_id ||&quot;&quot;&quot;`<br>OPTIONS (<br>  endpoint = &#39;&quot;&quot;&quot;|| endpoint_id ||&quot;&quot;&quot;&#39;<br>)<br>&quot;&quot;&quot;;</pre><h3>Deploying Cloud Functions within Dataform</h3><p>Let’s continue the previous example about deploying the BigQuery remote function and consider how to deploy the invoked Cloud function (my_function) depending on the environment. We can deploy the same name Cloud function in the development or production project simultaneously with SQL code. We need to add the function code to the Dataform repository and configure the GitHub action using the action YAML file to do it. We can create the new cloud-function directory and copy its function code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*j1394X2hmRH7ndx8bdcVmQ.png" /><figcaption>Adding Cloud function code to the repository</figcaption></figure><p>I’m not advocating developing the function Python code in the Dataform workspace (Hey, Dataform developers, seize the idea), but we can connect PyCharm (or another tool) to the repository for the function code development.</p><p>Also, we need to add a YAML file to configure the GitHub action to automate the Cloud function deployment, depending on the environment. To do it, let’s create the my_function_deploy.yaml file in the .github/workflows directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*XfPUt-QquyW6mPhxA6oyrQ.png" /><figcaption>Adding the YAML file.</figcaption></figure><p>The my_function_deploy.yaml code can look like this:</p><pre>on:<br>  pull_request:<br>    branches:<br>      - main<br>      - qa<br>    paths:<br>      - &#39;**cloud-functions/my_function/src/**&#39;<br><br>env:<br>  CLOUD_FUNCTION_NAME: &#39;my_function&#39;<br>  GCP_REGION: &#39;us-east1&#39;<br>  FILE_SOURCE: &#39;./cloud-functions/my_function/src/&#39;<br>  ENTRY_POINT: &#39;main&#39;<br><br><br>jobs:<br>  deploy-cloud-function:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: &#39;Set project based on branch&#39;<br>        run: |<br>          if [[ &quot;${{ github.event.pull_request.base.ref }}&quot; == &quot;main&quot; ]]; then<br>            echo &quot;GCP_PROJECT_ID=my-project-production&quot; &gt;&gt; &quot;$GITHUB_ENV&quot;<br>          elif [[ &quot;${{ github.event.pull_request.base.ref }}&quot; == &quot;qa&quot; ]]; then<br>            echo &quot;GCP_PROJECT_ID=my-project-development&quot; &gt;&gt; &quot;$GITHUB_ENV&quot;<br>          else<br>            echo &quot;Error: Unsupported destination branch. GCP_PROJECT_ID not set.&quot;<br>            exit 1  <br>          fi<br>        shell: bash<br><br>      - name: Checkout repository<br>        uses: actions/checkout@v3<br><br>      - name: &#39;Authenticate to Google Cloud&#39;<br>        id: &#39;auth&#39;<br>        uses: &#39;google-github-actions/auth@v1&#39;<br>        with:<br>          credentials_json: &#39;${{ secrets.SERVICE_ACCOUNT }}&#39;<br><br>      - name: &#39;Set up Cloud SDK&#39;<br>        id: &#39;sdk&#39;<br>        uses: &#39;google-github-actions/setup-gcloud@v1&#39;<br><br>      - name: &#39;Deploy Cloud function&#39;<br>        id: &#39;deploy&#39;<br>        run: |<br>          gcloud functions deploy $CLOUD_FUNCTION_NAME \<br>          --project=$GCP_PROJECT_ID \<br>          --region=$GCP_REGION \<br>          --no-allow-unauthenticated \<br>          --ingress-settings=internal-and-gclb \<br>          --runtime=python311 \<br>          --source=$FILE_SOURCE/ \<br>          --entry-point=$ENTRY_POINT \<br>          --trigger-http \<br>          --timeout=500 \<br>          --memory=512MB</pre><p>The on section triggers an action on pull requests for the main and qa branches, but only if changes affect a specific path.</p><pre>on:<br>  pull_request:<br>    branches:<br>      - main<br>      - qa<br>    paths:<br>      - &#39;**cloud-functions/my_function/src/**&#39;</pre><p>The environment variables are defined in the env section, except the GCP_PROJECT_ID variable.</p><pre>env:<br>  CLOUD_FUNCTION_NAME: &#39;my_function&#39;<br>  GCP_REGION: &#39;us-east1&#39;<br>  FILE_SOURCE: &#39;./cloud-functions/my_function/src/&#39;<br>  ENTRY_POINT: &#39;main&#39;</pre><p>The GCP_PROJECT_ID variable&#39;s value depends on the destination branch, which can be either main or qa. It is defined in the Set project based on branch step. The github.event.pull_request.base.ref system variable in charge of destination branch value. If the branch is main, GCP_PROJECT_ID is set as the production project, whereas the development project is set for qa.</p><pre>- name: &#39;Set project based on branch&#39;<br>        run: |<br>          if [[ &quot;${{ github.event.pull_request.base.ref }}&quot; == &quot;main&quot; ]]; then<br>            echo &quot;GCP_PROJECT_ID=my-project-production&quot; &gt;&gt; &quot;$GITHUB_ENV&quot;<br>          elif [[ &quot;${{ github.event.pull_request.base.ref }}&quot; == &quot;qa&quot; ]]; then<br>            echo &quot;GCP_PROJECT_ID=my-project-development&quot; &gt;&gt; &quot;$GITHUB_ENV&quot;<br>          else<br>            echo &quot;Error: Unsupported destination branch. GCP_PROJECT_ID not set.&quot;<br>            exit 1  <br>          fi<br>        shell: bash</pre><p>Then, the Google Cloud authentication and Cloud SDK set. Ensure that the <a href="https://cloud.google.com/iam/docs/keys-create-delete">service account keys</a> are added to <a href="https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository">GitHub secret settings</a> and that service account permissions allow the <a href="https://cloud.google.com/functions/docs/deploy#basics">deployment of Cloud functions</a>.</p><pre>- name: Checkout repository<br>        uses: actions/checkout@v3<br><br>      - name: &#39;Authenticate to Google Cloud&#39;<br>        id: &#39;auth&#39;<br>        uses: &#39;google-github-actions/auth@v1&#39;<br>        with:<br>          credentials_json: &#39;${{ secrets.SERVICE_ACCOUNT }}&#39;<br><br>      - name: &#39;Set up Cloud SDK&#39;<br>        id: &#39;sdk&#39;<br>        uses: &#39;google-github-actions/setup-gcloud@v1&#39;</pre><p><em>Google Cloud recommends using the </em><a href="https://cloud.google.com/iam/docs/workload-identity-federation"><em>workload identity federation</em></a><em> instead of the service account keys. See the </em><a href="https://cloud.google.com/iam/docs/best-practices-for-using-service-accounts-in-deployment-pipelines"><em>best practices for using service accounts in pipelines</em></a><em>.</em></p><p>Finally, the <a href="https://cloud.google.com/sdk/gcloud/reference/functions/deploy">Cloud SDK command deploys the function</a> using variables.</p><pre>gcloud functions deploy $CLOUD_FUNCTION_NAME \<br>          --project=$GCP_PROJECT_ID \<br>          --region=$GCP_REGION \<br>          --no-allow-unauthenticated \<br>          --ingress-settings=internal-and-gclb \<br>          --runtime=python311 \<br>          --source=$FILE_SOURCE/ \<br>          --entry-point=$ENTRY_POINT \<br>          --trigger-http \<br>          --timeout=500 \<br>          --memory=512MB</pre><p>After pushing the commit to GitHub, the function will be deployed in the my-organization-development project when we pull request code from the dev into qa branch. The function will be deployed to my-organization-production when pull-requesting is made into main.</p><h3>Environment security</h3><p>Another question is organizing appropriate <a href="https://cloud.google.com/dataform/docs/access-control">access</a> to the production environment for teams, including data engineers, analysts, QA specialists, and other users, to avoid intentional or accidental data pipeline execution or removing scheduling.</p><p>For example, if the QA team should test the new data pipeline after development, it requires QA and production compilation results inside corresponding release configurations with the possibility of executing the QA one. But we can’t configure access for the QA team to only specific release configurations. The solution is to use the environment separation by GCP project and <a href="https://cloud.google.com/dataform/docs/best-practices#code_lifecycle_in_multiple_repositories">configure Dataform in each project</a>. It should not have any additional costs as Dataform is a free service. We can provide QA team access only to the development project where we configure the QA compilation result.</p><p>This approach gives additional benefits, such as protection from mixing production and QA data. When we use Dataform in one project, we should grant read-write permissions for the Dataform service account to all projects where we materialize the execution results. If we configure Dataform in several GCP projects, we can grant full access to the local project and read-only access to others. If the QA compilation result is attempted to materialize in the production project due to code issues, an execution error will be raised.</p><p>Dataform&#39;s documentation provides <a href="https://cloud.google.com/dataform/docs/managing-code-lifecycle#best_practices_for_isolated_execution_environments">the best practice</a> for configuring various options for Dataform environments.</p><p>We discussed configuring release configurations and compilation overrides using the Dataform workflow tool, although other methods are available (<a href="https://cloud.google.com/python/docs/reference/dataform/latest/google.cloud.dataform_v1beta1.services.dataform.DataformClient#google_cloud_dataform_v1beta1_services_dataform_DataformClient_create_release_config">Python client</a>, <a href="https://cloud.google.com/dataform/docs/schedule-executions-workflows#customize_the_sql_workflow_create_compilation_result_request">Cloud Workflows</a>, <a href="https://cloud.google.com/dataform/docs/schedule-executions-composer#create-schedule-dag">Airflow</a>, <a href="https://cloud.google.com/dataform/docs/compilation-overrides">Dataform API</a>).</p><p>Thanks for reading. Please follow me to stay updated and not miss any upcoming articles.</p><p>Links:</p><ul><li><a href="https://cloud.google.com/dataform/docs/code-lifecycle">Dataform. Introduction to code lifecycle in Dataform</a>.</li><li><a href="http://Create workspace compilation overrides">Dataform. Create workspace compilation overrides</a>.</li><li><a href="https://cloud.google.com/dataform/docs/best-practices#best_practices_for_code_lifecycle">Dataform. Best practices for code lifecycle.</a></li><li><a href="https://cloud.google.com/dataform/docs/managing-code-lifecycle">Dataform. Managing code lifecycle</a>.</li><li><a href="https://medium.com/@alex-feldman/bigquery-and-cloud-functions-integration-by-using-remote-function-to-create-cost-effective-pipelines-c1b96c98f453">Medium. BigQuery and Cloud Functions integration by using Remote functions to create cost-effective data pipelines (Alex Feldman)</a></li><li><a href="https://docs.github.com/en/actions/deployment/about-deployments/deploying-with-github-actions">GitHub docs. Deploying with GitHub Actions.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f06359ff634c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/configuring-data-pipeline-environments-in-dataform-f06359ff634c">Configuring Data Pipeline Environments in Dataform</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data masking in BigQuery tables and Looker Studio reports]]></title>
            <link>https://medium.com/@alex-feldman/data-masking-in-bigquery-tables-and-looker-studio-reports-7e0166b82a77?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e0166b82a77</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[looker-studio]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 07:38:19 GMT</pubDate>
            <atom:updated>2024-04-08T06:41:19.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jxaaus-mKEFMaL59" /><figcaption>Photo by <a href="https://unsplash.com/@kris_ricepees?utm_source=medium&amp;utm_medium=referral">Gary Bendig</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For data analysts, this can be a burning question. How can data security be provided in reports when one user group must see all data, including sensitive data, but another group should not have access to it?</p><p>Let’s consider it an example. Imagine a Looker Studio report with the sales chart and the BigQuery table source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*8SkDMYd9qoPveJoUmyVrfw.png" /><figcaption>Looker Studio report</figcaption></figure><p>The table contains the customer name and email fields. Let’s requirements suppose that only the finance department should see these sensitive data fields. Other report users should not have access to them but should be able to see other columns.</p><p>Several options exist to provide it, such as using the custom query source and the ‘@DS_USER_EMAIL’ parameter. However, we are considering a more robust way: <a href="https://cloud.google.com/bigquery/docs/column-data-masking-intro">BigQuery data masking</a>.</p><p>This article discusses how to implement data masking to obscure sensitive data selectively in the BigQuery table and the Looker Studio report. After the data masking implementation, users, except the financial department, will see the following data in the report using the <a href="https://support.google.com/looker-studio/answer/6371135?hl=en&amp;sjid=2449234979688681322-EU#set-data-credentials-for-a-data-source&amp;zippy=%2Cin-this-article%2Cviewers-credentials">viewer’s credential</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*ZRjCMKzdRzy5QUq2BbciAg.png" /><figcaption>Looker Studio report after data masking</figcaption></figure><p>Moreover, it will also be protected if the user tries to access data through the BigQuery console or any other way using the user’s credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*VlXqRAOV4VcbSFmMbvbS1A.png" /><figcaption>BigQuery query result with masking data</figcaption></figure><p>The data masking process involves three steps:</p><ol><li>Creating Policy tags.</li><li>Setting permissions for users.</li><li>Set Policy tags on table columns.</li></ol><p>Let’s start with the first two items.</p><h3>Policy tags configuring and granting access</h3><p>The service responsible for policy tags lives inside BigQuery:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*StKRVVqKh4P7x_Yxqkoq6A.png" /></figure><p>Let’s open this service and create the Policy tags for our report.</p><blockquote>The user that creates a data policy must have the bigquery.dataPolicies.create, bigquery.dataPolicies.setIamPolicy, and datacatalog.taxonomies.get permissions.</blockquote><p>First, we must create a taxonomy (set of rules) by clicking the CREATE TAXONOMY button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*HvZ9tR9KM79aowNDWzmOtw.png" /><figcaption>Taxonomy creating</figcaption></figure><p>Next, create two policy tags inside the taxonomy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*WPyVRSLKmJdRz5rYz6Qkxg.png" /><figcaption>Policy tags creating</figcaption></figure><p>After creating the policy tags, we need to grant permissions for the finance department to see unmasked data (Fine-Grained Reader role). To do it, select all rows in the policy tags table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*6ISDqhs_SRHPk4UsEebYrQ.png" /><figcaption>Policy tags list</figcaption></figure><blockquote>Note the copy symbols inside the ID column. In the following steps, we will use them to copy the Policy tag resource name.</blockquote><p>Click ADD PRINCIPAL on the right panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*-atKJWkQ2hVFF6nJxHgFuw.png" /><figcaption>Adding a principle</figcaption></figure><p>In the opened window, add the finance department group account (that needs to be created before) in the principal’s field and choose the Fine-Graind Reader in the role field. Save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*fQ0sAQtk62_pZr05wDH3AA.png" /><figcaption>Assigning the Fine-Grained Reader role</figcaption></figure><p>To define the masking rules and permit other users to see only masked data (Masked Reader role), select the policy tag in the list and click MANAGE DATA POLICIES.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*Sm5k3IkR7QoX1zrJ9RXPLg.png" /><figcaption>Managing the data policy</figcaption></figure><p>In the opened window, click ADD RULE and put any data policy name. Select the Hash(SHA256) rule for this policy. Add my-project.com to the principal’s field to grant the Masked Reader role to all domain users (or we can add a specific group here). Click SUBMIT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*gz8cM5PmfTgvEo_WwU7xxA.png" /><figcaption>Adding the Hash masking rule and Masked Reader role</figcaption></figure><p>The Hash(SHA256) masking rule replaces the original column value with the hashed value.</p><p>Do the same for the hide_email policy tag, but select the Email mask rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*p4L_quQ62MsFhNuT9RDO4g.png" /><figcaption>Adding Email mask rule</figcaption></figure><p>The Email mask rule replaces the user name in the email address with ‘xxxxx’ and leaves the domain untouched (for example, xxxxx@example.com).</p><p>If the user doesn’t have the Fine-Gained Reader or Masked Reader role, access to the table will be denied, and the user can query the table only without masked columns.</p><p>Congratulations! We configured policy tags and granted permission to see masked or unmasked data.</p><h3>Creating a table with policy tags using Dataform</h3><p>Next, we need to set policy tags on table columns. We can do it during the development process in Dataform.</p><p>When we create the table, we can add the bigqueryPolicyTags parameters to the config block to set tags for columns. The policy tag resource name should be copied from the policy tag table we configured in the previous step.</p><pre>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  tags: [&quot;my_tag&quot;],<br>  columns: {<br>      customer_name: {<br>        bigqueryPolicyTags: [&quot;projects/my-project/locations/us-east1/taxonomies/5339304217738278582/policyTags/6765370159562199878&quot;]<br>      },<br>      email: {<br>        bigqueryPolicyTags: [&quot;projects/my-project/locations/us-east1/taxonomies/5339304217738278582/policyTags/6765370159562199878&quot;]<br>      }<br>    }   <br>}<br><br>SELECT *<br>FROM ${ref(&#39;sales&#39;)}</pre><blockquote>The Dataform service account that sets a policy tag needs the datacatalog.taxonomies.get and bigquery.tables.setCategory permissions.</blockquote><p>After executing the action, we see masking columns in the BigQuery table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*aZaSb4lfgC4lSfoTqrWqFQ.png" /><figcaption>BigQuery table with masked columns</figcaption></figure><p><a href="https://cloud.google.com/bigquery/docs/column-data-masking#set_policy_tags_on_columns">Other ways to set policy tags</a> on columns are:</p><ul><li>Editing BigQuery table schema in the console.</li><li>Using the Cloud CLI commands, reading the existing schema (bq show), editing the schema file, and updating the table schema (bq update) with the new version.</li><li>Using API request (<a href="https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/patch">tables.patch</a>)</li></ul><p>Dataform only allows us to apply data masking when we develop SQL code. We can not do it in the BigQuery editor.</p><h3>Set policy tags on columns using Cloud CLI</h3><p>The difference between the data-masked table and the unprotected table lies in the table schema. Let’s explore the sales table schema before data masking using the Cloud SLI command:</p><pre>bq show --schema --format=prettyjson \<br>   my-project:my_dataset.sales &gt; schema_sales.json</pre><p>And look into the result in schema_sales.json</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;customer_id&quot;,<br>    &quot;type&quot;: &quot;INTEGER&quot;<br>  },<br>  {<br>    &quot;name&quot;: &quot;customer_name&quot;,<br>    &quot;type&quot;: &quot;STRING&quot;<br>  },<br>  {<br>    &quot;name&quot;: &quot;email&quot;,<br>    &quot;type&quot;: &quot;STRING&quot;<br>  },<br>  {<br>    &quot;name&quot;: &quot;purchased_total&quot;,<br>    &quot;type&quot;: &quot;FLOAT&quot;<br>  }<br>]</pre><p>We need to add the policyTags key with the tag name to the column object to apply data masking to a specific column.</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;customer_id&quot;,<br>    &quot;type&quot;: &quot;INTEGER&quot;<br>  },<br>  {<br>    &quot;name&quot;: &quot;customer_name&quot;,<br>    &quot;type&quot;: &quot;STRING&quot;,<br>    &quot;policyTags&quot;: {<br>      &quot;names&quot;: [<br>        &quot;projects/my-project/locations/us-east1/taxonomies/5339304217738278582/policyTags/6765370159562199878&quot;<br>      ]<br>    }<br>  },<br>  {<br>    &quot;name&quot;: &quot;email&quot;,<br>    &quot;type&quot;: &quot;STRING&quot;,<br>    &quot;policyTags&quot;: {<br>      &quot;names&quot;: [<br>        &quot;projects/my-project/locations/us-east1/taxonomies/5339304217738278582/policyTags/2968485733011117082&quot;<br>      ]<br>    }<br>  },<br>  {<br>    &quot;name&quot;: &quot;purchased_total&quot;,<br>    &quot;type&quot;: &quot;FLOAT&quot;<br>  }<br>]</pre><p>The customer_name and email columns were enriched with the policyTags parameter and its specific name value in the Cloud resource name format.</p><p>After we insert the policyTags parameters in the schema, we can update the table schema using the bq update command.</p><pre>bq update \<br>   my-project:my_dataset.sales new_schema_sales.json</pre><p>From the data analyst’s view, this way looks dull, but a data engineer can create the automation based on it.</p><h3>Data masking automation</h3><p>We can create the automation that scans all tables, checks if a table contains sensitive columns, and masks it using default policy. Such a data pipeline can be realized differently, and we will not discuss specific realizations here. We describe the possible steps. The pipeline could have the following steps:</p><ol><li>Creating a list of fields to check (for example, email, email_address, first_name, last_name, customer_name, etc.). The <a href="https://cloud.google.com/sensitive-data-protection/docs/profile-org-folder">Cloud DLP BigQuery profile tool</a> can help identify them.</li><li>Creating the list of project datasets using the <a href="https://cloud.google.com/bigquery/docs/information-schema-datasets-schemata">INFORMATION_SCHEMA.SCHEMATA</a> query.</li><li>Creating the list of tables for each dataset using the <a href="https://cloud.google.com/bigquery/docs/information-schema-tables">INFORMATION_SCHEMA.TABLES</a> query.</li><li>Processing each table, including:</li></ol><p>4.1. The Bash command extracts the table schema and saves it locally in the JSON file (bq show --schema).</p><p>4.2. The data masking function checks the JSON file to see if it contains the checking fields and the policy tags. If not, it sets the policy tags parameter in the fields and saves the new schema. The function may look like this:</p><pre>import json<br><br># set the list of checking fields<br>CHECKED_FIELDS = [&#39;email&#39;, &#39;email_address&#39;, &#39;customer_name&#39;, &#39;first_name&#39;, &#39;last_name&#39;]<br># define the policy tags with different masking rules<br>EMAIL_HIDE_TAG = &#39;projects/my-project/locations/us-east1/taxonomies/5339304217738278582/policyTags/6765370159562199878&#39;<br>FIELD_HASH_TAG = &#39;projects/my-project/locations/us-east1/taxonomies/5339304217738278582/policyTags/2968485733011117082&#39;<br><br>def data_masking_function():<br>    # open json file locally<br>    with open(&#39;schema.json&#39;) as f:<br>        data = json.load(f)<br>    # check if the data contains at least one of the name keys with the value from the list CHECKED_FIELDS<br>    for item in data:<br>        if &#39;name&#39; in item and item[&#39;name&#39;].lower() in CHECKED_FIELDS:<br>            # check if the current item has &#39;policyTags&#39; key<br>            if &#39;policyTags&#39; not in item:<br>                if item[&#39;name&#39;].lower() in [&#39;email&#39;, &#39;email_address&#39;]:<br>                    policy_tag_name = EMAIL_HIDE_TAG<br>                else:<br>                    policy_tag_name = FIELD_HASH_TAG<br><br>                # if not, add the policyTags key in the item as:<br>                item[&#39;policyTags&#39;] = {<br>                    &quot;names&quot;: [<br>                        policy_tag_name<br>                    ]<br>                }<br><br>    # write the updated data to a new json file<br>    with open(&#39;schema_updated.json&#39;, &#39;w&#39;) as f:<br>        json.dump(data, f, indent=2)</pre><p>5. The Bash command updates the table schema (bq update).</p><p>The developed data pipeline can run periodically and mask data using these steps.</p><p>Thanks for reading it. The following article will discuss the configuration of the Dataform environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e0166b82a77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to grant access to specific BigQuery tables using Dataform]]></title>
            <link>https://medium.com/@alex-feldman/how-to-grant-access-to-specific-bigquery-tables-using-dataform-eabfd382c8b3?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eabfd382c8b3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 18:00:41 GMT</pubDate>
            <atom:updated>2024-02-26T18:00:41.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bnEpnlKR_KKONW49" /><figcaption>Photo by <a href="https://unsplash.com/@jwimmerli?utm_source=medium&amp;utm_medium=referral">jean wimmerlin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If it’s necessary to provide user access to a specific BigQuery table or views rather than using the IAM policy for all BigQuery data, this article can help to do it using Dataform.</p><p>As a rule, persons who develop BigQuery resources and those who provide data security differ. The security provider team (for example, DevOps) strives to apply some universal general permission settings for different user groups. Still, they often can’t grant access permissions for specific BigQuery datasets and tables because the data team develops new data pipelines with new datasets and tables daily.</p><p>Let’s explore a case when we have a BigQuery dataset with several staging tables with sensitive data and one result table with aggregated data. We must provide user access only for the result table and protect sensitive data in the staging tables.</p><p>There are different ways to do it. One of them is granting local access to the specific table only. Let’s we should grant access to the result table for the bq_viewres group and <a href="https://support.google.com/looker-studio/answer/10835295?sjid=7177283660764190116-EU#zippy=%2Cin-this-article">the Looker Studio service account</a> looker-studio@my-project.iam.gserviceaccount.com.</p><p>The BigQuery Data Viewer role provides minimal permissions for accessing BigQuery data. Besides that, in order to access from Looker Studio, users must have the BigQuery Job User role, and the Looker Studio service account must have the Service Account Token Creator role. With the exception of BigQuery Data Viewer, all of these roles should be granted by IAM police.</p><p>The last required role will be granted via SQL code during the Dataform development. To provide the BigQuery Data Viewer role for the group and the service account to the result table, we should add <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-control-language#grant_statement">the DCL statement</a> in SQL code:</p><pre>-- DCL statement<br>GRANT `roles/bigquery.dataViewer` ON TABLE `my-project.my_dataset.result_table` <br>  TO &quot;group:bq_viewers@my_org.com&quot;, &quot;serviceAccount:looker-studio@my-project.iam.gserviceaccount.com&quot;;</pre><p>In Dataform, we add the code in the post_operations block of the result table SQLX file.</p><pre>-- result_table.sqlx<br><br>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>SELECT *<br>FROM  ${ref(&#39;stg_table1&#39;)}<br><br>post_operations {<br>  GRANT `roles/bigquery.dataViewer` ON TABLE ${self()} <br>    TO &quot;group:bq_viewers@my_org.com&quot;,<br>       &quot;serviceAccount:looker-studio@my-project.iam.gserviceaccount.com&quot;;<br>}</pre><p>If the result table is a view, we should grant access to the view and underlying tables.</p><pre> -- result_table.sqlx<br><br>config {<br>  type: &quot;view&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>SELECT *<br>FROM  ${ref(&#39;stg_table1&#39;)}<br><br>post_operations {<br>  GRANT `roles/bigquery.dataViewer` ON VIEW ${self()} <br>    TO &quot;group:bq_viewers@my_org.com&quot;,<br>       &quot;serviceAccount:looker-studio@my-project.iam.gserviceaccount.com&quot;;<br><br>  GRANT `roles/bigquery.dataViewer` ON TABLE ${ref(&#39;stg_table1&#39;)}<br>    TO &quot;group:bq_viewers@my_org.com&quot;,<br>       &quot;serviceAccount:looker-studio@my-project.iam.gserviceaccount.com&quot;;<br><br>}</pre><p>To reduce the amount of code, we can create a JavaScript function. Let&#39;s create a new file called including/functions.js (or use an existing one) and add the following code:</p><pre>function GrantAccess(TableName, type) {<br>  const objectType = {<br>    &#39;table&#39;: &#39;TABLE&#39;,<br>    &#39;view&#39;: &#39;VIEW&#39;<br>  };<br><br>//  Validate selfTableName and type<br> if (!TableName || !type || !objectType[type]) {<br>   throw new Error(&#39;Invalid arguments: selfTableName and type are required, and type must be a valid object type (table, view).&#39;);<br> }<br><br>// Create a GRANT statement<br>  const grant_string = <br>    `GRANT \`roles/bigquery.dataViewer\` ON ${objectType[type]} ${TableName} TO &quot;group:group:bq_viewers@my_org.com&quot;, &quot;serviceAccount:looker-studio@my-project.iam.gserviceaccount.com&quot;;`<br><br>  return grant_string; // Return the grant statement string<br>}<br><br>module.exports = {<br>    GrantAccess<br>};</pre><p>The function takes two arguments: a table or view name and an object type. The function validates the arguments, produces an error message if they are invalid, and returns the GRANT statement string.</p><p>The result_table view code:</p><pre>-- result_table.sqlx<br><br>config {<br>  type: &quot;view&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>SELECT *<br>FROM  ${ref(&#39;stg_table1&#39;)}<br><br>post_operations {<br>  ${ functions.GrantAccess(`${self()}`, &#39;view&#39;) }<br>  ${ functions.GrantAccess(`${ref(&#39;stg_table1&#39;)}`, &#39;table&#39;) }<br>}</pre><p>In the next article, we will discuss another method of safeguarding sensitive data — <a href="https://cloud.google.com/bigquery/docs/column-data-masking">data masking</a>. Please follow me so that you don&#39;t miss it.</p><p>Thanks for your attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eabfd382c8b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to avoid circular dependencies in Dataform]]></title>
            <link>https://medium.com/@alex-feldman/how-to-avoid-circular-dependencies-in-dataform-38a29e3e32ec?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/38a29e3e32ec</guid>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 17:00:10 GMT</pubDate>
            <atom:updated>2024-02-05T17:00:10.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Despite the answer to this question lying on the surface for most Dataform users, it took me some time to figure out how it works. Maybe I’m not alone in here.</p><p>If downstream dependence is put in the action code, Dataform raises the circular dependence error. For instance, we have table_1.sqlx and table_2.sqlx files.</p><pre>-- table_1.sqlx<br><br>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;my_dataset&quot;<br>}<br><br>SELECT *<br>FROM ${ref(&#39;source_table&#39;)}<br>WHERE timestamp &gt; (SELECT MAX(timestamp) FROM ${ref(&#39;table_2)})<br><br></pre><pre>-- table_2.sqlx<br><br>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;my_dataset&quot;<br>}<br><br>SELECT *<br>FROM ${ref(&#39;table_1&#39;)}</pre><p>In this case, Dataform produces the error: Error in definitions/table_1.sqlx. Circular dependency detected in chain: …</p><p>Of course, using such dependencies is not the best practice (instead, it&#39;s better to use the incremental type for table 1 and the self() function). However, in some cases, we might not have better options.</p><p>Let&#39;s explore three methods to prevent the circular dependencies error in Dataform.</p><h3>Using a direct table name</h3><p>We can use the direct name of the table_2 to avoid an error.</p><pre>-- table_1.sqlx<br><br>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;my_dataset&quot;<br>}<br><br><br>SELECT *<br>FROM ${ref(&#39;source_table&#39;)}<br>WHERE timestamp &gt; (SELECT MAX(timestamp) FROM `my_project.my_dataset.table_2`)</pre><p>It works, but it may not be suitable if we use separate workspaces for development and production environments using the <a href="https://cloud.google.com/dataform/docs/workspace-compilation-overrides">compilation overrides</a>. It also deprives us of other Dataform benefits. This is the least recommended option.</p><h3>Using resolve() function</h3><p>Dataform has a <a href="https://cloud.google.com/dataform/docs/reference/dataform-core-reference#commoncontext">resolve() function</a> that works like ref() but does not add the referenced action as a dependency to this action.</p><pre>-- table_1.sqlx<br><br>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;my_dataset&quot;<br>}<br><br>SELECT *<br>FROM ${ref(&#39;source_table&#39;)}<br>WHERE timestamp &gt; (SELECT MAX(timestamp) FROM ${resolve(&#39;table_2)})</pre><p>We replaced the ref() function with the resolve(), and the error disappeared.</p><h3>Calculating the table name</h3><p>If, for some reason, the resolve() function cannot be used, we can utilize a more complex solution and calculate the target name using <a href="https://cloud.google.com/dataform/docs/reference/dataform-core-reference#commoncontext">self() or </a><a href="https://cloud.google.com/dataform/docs/reference/dataform-core-reference#commoncontext">name() functions</a>. For example, if our production dataset has _production suffix, we can utilize the self() function to define the current environment.</p><pre>-- table_1.sqlx<br><br>config {<br>  type: &quot;operations&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  hasOutput: true<br>}<br><br>DECLARE current_dataset STRING;<br><br>SET current_dataset = (<br>  IF(<br>    &#39;${self()}&#39; LIKE &#39;%_production%&#39;, <br>    &#39;my_dataset_production&#39;, <br>    &#39;my_dataset&#39;)<br>);<br><br>EXECUTE IMMEDIATE &quot;&quot;&quot;<br>SELECT *<br>FROM ${ref(&#39;source_table&#39;)}<br>WHERE timestamp &gt; (SELECT MAX(timestamp) FROM <br> `my_project.&quot;&quot;&quot; || current_dataset || &quot;&quot;&quot;.table_2`<br>)<br>&quot;&quot;&quot;;</pre><p>We must use the operations type in the config block because we used a dynamic SQL.</p><p>First, we created a string variable called current_dataset. Then, we assign a value based on the current table name. If the whole table name is my_project.my_dataset_production.table_1, the current_dataset value is set to my_dataset_production, otherwise it is set to my_dataset. After that, we concatenated the current dataset value into the whole table name string using the <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#execute_immediate">EXECUTE IMMEDIATE</a> statement and the || <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/operators">operator</a>.</p><p>If we use a different table prefix, we can define it the same way using the name() function instead of self().</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38a29e3e32ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical and Business data alerts using Dataform]]></title>
            <link>https://medium.com/google-cloud/technical-and-business-data-alerts-using-dataform-6e0e7f504f0e?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0e7f504f0e</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 12:43:45 GMT</pubDate>
            <atom:updated>2024-01-31T12:43:45.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B08Mt13PhPUABh59" /><figcaption>Photo by <a href="https://unsplash.com/@rthiemann?utm_source=medium&amp;utm_medium=referral">Robert Thiemann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I want to continue discussing the topic of creating and tracking data alerts. Last year, I wrote a series of posts (<a href="https://medium.com/@alex-feldman/how-to-track-bigquery-data-alerts-65892febbf8b">1</a>, <a href="https://medium.com/@alex-feldman/advanced-assert-queries-for-bigquery-data-alerts-14c9859a78cc">2</a>, <a href="https://medium.com/@alex-feldman/sending-bigquery-data-alerts-to-the-slack-channel-e26bd0ae8d5">3</a>) on creating BigQuery data alerts using the Scheduled Queries service, Pub/Sub, and Cloud Functions. However, since then, Google Cloud has introduced new tools that have improved data pipeline development - Dataform and Remote Function. So, I’ve changed my approach and will discuss the latest way in this article.</p><p>Let&#39;s see how to create and run data alerts using Dataform and send notifications to Slack.</p><p>We can categorize alerts into two types:</p><ul><li><strong>Technical alerts </strong>are notifications for the technical team about data errors, with no complex requirements for message content.</li><li><strong>Business alerts </strong>notify other teams (marketing, product, finance) of data-driven events and their details.</li></ul><h3>Technical alerts</h3><p>We will use Dataform&#39;s assertion features and a Cloud Logging service to create and track technical alerts.</p><p>Dataform lets us create <a href="https://cloud.google.com/dataform/docs/assertions#built-in">built-in assertions</a> in the config block or <a href="https://cloud.google.com/dataform/docs/assertions#manual">manual assertions with SQLX files</a>.</p><h4>Built-in assertion</h4><p>We can add a built-in assertion option to any table by defining the assertion conditions in the config block. Dataform compiles the additional debugging statement to check these conditions and produces an error if conditions are not met.</p><p>Built-in assertions can check the following conditions: nonNull, rowConditions, uniqueKey, and uniqueKeys. For example:</p><pre>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  assertions: {<br>    uniqueKey: [&quot;id&quot;],<br>    nonNull: [&quot;user_id&quot;]<br>    }<br>}<br><br>SELECT id, user_id<br>FROM ${ref(&#39;source_table&#39;)}<br></pre><p>In this case, the assertion checks for duplicates in the ID field and null values in the user ID field. If either of these conditions is not met, the workflow execution will produce an error.</p><h4>Manual assertion</h4><p>A manual assertion with SQLX files can be set up to check certain conditions in a query. If the query returns any results, an error will be produced. For instance, the following assertion checks whether the table has been re-created within a specific time period.</p><pre>config {<br>  type: &quot;assertion&quot;,<br>  schema: &quot;my_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>SELECT creation_time, CURRENT_TIMESTAMP() as currect_time<br>FROM `my_project.my_dataset.INFORMATION_SCHEMA.TABLES`<br>WHERE table_name = &#39;checked_table_name&#39;<br>AND (creation_time &gt;= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), <br>  INTERVAL 3 HOUR) ) IS FALSE</pre><p>The query will only produce results if the table was created more than 3 hours ago.</p><p>To enable alerts, we need to create a Dataform <a href="https://cloud.google.com/dataform/docs/workflow-configurations">workflow configuration</a>, add SQLX files by tags or file names, and schedule the run frequency, for instance, every hour. Let’s name the workflow configuration alerts_hourly. After its execution, we can view the execution status in the Dataform <a href="https://cloud.google.com/dataform/docs/execution-logs#inspect_repository_execution_logs">workflow execution log</a>.</p><h4>Slack notification using Cloud Logging</h4><p>To deliver an alert notification to Slack, we can <a href="https://cloud.google.com/dataform/docs/log-based-alerts">Configure alerts for failed workflow invocation</a> using <a href="https://cloud.google.com/monitoring/support/notification-options#creating_channels">Slack as a notification channel</a>.</p><p>A query for the log entries alert policy section can look like this.</p><pre>resource.type=&quot;dataform.googleapis.com/Repository&quot;<br>severity=ERROR<br>jsonPayload.workflowConfigId=&quot;alerts_hourly&quot;<br></pre><p>Creating alerts this way catches alerts as errors from logs and delivers minimal information about incidents to the technical team for deeper analysis in the next step.</p><h3>Business alerts</h3><p>Business alerts have different requirements than technical alerts. The people who receive these alerts are often colleagues from other departments who may not be tech-savvy. Including too many technical details in the message can confuse and distract them. Instead, we should focus on providing specific information about the events in the message, as that is what the receivers are more likely to need.</p><p>To send the Slack notification, we will use a <a href="https://cloud.google.com/bigquery/docs/remote-functions">BigQuery remote function</a> that invokes the Cloud Function, which will deliver the text to the Slack channel (more details about using a remote function in BigQuery in <a href="https://medium.com/@alex-feldman/bigquery-and-cloud-functions-integration-by-using-remote-function-to-create-cost-effective-pipelines-c1b96c98f453">my article</a>).</p><h4>Preparations</h4><p>To proceed, we must prepare by creating a Cloud Function, configuring Slack, setting up a BigQuery connection, and creating a remote function.</p><p>Let’s create the send_to_slack Cloud Function with a code:</p><pre>import os<br>from slack_sdk import WebClient<br>from slack_sdk.errors import SlackApiError<br>import functions_framework<br>import json<br>import google.cloud.logging<br><br>log_client = google.cloud.logging.Client()<br>log_client.setup_logging()<br><br><br>def send_slack_message(message_text, sender, channel):<br>slack_token = os.environ[&#39;SLACK_TOKEN&#39;]<br>    client = WebClient(token=slack_token)<br>    message = f&quot;{sender}: {message_text}&quot;<br>    try:<br>        client.chat_postMessage(channel=channel_id, text=message)<br>        logging.info(f&quot;Message sent to Slack: {message}&quot;)<br>        return 0<br>    except SlackApiError as e:<br>        logging.error(f&quot;Error sending message: {e}&quot;)<br>        return 1<br><br><br>@functions_framework.http<br>def main(bq_request):<br>    request_json = bq_request.get_json()<br>    message_text = request_json[&#39;calls&#39;][0][0]<br>    sender = request_json[&#39;calls&#39;][0][1]<br>    channel = request_json[&#39;calls&#39;][0][2]<br>    if message_string is not None and len(message_string) &gt; 3:<br>        try:<br>            send_slack_message(message_text, sender, channel)<br>        except Exception as e:<br>            logging.error(e)<br>            exit(1)<br>    Else:<br>        logging.info(&quot;No data to send to Slack.&quot;)<br>    resp = json.dumps({&quot;replies&quot;: [&quot;Job is finished&quot;]})<br>    logging.info(resp)<br>    return resp</pre><p>The function accepts three arguments: message_text, sender, and channel. It sends a message to a particular Slack channel, along with the sender&#39;s name and the message text. When you deploy the Cloud Function, add your Slack token as an environment variable (it&#39;s better <a href="https://cloud.google.com/functions/docs/configuring/secrets#making_a_secret_accessible_to_a_function">to use Cloud Secret</a>) and include a requirements.txt file with dependencies.</p><pre>slack-sdk&gt;=3.20.0<br>google-cloud-logging~=3.6.0</pre><p>We also need to configure Slack to receive messages from Google Cloud. <a href="https://medium.com/@alex-feldman/sending-bigquery-data-alerts-to-the-slack-channel-e26bd0ae8d5">One of my articles</a> explains how to do it.</p><p>Then, we need to <a href="https://cloud.google.com/bigquery/docs/remote-functions#create_a_connection">create a BigQuery connection</a> with the <strong>BigLake type and remote functions (Cloud Resource)</strong> (please read my other <a href="https://medium.com/@alex-feldman/bigquery-and-cloud-functions-integration-by-using-remote-function-to-create-cost-effective-pipelines-c1b96c98f453">article</a> on how to do it in detail). The connection name is cloud_func_connection.</p><p>Next, let’s start developing code in Dataform. Initially, we create the remote function that invokes our send_to_slack Cloud function. The file name is send_to_slack_remote.sqlx.</p><pre>config {<br>  type: &quot;operations&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;],<br>  hasOutput: true<br>}<br><br>CREATE FUNCTION IF NOT EXISTS ${self()}(<br>  message_text STRING, <br>  sender STRING, <br>  channel STRING) <br>RETURNS STRING<br>REMOTE WITH CONNECTION `my_project.us-east1.cloud_func_connection`<br>OPTIONS (<br>  endpoint = &#39;https://us-east1-my_project.cloudfunctions.net/send_to_slack&#39;<br>)</pre><p>In the operations-type SQLX file, a code creates a remote function using the cloud_func_connection in the us-east1 region. This remote function is built with the endpoint of the send_to_slack function. The remote function is then saved in the my_alerts dataset with the name send_to_slack_remote, thanks to the hasOutput: true option.</p><p>We are now prepared to create business alerts using Dataform.</p><h4>Alert query view</h4><p>Let’s consider an alert for the case: an order without payment. We must create a query defining these issues and producing an alert text about incidents. We will make a Dataform view in the order_without_payment.sqlx file.</p><pre>config {<br>  type: &quot;view&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;]<br>}<br>SELECT a.order_id, a.order_timestamp, a.user_id, b.payment_id<br>FROM ${ref(&#39;orders&#39;)} a<br>LEFT JOIN ${ref(&#39;payments&#39;)} b ON a.order_id=b.order_id<br>WHERE b.payment_id IS NULL <br>  AND a.status = &#39;delivered&#39;<br>  AND DATE(a.order_timestamp) = CURRENT_DATE()-1    -- date filter</pre><p>The query produces the list of orders delivered but not paid from the previous day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*yKY9V_-9oEMygp2vhp9MJQ.png" /></figure><p>Let’s compose a message.</p><pre>config {<br>  type: &quot;view&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;]<br>}<br>WITH<br>orders_payments as (<br>SELECT a.order_id, a.order_timestamp, a.user_id, b.payment_id<br>FROM ${ref(&#39;orders&#39;)} a<br>LEFT JOIN ${ref(&#39;payments&#39;)} b ON a.order_id=b.order_id<br>WHERE b.payment_id IS NULL <br>  AND a.status = &#39;delivered&#39;<br>  AND DATE(a.order_timestamp) = CURRENT_DATE()-1    -- date filter<br>)<br><br>-- compose message <br>SELECT order_timestamp,<br>FORMAT(&quot;Alert. Order #%d was delivered at %t for the user: %s without a payment&quot;,<br>  order_id, FORMAT_TIMESTAMP(&#39;%H:%M on %d %b %Y&#39;, <br>  order_timestamp), user_id) as message_text<br>FROM orders_payments</pre><p>Look at the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*YNoFD6f8g1jaRVn1REBKTw.png" /></figure><p>We composed the alert messages with information about the order ID, user ID, and order time using the FORMAT function. The message_text field contains the result as Alert. Order #3000432 was delivered at 21:32 on 26 Jan 2024 for the user A001234 without a payment. The text is quite evident in describing what happened and when it occurred.</p><p>Since we want to send all information by one alert notification, let’s wrap up all messages in one, separated by the new line symbol.</p><pre>config {<br>  type: &quot;view&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;]<br>}<br>WITH<br>orders_payments as (<br>SELECT a.order_id, a.order_timestamp, a.user_id, b.payment_id<br>FROM ${ref(&#39;orders&#39;)} a<br>LEFT JOIN ${ref(&#39;payments&#39;)} b ON a.order_id=b.order_id<br>WHERE b.payment_id IS NULL <br>  AND a.status = &#39;delivered&#39;<br>  AND DATE(a.order_timestamp) = CURRENT_DATE()-1    -- date filter<br>),<br><br>compose_message as (<br>SELECT order_timestamp,<br>FORMAT(&quot;Alert. Order #%d was delivered at %t for the user: %s without a payment&quot;,<br>  order_id, FORMAT_TIMESTAMP(&#39;%H:%M on %d %b %Y&#39;, <br>  order_timestamp), user_id) as message_text<br>FROM orders_payments<br>)<br><br>SELECT <br>ARRAY_TO_STRING(ARRAY_AGG(message_text), &#39;\n&#39;) as message_text<br>FROM compose_message</pre><p>The result is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*_LL0QlfGWxrq6TZQSVfQ7w.png" /></figure><p>Now we have one message about all 3 incidents.</p><p>Next, we will create the alert script and send this message to Slack.</p><h4>Alert with assertion</h4><p>We can create an alert using the assertion type in the config block and invoking the send_to_slack_remote function. Let’s create the order_without_payment_alert.sqlx file as</p><pre>config {<br>  type: &quot;assertion&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;]<br>}<br><br>WITH <br>order_without_payment as (<br>SELECT message_text<br>FROM ${ref(&#39;order_without_payment&#39;)}<br>WHERE message_text IS NOT NULL<br>),<br><br>SELECT ${ref(&#39;send_to_slack_remote&#39;)} (  -- calling remote function<br>   message_text,                  -- the message text argument<br>  &#39;order_without_payment_alert&#39;,  -- the sender argument<br>  &#39;#operational_alerts&#39;           -- the channel argument<br>) as send_message_job<br>FROM order_without_payment<br></pre><p>In the config block, we used the assertion type. We added the message_text null values filter to avoid sending empty messages.</p><p>In the last SELECT, we added calling the send_to_slack_remote function. The function sends the message text to Slack if the previous subquery has any output. The function has three arguments: message_text (composed alert text), sender with order_without_payment_alert value, and channel as #operational_alerts (the Slack channel where we expect to receive an alert).</p><p>The query has returned the remote function&#39;s response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*7-2Z4_lT6Ea3WCGw9BjF0Q.png" /></figure><p>Thus, If the alert is triggered, the script will notify Slack and log the error in the execution log. The date filter we used in the view implies running the workflow every morning to check the data from the previous day.</p><p>Great, we have achieved it!</p><p>Let&#39;s explore some other options. What if we want to avoid any errors appearing in the execution log? What if we need to run it more often and keep track of all alerts sent for future analysis? What if we use separate datasets and Slack channels for production and development?</p><h4>Alert with incremental table</h4><p>To prevent errors from appearing in the logs, we can modify the config block from an assertion type to a table type. Additionally, if we want to save all incidents and only check for new ones, we should use the incremental table type and activate the protected flag.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;],<br>  protected: true<br>}</pre><p>We will consolidate the code into a single file to update both the view and table.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;],<br>  protected: true<br>}<br><br>WITH <br>orders_payments as (<br>SELECT a.order_id, a.order_timestamp, a.user_id, b.payment_id<br>FROM ${ref(&#39;orders&#39;)} a<br>LEFT JOIN ${ref(&#39;payments&#39;)} b ON a.order_id=b.order_id<br>WHERE b.payment_id IS NULL <br>  AND a.status = &#39;delivered&#39;<br>${when(incremental(),    -- new date filter<br>    `AND a.order_timestamp &gt; (SELECT MAX(last_timestamp) FROM ${self()})` <br>),<br><br>compose_message as (<br>SELECT order_timestamp,<br>FORMAT(&quot;Alert. Order #%d was delivered at %t for the user: %s without a payment&quot;,<br>  order_id, FORMAT_TIMESTAMP(&#39;%H:%M on %d %b %Y&#39;, <br>  order_timestamp), user_id) as message_text<br>FROM orders_payments<br>),<br><br>wrap_up_message as (<br>SELECT MAX(order_timestamp) as last_timestamp,    -- new field added<br>ARRAY_TO_STRING(ARRAY_AGG(message_text), &#39;\n&#39;) as message_text<br>FROM compose_message<br>),<br><br>SELECT &#39;${name()}&#39; as sender,       -- new field with file name value<br>CURRENT_TIMESTAMP() as created_at,  -- new field<br>message_text,                       -- new field<br>${ref(&#39;send_to_slack_remote&#39;)} (  <br>   message_text,                  <br>  &#39;${name()}&#39;,                    <br>  &#39;#operational_alerts&#39;           <br>) as send_message_job,<br>last_timestamp,                  -- new field <br>FROM wrap_up_message<br>WHERE message_text IS NOT NULL</pre><p>We replaced the date filter in the orders_payments subquery with the latest timestamp value, which will only work in incremental execution mode.</p><pre>${when(incremental(),<br>    `AND a.order_timestamp &gt; (SELECT MAX(last_timestamp) FROM ${self()})`</pre><blockquote>Using query conditions like <em>date = CURRENT_DATE()-1</em> is not a best practice because if the execution is filed someday, we can miss some alert incidents on this day. It would be preferable if the code takes into account the previous timestamp.</blockquote><p>We add the MAX(order_timestamp) as last_timestamp field in the wrap_up_message subquery to provide incremental condition working.</p><p>In the last SELECT, we added fields: sender, created_at, message_text, and last_timestamp. Since we use the incremental table name as the sender name, we can utilize the name() function.</p><p>Whenever we have an alert incident, a new notification will be sent to the Slack channel, and a new row will be inserted into the table in the following format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2quyH2TbQX_WDnxTloEyA.png" /><figcaption>Inserted row</figcaption></figure><p>We can use the first three columns to gather statistics from various alerts in a single table if we have multiple alerts.</p><h4>Alert in separate environments</h4><p>It is helpful to have a separate development workspace from the production when building a pipeline. Dataform lets us do it using <a href="https://cloud.google.com/dataform/docs/workspace-compilation-overrides?hl=en">workspace compilation overrides</a>. We can use the <strong>Schema suffix</strong> feature to add our production dataset name _production suffix. Also, using the test Slack channel when developing an alert is a good idea. The self() function can help to define the channel where the script should send notifications.</p><p>To do it, we need to replace the #operational_alerts value with an expression:</p><pre> IF(&#39;${self()}&#39; LIKE &#39;%_production%&#39;, &#39;#operational_alerts&#39;, &#39;#test_channel&#39;) </pre><p>The final alert code</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  schema: &quot;my_alerts&quot;,<br>  tags: [&quot;alert&quot;],<br>  protected: true<br>}<br><br>WITH <br>orders_payments as (<br>SELECT a.order_id, a.order_timestamp, a.user_id, b.payment_id<br>FROM ${ref(&#39;orders&#39;)} a<br>LEFT JOIN ${ref(&#39;payments&#39;)} b ON a.order_id=b.order_id<br>WHERE b.payment_id IS NULL <br>  AND a.status = &#39;delivered&#39;<br>${when(incremental(),    -- new date filter<br>    `AND a.order_timestamp &gt; (SELECT MAX(last_timestamp) FROM ${self()})` <br>),<br><br>compose_message as (<br>SELECT order_timestamp,<br>FORMAT(&quot;Alert. Order #%d was delivered at %t for the user: %s without a payment&quot;,<br>  order_id, FORMAT_TIMESTAMP(&#39;%H:%M on %d %b %Y&#39;, <br>  order_timestamp), user_id) as message_text<br>FROM orders_payments<br>),<br><br>wrap_up_message as (<br>SELECT MAX(order_timestamp) as last_timestamp,   <br>ARRAY_TO_STRING(ARRAY_AGG(message_text), &#39;\n&#39;) as message_text<br>FROM compose_message<br>),<br><br>SELECT &#39;${name()}&#39; as sender,       <br>CURRENT_TIMESTAMP() as created_at,  <br>message_text,                       <br>${ref(&#39;send_to_slack_remote&#39;)} (       -- calling remote function<br>   message_text,                  <br>  &#39;${name()}&#39;,                    <br>  IF(                             <br>    &#39;${self()}&#39; LIKE &#39;%_production%&#39;,  -- calculating the Slack channel<br>    &#39;#operational_alerts&#39;,                 -- production channel<br>    &#39;#test_channel&#39;                        -- testing channel<br>  )        <br>) as send_message_job,<br>last_timestamp,                 <br>FROM wrap_up_message<br>WHERE message_text IS NOT NULL</pre><p>When we develop the script in Dataform, it sends messages to #test_channel. After compiling the code in the production release with the _production suffix, the dataset name is overridden as my_alerts_production. Messages are then sent to the #operational_alerts channel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0e7f504f0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/technical-and-business-data-alerts-using-dataform-6e0e7f504f0e">Technical and Business data alerts using Dataform</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More Ways to Create Incremental Tables in Dataform]]></title>
            <link>https://medium.com/google-cloud/more-ways-to-create-incremental-tables-in-dataform-c0fd35650494?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0fd35650494</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 15:20:04 GMT</pubDate>
            <atom:updated>2024-07-20T08:42:20.682Z</atom:updated>
            <content:encoded><![CDATA[<p>If you use BigQuery to build complex queries and haven’t started using Dataform, it is worth starting to do so. In a nutshell, Dataform is almost like DBT but is better because it lives inside GCP. There are many valuable resources on how to get started with Dataform, including pretty good <a href="https://cloud.google.com/dataform/docs/">official documentation</a>.</p><p>This article will discuss Dataform’s built-in capabilities for creating incremental tables. About what works well and what doesn’t work so well yet. And how we can improve the standard Dataform capabilities using some tricks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ht7rmD8WLA73lJ7X" /><figcaption>Photo by <a href="https://unsplash.com/@sid_balachandran?utm_source=medium&amp;utm_medium=referral">Sid Balachandran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working in BigQuery to create incremental tables, we often develop procedures that include <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax">DML statements</a> such as INSERT, DELETE, UPDATE, and MERGE.</p><p>Dataform uses the config constructs with type = “incremental” to build incremental tables, as well as the ${when(incremental() <em>... condition ...</em>)} operator to define the conditions.<br>For example:</p><pre>config {<br>  type: &quot;incremental&quot;<br>}<br><br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>${when(incremental(),<br>    `WHERE updated_at &gt; (SELECT MAX(updated_at) FROM ${self()})`)}<br>}</pre><p>Using such constructs, the Dataform generates the same CREATE/INSERT /MERGE statements that we would use in BigQuery, but with some restrictions (which we must overcome).</p><p>Let’s consider different options for <a href="https://cloud.google.com/dataform/docs/incremental-tables">configuring incremental tables in Dataform</a> and look at their analogs in BigQuery.</p><h3>Inserting new rows into the destination table</h3><p>Let’s create a Dataform file with the path and name as definitions/explore_incremental/destination_table.sqlx:</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  bigquery: {<br>    partitionBy: &quot;TIMESTAMP_TRUNC(updated_at, HOUR)&quot;<br>  },<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n<br>${when(incremental(), <br>`WHERE updated_at &gt; (SELECT MAX(updated_at) FROM ${self()})`<br>) }</pre><p>In this example, we have the source_table that contains the updated_at field with the timestamp type (we should <a href="https://cloud.google.com/dataform/docs/declare-source">declare this data source</a> before using the source_table. The result loads in the destination_table of the destination_dataset.</p><p>The script uploads all rows from the source table in the first subquery. In the next subqueries, we have some transformations. The last subquery extracts the MAX value of the updated_at field from the current version of the destination table and filters data by this value. We use the ${self()} JS operator to refer to the destination table.</p><p>In addition, by <a href="https://cloud.google.com/dataform/docs/partitions-clusters">creating table partitions</a> as TIMESTAMP_TRUNC(updated_at, HOUR), we can minimize the amount of data that needs to be scanned in the destination table.</p><p>The script generates the following BigQuery code.</p><pre>INSERT INTO `my_project.destination_dataset.destination_table` (<br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM `my_project.source_dataset.source_table`<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n<br>WHERE updated_at &gt; (<br>  SELECT MAX(updated_at) <br>  FROM `my_project.destination_dataset.destination_table`<br>  )<br>)</pre><p>If we run it with the <a href="https://cloud.google.com/dataform/docs/incremental-tables#rebuild_an_incremental_table_from_scratch_with_full_refresh">Run with full refresh</a> execution options, the BigQuery code will look like this:</p><pre>CREATE OR REPLACE TABLE `my_project.destination_dataset.destination_table` <br>PARTITION BY TIMESTAMP_TRUNC(updated_at, HOUR)<br>AS (<br><br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM `my_project.source_dataset.source_table`<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n<br>)</pre><p>In regular incremental execution mode, the script generates the INSERT statement with WHERE cloud at the last subquery. As a result, only rows with a timestamp greater than the previously existing max timestamp have been inserted in the destination table.</p><p>In the full refresh mode, the script overwrites the existing destination table by all rows from the source table.</p><h3>Uploading selected rows from the source table</h3><p>If the source table is partitioned, using the WHERE clause in the first subquery efficiently minimizes the table scan.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  bigquery: {<br>    partitionBy: &quot;TIMESTAMP_TRUNC(updated_at, HOUR)&quot;<br>  },<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br><br>pre_operations {<br>  DECLARE last_timestamp TIMESTAMP DEFAULT (<br>    ${when(incremental(),<br>    `SELECT MAX(updated_at) FROM ${self()}`,<br>    `SELECT TIMESTAMP(&#39;2023-01-01&#39;)`)}<br>  );<br>}<br><br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>WHERE updated_at &gt; last_timestamp<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n</pre><p>We can declare the last_timestamp variable in the pre_operations block and use it in the first subquery WHERE cloud. We can also declare the value for non-incremental (full refresh) mode (2023–01–01, for our example).</p><p>To run the action in the preview mode (by the Run button), we should comment on two rows to run it in the Dataform editor. But uncomment them if we execute it.</p><pre>-- Comment rows for the preview RUN<br> <br>-- pre_operations {<br>  DECLARE last_timestamp TIMESTAMP DEFAULT (<br>    ${when(incremental(),<br>    `SELECT MAX(updated_at) FROM ${self()}`,<br>    `SELECT TIMESTAMP(&#39;2023-01-01&#39;)`)}<br>  );<br>-- }</pre><p>Dataform generates the following BigQuery code in the incremental execution.</p><pre>DECLARE last_timestamp TIMESTAMP DEFAULT (<br>    SELECT MAX(created_at) <br>    FROM `my_project.destination_dataset.destination_table`<br>);<br><br>INSERT INTO `my_project.destination_dataset.destination_table` (<br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM `my_project.source_dataset.source_table`<br>WHERE updated_at &gt; last_timestamp<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n<br>)</pre><p>And for the full refresh mode.</p><pre>DECLARE last_timestamp TIMESTAMP DEFAULT TIMESTAMP(&#39;2023-01-01&#39;);<br><br>CREATE OR REPLACE TABLE `my_project.destination_dataset.destination_table` <br>PARTITION BY TIMESTAMP_TRUNC(updated_at, HOUR)<br>AS (<br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM `my_project.source_dataset.source_table`<br>WHERE updated_at &gt; last_timestamp<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n<br>)</pre><h3>Truncate the destination table before the row inserting</h3><p>Sometimes, we need to upload and process a portion of the data, replacing the destination table data every time. At first glance, it is simple. Just switch the “incremental” type of the script to the “table” type in the config block and use the condition of the selected row from the other place of the data pipeline. Something like:</p><pre>config {<br>  type: &quot;table&quot;,<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>pre_operations {<br>  DECLARE last_timestamp TIMESTAMP DEFAULT (<br>   SELECT MAX(created_at) FROM ${resolve(&#39;table_downstream&#39;)} -- use &#39;resolve&#39; instaed of &#39;ref&#39;<br>  );<br>}<br><br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>WHERE updated_at &gt; last_timestamp<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n</pre><p>The ‘table_downstream’ is the table downstream of the pipeline, and the ${ref(‘table_downstream’)}option produces a circular error because the destination_table is a transitive dependence of the table_downstream. We can force it to work by replacing ${ref(‘table_downstream’)} with ${resolve(‘table_downstream’)}.</p><p>Another option is to use the incremental table with a truncating step.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>pre_operations {<br>  DECLARE last_timestamp TIMESTAMP DEFAULT (<br>    ${when(incremental(),<br>    `SELECT MAX(updated_at) FROM ${self()}`,<br>    `SELECT TIMESTAMP(&#39;2023-01-01&#39;)`)}<br>  );<br>---<br>  ${when(incremental(),<br>    `TRUNCATE TABLE ${self()}`)};<br>}<br><br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>WHERE updated_at &gt;= last_timestamp  -- use &#39;&gt;=&#39;<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n</pre><p>We added a TRUNCATE statement in the pre_operations block. The script first checks the last timestamp value and then truncates the table. We use &gt;= instead of &gt; in the WHERE updated_at &gt;= last_timestamp expression to avoid an issue if the source_table has no new rows and the destination_table remains empty after the truncation. The destination table should have at least one row with the last_timestamp value. But if we ensure the source table always has new rows, we can use &gt; in the condition.</p><p>BigQuery code for the regular incremental mode.</p><pre>DECLARE last_timestamp TIMESTAMP DEFAULT (<br>    SELECT MAX(created_at) <br>    FROM `my_project.destination_dataset.destination_table`<br>);<br><br>TRUNCATE TABLE `my_project.destination_dataset.destination_table`;<br><br>INSERT INTO `my_project.destination_dataset.destination_table` (<br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM `my_project.source_dataset.source_table`<br>WHERE updated_at &gt;= last_timestamp<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n<br>)</pre><p>And for the full refresh mode.</p><pre>DECLARE last_timestamp TIMESTAMP DEFAULT TIMESTAMP(&#39;2023-01-01&#39;);<br><br>CREATE OR REPLACE TABLE `my_project.destination_dataset.destination_table` (<br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM `my_project.source_dataset.source_table`<br>WHERE updated_at &gt;= last_timestamp<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n<br>)</pre><p>A disadvantage of this solution is duplicated rows in every session (if we use &gt;=). We should handle such rows in the following steps.</p><p>If you want to avoid duplication of rows, the solution is to insert the row with only the updated_at value after the transition if there are no new rows in the source table.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>pre_operations {<br>  DECLARE last_timestamp TIMESTAMP DEFAULT (<br>    ${when(incremental(),<br>    `SELECT MAX(updated_at) FROM ${self()};`,<br>    `SELECT TIMESTAMP(&#39;2023-01-01&#39;);`)}<br>  )<br><br>CREATE TEMP TABLE stg_table AS<br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>WHERE updated_at &gt; last_timestamp  -- use &#39;&gt;&#39; here<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n;<br><br>-- Truncate the table and insert an empty row <br>-- with the updated_at value if there are no new records.<br><br>  ${when(incremental(),<br>    `TRUNCATE TABLE ${self()}<br>    IF NOT EXISTS (SELECT * FROM stg_table) THEN<br>    INSERT INTO stg_table (updated_at)<br>    VALUES (last_timestamp)<br>    `)<br>  }<br><br>}  -- end pre_operations<br><br>SELECT *<br>FROM stg_table</pre><p>We created the temporary table for the main query with WHERE updated_at &gt; last_timestamp. Then, we truncated the table and checked if the stg_table was empty (no new rows in the source table). If it was empty, we inserted a new row with only the updated_at field populated with the last_timastamp value. We must remember to filter this technical row in the next pipeline step.</p><p>An advantage of truncating the destination table before the row-inserting approach is that the script works in both regular incremental and full fresh modes. This is useful if we need to upload the source table frequently (every hour, for example) in the incremental mode and once a day in the full refresh mode to make some additional calculations and remove possible incremental uploading errors. We can set the execution mode when we <a href="https://cloud.google.com/dataform/docs/workflow-configurations#create_a_workflow_configuration">schedule the workflow</a>.</p><h3>Merge rows in incremental table</h3><p>Let&#39;s discuss merging rows, including updating existing rows and inserting new rows.</p><p>Dataform suggests us using the following construct for that.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  uniqueKey: [&quot;id&quot;],<br>  bigquery: {<br>    partitionBy: &quot;DATE(updated_at)&quot;,<br>    updatePartitionFilter:<br>        &quot;updated_at &gt;= timestamp_sub(current_timestamp(), interval 24 hour)&quot;<br>  },<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>),<br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br>SELECT *<br>FROM transformation_n</pre><p>The uniqueKey in the config block means that Dataform generates the MERGE statement to compile it.</p><p>The MERGE statement is an excellent feature but has some drawbacks. The first one is it’s resource-consuming. The second is it is pretty hard to optimize for wide tables with many columns (How to do it in BigQuery, including working with nested fields — you can read it in my article <a href="https://medium.com/@alex-feldman/how-to-merge-bigquery-tables-with-nested-fields-for-incremental-uploading-c3219c965d3">How to merge BigQuery tables with nested fields for incremental uploading</a>). The third is that Dataform is not very flexible when configuring the MERGE. It only lets us configure the ON cloud by defining the list of unique columns with additional conditions from the updatePartitionFilter.</p><p>It generates the BigQuery code:</p><pre>MERGE `my_project.destination_dataset.destination_table` T<br>USING (<br><br>  WITH<br>  upload_source_table AS (<br>  SELECT *<br>  FROM `my_project.source_dataset.source_table`<br>  ),<br>  transformation_1 AS (<br>  ...<br>  ),<br>  ...<br>  transformation_n AS (<br>  ...<br>  )<br>  SELECT *<br>  FROM transformation_n<br><br>) S<br>ON T.id = S.id<br>  AND T.updated_at &gt;= timestamp_sub(current_timestamp(), interval 24 hour)<br>WHEN MATCHED THEN<br>  UPDATE SET T.column1 = S.column1 AND T.column2 = S.column2 AND ... <br>WHEN NOT MATCHED THEN<br>  INSERT ROW;<br><br></pre><p>We can use updatePartitionFilter if we know the period during which rows can be changed. If we don’t know this, we can omit the updatePartitionFilter and use only uniqueKey, but this leads to scanning the whole table and updating all existing rows.</p><p>BigQuery code for the full refresh mode will be the CREATE TABLE statement with the PARTITION BY DATE(updated_at) row.</p><p>It is worth using the MERGE statement in Dataform if we have the updatePartitionFilter or if resource consumption does not matter. For the last case, we can use a straightforward construct where all rows with the new IDs will be inserted, and all rows with existing IDs will be updated.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  uniqueKey: [&quot;id&quot;],<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>WITH<br>upload_source_table AS (<br>SELECT *<br>FROM $(ref(&#39;source_table&#39;)}<br>),<br><br>transformation_1 AS (<br>...<br>),<br>...<br>transformation_n AS (<br>...<br>)<br><br>SELECT *<br>FROM transformation_n</pre><p>If resource consumption matters to us, and we strive to optimize our queries, let’s consider other ways to update rows.</p><h3>Updating rows by deleting and inserting rows</h3><p>We can combine INSERT and DELETE statements in our query with table partitions.</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  bigquery: {<br>    partitionBy: &quot;RANGE_BUCKET(&quot;id&quot;, GENERATE_ARRAY(0, 100000, 100))&quot;<br>  },<br>  schema: &quot;destination_dataset&quot;,<br>  tags: [&quot;my_tag&quot;]<br>}<br><br>pre_operations {<br>  CREATE TEMP TABLE stg_table AS (<br><br>    WITH<br>    upload_source_table AS (<br>    SELECT *<br>    FROM $(ref(&#39;source_table&#39;)}<br>    ),    <br>    transformation_1 AS (<br>    ...<br>    ),<br>    ...<br>    transformation_n AS (<br>    ...<br>    )<br>    SELECT *<br>    FROM transformation_n<br>  )};<br>  ---<br>  ${when(incremental(),<br>    `DELETE ${self()} WHERE id IN (SELECT id FROM stg_table)`<br>  )};<br>}<br><br>SELECT * FROM stg_table</pre><p>To reduce table scanning, we create integer-range partitions by the ID columns. In the pre_operations block, we create the temp staging table. Then, we check existing IDs in the destination table and delete them. Finally, we insert all rows from the staging table into the destination table.</p><p>The BigQuery code for the incremental mode.</p><pre>CREATE TEMP TABLE stg_table AS (<br><br>    WITH<br>    upload_source_table AS (<br>    SELECT *<br>    FROM `my_project.source_dataset.source_table`<br>    ), <br>    transformation_1 AS (<br>    ...<br>    ),<br>    ...<br>    transformation_n AS (<br>    ...<br>    )<br>    SELECT *<br>    FROM transformation_n<br>);<br><br>DELETE `my_project.destination_dataset.destination_table` <br>WHERE id IN (SELECT id FROM stg_table);<br>          <br>INSERT INTO `my_project.destination_dataset.destination_table` (<br>SELECT *<br>FROM stg_table<br>);</pre><p>The BigQuery code for the full refresh mode.</p><pre>CREATE TEMP TABLE stg_table AS <br>    WITH<br>    upload_source_table AS (<br>    SELECT *<br>    FROM `my_project.source_dataset.source_table`<br>    ),<br>    <br>    transformation_1 AS (<br>    ...<br>    ),<br>    ...<br>    transformation_n AS (<br>    ...<br>    )<br>    <br>    SELECT *<br>    FROM transformation_n;<br><br>          <br>CREATE OR REPLACE TABLE `my_project.destination_dataset.destination_table`<br>PARTITION BY RANGE_BUCKET(&quot;id&quot;, GENERATE_ARRAY(0, 100000, 100))<br>AS (<br>SELECT *<br>FROM stg_table<br>);</pre><p>In this article, we considered Dataform&#39;s ability to configure incremental tables. Although not all incremental scenarios work natively in Dataform, over time, we will see improvements in this area because the platform is actively evolving.</p><p>When incorporating incremental tables into data pipelines, it is important to minimize table scanning, not just the amount of data being loaded. This is where partitioning and clustering tables come into play.</p><p>Thank you for your attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0fd35650494" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/more-ways-to-create-incremental-tables-in-dataform-c0fd35650494">More Ways to Create Incremental Tables in Dataform</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BigQuery and Cloud Functions integration by using Remote function to create cost-effective pipelines]]></title>
            <link>https://medium.com/@alex-feldman/bigquery-and-cloud-functions-integration-by-using-remote-function-to-create-cost-effective-pipelines-c1b96c98f453?source=rss-df0ac233814a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1b96c98f453</guid>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Alex Feldman]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 15:26:57 GMT</pubDate>
            <atom:updated>2023-07-24T15:26:57.879Z</atom:updated>
            <content:encoded><![CDATA[<h3>BigQuery and Cloud Functions integration by using Remote function to create cost-effective data pipelines</h3><p>In this article, I would like to consider <a href="https://cloud.google.com/bigquery/docs/remote-functions?hl=en#console">using the BigQuery Remote function</a> feature. The BigQuery Remote function lets us create a direct integration BigQuery and Google Functions. The direct integration, in turn, allows us to build flexible data pipelines that include SQL and Python (or other languages) code steps in a single process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hl9hPRAjjE2s8QHU" /><figcaption>Photo by <a href="https://unsplash.com/@sebaspenalambarri?utm_source=medium&amp;utm_medium=referral">Sebastian Pena Lambarri</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Approach differences</h3><p>Let&#39;s take a typical task — loading and processing the billing system data such as Stripe or Zuora. We need periodically load raw data by API requests and process it in BigQuery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*Vi_LvEYAJQKa79Cc10kpvw.png" /><figcaption>My old approach</figcaption></figure><p>Previously I used an approach when I ran the Cloud function Python script by Cloud scheduler and then processed data in BigQuery, using stored procedures, independently running them by scheduled queries tool.</p><p>I changed this approach after I began using <a href="https://cloud.google.com/dataform/docs/overview">Dataform</a> because, besides other outstanding features, Dataform contains <a href="https://cloud.google.com/dataform/docs/workflow-configurations">an excellent orchestration tool (Workflow)</a>, which solves many inconveniences of running a sequence of queries specific to bare BigQuery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*o28b6pT7IeHw9nExE86VjQ.png" /><figcaption>My new approach</figcaption></figure><p>As we can see, in this case, the Cloud function is a part of the single data pipeline, scheduled and run by Dataform Workflow. And the BigQuery Remote function allows us to call the Cloud function from the SQL query directly.</p><p>In more detail, let&#39;s consider this step — executing the Cloud function script by invoking the Remote function from the BigQuery SQL query.</p><p>So, the Cloud function task is requesting the billing system API, extracting data, and uploading it to the BigQuery tables. We will not focus on creating the Cloud function itself, only on calling it and creating a response, but you can find the script example <a href="https://raw.githubusercontent.com/alex-feldman9/zuora_etl/main/main.py">here</a>.</p><p>To create and run the Remote function, we need to:</p><ol><li>Have a Cloud function with a Python script.</li><li>Create the new external connection source (BigLake and Remote function type) in BigQuery.</li><li>Grant permissions for the connection service account.</li><li>Create the BigQuery Remote function.</li><li>Create the SQL query that invokes the Remote function.</li></ol><p>Let&#39;s delve into it further.</p><h3>Create a connection and grant permissions</h3><p>To create the new external connection, go to the BigQuery page, click <strong>Add data</strong>, and then click <strong>Connections to external data sources</strong>. Select <strong>BigLake and remote functions (Cloud Resource) </strong>as a connection type. In the <strong>Connection ID</strong> field, enter a name for your connection (for example, cloud_func_connection). Choose your data location (for example, us-east1). Click <strong>Create Connection</strong>.</p><p>If you prefer the Cloud Shell, use a code like this:</p><pre>bq mk --connection --location=us-east1 --project_id=my_project\<br>--connection_type=CLOUD_RESOURCE cloud_func_connection</pre><p>We will be able to use this connection not to invoke one specific Cloud function only but for any future functions we may need to call.</p><p>After creating a connection, we need to open the connection info pane and copy the service account ID (for example, <em>hdfk-123123412345–7ci3@gcp-sa-bigquery-condel.iam.gserviceaccount.com</em>).</p><p>To grant permissions for the service account, go to the <strong>IAM &amp; Admin</strong> page, and click <strong>Grant Access.</strong> In the opened dialog, enter the service account ID in the <strong>New principals</strong> field and select the roles <em>Cloud Function Invoker</em> and <em>Cloud Run invoker</em>. Click <strong>Save</strong>.</p><h3>Create the BigQuery Remote function</h3><p>For creating the Remote function, we need to know the trigger URL, which we can find in the trigger tab of the Cloud function (for example, <em>https://us-east1-my_project.cloudfunctions.net/billing_etl_func</em>).</p><p>To create the BigQuery Remote function, use the following query:</p><pre>CREATE FUNCTION `my_project.my_dataset.billing_etl`(start_time TIMESTAMP, <br>                                                    end_time TIMESTAMP)<br>RETURNS STRING<br>REMOTE WITH CONNECTION `my_project.us-east1.cloud_func_connection`<br>OPTIONS<br>(endpoint =&#39;https://us-east1-my_project.cloudfunctions.net/billing_etl_func&#39;)</pre><p>Our Remote function has two timestamp-type arguments: <em>start_time</em> and <em>end_time</em>, which define the uploading time range. The Remote function receives a response with the executing status string (in a specific JSON format).</p><p>The Remote function is ready for work, but we need to ensure that the Cloud function is also prepared to execute and can accept arguments and send responses in the appropriate format.</p><h3>Cloud function code features</h3><p>Let&#39;s look into the Cloud function source code.</p><pre>import functions_framework<br>import json<br><br>...<br>...<br><br>@functions_framework.http<br>def main(request):<br>    # Parsing arguments<br>    request_json = request.get_json()<br>    start_time = request_json[&#39;calls&#39;][0][0]<br>    end_time = request_json[&#39;calls&#39;][0][1]<br>    <br>    try:<br>        ...    <br>        Our function code<br>        ...<br>      # Create the successful response<br>      return json.dumps({&quot;replies&quot;: [&quot;Job is finished&quot;]})<br><br>    except Exception as e:<br>      # Create the failed response  <br>      return json.dumps({&quot;errorMessage&quot;: str(e)})</pre><p>The <em>main</em> function code should have two features that answer the following questions. First is how to recognize input arguments. We sent two values in the calling Remote function (<em>start_time</em> and <em>end_time</em>), but on the Cloud function side, the main function receives the JSON object, which contains an encoded argument list in the calls field. The BigQuery request may look like this.</p><pre>{<br> &quot;requestId&quot;: &quot;124ab1c&quot;,<br> &quot;caller&quot;: &quot;//bigquery.googleapis.com/projects/my_project/jobs/my_project:us-east1.bquxjob_5b4c112c_17961fafeaf&quot;,<br> &quot;sessionUser&quot;: &quot;user@company.com&quot;,<br> &quot;userDefinedContext&quot;: {},<br><strong> &quot;calls&quot;: [<br>  [&quot;2023-07-09 14:15:00&quot;, &quot;2023-07-09 18:15:00&quot;]</strong><br> ]<br>}</pre><p>We use the Flask <em>get_json</em> function that the <a href="https://cloud.google.com/functions/docs/functions-framework">Function framework library</a> provided for the parsing argument values.</p><p>The second question is how to create the response object properly. The SQL query expects the function response by <a href="https://cloud.google.com/bigquery/docs/remote-functions?hl=en#output_format">the specific JSON object</a>. If the response format is not appropriate, the script produces the error. The response object for our case may look like this for successful and failed results:</p><pre># Successfule response<br>{<br>  &quot;replies&quot;: [ &quot;Job is finished&quot; ]<br>}<br><br># Failed response<br>{<br>  &quot;errorMessage&quot;: &quot;The function finished with status: &#39;error&#39;&quot;.<br>}</pre><p>Using the try-except statement and the <em>json</em> library, we form the response object for any execution outcome.</p><p>Suppose the Cloud function finishes with an error because of timeout or unavailable extracting data. In that case, the Cloud function tries new execution attempts again several times (5 by default) and sends the failed response only after all retries.</p><h3>Call the Remote function</h3><p>So, everything is ready for running the SQL script with the Remote function:</p><pre>SELECT `my_project.my_dataset.billing_etl`(&#39;2023-07-15 00:00:00&#39;, &#39;2023-07-16 00:00:00&#39;) as result</pre><p>The script calls the Remote function to upload data on 15 July 2023.</p><h3>Conclusions</h3><p>Thus, in the article, we explored utilizing the Remote function in BigQuery SQL query to call the Cloud function. And the benefits of using the data pipeline-building approach where we have a single Dataform pipeline for SQL and Python code.</p><p>There are some great services available in GCP that can assist with data pipeline creation and orchestration. However, it should be noted that many of these services can be quite costly. If you are looking for affordable options, a combination of such services as Dataform (over BigQuery), Cloud Function, Pub/Sub, and Cloud Storage (within their performance limitations) can be a smart choice. And Dataform takes a central place here as the leading platform for code generating, dependence management (including dependencies between other data pipelines), and orchestration. This way allows us to use SQL as much as possible for data transformations and insert steps that can not be implemented without Python into a single chain using Remote functions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1b96c98f453" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>