<?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 Ahmed Mokbel on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Mokbel on Medium]]></description>
        <link>https://medium.com/@ahmed-mokbel?source=rss-369ff6b86f91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BhBsHbQR30jFnrImjCE7_A.jpeg</url>
            <title>Stories by Ahmed Mokbel on Medium</title>
            <link>https://medium.com/@ahmed-mokbel?source=rss-369ff6b86f91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:39:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmed-mokbel/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[Build a Pipeline for transferring data from S3 to Redshift with Apache Airflow]]></title>
            <link>https://ahmed-mokbel.medium.com/build-a-pipeline-for-transferring-data-from-s3-to-redshift-with-apache-airflow-d73348ac1da9?source=rss-369ff6b86f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73348ac1da9</guid>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[redshift]]></category>
            <dc:creator><![CDATA[Ahmed Mokbel]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 11:19:32 GMT</pubDate>
            <atom:updated>2024-07-05T11:19:32.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*EfZycL-BtgDoxtonkUWhyg.png" /></figure><p>Apache Airflow, a powerful workflow orchestration tool, simplifies the management of complex data pipelines. In this article, we will guide you through the process of building a data pipeline that transfers data from a data source to Amazon S3, and then to Amazon Redshift using Apache Airflow.</p><blockquote><strong>We will break down the pipeline into three phases:</strong></blockquote><ul><li>Loading Data from the Source</li><li>Transferring Data to S3</li><li>Transferring Data from S3 to Redshift:</li></ul><h3>Phase 1: Load Data from Source</h3><p>The first phase involves extracting data from the source system. This could be a database, an API, or any other data source. We’ll use Airflow Python operators to fetch the data and prepare it for transfer to S3.</p><pre>def customers(conn_str: str, ds: str, ds_nodash: str, dag_id: str, **kwargs):<br>    df = conn_str.get_pandas_df(<br>        f&quot;&quot;&quot;<br>            with transformed_customers (<br>              select <br>              id ,<br>             creation_date,<br>            customer_fullname, <br>           customer_city ,<br>          customer_address<br>           from customers)<br>            select * from transformed_customers<br>              where  creation_date =&#39;{ds}&#39;<br>                    ;&quot;&quot;&quot;<br>    )<br><br>    schema = pa.schema(<br>        [<br>            pa.field(&quot;id&quot;, pa.string()),<br>            pa.field(&quot;creation_date&quot;, pa.date32()),<br>            pa.field(&quot;customer_fullname&quot;, pa.string()),<br>            pa.field(&quot;customer_city&quot;, pa.string()),<br>            pa.field(&quot;customer_address&quot;, pa.string()),<br>        ]<br>    )<br><br>    print(&quot;Size Of DataFrame-----&gt;&quot;, df.shape)<br>    file_dir = path_files.format(dag_id, f&quot;customers_{dsnodash}.pqt&quot;)<br>    df.to_parquet(file_dir, schema=schema, index=False)<br>    kwargs[&quot;ti&quot;].xcom_push(key=dag_id, value=file_dir)</pre><pre>def branch(conn_str: str, dag_id: str, **kwargs):<br>    df = conn_str.get_pandas_df(<br>        f&quot;&quot;&quot;<br>            with transformed_branch (<br>              select <br>              id ,<br>             creation_date,<br>            branch_name, <br>           branch_city ,<br>             branch_code <br>           from branch)<br>            select * from transformed_branch<br>                    ;&quot;&quot;&quot;<br>    )<br><br>    schema = pa.schema(<br>        [<br>            pa.field(&quot;id&quot;, pa.string()),<br>            pa.field(&quot;creation_date&quot;, pa.date32()),<br>            pa.field(&quot;branch_name&quot;, pa.string()),<br>            pa.field(&quot;branch_city&quot;, pa.string()),<br>            pa.field(&quot;branch_code&quot;, pa.string()),<br>        ]<br>    )<br><br>    print(&quot;Size Of DataFrame-----&gt;&quot;, df.shape)<br>    file_dir = path_files.format(dag_id, f&quot;branch_{dsnodash}.pqt&quot;)<br>    df.to_parquet(file_dir, schema=schema, index=False)<br>    kwargs[&quot;ti&quot;].xcom_push(key=dag_id, value=file_dir)</pre><h3>Extracting Data from Two Different Tables: Customers and Branches</h3><blockquote>In this section, we will explain how to extract data from two different tables, customers and branches, using Apache Airflow. We&#39;ll walk through the customers function parameters:</blockquote><ul><li><strong>conn_str</strong>: A connection string or object used to connect to a database.</li><li><strong>ds</strong>: A template field in Airflow that provides the DAG run&#39;s logical date in the format YYYY-MM-DD. This is used in the SQL query to get a snapshot of the customers table for the current date minus one day.</li><li><strong>ds_nodash</strong>: A template field in Airflow that provides the DAG run&#39;s logical date without dashes (YYYYMMDD). This is used to prepare the file name for the snapshot.</li><li><strong>dag_id</strong>: A template field in Airflow that provides the ID of the DAG. This is used to create a dynamic folder with the same name as the DAG ID to save the DataFrame as a Parquet file.</li></ul><p><strong>Body:</strong></p><p><strong>Schema Definition:</strong> A PyArrow schema is defined to match DataFrame columns with corresponding Redshift data types, ensuring data quality and compatibility.</p><p><strong>Save DataFrame to Parquet:</strong> The DataFrame size is printed for debugging. The DataFrame is saved as a Parquet file at a specified location with the defined schema.</p><p><strong>Push File Path to XCom:</strong> The file path is pushed to Airflow’s XCom for use by other tasks in the DAG.</p><blockquote>We didn’t use ds in the branch query because the customers table is append-only, where new records are added daily, whereas the branch table is completely replaced each day to reflect the most up-to-date data.&quot;</blockquote><h3>Phase 2: transferring data to S3</h3><blockquote>In the second phase, we transfer the extracted data to Amazon S3 for storage. This involves uploading the locally saved Parquet file to an S3 bucket using <strong><em>LocalFilesystemToS3Operator</em></strong></blockquote><p>If we have multiple tables, such as two in this example, we need separate operators for each one, like LocalFilesystemToS3Operator for customers and another for branch. However, if we have more tables, such as five or more, writing individual operators for each table would be inefficient. Instead, we can create a function that generates the necessary profile for each table and use a loop to apply the same operator for all tables. This approach streamlines the process and scales better for managing multiple tables.</p><pre>def generate_tables_profile():<br><br>    tables_profile = {<br>        &quot;snp_customers&quot;: {<br>            &quot;upsert_keys&quot;: [&#39;id&#39;],<br>            &quot;replace&quot;: False ,<br>            &quot;function&quot;: customers,<br>            &quot;params&quot;: {&quot;conn_str&quot;: PostgresHook(&quot;pos_conn&quot;), <br>                       &quot;dag_id&quot;: &quot;{{dag.dag_id}}&quot;<br>                          },<br>        } ,<br><br>      &quot;snp_branch&quot;: {<br>            &quot;upsert_keys&quot;: None,<br>            &quot;replace&quot;: True,<br>            &quot;function&quot;: branch,<br>            &quot;params&quot;: {&quot;conn_str&quot;: mysqlhook(&quot;mysql_conn&quot;),<br>                   &quot;dag_id&quot;: &quot;{{dag.dag_id}}&quot;<br>             },<br>        } <br>    }<br><br>    return tables_profile</pre><p>This function generates profiles for each table, which likely include details like the table name, associated functions, parameters, and whether the data should be replaced in S3.</p><pre>default_args = {<br>    &quot;owner&quot;: &quot;Ahmed&quot;,<br>    &quot;depends_on_past&quot;: False,<br>    &quot;email_on_failure&quot;: False,<br>    &quot;email_on_retry&quot;: False,<br>    &quot;retries&quot;: 2,<br>    &quot;retry_delay&quot;: timedelta(minutes=30),<br>}<br><br>with DAG(<br>    &#39;s3_to_redshift_pipeline&#39;,<br>    default_args=default_args,<br>    description=&#39;A simple data pipeline to transfer data from S3 to Redshift&#39;,<br>    schedule_interval=&#39;@daily&#39;,<br>    start_date=datetime(2023, 1, 1),<br>    catchup=False,<br>  ) as dag:  <br><br>  tables_profile= generate_tables_profile()<br>  for table_name, profile in tables_profile.items():<br><br>        with TaskGroup(group_id=f&quot;{table_name}_group&quot;) as tg:<br>            read_from_db_task = PythonOperator(<br>                task_id=f&quot;read_from_{table_name}_task&quot;,<br>                python_callable=profile[&quot;function&quot;],<br>                op_kwargs=profile[&quot;params&quot;],<br>                provide_context=True,<br>                on_failure_callback=slack_failed_callback,<br>                dag=dag,<br>            )<br><br>            upload_to_s3_operator_task = LocalFilesystemToS3Operator(<br>                task_id=f&quot;write_{table_name}_To_S3&quot;,<br>                filename=&quot;{{ ti.xcom_pull(task_ids=params.task, key=dag.dag_id) }}&quot;,<br>                dest_key=dest_key_folder(<br>                    table_name, profile[&quot;replace&quot;]<br>                ),<br>                dest_bucket=&quot;datamart_pod&quot; ,<br>                aws_conn_id=&quot;AWS_CONN_S3_TO_REDSHIFT&quot;,<br>                replace=profile[&quot;replace&quot;],<br>                params={<br>                    &quot;task&quot;: f&quot;{table_name}_group.read_from_{table_name}_task&quot;,<br>                },<br>                on_failure_callback=slack_failed_callback,<br>                dag=dag,<br>            )<br><br>         </pre><p>let’s explain LocalFilesystemToS3Operator <br> . <strong>task_id</strong>: Unique identifier for the task.</p><ul><li><strong>filename</strong>: Retrieves the filename from XCom, where the previous task stored it.</li><li><strong>dest_key</strong>: Destination key (path) in the S3 bucket.</li></ul><blockquote>The dest_key_folder function generates an S3 destination key based on the replace_flag for the table. If replace_flag is False, the path includes year, month, and day to structure the files by date like this : <em>datamart_pod/customers/2024/06/03/customers_20240603.pqt</em>.</blockquote><blockquote>If replace_flag is True, the path is simpler and does not include the date, following the format bucket_name/folder_name/file.</blockquote><pre>def dest_key_folder(table:str, replace_flag:bool):<br>    if replace_flag:<br>        return &quot;{}/{}/{}&quot;.format(<br>            &#39;datamart-pod&#39;,<br>            table,<br>            &quot;{{ ti.xcom_pull(task_ids=params.task, key=dag.dag_id).split(&#39;/&#39;)[-1] }}&quot;,<br>        )<br>    else:<br>        return &quot;{}/{}/{}/{}/{}/{}&quot;.format(<br>            &#39;datamart-pod&#39;,<br>            table,<br>            &quot;{{ ds.split(&#39;-&#39;)[0] }}&quot;,<br>            &quot;{{ ds.split(&#39;-&#39;)[1] }}&quot;,<br>            &quot;{{ ds.split(&#39;-&#39;)[2] }}&quot;,<br>            &quot;{{ ti.xcom_pull(task_ids=params.task, key=dag.dag_id).split(&#39;/&#39;)[-1] }}&quot;,<br>        )</pre><ul><li><strong>dest_bucket</strong>: The S3 bucket name.</li><li><strong>aws_conn_id</strong>: AWS connection ID configured in Airflow.</li><li><strong>replace</strong>: Indicates whether to replace the file in S3 if it already exists.</li><li><strong>params</strong>: Parameters passed to the task, including the task ID for the previous task.</li></ul><h3>Phase 3: transferring data from S3 to Redshift</h3><blockquote>In the final phase, we transfer the data stored in Amazon S3 to Amazon Redshift for further analysis and processing. This involves using Airflow’s S3ToRedshiftOperator to copy the data efficiently from S3 to Redshift.</blockquote><p>inside the loop, we will put this operator</p><pre>transfer_to_redshift_task = S3ToRedshiftOperator(<br>                task_id=f&quot;transfer_{table_name}_to_redshift&quot;,<br>                redshift_conn_id=&quot;Redshift_dm_conn&quot;,<br>                s3_bucket=&quot;datamart_pod&quot; ,<br>                s3_key=s3_key_template(profile[&quot;replace&quot;]),<br>                schema=&quot;eng&quot; ,<br>                aws_conn_id=&quot;AWS_CONN_S3_TO_REDSHIFT&quot;,<br>                table=f&quot;{table_name}&quot;,<br>                copy_options=[&quot;FORMAT AS PARQUET&quot;, &quot;FILLRECORD&quot;],<br>                method=rebuild_method(profile[&quot;replace&quot;]),<br>                upsert_keys=profile[&quot;upsert_keys&quot;],<br>                params={<br>                    &quot;task&quot;: f&quot;{table_name}_group.read_from_{table_name}_task&quot;,<br>                    &quot;table&quot;: table_name,<br>                },<br>                on_failure_callback=slack_failed_callback,<br>                dag=dag,<br>            )<br><br>read_from_db_task &gt;&gt; upload_to_s3_operator_task &gt;&gt; transfer_to_redshift_task</pre><p>so how does it work?</p><h3>Parameters</h3><ul><li><strong>redshift_conn_id</strong>: The Airflow connection ID for Redshift.</li><li><strong>s3_bucket</strong>: The name of the S3 bucket.</li><li><strong>s3_key</strong>: The S3 key (path) to the data file. It is generated using the s3_key_template function which uses the replace flag from the profile to determine the key structure.</li><li><strong>schema</strong>: The Redshift schema where the table resides.</li><li><strong>aws_conn_id</strong>: The Airflow connection ID for AWS credentials.</li><li><strong>table</strong>: The name of the Redshift table where the data will be loaded. It uses the table name from the profile.</li><li><strong>copy_options</strong>: A list of options for the Redshift COPY command. In this case, it includes options to format the data as Parquet and to fill in missing records (e.g., [&quot;FORMAT AS PARQUET&quot;, &quot;FILLRECORD&quot;]).</li><li><strong>method</strong>: The method used for loading data, determined by the rebuild_method function using the replace flag from the profile. This could specify whether to append or replace data in the Redshift table.</li></ul><pre>def rebuild_method(replace_flag, **kwargs):<br>    # Initialize Method with a default value<br>    Method = &quot;UPSERT&quot;  # Default method<br><br>    if replace_flag == True:<br>        Method = &quot;REPLACE&quot;<br>    else:<br>        dag_run = kwargs.get(&quot;dag_run&quot;)<br>        dag_run_conf = dag_run.conf<br>        if dag_run_conf and dag_run_conf.get(&quot;rebuild_mode&quot;) == &quot;full&quot;:<br>                Method = &quot;REPLACE&quot;<br>            # Else, Method remains &#39;UPSERT&#39;<br>    logging.info(&quot;Method Rebuild-----------&gt;&quot;, Method)<br>    return Method</pre><ul><li><strong>upsert_keys</strong>: The primary key(s) for the table, is used for upserting but in this operator follow this approach (delete and inserting) data.</li></ul><h4>Conclusion</h4><p>In this article, we walked through the process of building a data pipeline using Apache Airflow to transfer data from a data source to Amazon S3 and then to Amazon Redshift. We divided the pipeline into three phases: loading data from the source, transferring data to S3, and transferring data from S3 to Redshift.</p><p>I hope you enjoyed it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73348ac1da9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Use Soda For Data Quality Checks With Apache Airflow]]></title>
            <link>https://ahmed-mokbel.medium.com/how-to-use-soda-for-data-quality-checks-with-apache-airflow-cf249a737b5a?source=rss-369ff6b86f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf249a737b5a</guid>
            <category><![CDATA[soda]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[data-quality]]></category>
            <dc:creator><![CDATA[Ahmed Mokbel]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 15:04:26 GMT</pubDate>
            <atom:updated>2024-04-26T15:07:08.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIORVN0pzIhAPGwVicTE5g.jpeg" /></figure><blockquote>In the world of data, quality is like the superhero cape that keeps your databases flying high above the chaos! Employing data quality tools is crucial, as they ensure the accuracy, consistency, and reliability of data — fundamental for effective decision-making, compliance, and operational efficiency. These tools keep your data pristine and trustworthy, safeguarding against costly errors. By prioritizing high data standards, organizations can avoid costly mistakes and inefficiencies that arise from poor data quality, leading to better business outcomes and improved data-driven strategies.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czepTg3ioMO8fPUSJat3vQ.jpeg" /></figure><h3>Soda Data Quality Framework</h3><p>Soda Core is a powerful open source Framework and Python library that enables you to use the Soda Checks Language to turn user-defined input into aggregated SQL queries. When it runs a scan on a dataset, Soda Core executes the checks to find invalid, missing, or unexpected data. When your Soda Checks fail, they surface the data that you defined as bad quality.</p><h3>How it works</h3><blockquote>Soda works by taking the data quality checks that you prepare and using them to run a scan of datasets in a data source. A scan is a command that instructs Soda to prepare optimized SQL queries that execute data quality checks on your data source to find invalid, missing, or unexpected data. When checks fail, they surface bad-quality data and present check results that help you investigate and address quality issues.</blockquote><p>To test your data quality, you choose a flavor of Soda (choose a deployment model) which enables you to configure connections with your data sources and define data quality checks, then run scans that execute your data quality checks.</p><ul><li><strong>Connect to your data source.</strong><br>Connect Soda to a data source such as Snowflake, Amazon Athena, or BigQuery by providing access details for your data source such as host, port, and data source login credentials.</li><li><strong>Define checks to surface bad-quality data.</strong><br>Define data quality checks using Soda Checks Language (SodaCL), a domain-specific language for data quality testing. A Soda Check is a test that Soda performs when it scans a dataset in your data source.</li><li><strong>Run a scan to execute your data quality checks.</strong><br>During a scan, Soda does not ingest your data, it only scans it for quality metrics, and then uses the metadata to prepare scan results. After a scan, each check results in one of three default states:</li><li>pass: the values in the dataset match or fall within the thresholds you specified</li><li>fail: the values in the dataset do not match or fall within the thresholds you specified</li><li>error: the syntax of the check is invalid, or there are runtime or credential errors</li><li>A fourth state, warn, is something you can explicitly configure for individual checks.</li></ul><p><strong>Review scan results and investigate issues.</strong><br>You can review the scan output in the command line and in your Soda Cloud account.</p><h3><strong>How to Integrate Soda with Apache Airflow :</strong></h3><h4>Install Soda SQL:</h4><pre>pip install soda-core-scientific<br>pip install soda-core-redshift</pre><p>soda-core-redshift can be any other data source (soda-core- postgres)</p><h4>Create Custom Operator For Soda:</h4><p>Airflow doesn&#39;t have an operator For the soda Quality Framework So We Need to make our own</p><blockquote>create a file named ‘Customoperators.py’ and insert the following code into it :</blockquote><pre>from soda.scan import Scan<br>from airflow.hooks.base_hook import BaseHook<br>import os<br><br>class SodaScanOperator(BaseOperator):<br>    @apply_defaults<br>    def __init__(<br>        self,<br>        scan_name: str,<br>        conn_id:str ,<br>        schema_name:str ,<br>        data_source: str = &#39;redshift_datamart&#39;,<br>        project_root: str = &#39;soda&#39;,<br>        *args, **kwargs<br>    ):<br>        super().__init__(*args, **kwargs)<br>        self.conn_id=conn_id<br>        self.scan_name = scan_name<br>        self.data_source = data_source<br>        self.project_root = project_root<br>        self.schema_name=schema_name <br><br>    <br>    def define_Variables(self) :<br>        username=BaseHook.get_connection(self.conn_id).login<br>        password = BaseHook.get_connection(self.conn_id).password<br>        host = BaseHook.get_connection(self.conn_id).host<br>        port=BaseHook.get_connection(self.conn_id).port<br><br>        os.environ[&#39;username&#39;] = username<br>        os.environ[&#39;password&#39;] = password<br>        os.environ[&#39;host&#39;] = host<br>        os.environ[&#39;schema_name&#39;] = self.schema_name<br>        os.environ[&#39;port&#39;] = str(port)<br><br>    def execute(self, context):<br><br>        self.define_Variables()<br>        self.log.info(&#39;Running Soda Scan ...&#39;)<br>        config_file = f&#39;{self.project_root}/configuration.yml&#39;<br>        checks_path = f&#39;{self.project_root}/schema/{self.schema_name}.yml&#39;<br><br><br><br>        scan = Scan()<br>        scan.set_verbose()<br>        scan.add_configuration_yaml_file(config_file)<br>        scan.set_data_source_name(self.data_source)<br>        scan.add_sodacl_yaml_files(checks_path)<br>        scan.set_scan_definition_name(self.scan_name)<br>        result = scan.execute()<br>        self.log.info(scan.get_logs_text())<br>        <br>        if result != 0:<br>            raise ValueError(&#39;Soda Scan failed&#39;)<br><br>        return result<br><br></pre><h4>1. Initialization (__init__ method):</h4><ul><li>This method sets up the operator with necessary parameters such as scan_name, conn_id, schema_name, data_source, and project_root.</li><li>scan_name: Name of the specific scan to execute.</li><li>conn_id: Airflow connection ID used to fetch database credentials.</li><li>schema_name: Specifies the schema within the database to be scanned.</li><li>data_source: Indicates the type of database (e.g., &#39;redshift_datamart&#39;).</li><li>project_root: The directory path where the Soda project and configuration files are stored.</li></ul><h4>2. Environment Setup (define_Variables method):</h4><ul><li>Retrieves database credentials using the connection ID from Airflow’s connection management system.</li><li>Sets these credentials and connection details as environment variables, which are presumably used by the Soda scan to access the database.</li></ul><h4>3. Execution (execute method):</h4><ul><li>Calls the define_Variables method to set up the environment.</li><li>Constructs paths for the Soda configuration file (configuration.yml) and the checks file (schema_name.yml).</li><li>A <strong>Soda scan</strong> executes the checks you write in an agreement, in a checks YAML file, or inline in a programmatic invocation, and returns a result for each check: pass, fail, or error.</li><li>Initializes a Scan object from Soda SQL and configures it with verbose logging, data source name, scan configuration, and checks file.</li><li>Executes the scan and logs the results or errors.</li></ul><h4>Create Configuration File and Checks File :</h4><blockquote>For Soda to run quality scans on your data, you must configure it to connect to your data source.</blockquote><ul><li>create a folder called soda have file <em>configuration.yml</em></li></ul><pre>data_source redshift_datamart:<br>  type: redshift<br>  host: ${host}<br>  username: ${username}<br>  password: ${password}<br>  database: data_mart<br>  schema: ${schema_name}<br></pre><ul><li>create a file named ‘bank_customers.yml’ within the ‘schema’ folder located inside the ‘soda’ directory “soda/schema/bank_customers.yml”. This folder called schemas should contain all the necessary files schemas. We will conduct checks on these schemas</li></ul><blockquote><strong>hint<em>:</em></strong> Ensure that the file name ‘bank_customers.yml’ matches the schema name. in the database</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*DQyQd3G_fQ-sxmSWs2jO_A.png" /></figure><p><strong>Soda Checks Language (SodaCL)</strong> is a YAML-based, domain-specific language for data reliability. Used in conjunction with Soda tools, you use SodaCL to write checks for data quality, and then run a scan of the data in your data source to execute those checks.</p><h4>Example :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbdS4u5IFj4d-6Kv8iTKwQ.png" /></figure><h4>Initialize our dag :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hE0KkbY2oabTfiS0IOx21g.png" /></figure><p>In conclusion, the integration of Soda with Apache Airflow offers a powerful solution for maintaining data quality and ensures their pipelines effectively. By leveraging Soda’s Data Quality Framework, Data Engineers can define and execute comprehensive data quality checks tailored to their specific requirements. Through custom operators, such as the one outlined above.</p><p><strong>Thank you for getting this far 🫡</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf249a737b5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to connect dbt to multiple databases in the same project]]></title>
            <link>https://towardsdev.com/how-to-connect-dbt-to-multiple-databases-in-the-same-project-959fc8cc55a8?source=rss-369ff6b86f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/959fc8cc55a8</guid>
            <category><![CDATA[starburst]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[transformation]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[trinos]]></category>
            <dc:creator><![CDATA[Ahmed Mokbel]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 14:26:11 GMT</pubDate>
            <atom:updated>2023-12-11T15:25:41.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*zfUviogyaXLur1T4-txxzA.png" /></figure><h3>What is dbt?</h3><p>dbt(data build tool) is a transformation tool that enables users to write modular SQL queries, which are then executed in the data warehouse in the correct sequence, with dbt managing dependencies and execution order. It brings software engineering best practices to the world of data transformation, including version control, testing, and deployment.</p><h3>Understanding dbt’s Connection Mechanism</h3><p>dbt typically connects to one primary data source per project, managed via the profiles.yml configuration file. This pivotal file, located in the user&#39;s home directory (e.g., ~/.dbt/), contains all necessary information for dbt to establish connections.</p><p>The profiles.yml file is the central place for configuring the connection to your data warehouse(s). Located in the user&#39;s home directory (e.g., ~/.dbt/), this file contains all the necessary information for dbt to establish</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ipzbzdPpvhceP4jgWApYQ.png" /></figure><p>let’s dive into how to create a project in dbt. This process involves setting up the necessary environment and files to get your dbt project up and running.</p><h3><strong>Installing dbt</strong></h3><p>1-create new environment for dbt</p><pre> conda create --name dbt-env</pre><p>2-Activate that same virtual environment</p><pre>conda activate dbt-env</pre><p>3- install these package</p><pre> pip install\ <br> dbt-core \<br> dbt-postgres \ <br> dbt-redshift \<br> dbt-snowflake \<br> dbt-bigquery \ <br> dbt-trino</pre><p>4-create the project</p><pre>dbt init project_name</pre><p>This command creates a new directory with the given project name, containing a set of files and directories that form the base structure of a dbt project then choose your connection</p><p>Great now we created a project connected to one data source, Let’s look at how you can connect DBT to multiple databases in the same project through Trino but first, let me tell you what is trino</p><h3>What does Trino do?</h3><p>Trino(formerly known as PrestoSQL) is fast distributed SQL query engine for big data analytics that combines and analyzes data from various sources</p><p>trino connects to a multi data sources through a single connection and processes SQL queries at scale and speed.</p><p>In this tutorial, we will explore the approach to connect trino with dbt</p><h3>Installing trino with dbt</h3><p>1-Run Trino in a Docker Container :</p><pre>docker run --name trino -d -p 8080:8080 trinodb/trino</pre><p>2-Access the Trino CLI :</p><pre>docker exec -it trino trino </pre><p>3-Create Configuration Files: Develop postgres.properties and mysql.properties for PostgreSQL and MySQL connections.</p><p>Contents of postgres.properties:</p><pre>connector.name=postgresql<br>connection-url=jdbc:postgresql://example.net:5432/database<br>connection-user=root<br>connection-password=secret<br>allow-drop-table=true</pre><p>And for MySQL mysql.properties :</p><pre>connector.name=mysql<br>connection-url=jdbc:mysql://example.net:3306/database<br>connection-user=root<br>connection-password=secret</pre><p>4- Moving the Configuration File:</p><ul><li>Access the Container: First, access the Trino container’s shell:</li></ul><pre>docker exec -it trino /bin/bash</pre><ul><li>Copy the File: Use the docker cp command to move the postgres.properties file into the Trino container’s etc/trino/catalog directory:</li></ul><pre>  docker cp &lt;path_to_file&gt;/postgres.properties   trino:/etc/trino/catalog/<br>  docker cp &lt;path_to_file&gt;/mysql.properties   trino:/etc/trino/catalog/</pre><p>After finishing our steps start trino conatiner:</p><pre>docker restart trino</pre><h4>Let’s test our connections in trino :</h4><pre>docker exec -it trino trino show catalogs;</pre><p>you should see the names of our connections postgres and mysql</p><p>Also, Trino not only excels as a powerful distributed SQL query engine but also provides a user-friendly web UI (User Interface) for monitoring and managing queries. This UI adds an accessible layer of interaction with Trino, making it easier to visualize and manage the performance and execution of queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yB8FziLWkPM_Wn1gBV5lWg.png" /></figure><p>wonderful is it ?</p><p>let me show you how we can make dbt connect to trino</p><p>1-First, let’s create our profiles.yml :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CnKfJfnsAErhxPKcrVtDw.png" /></figure><p>2-move trino profile into /.dbt/folder</p><p>3- change profile_name trinoin dbt_project.yml</p><pre>profile: &#39;trino&#39;</pre><h3>Testing Our dbt Connection with Multi-Database Models</h3><p>We’re now set to put our dbt setup to the test by creating models that interact with both PostgreSQL and MySQL databases, and then merging data from these sources. Here’s how we’ll proceed:</p><h4>Step 1: Creating Individual Models for PostgreSQL and MySQL</h4><ul><li>PostgreSQL Model (reading_postgres.sql): We&#39;ll start by creating a model to read data from our PostgreSQL database. This model will contain SQL queries specific to the data structure in PostgreSQL.</li><li>MySQL Model (reading_mysql.sql): Similarly, we&#39;ll create another model dedicated to querying data from the MySQL database.</li></ul><h4>Step 2: Creating a Merged Model</h4><ul><li>Final Merge Model (final_merge.sql): The third model will be the crux of our test. It&#39;s designed to join data from the PostgreSQL and MySQL models. This model demonstrates the ability of dbt to harmonize and merge data across different database systems.</li></ul><h4>Step 3: Customizing Schema Generation with a dbt Macro</h4><ul><li>Macro for Schema Generation: To flexibly manage schema names, we’ll define a dbt macro. This macro allows us to either use a custom schema name or default to the target schema, based on our requirements.</li><li>Macro Definition:</li></ul><pre>{% macro generate_schema_name(custom_schema_name, node) -%}<br>    {%- set default_schema = target.schema -%}<br>    {%- if custom_schema_name is none -%}<br>        {{ default_schema }}<br>    {%- else -%}<br>        {{ custom_schema_name | trim }}<br>    {%- endif -%}<br>{%- endmacro %}</pre><ul><li>This macro checks if custom_schema_name is provided; if not, it defaults to the target.schema.</li></ul><h4>Step 4: Configuring the Merge Model</h4><ul><li>Model Configuration: In our final_merge.sql model, we&#39;ll configure dbt to materialize the output as a table. We&#39;ll also specify the database connection, schema, and table name.</li><li>Configuration Syntax:</li></ul><pre>{{<br>  config(<br>    materialized = &#39;table&#39;,<br>    alias = &#39;&lt;table_name&gt;&#39;,<br>    catalog = &#39;&lt;connection_name&gt;&#39;,<br>    schema = generate_schema_name(&#39;&lt;schema_name&gt;&#39;)<br>  )<br>}</pre><ul><li>Replace &lt;table_name&gt;, &lt;connection_name&gt;, and &lt;schema_name&gt; with your actual table name, database connection name, and schema name.</li></ul><h3>Conclusion</h3><p>The journey of integrating dbt with Trino in this guide demonstrates a powerful combination for handling data across multiple databases. This setup not only simplifies the complexities of working with diverse data sources but also empowers teams to conduct deeper and more efficient analytics.</p><p>By utilizing Trino’s ability to seamlessly connect to various data stores and dbt’s robust transformation capabilities, we unlock a new realm of possibilities in data processing and analysis. This integration represents a significant stride in modern data management, allowing teams to access, transform, and analyze data at scale.</p><p>Embracing this approach provides a flexible and powerful framework, essential for today’s dynamic data environments. It’s an exemplary model for data professionals looking to enhance their workflow efficiency and data insights.</p><p>Thank you for getting this far!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=959fc8cc55a8" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-to-connect-dbt-to-multiple-databases-in-the-same-project-959fc8cc55a8">How to connect dbt to multiple databases in the same project</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing Data Between Two Databases Using GenericTransfer Operator In Apache Airflow]]></title>
            <link>https://ahmed-mokbel.medium.com/passing-data-between-two-databases-using-generictransfer-operator-in-apache-airflow-37d06e32b0a3?source=rss-369ff6b86f91------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d06e32b0a3</guid>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Ahmed Mokbel]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 23:43:36 GMT</pubDate>
            <atom:updated>2023-04-20T23:43:36.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPF_70zBWvdhV_G5Ft41Wg.png" /></figure><p>Airflow is a great data pipeline platform however, moving data between databases is a somewhat complicated topic but Writing Airflow DAGs and tasks is a ton of fun, but how can you exchange data between databases in airflow?</p><p>In this tutorial, we will explore various approaches to achieve the desired outcome, and one of these approaches involves utilizing the powerful pandas library. To begin with, we will start loading and uploading data using pandas, which is a fundamental aspect of data analysis and manipulation.</p><h3>loading data <strong>from</strong> the database</h3><pre>def load_data (conn_str) :<br>     df=pd.read_sql_query(f&#39;&#39;&#39; select * from analytics.customers &#39;&#39;&#39;<br>                            ,conn_str) <br> <br>    return df     <br></pre><p>we loaded the data into a data frame</p><h3>uploading data to another database</h3><pre><br>def upload_data(df , conn_str):<br>    <br>    conn = conn_str.connect()<br>    conn.execute(&quot;TRUNCATE TABLE datamart.tags &quot;)<br>    with conn_str.connect() as conn, conn.begin():<br>        df.to_sql(&#39;datamart&#39;,<br>                  conn,<br>                  chunksize=30000,<br>                  method=&#39;multi&#39;,<br>                  if_exists=&#39;append&#39;,<br>                  schema=&#39;tags&#39;,<br>                  index=False)</pre><p>then we passed the data frame to uploading into another database with a different schema</p><p>The good news is that achieving the same task can also be accomplished in simplest way through Apache Airflow, utilizing the Generic Transfer operator.</p><p>let me show you how to do that but first, let me tell you what is the Generic Transfer operator in airflow</p><p><em>“The Generic Transfer operator in Apache Airflow is a flexible operator that enables the movement of data between different sources, formats, and transfer protocols. ”</em></p><h3>Create a Generic Transfer Operator</h3><pre>from airflow.operators.python import PythonOperator<br>from airflow.operators.generic_transfer import GenericTransfer<br>from airflow import DAG<br><br>with  DAG(dag_id=&#39;Generic Transfer Operator&#39;, <br>        schedule_interval=None ,<br>        start_date=datetime(2023,2,2) ,<br>        catchup=False) as dag :<br><br>        load_upload_data=GenericTransfer(<br>                        task_id=&#39;load_upload_data&#39; ,<br>                        sql=&quot;select * from analytics.customers &quot;<br>                        destination_table =&quot;datamart.tags&quot;  ,<br>                        source_conn_id=&quot;analytics_conn&quot;  ,<br>                        destination_conn_id=&quot;datamart_conn&quot; ,<br>                        preoperator=&quot;TRUNCATE TABLE datamart.tags&quot; ,<br>                        dag=dag<br><br>                    )<br><br>load_upload_data<br></pre><p>In this code snippet, we see an example of how the GenericTransfer operator in Apache Airflow can be utilized to transfer data between two database connections. The code defines a DAG that has a single task named “upload_data”.</p><p>The task uses the GenericTransfer operator to transfer data from a source table named “analytics.customers” to a destination table named “datamart.tags”. The operator uses two database connections, “analytics_conn” as the source connection and “datamart_conn” as the destination connection and preoperator parameter is sql statement or list of statements to be executed before loading the data.</p><p>boom so easy, is it?</p><h3>Conclusion</h3><p>In conclusion, transferring data between two databases is a common requirement in data pipeline development, and Apache Airflow provides various approaches to accomplish this task. In this tutorial, we have explored how to pass data between two databases using pandas and the GenericTransfer operator in Apache Airflow. The GenericTransfer operator provides a simple and flexible way to move data between different sources, formats, and transfer protocols. By using this operator, we can easily transfer data from a source table to a destination table by specifying the appropriate database connections, source and destination tables, and pre-operator SQL statements. Overall, the GenericTransfer operator in Apache Airflow makes the data transfer process more efficient, automated, and scalable.</p><p>Thank you for taking the time 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37d06e32b0a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>