<?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 Drishi Gupta on Medium]]></title>
        <description><![CDATA[Stories by Drishi Gupta on Medium]]></description>
        <link>https://medium.com/@drishigupta?source=rss-67eca4b1a168------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g87rwqySEGopI_vl</url>
            <title>Stories by Drishi Gupta on Medium</title>
            <link>https://medium.com/@drishigupta?source=rss-67eca4b1a168------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:04:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drishigupta/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 Build a Custom Decimal Precision Expectation in Great Expectations]]></title>
            <link>https://medium.com/@drishigupta/how-to-build-a-custom-decimal-precision-expectation-in-great-expectations-1c720efaaa94?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c720efaaa94</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[great-expectations]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 11:32:13 GMT</pubDate>
            <atom:updated>2026-10-09T11:32:13.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8klZxGffC28UGYhxF7b_g.png" /></figure><h3>Introduction</h3><p>Data quality is a critical aspect of any data engineering pipeline. Ensuring that data follows the expected format, structure, and business rules helps maintain consistency and reliability across downstream systems.</p><p>One common data quality requirement is <strong>validating decimal precision in numeric columns</strong>. For example, a price column may be expected to contain values with exactly two decimal places, such as 10.99 or 25.50. Identifying values that do not meet this requirement can help prevent data inconsistencies and ensure compliance with business rules.</p><p><a href="https://greatexpectations.io/">Great Expectations</a> is a popular Python-based framework for validating data quality through reusable expectations. While it provides many built-in expectations, certain validation requirements may need custom logic.</p><p>In this article, we will explore how to <strong>create a custom expectation in Great Expectations to validate decimal precision across a dataset</strong>. We will walk through the implementation, configure the expectation, and test it using sample data to understand how it identifies values that do not meet the specified precision.</p><h3>Install Great Expectations</h3><p>If you haven’t already, install Great Expectations by running the following command in your terminal:</p><pre>pip install great_expectations</pre><h3>Initialize a new Data Context</h3><p>In Great Expectations, your project configuration and metadata, including datasources, expectation suites, validation results, etc., are all maintained in a data context. You can initialize a new data context in an existing directory like so:</p><h4><strong><em>Option 1</em></strong></h4><pre>import great_expectations as ge<br>context = ge.data_context.DataContext.create(&quot;./my_ge_project&quot;)</pre><h4><strong><em>Option 2</em></strong></h4><pre>great_expectation init</pre><h3>Connect to your MySQL database</h3><p>You’ll need to set up a datasource for your MySQL database.</p><pre>import great_expectations as gx<br>from great_expectations.cli.datasource import sanitize_yaml_and_save_datasource<br>from ruamel.yaml import YAML<br><br>yaml=YAML()<br>context = gx.get_context()<br><br>datasource_name = &quot;orders_decimal_check&quot;<br>connection_string = &quot;mysql+pymysql://root:test@localhost:3306/sample_db&quot;<br><br>datasource = context.sources.add_sql(name=&quot;orders_decimal_check&quot;,connection_string=connection_string)<br><br>table_name=&quot;orders_decimal_check&quot;<br>asset_name=&quot;orders_decimal_check_asset&quot;<br>asset_table_name=table_name<br><br>table_asset=datasource.add_table_asset(name=asset_name,table_name=asset_table_name)<br>my_datasource=context.get_datasource(&quot;orders_decimal_check&quot;)<br>my_table_asset=my_datasource.get_asset(asset_name=&quot;orders_decimal_check_asset&quot;)</pre><p>This script is used to set up a data source for the Great Expectations library, which is used for data validation and testing. Here’s a breakdown of the code:</p><ul><li><strong>Import necessary modules</strong>: The code starts by importing the necessary modules. great_expectations is the main library used for data validation, sanitize_yaml_and_save_datasource is a utility function for handling data source configuration, and ruamel.yaml is a YAML parser/emitter.</li><li><strong>Create a YAML object</strong>: This line creates a new YAML object which can be used to parse and emit YAML data.</li><li><strong>Get the Great Expectations context</strong>: The get_context function is called to get the current Great Expectations context. This context is used to manage and interact with your project’s configuration.</li><li><strong>Define the data source name and connection string</strong>: The name of the data source and the connection string for the database are defined. The connection string includes the type of database (MySQL), the username and password, and the host and database name.</li><li><strong>Add the data source to the context</strong>: The add_sql method is called on the sources attribute of the context to add a new SQL data source. The name of the data source and the connection string are passed as arguments.</li><li><strong>Define the table name and asset name</strong>: The name of the table in the database and the name of the asset are defined. In Great Expectations, an “asset” is a specific dataset that you want to validate.</li><li><strong>Add the table asset to the data source</strong>: The add_table_asset method is called on the data source to add a new table asset. The name of the asset and the name of the table are passed as arguments.</li><li><strong>Get the data source and table asset from the context</strong>: The get_datasource and get_asset methods are called to retrieve the data source and table asset that were just added. These objects can then be used for data validation.</li></ul><h3>Create a custom expectation</h3><p>This is where you’ll define your custom expectation to check the decimal precision. For this example, let’s say you want to verify that a column my_column has a precision of 2 decimal places. You can define a custom expectation like this:</p><pre>from great_expectations.execution_engine import ExecutionEngine<br>from great_expectations.expectations.expectation import ColumnExpectation<br>from great_expectations.expectations.registry import register_expectation<br>from sqlalchemy import text<br><br>class ExpectColumnDecimalPrecisionToEqual(ColumnExpectation):<br>    &quot;&quot;&quot;<br>   Expect the decimal precision of a numeric column to be equal to the specified precision.<br>   &quot;&quot;&quot;<br><br>    @classmethod<br>    def _validate(cls, configuration=None, batch_data=None, result=None, runtime_configuration=None,<br>                  execution_engine=None, **kwargs):<br>        # Ensure configuration and execution_engine are not None<br>        if configuration is None or execution_engine is None:<br>            raise ValueError(&quot;Configuration or ExecutionEngine cannot be None.&quot;)<br><br>        # Extract column and precision from the configuration<br>        column = configuration.kwargs.get(&quot;column&quot;)<br>        precision = configuration.kwargs.get(&quot;precision&quot;)<br>        table = configuration.kwargs.get(&quot;table&quot;)<br><br>        # Ensure column and precision are provided<br>        if column is None or precision is None or table is None:<br>            raise ValueError(&quot;Column, Table and precision must be provided.&quot;)<br><br>        # Construct the SQL query using the text() construct<br>        query = text(f&quot;SELECT {column} FROM {table}&quot;)<br><br>        # Create a connection and execute the query<br>        with execution_engine.engine.connect() as connection:<br>            column_data = connection.execute(query).fetchall()<br><br>        # Iterate over all the values in the column<br>        for idx, value in enumerate(column_data):<br>            # Check if the decimal precision of the value matches the expected precision<br>            if value[0] is not None and isinstance(value[0], float):<br>                decimal_part = str(value[0]).split(&quot;.&quot;)[1] if &#39;.&#39; in str(value[0]) else &#39;&#39;<br>                if len(decimal_part) != precision:<br>                    return {<br>                        &quot;success&quot;: False,<br>                        &quot;result&quot;: {<br>                            &quot;unexpected_list&quot;: [value[0]],<br>                            &quot;unexpected_index_list&quot;: [idx],<br>                        },<br>                    }<br><br>        # If all values meet the expectation, return success<br>        return {&quot;success&quot;: True,<br>                &quot;result&quot;: {&quot;unexpected_list&quot;: [], &quot;unexpected_index_list&quot;: [], &quot;observed_value&quot;: len(column_data)}}<br><br><br># Register the custom expectation with Great Expectations<br>register_expectation(ExpectColumnDecimalPrecisionToEqual)</pre><p>This is a custom expectation for the Great Expectations library, which is used for data validation and testing. The custom expectation is called ExpectColumnDecimalPrecisionToEqual, and it checks whether the decimal precision of a numeric column in a SQL database matches a specified precision.</p><p>Here’s a breakdown of the code:</p><ul><li><strong>Import necessary modules</strong>: The code starts by importing the necessary modules from great_expectations and sqlalchemy.</li><li><strong>Define the custom expectation class</strong>: The ExpectColumnDecimalPrecisionToEqual class is defined, which inherits from ColumnExpectation. This class represents the custom expectation.</li><li><strong>Define the _validate method</strong>: This method is where the actual validation logic is implemented. It takes several parameters, including configuration (which contains the column name and the expected precision), batch_data (not used in this code), result (also not used), runtime_configuration (not used), and execution_engine (which is used to execute the SQL query).</li><li><strong>Extract column, precision, and table from the configuration</strong>: The column name, precision, and table name are extracted from the configuration object.</li><li><strong>Construct and execute the SQL query</strong>: A SQL query is constructed to select the specified column from the specified table. The query is then executed using the execution_engine, and the results are fetched.</li><li><strong>Check the decimal precision of each value</strong>: The code then iterates over each value in the column. If the value is a float, it checks whether the decimal precision of the value matches the expected precision. If it doesn’t, it returns a dictionary indicating that the expectation was not met (“success”: False), along with the unexpected value and its index.</li><li><strong>Return success if all values meet the expectation</strong>: If all values in the column meet the expectation, the method returns a dictionary indicating success (“success”: True), along with an empty list of unexpected values and indices, and the total number of values checked as the observed_value.</li><li><strong>Register the custom expectation</strong>: Finally, the custom expectation is registered with Great Expectations using the register_expectation function. This makes the custom expectation available for use in your data validation tests.</li></ul><h3>Use the custom expectation</h3><p>Now you can use your custom expectation on your data asset like this:</p><pre>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from plugins.expectations.decimal_check import ExpectColumnDecimalPrecisionToEqual<br><br># Now you can use your custom expectation<br>context = ge.get_context()<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>    expectation_type=&quot;expect_column_decimal_precision_to_equal&quot;,<br>    kwargs={<br>        &quot;table&quot;: &quot;orders_decimal_check&quot;,<br>        &quot;column&quot;: &quot;price&quot;,<br>        &quot;precision&quot;: 2<br>    },<br>)<br><br># Attempt to get the existing expectation suite<br>expectation_suite_name = &quot;my_expectation_suite_1&quot;<br>suite = context.add_or_update_expectation_suite(expectation_suite_name=expectation_suite_name)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=expectation_suite_name, expectation_suite=suite)<br><br>data_asset = context.get_datasource(&quot;orders_decimal_check&quot;).get_asset(&quot;orders_decimal_check_asset&quot;)<br>batch_request = data_asset.build_batch_request()<br>batch_list = data_asset.get_batch_list_from_batch_request(batch_request)<br>batch_request_list = [batch.batch_request for batch in batch_list]<br>validations = [{&quot;batch_request&quot;: batch.batch_request, &quot;expectation_suite_name&quot;: &quot;my_expectation_suite_1&quot;} for batch in batch_list]<br><br>checkpoint = context.add_or_update_checkpoint(name=&quot;orders_decimal_check&quot;, validations=validations)<br><br>checkpoint_result = checkpoint.run()<br>context.build_data_docs()</pre><p>This script is used to define and run a custom expectation in Great Expectations, a Python-based data testing, documentation, and profiling library. Here’s a breakdown of the code:</p><ul><li><strong>Import necessary modules and custom expectation</strong>: The script starts by importing the necessary modules from great_expectations and the custom expectation ExpectColumnDecimalPrecisionToEqual from plugins.expectations.decimal_check.</li><li><strong>Get the Great Expectations context</strong>: The get_context function is called to get the current Great Expectations context. This context is used to manage and interact with your project’s configuration.</li><li><strong>Define the custom expectation configuration</strong>: An ExpectationConfiguration object is created, which specifies the type of the expectation (expect_column_decimal_precision_to_equal) and its parameters (the table name, column name, and precision).</li><li><strong>Get or create the expectation suite</strong>: The add_or_update_expectation_suite method is called on the context to get or create an expectation suite with the specified name. An expectation suite in Great Expectations is a collection of expectations that you want to validate against your data.</li><li><strong>Add the custom expectation to the suite</strong>: The custom expectation is added to the suite using the add_expectation method.</li><li><strong>Save the expectation suite</strong>: The suite is saved back to the context using the _save_expectation_suite method.</li><li><strong>Get the data asset</strong>: A specific data asset is retrieved from the data source. In Great Expectations, a data asset is a specific piece of data you want to validate.</li><li><strong>Build the batch request</strong>: A batch request is built from the data asset. A batch in Great Expectations is a specific slice of your data that you want to validate.</li><li><strong>Get the batch list from the batch request</strong>: The get_batch_list_from_batch_request method is called to get a list of batches from the batch request.</li><li><strong>Build the validations list</strong>: A list of validations is built. Each validation specifies a batch request and an expectation suite name.</li><li><strong>Add or update the checkpoint</strong>: A checkpoint is added or updated in the context. A checkpoint in Great Expectations is a bundle of one or more validations.</li><li><strong>Run the checkpoint</strong>: The checkpoint is run, which means all the validations in the checkpoint are executed.</li><li><strong>Build the data docs</strong>: Finally, the build_data_docs method is called to build the data documentation. This generates a visual representation of all the validations.</li></ul><p>Let’s say we have table orders_decimal_check and we want to check the precision of the price column.</p><pre>Create the `orders_decimal_check` table<br>CREATE TABLE orders_decimal_check(<br>id INT AUTO_INCREMENT PRIMARY KEY,<br>product VARCHAR(255),<br>price DECIMAL(10, 2)<br>);<br> - Insert data for positive test cases (prices with 2 decimal places)<br>INSERT INTO orders_decimal_check(product, price) VALUES<br>(&#39;Product 1&#39;, 10.99),<br>(&#39;Product 2&#39;, 20.00),<br>(&#39;Product 3&#39;, 30.50);<br> - Insert data for negative test cases (prices with more than 2 decimal places)<br>INSERT INTO orders_decimal_check(product, price) VALUES<br>(&#39;Product 4&#39;, 40.123),<br>(&#39;Product 5&#39;, 50.009);<br> - Insert data for negative test cases (prices with more than 2 decimal places)<br>INSERT INTO orders_decimal_check(product, price) VALUES<br>(&#39;Product 6&#39;, 40.1),<br>(&#39;Product 7&#39;, 50.0);</pre><h3>Use the custom expectation on batch of data</h3><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from gx.plugins.expectations.decimal_precision_batches import ExpectColumnDecimalPrecisionToEqual<br><br># Get the context<br>context = ge.get_context()<br># Define your datasources<br>datasource_name = &quot;sample_data&quot;<br># Define your assets<br>asset_name = &quot;sample_data_asset&quot;<br># Get the datasource<br>datasource = context.get_datasource(datasource_name)<br># Get the asset<br>datasource_asset = datasource.get_asset(asset_name=asset_name)<br># Add the splitter and sorters<br>datasource_asset.add_splitter_year_and_month(column_name=&quot;date_column&quot;)<br>datasource_asset = datasource_asset.add_sorters([&quot;+year&quot;, &quot;-month&quot;])<br># Build the batch request<br>datasource_batch_request = datasource_asset.build_batch_request(options={&quot;year&quot;: 2024})<br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;my_expectation_suite4&quot;)<br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>    expectation_type=&quot;expect_column_decimal_precision_to_equal&quot;,<br>    kwargs={<br>        &quot;column&quot;: &quot;value&quot;,<br>        &quot;precision&quot;: 2,<br>    },<br>)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=&quot;my_expectation_suite4&quot;, expectation_suite=suite)<br># Get the validator<br>validator = context.get_validator(<br>   batch_request=datasource_batch_request,<br>   expectation_suite_name=&quot;my_expectation_suite4&quot;,<br>)<br>print(validator.head())<br>res = validator.validate()<br># Save the expectation suite<br>validator.save_expectation_suite(discard_failed_expectations=False)<br># Define the checkpoint configuration<br>checkpoint_config = {<br>    &quot;class_name&quot;: &quot;SimpleCheckpoint&quot;,<br>    &quot;validations&quot;: [<br>        {<br>            &quot;batch_request&quot;: datasource_batch_request,<br>            &quot;expectation_suite_name&quot;: &quot;my_expectation_suite4&quot;<br>        }<br>    ]<br>}<br># Add or update the checkpoint<br>checkpoint_name = &quot;my_checkpoint&quot;<br>context.add_or_update_checkpoint(name=checkpoint_name, **checkpoint_config)<br># Run the checkpoint<br>checkpoint_result = context.run_checkpoint(checkpoint_name)<br># Build data docs<br>context.build_data_docs()</pre><p>This code demonstrates how to use Great Expectations to set up and run data validation checks, including creating custom expectations and checkpoints, and generating data documentation. Here’s a breakdown of each part:</p><ul><li><strong>Imports</strong>: Necessary libraries and modules are imported, including Great Expectations (great_expectations) and the ExpectationConfiguration class.</li><li><strong>Custom Expectation Import</strong>: The custom expectation ExpectColumnDecimalPrecisionToEqual is imported from the gx.plugins.expectations.decimal_precision_batches module.</li><li><strong>Get Context</strong>: The context is retrieved using ge.get_context(). This context allows access to datasources, expectations, validations, etc.</li><li><strong>Define Datasources</strong>: The datasource named “sample_data” is defined.</li><li><strong>Define Assets</strong>: The asset named “sample_data_asset” is defined within the datasource.</li><li><strong>Splitter and Sorters</strong>: A splitter and sorters are added to the datasource asset to organize and structure the data.</li><li><strong>Build Batch Request</strong>: A batch request is built for the datasource asset, specifying options such as the year 2024.</li><li><strong>Expectation Suite</strong>: An expectation suite named “my_expectation_suite4” is created or updated in the context.</li><li><strong>Custom Expectation Configuration</strong>: An expectation configuration for the custom expectation ExpectColumnDecimalPrecisionToEqual is defined, specifying the column “value” and a precision of 2.</li><li><strong>Add Expectation</strong>: The expectation configuration is added to the expectation suite.</li><li><strong>Save Expectation Suite</strong>: The expectation suite is saved in the context.</li><li><strong>Get Validator</strong>: A validator is obtained using the batch request and expectation suite.</li><li><strong>Validate Data</strong>: The validator performs data validation checks.</li><li><strong>Save Expectation Suite (Again)</strong>: The expectation suite is saved again, this time with an option to discard failed expectations.</li><li><strong>Checkpoint Configuration</strong>: A checkpoint configuration is defined, specifying a simple checkpoint with a single validation.</li><li><strong>Add or Update Checkpoint</strong>: The checkpoint is added or updated in the context.</li><li><strong>Run Checkpoint</strong>: The checkpoint is executed, performing the validation defined in the checkpoint configuration.</li><li><strong>Build Data Docs</strong>: Data documentation is generated.</li></ul><p>This code demonstrates a comprehensive workflow for setting up and running data validation checks using Great Expectations, including the use of custom expectations and checkpoints, as well as generating data documentation.</p><p>Let’s say we have table sample_data and we want to check the precision of the value column.</p><pre>Create the table<br>CREATE TABLE sample_data (<br>id INT AUTO_INCREMENT PRIMARY KEY,<br>value DECIMAL(10, 2),<br>date_column DATE<br>);<br>Insert sample data<br>INSERT INTO sample_data (value, date_column) VALUES<br>(123.45, &#39;2023–04–01&#39;),<br>(67.89, &#39;2023–04–02&#39;),<br>(101.11, &#39;2024–04–03&#39;),<br>(88.00, &#39;2024–04–04&#39;),<br>(99.99, &#39;2024–04–05&#39;);</pre><h3>Conclusion</h3><p>Validating decimal precision is an important data quality check that helps maintain consistency and reliability in data pipelines. While Great Expectations provides several built-in expectations, custom expectations allow us to implement validation rules tailored to specific business requirements.</p><p>In this article, we explored how to create a custom expectation, ExpectColumnDecimalPrecisionToEqual, to validate decimal precision across a dataset. We also covered how to configure the expectation, execute the validation, and identify values that do not meet the expected precision.</p><p>By extending Great Expectations with custom validation logic, data engineers can build more flexible and reusable data quality frameworks that address their specific needs.</p><p><strong>The key takeaway:</strong> Custom expectations help bridge the gap between standard data validation capabilities and real-world business requirements, making data quality checks more adaptable and effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c720efaaa94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Referential Integrity Check with Great Expectations]]></title>
            <link>https://medium.com/@drishigupta/building-a-custom-referential-integrity-check-with-great-expectations-bc170f4efe92?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc170f4efe92</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[great-expectations]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 13:02:36 GMT</pubDate>
            <atom:updated>2026-08-24T13:02:36.384Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide to validating foreign key relationships using Python and SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qEdOnif6A4wqJjTghtS_A.png" /></figure><h3>Introduction</h3><p>Maintaining data integrity is essential when working with relational databases. One common issue is <strong>referential integrity</strong> — ensuring that every foreign key value in a child table corresponds to a valid primary key in a parent table. When this relationship breaks, orphaned records can appear and affect downstream analytics, reporting, and data quality.</p><p>While Great Expectations provides many built-in data quality validations, real-world projects often require custom rules tailored to a specific data model.</p><p>In this article, we’ll build a <strong>custom Great Expectations expectation in Python</strong> to validate referential integrity between two SQL tables. We’ll connect Great Expectations to a MySQL database, implement the custom expectation, configure the validation, and run it across the table to identify missing foreign-key references.</p><h3>What you’ll learn</h3><ul><li>Connect Great Expectations to a MySQL database</li><li>Create a custom expectation in Python</li><li>Validate foreign key relationships across tables</li><li>Configure an expectation suite and checkpoint</li><li>Generate Data Docs to visualize validation results</li></ul><h3>Understanding Referential Integrity</h3><p>Referential integrity ensures that foreign key values in a table (child table) have corresponding primary key values in another table (parent table). This prevents orphaned records and maintains data consistency.</p><p>Great Expectations is a popular Python library used for validating, documenting, and profiling data. It allows you to define custom expectations to enforce data integrity and quality.</p><h3>Custom Expectation Development — To test on full table</h3><p><strong>Step 1: Install Great Expectations</strong></p><p>If you haven’t already installed Great Expectations, you can do so via pip:</p><pre>pip install great_expectations</pre><p><strong>Step 2: Initialize Great Expectations Project</strong></p><p>Navigate to your project directory and initialize a Great Expectations project:</p><pre>cd your_project_directory<br>great_expectations init</pre><p><strong>Step 3: Configure the Data Context to connect to your MySQL database:</strong></p><pre>import great_expectations as gx<br>from great_expectations.cli.datasource import sanitize_yaml_and_save_datasource<br>from ruamel.yaml import YAML<br><br>yaml=YAML()<br>context = gx.get_context()<br><br>datasource_name = &quot;orders&quot;<br>connection_string = &quot;mysql+pymysql://root:test@localhost:3306/sample_db&quot;<br>datasource = context.sources.add_sql(name=&quot;orders&quot;,connection_string=connection_string)<br>table_name=&quot;orders&quot;<br>asset_name=&quot;orders_asset&quot;<br>asset_table_name=table_name<br>table_asset=datasource.add_table_asset(name=asset_name,table_name=asset_table_name)<br>my_datasource=context.get_datasource(&quot;orders&quot;)<br>my_table_asset=my_datasource.get_asset(asset_name=&quot;orders_asset&quot;)</pre><ul><li>import great_expectations as gx: This line imports the Great Expectations library and aliases it as gx for convenience.</li><li>from great_expectations.cli.datasource import sanitize_yaml_and_save_datasource: This line imports the sanitize_yaml_and_save_datasource function from the great_expectations.cli.datasource module. This function is used to sanitize and save a datasource configuration in a YAML file.</li><li>from ruamel.yaml import YAML: This line imports the YAML class from the ruamel.yaml library, which is a YAML parser/emitter that supports roundtrip preservation of comments, seq/map flow style, and map key order.</li><li>yaml=YAML(): This line creates an instance of the YAML class.</li><li>context = gx.get_context(): This line gets the current Great Expectations context, which is the main object for configuring and managing data sources, data contexts, and data docs.</li><li>datasource_name = “orders”: This line sets the name of the datasource to “orders”.</li><li>connection_string = “mysql+pymysql://root:test@localhost:3306/sample_db”: This line sets the connection string for the MySQL database.</li><li>datasource = context.sources.add_sql(name=”orders”,connection_string=connection_string): This line adds a new SQL datasource to the Great Expectations context.</li><li>table_name=”orders”: This line sets the name of the table to “orders”.</li><li>asset_name=”orders_asset”: This line sets the name of the asset to “orders_asset”.</li><li>asset_table_name=table_name: This line sets the name of the asset table to the value of table_name.</li><li>table_asset=datasource.add_table_asset(name=asset_name,table_name=asset_table_name): This line adds a new table asset to the datasource.</li><li>my_datasource=context.get_datasource(“orders”): This line retrieves the datasource named “orders” from the Great Expectations context.</li><li>my_table_asset=my_datasource.get_asset(asset_name=”orders_asset”): This line retrieves the asset named “orders_asset” from the datasource.</li></ul><p>In summary, this code is setting up a Great Expectations context with a MySQL datasource and a table asset, and then retrieving the datasource and the asset. The purpose of this setup is to allow for data validation and quality checks on the “orders” table in the MySQL database.</p><p><strong>Step 4 : Create the custom expectation</strong></p><pre>from sqlalchemy import text<br>from great_expectations.execution_engine.sqlalchemy_execution_engine import SqlAlchemyExecutionEngine<br>from great_expectations.expectations.expectation import Expectation<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from great_expectations.execution_engine import ExecutionEngine<br>from typing import Dict<br>import great_expectations as ge<br><br>class ExpectReferentialIntegrity(Expectation):<br><br>library_metadata = {<br>&quot;maturity&quot;: &quot;experimental&quot;,<br>&quot;package&quot;: &quot;custom_expectations&quot;,<br>&quot;tags&quot;: [&quot;sql&quot;],<br>&quot;contributors&quot;: [&quot;YOUR NAME&quot;],<br>}<br><br>def _validate(self, configuration: ExpectationConfiguration, metrics: Dict, runtime_configuration: dict = None, execution_engine: ExecutionEngine = None):<br>primary_table = configuration.kwargs.get(&quot;primary_table&quot;)<br>foreign_table = configuration.kwargs.get(&quot;foreign_table&quot;)<br>primary_column = configuration.kwargs.get(&quot;primary_column&quot;)<br>foreign_column = configuration.kwargs.get(&quot;foreign_column&quot;)<br><br>sql = text(f&quot;&quot;&quot;<br>SELECT COUNT(*)<br>FROM {foreign_table} AS f<br>LEFT JOIN {primary_table} AS p<br>ON f.{foreign_column} = p.{primary_column}<br>WHERE p.{primary_column} IS NULL<br>&quot;&quot;&quot;)<br><br>with execution_engine.engine.connect() as connection:<br>result = connection.execute(sql)<br>count = result.scalar()<br><br>return {&quot;success&quot;: count == 0, &quot;result&quot;: {&quot;unexpected_count&quot;: count, &quot;observed_value&quot;: count}}</pre><p>This code is defining a custom expectation class ExpectReferentialIntegrity for the Great Expectations library. The purpose of this class is to validate referential integrity between two tables in a SQL database. Here’s a breakdown of the code:</p><ul><li>from sqlalchemy import text: This line imports the text function from SQLAlchemy, which allows for flexible, SQL-like operations.</li><li>from great_expectations.execution_engine.sqlalchemy_execution_engine import SqlAlchemyExecutionEngine: This line imports the SqlAlchemyExecutionEngine class from Great Expectations, which is used to interact with SQLAlchemy to run validation checks against a SQL database.</li><li>from great_expectations.expectations.expectation import Expectation: This line imports the Expectation class from Great Expectations, which is the base class for all expectation classes.</li><li>from great_expectations.core.expectation_configuration import ExpectationConfiguration: This line imports the ExpectationConfiguration class from Great Expectations, which is used to configure expectations.</li><li>from great_expectations.execution_engine import ExecutionEngine: This line imports the ExecutionEngine class from Great Expectations, which is the base class for all execution engines.</li><li>from typing import Dict: This line imports the Dict class from the typing module, which is used for type hinting.</li><li>import great_expectations as ge: This line imports the Great Expectations library and aliases it as ge.</li><li>class ExpectReferentialIntegrity(Expectation): This line defines the ExpectReferentialIntegrity class, which inherits from the Expectation class.</li><li>library_metadata = {…}: This dictionary contains metadata about the expectation.</li><li>def _validate(self, configuration: ExpectationConfiguration, metrics: Dict, runtime_configuration: dict = None, execution_engine: ExecutionEngine = None): This method is where the actual validation logic is implemented. It takes in an ExpectationConfiguration object, a dictionary of metrics, an optional runtime configuration dictionary, and an optional ExecutionEngine object.</li><li>primary_table = configuration.kwargs.get(“primary_table”): This line retrieves the primary table name from the configuration.</li><li>foreign_table = configuration.kwargs.get(“foreign_table”): This line retrieves the foreign table name from the configuration.</li><li>primary_column = configuration.kwargs.get(“primary_column”): This line retrieves the primary column name from the configuration.</li><li>foreign_column = configuration.kwargs.get(“foreign_column”): This line retrieves the foreign column name from the configuration.</li><li>sql = text(…): This line constructs a SQL query that counts the number of rows in the foreign table where the foreign key is not present in the primary table.</li><li>with execution_engine.engine.connect() as connection: This line establishes a connection to the SQL database using the execution engine.</li><li>result = connection.execute(sql): This line executes the SQL query.</li><li>count = result.scalar(): This line retrieves the count from the result of the SQL query.</li><li>return {“success”: count == 0, “result”: {“unexpected_count”: count, “observed_value”: count}}: This line returns a dictionary indicating whether the validation was successful (i.e., there are no rows in the foreign table where the foreign key is not present in the primary table) and the count of such rows.</li></ul><p>In summary, this code defines a custom expectation for validating referential integrity between two tables in a SQL database using the Great Expectations library. The expectation is successful if there are no rows in the foreign table where the foreign key is not present in the primary table. The count of such rows is also returned. This expectation can be useful for ensuring data quality and integrity in a SQL database.</p><p><strong>Step 5 : Create the validation</strong></p><pre>import great_expectations as gx<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from plugins.expectations.referential_integrity import ExpectReferentialIntegrity<br><br>context=gx.get_context()<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>expectation_type=&quot;expect_referential_integrity&quot;,<br>kwargs={<br>&quot;primary_table&quot;: &quot;product&quot;,<br>&quot;foreign_table&quot;: &quot;ordered&quot;,<br>&quot;primary_column&quot;: &quot;id&quot;,<br>&quot;foreign_column&quot;: &quot;product_id&quot;,<br>},<br>)<br><br># Attempt to get the existing expectation suite<br>expectation_suite_name = &quot;my_expectation_suite&quot;<br>suite=context.add_or_update_expectation_suite(expectation_suite_name=expectation_suite_name)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=expectation_suite_name,expectation_suite=suite)<br>data_asset=context.get_datasource(&quot;orders&quot;).get_asset(&quot;orders_asset&quot;)<br>batch_request=data_asset.build_batch_request()<br>batch_list=data_asset.get_batch_list_from_batch_request(batch_request)<br>batch_request_list=[batch.batch_request for batch in batch_list]<br>validations=[{&quot;batch_request&quot;:batch.batch_request,&quot;expectation_suite_name&quot;:&quot;my_expectation_suite&quot;} for batch in batch_list]<br>checkpoint=context.add_or_update_checkpoint(name=&quot;orders&quot;,validations=validations)<br>checkpoint_result=checkpoint.run()<br>context.build_data_docs()</pre><p>This code is using the Great Expectations library to define a custom expectation, add it to an expectation suite, and then run a checkpoint that validates a data asset against the expectation suite. Here’s a breakdown of what each part of the code does:</p><ul><li>import great_expectations as gx: This line imports the Great Expectations library and aliases it as gx for convenience.</li><li>from great_expectations.core.expectation_configuration import ExpectationConfiguration: This line imports the ExpectationConfiguration class from Great Expectations, which is used to configure expectations.</li><li>from plugins.expectations.referential_integrity import ExpectReferentialIntegrity: This line imports the custom expectation ExpectReferentialIntegrity that was defined in a previous step.</li><li>context = gx.get_context(): This line gets the current Great Expectations context, which is the main object for configuring and managing data sources, data contexts, and data docs.</li><li>expectation_config = ExpectationConfiguration(…): This line defines the configuration for the custom expectation. The expectation is of type expect_referential_integrity and checks for referential integrity between the product and ordered tables using the id and product_id columns, respectively.</li><li>suite = context.add_or_update_expectation_suite(expectation_suite_name=expectation_suite_name): This line attempts to get the existing expectation suite named my_expectation_suite from the context, or creates a new one if it doesn’t exist.</li><li>suite.add_expectation(expectation_config): This line adds the custom expectation to the expectation suite.</li><li>context._save_expectation_suite(expectation_suite_name=expectation_suite_name,expectation_suite=suite): This line saves the updated expectation suite back to the context.</li><li>data_asset = context.get_datasource(“orders”).get_asset(“orders_asset”): This line retrieves the data asset named orders_asset from the datasource named orders.</li><li>batch_request = data_asset.build_batch_request(): This line builds a batch request for the data asset.</li><li>batch_list = data_asset.get_batch_list_from_batch_request(batch_request): This line retrieves a list of batches from the batch request.</li><li>validations = [{“batch_request”:batch.batch_request,”expectation_suite_name”:”my_expectation_suite”} for batch in batch_list]: This line builds a list of validations to be performed. Each validation consists of a batch request and the name of the expectation suite to validate against.</li><li>checkpoint = context.add_or_update_checkpoint(name=”orders”,validations=validations): This line adds or updates a checkpoint named orders with the list of validations.</li><li>checkpoint_result = checkpoint.run(): This line runs the checkpoint, which performs all the validations.</li><li>context.build_data_docs(): This line builds the data docs, which are a visual representation of the validation results.</li></ul><p>In summary, this code is setting up a Great Expectations context with a custom expectation, adding the expectation to an expectation suite, running a checkpoint that validates a data asset against the expectation suite, and then building the data docs to visualize the validation results. The purpose of this setup is to ensure data quality and integrity in the orders data asset.</p><h3>Conclusion</h3><p>Referential integrity is a fundamental part of maintaining reliable and consistent data in relational databases. By extending Great Expectations with a custom expectation, we can implement validation rules that are specific to our data model rather than relying only on built-in expectations.</p><p>In this example, we created a custom ExpectReferentialIntegrity expectation that checks whether foreign key values in a child table have corresponding primary key values in the parent table. We then configured the expectation, added it to an expectation suite, executed the validation through a checkpoint, and generated Data Docs to visualize the results.</p><p>The same approach can be extended to other business-specific data quality rules, making Great Expectations a flexible framework for building reusable and automated data validation checks.</p><p><strong>Key takeaway:</strong> custom expectations allow you to turn your data quality requirements into automated, repeatable validations that can be integrated into your broader data quality pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc170f4efe92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless API to Upload Data to S3 Using AWS Lambda & API Gateway]]></title>
            <link>https://medium.com/@drishigupta/building-a-serverless-api-to-upload-data-to-s3-using-aws-lambda-api-gateway-71eedd68c4eb?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/71eedd68c4eb</guid>
            <category><![CDATA[pytho]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 09:12:59 GMT</pubDate>
            <atom:updated>2026-04-17T09:12:59.949Z</atom:updated>
            <content:encoded><![CDATA[<p>A step-by-step guide to ingesting JSON messages into S3 with Python and AWS services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jtdKSzeVMcTW6aJ3JFjeOA.png" /></figure><p>Building a reliable data ingestion layer doesn’t have to mean managing servers or complex infrastructure. With AWS serverless services, you can quickly create a scalable API that accepts incoming data and stores it directly in S3.</p><p>In this guide, we’ll walk through how to build a simple yet powerful pipeline using API Gateway, Lambda, and S3. Whether you’re capturing JSON payloads this setup gives you a flexible foundation for real-time data ingestion with minimal operational overhead.</p><p>By the end, you’ll have a fully working API that receives requests and writes them to S3 with proper structuring, security, and logging in place.</p><h3>Step 1: Create an S3 Bucket</h3><ul><li><strong>Open AWS S3 Console</strong> →<a href="https://s3.console.aws.amazon.com/s3/home"> AWS S3</a></li><li><strong>Click “Create bucket”</strong></li><li><strong>Enter a Bucket Name</strong></li><li><strong>Set Region</strong>: (Use the same region where API Gateway and Lambda will be deployed)</li><li><strong>Block Public Access</strong>: <strong>Enabled</strong> (recommended)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*t44yYvCwzHCjIAgKL4Q-Yw.png" /></figure><ul><li><strong>Click “Create bucket”</strong></li></ul><h3>Step 2: Create an IAM Role for Lambda</h3><ul><li><strong>Go to AWS IAM Console</strong> →<a href="https://console.aws.amazon.com/iam/home"> AWS IAM</a></li><li><strong>Click “Roles” → “Create Role”</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*PQIEjPrhW0iINF6OF90Uvg.png" /></figure><ul><li><strong>Select “AWS Service” → Choose “Lambda”</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*88PQUGbUbvceeLF3_sUIxg.png" /></figure><ul><li><strong>Attach Policies</strong>:AWSLambdaBasicExecutionRole and AmazonS3FullAccess (or restrict access to your bucket)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*ynez3n2j5OMtw_0mGwIbBQ.png" /></figure><ul><li><strong>Name the Role</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*eykHmeWCzzD4A5xbkUQPBA.png" /></figure><ul><li><strong>Click “Create Role”</strong></li></ul><h3>Step 3: Create a Lambda Function to Upload JSON to S3</h3><ul><li><strong>Go to AWS Lambda Console</strong> →<a href="https://console.aws.amazon.com/lambda/home"> AWS Lambda</a></li><li><strong>Click “Create function”</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*AHuSYgiCNGnCX6QoqBdGNQ.png" /></figure><ul><li><strong>Choose “Author from scratch”</strong></li><li><strong>Function Name</strong>: uploadToS3</li><li><strong>Runtime</strong>: Python 3.9 (or latest)</li><li><strong>Execution Role</strong>: Choose <strong>“LambdaS3UploadRole”</strong> (created earlier)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*glmC8m_vGlJwzt7T5FzY_g.png" /></figure><ul><li><strong>Click “Create Function”</strong></li><li><strong>Edit the function code</strong></li><li>Go to the <strong>Code</strong> tab and replace the code with:</li></ul><pre>import json<br>import boto3<br>import datetime<br><br><br>s3 = boto3.client(&quot;s3&quot;)<br>BUCKET_NAME = &quot;&quot;  <br><br><br>def lambda_handler(event, context):<br>    try:<br>        # Debug: Print received event<br>        print(&quot;Received event:&quot;, json.dumps(event))<br><br><br>        # Ensure API Gateway sends a valid body<br>        if &quot;body&quot; not in event or not event[&quot;body&quot;]:<br>            return {<br>                &quot;statusCode&quot;: 400,<br>                &quot;body&quot;: json.dumps({&quot;error&quot;: &quot;Missing &#39;body&#39; in request&quot;})<br>            }<br><br><br>        data=event[&quot;body&quot;]<br><br><br>        resource_path=event.get(&quot;resource&quot;, &quot;/upload&quot;)<br>        if resource_path.endswith(&quot;/1&quot;):<br>            folder=&quot;1&quot;<br>        if resource_path.endswith(&quot;/2&quot;):<br>            folder=&quot;2&quot;<br><br><br>        # Generate a filename with a timestamp<br>        timestamp = datetime.datetime.utcnow().strftime(&quot;%Y-%m-%d_%H-%M-%S&quot;)<br>        file_key = f&quot;{folder}/{timestamp}.txt&quot;<br><br><br>        # Upload file to S3<br>        s3.put_object(<br>            Bucket=BUCKET_NAME,<br>            Key=file_key,<br>            Body=data,  <br>            ContentType=&quot;text/plain&quot;<br>        )<br><br><br>        # Correct return format<br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;message&quot;: &quot;Data uploaded successfully&quot;, &quot;s3_key&quot;: file_key})<br>        }<br>   <br>    except Exception as e:<br>        print(&quot;Error:&quot;, str(e))  # Log error to CloudWatch<br>        return {<br>            &quot;statusCode&quot;: 500,<br>            &quot;body&quot;: json.dumps({&quot;error&quot;: str(e)})  # Ensure JSON response is a string<br>        }</pre><ul><li><strong>Click “Deploy”</strong></li></ul><h3>Step 4: Create an API Gateway</h3><ul><li><strong>Go to API Gateway Console</strong> →<a href="https://console.aws.amazon.com/apigateway"> API Gateway</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*48nCJYFM_wnv8TNV6Sezjw.png" /></figure><ul><li><strong>Click “Create API”</strong></li><li><strong>Select “REST API”</strong> → Choose “Build”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*5TV9J2ZHCZUOppa5U3yC9Q.png" /></figure><ul><li><strong>API Name</strong></li><li><strong>Endpoint Type</strong>: Regional</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*_atPPGUZ9E6My0E1gtJdMg.png" /></figure><ul><li><strong>Click “Create API”</strong></li></ul><h3>Step 5: Create the /upload Resource</h3><ul><li><strong>Under your API, click “Create Resource”</strong></li><li><strong>Create lab resource</strong></li><li><strong>Method: POST</strong></li><li><strong>Integration: Lambda (uploadToS3)</strong></li><li><strong>Add the same mapping template:</strong></li></ul><pre>{<br>   &quot;body&quot;: $input.json(&#39;$&#39;)<br>}</pre><h3>Step 6: Create a POST Method</h3><ul><li><strong>Click on /upload</strong> → Click “Create Method”</li><li><strong>Choose “POST”</strong> → Click ✓ (checkmark)</li><li><strong>Integration Type</strong>: Choose “Lambda Function”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*4dSmwm1XJcD5tLoKiNg6rg.png" /></figure><ul><li><strong>Lambda Function Name</strong>: uploadToS3</li><li><strong>Click “Save”</strong> → Click “OK”</li><li><strong>Generate API key and usage plan and linked it to stage</strong></li></ul><h3>Step 7: Deploy the API</h3><ul><li><strong>Go to API Gateway → Click “Actions” → Deploy API</strong></li><li><strong>Create a New Stage</strong> → Name it prod</li><li><strong>Click “Deploy”</strong></li><li><strong>Copy the API Invoke URL</strong> (e.g., <a href="https://abc123.execute-api.us-east-1.amazonaws.com/prod/upload)">https://abc123.execute-api.us-east-1.amazonaws.com/prod/upload)</a></li></ul><h3>Step 10: Test the API</h3><h4>Using Postman or Curl</h4><p>Run the following <strong>cURL</strong> command:</p><pre>curl -X POST &quot;https://your-api-id.execute-api.region.amazonaws.com/prod/upload/lab&quot; \<br>-H &quot;Content-Type: text/plain&quot; \<br> - data-binary $&#39;Facility|RecApp|RecFacility&#39;</pre><p>In just a few steps, you’ve built a serverless ingestion pipeline that can receive data via API Gateway, process it with Lambda, and store it reliably in S3. This pattern is widely used in modern data architectures because it’s scalable, cost-efficient, and easy to extend.</p><p>From here, you can enhance the solution by adding validation layers, integrating with data processing tools like AWS Glue or Dataflow, or implementing monitoring and alerting for production readiness. You could also refine access controls to follow least-privilege principles and improve security.</p><p>This setup is a strong starting point for building real-time data platforms — simple enough to get running quickly, but flexible enough to grow with your needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71eedd68c4eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Python Setup with Firebird (FDB) & Task Scheduler — A Practical Guide]]></title>
            <link>https://medium.com/@drishigupta/complete-python-setup-with-firebird-fdb-task-scheduler-a-practical-guide-481cb7238e1a?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/481cb7238e1a</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[firebird-database]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 07:50:50 GMT</pubDate>
            <atom:updated>2026-03-23T07:50:50.250Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to work with Firebird databases in Python and run automated workflows reliably</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CaNbjG0taP7JzbzDX94Aew.png" /></figure><p>While setting up Python is straightforward, working with <strong>Firebird databases using the </strong><strong>fdb library</strong> can quickly become challenging—especially due to limited documentation and unexpected errors.</p><p>In this guide, we go beyond basic setup and cover a <strong>complete, real-world workflow</strong>, including:</p><ul><li>Installing Python with the correct configuration</li><li>Setting up essential libraries like pandas, watchdog, and <strong>fdb</strong></li><li>Fixing a critical issue in the fdb package (rare but important)</li><li>Connecting Python to Firebird using embedded drivers</li><li>Automating your script using Windows Task Scheduler</li></ul><p>If you’ve struggled with Firebird integration in Python — or couldn’t find a clear guide — this article is designed specifically for you.</p><h3>Install and setup python</h3><h4>Step 1: Download Python Installer</h4><p>Go to the official Python website:<a href="https://www.python.org/downloads/windows/">https://www.python.org/downloads/windows/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*BROe37JllwBDWffk.png" /></figure><p>Click “Download Python” (or latest version)</p><h4>Step 2: Run the Installer (IMPORTANT SETTINGS)</h4><p>When the installer opens:</p><p>Check these boxes before clicking “Install”:</p><ul><li>Add Python to PATH (very important!)</li><li>Click Customize installation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*-j5KDDRw_QlmFqAO.png" /></figure><p>Then, in the next screens:</p><ul><li>Keep everything checked</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/0*FbVgjwKJr43pXEnr.png" /></figure><ul><li>Enable:<br>“Install for all users”<br>“Precompile standard library”</li><li>Choose install location: Example: C:\Python312 (or leave the default)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*uNlgC4vrgi_fAVxR.png" /></figure><p>Click Install</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*v7bAXl1S0YR_j-cl.png" /></figure><h4>Step 3: Verify Installation</h4><p>After install finishes:</p><p>Open Command Prompt</p><p>Run: <strong><em>where python</em></strong></p><p>You should now see something like:</p><p><strong><em>C:\Python312\python.exe</em></strong></p><p><strong><em>C:\Python312\Scripts\python.exe</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*UFrbtP5mnp9zvx2r.png" /></figure><p>This means Python is now properly installed.</p><h3>Install Necessary Modules</h3><p>Run this in Command Prompt</p><p><strong><em>python -m pip install watchdog</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/0*lQUg7kZm2fG8406M.png" /></figure><p>This ensures you’re installing watchdog into <strong>that exact Python</strong> which Task Scheduler is using.</p><p><strong><em>python -m pip install fdb</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Bo-oylPbZzQU5J91-fP65Q.png" /></figure><p><strong><em>python -m pip install pandas</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/0*5RkabJTIG7YKMb1N.png" /></figure><h4>Verify it is installed</h4><p><strong><em>python -m pip show watchdog</em></strong></p><p>You should see:</p><p><strong><em>Name: watchdog</em></strong></p><p><strong><em>Version: x.y.z</em></strong></p><p><strong><em>Location: C:\Python312\Lib\site-packages</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*i5_cxiJOfIBGwG42.png" /></figure><p><strong><em>python -m pip show pandas</em></strong></p><p>You should see:</p><p><strong><em>Name: pandas</em></strong></p><p><strong><em>Version: x.y.z</em></strong></p><p><strong><em>Location: C:\Python312\Lib\site-packages</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*ZTf8epTr4H17Sh9W.png" /></figure><p><strong><em>python -m pip show fdb</em></strong></p><p>You should see:</p><p><strong><em>Name: fdb</em></strong></p><p><strong><em>Version: x.y.z</em></strong></p><p><strong><em>Location: C:\Python312\Lib\site-packages</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*W0jvJjawzWVpmT-orwIt_w.png" /></figure><h3>Add the necessary changes to the above installed packages</h3><p>Navigate to the location of FDB package using location in above command</p><p>Inside site-packages navigate to fdb folder and open gstat.py file</p><p>Remove the below line</p><p><strong><em>from locale import LC_ALL, LC_CTYPE, getlocale, setlocale, resetlocale</em></strong></p><p>And add below line</p><p><strong><em>from locale import LC_ALL, LC_CTYPE, getlocale, setlocale</em></strong></p><p>Save and close the file.</p><h3>Download the Zip folder and Extract it</h3><p><a href="https://www.firebirdsql.org/en/firebird-2-5/">https://www.firebirdsql.org/en/firebird-2-5/</a></p><h3>Update the paths in Python File to Run the Script</h3><h4>Update the below path in the scripts</h4><p><strong>run_script.bat</strong></p><pre>@echo off<br>cd /d C:\Script<br>echo Running script at %date% %time% &gt;&gt; run_script.log<br>python script.py &gt;&gt; run_script.log 2&gt;&amp;1<br>echo Finished at %date% %time% &gt;&gt; run_script.log</pre><p><strong>Main Script.py</strong></p><pre>import pandas as pd<br>from watchdog.observers import Observer<br>from watchdog.events import FileSystemEventHandler<br># Configurations<br>fdb.load_api(&quot;C:/Firebird-2.5.9.27139–0_x64_embed/fbembed.dll&quot;)<br>FDB_EXTENSION = &quot;.fdb&quot;<br>FOLDER_PATH = &quot;C:/testing/&quot;<br>DEBOUNCE_INTERVAL = 10 # seconds<br>FILE_NAME = &quot;I3020.FDB&quot;<br>….</pre><h3>Set Up Task Scheduler on Windows</h3><h4>Open Task Scheduler</h4><ul><li>Press Win + R → type taskschd.msc → Enter</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*8NJJwk7FOsSBaVKA.png" /></figure><h4>Create a New Task</h4><ul><li>In the right pane, click <strong>“Create Task…”</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*vgMMEGE1d6Rr4gkV.png" /></figure><h4>General Tab</h4><ul><li><strong>Name</strong>: ScheduleScript</li><li><strong>Description</strong>: description</li><li><strong>Run whether user is logged on or not</strong></li><li><strong>Run with highest privileges</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*k-7JavjNGLzkimh_.png" /></figure><h4>Triggers Tab</h4><ul><li>Click <strong>New…</strong></li><li><strong>Begin the task</strong>: At startup</li><li><strong>Enabled</strong>: tick</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*ARmmGZW1YFsU1GM_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*DViMxPRSJPB876BZ.png" /></figure><p>Click OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/0*UBCgIT7roBiB77ws.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*sVBCswIuJfs2ybJx.png" /></figure><h4>Actions Tab</h4><ul><li>Click <strong>New…</strong></li><li><strong>Action</strong>: Start a program</li><li><strong>Program/script</strong>: C:\Path\To\Your\run_script.bat</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/0*TSfg0pQjvgPz1r5N.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*bIfYXzIe9TO3FQQf.png" /></figure><p>Click OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/0*sWkLKTnhwJYBodd_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*GglM-ZEiiVgfvjOl.png" /></figure><h4>Conditions Tab</h4><ul><li>Uncheck Start the task only if the computer is on AC power and Start the task only if idle</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*fQXcHfVZ3BC1iq8R.png" /></figure><h4>Settings Tab</h4><ul><li>Check:Allow task to be run on demand</li><li>Allow task to be run on demand</li><li>Restart if fails</li><li>If the task is already running, then the following rule applies: Do not start a new instance</li></ul><p>Click OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*MMZL6jWcPWIhe_DQ.png" /></figure><h4>Enter Admin Password (if prompted)</h4><p>Task will be saved and ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*eYOTvS98khcSgKg8.png" /></figure><p>Restart the System</p><p>Working with Firebird in Python isn’t always straightforward — but once properly configured, it becomes a powerful tool for automation and data processing.</p><p>In this guide, you’ve:</p><ul><li>Successfully installed and configured Python</li><li>Integrated Firebird using the fdb library</li><li>Resolved a key issue inside the package (often undocumented)</li><li>Built an automated workflow using Task Scheduler</li></ul><p>This setup is especially useful for:</p><ul><li>Legacy database integrations</li><li>Healthcare or enterprise systems using Firebird</li><li>Automated data extraction and monitoring pipelines</li></ul><p>With everything in place, your Python script can now seamlessly interact with Firebird databases and run automatically — turning a complex setup into a reliable system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=481cb7238e1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install Python Once, Automate Forever: A Windows Setup Guide]]></title>
            <link>https://medium.com/@drishigupta/install-python-once-automate-forever-a-windows-setup-guide-4febdbc74fd9?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/4febdbc74fd9</guid>
            <category><![CDATA[windows-automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 09:49:00 GMT</pubDate>
            <atom:updated>2026-03-23T07:30:38.880Z</atom:updated>
            <content:encoded><![CDATA[<p>From Python installation to Task Scheduler, and production-ready background scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-djQs0t_S0CmJ3pKfJFZZA.png" /></figure><p>Installing Python on Windows sounds simple — until your script works locally but fails in production, scheduled jobs don’t run, or libraries mysteriously go missing.</p><p>If you’ve ever struggled with:</p><ul><li>Python not being detected in Command Prompt</li><li>pip installing packages in the <em>wrong</em> Python version</li><li>Scripts failing silently in Windows Task Scheduler</li></ul><p>— you’re not alone.</p><p>This guide walks you through a <strong>production-ready Python setup on Windows</strong>, starting from installation and verification to installing the exact libraries your automation needs. We’ll also cover common pitfalls, package fixes, and finally set up <strong>Windows Task Scheduler</strong> to run your Python scripts reliably in the background.</p><p>By the end of this article, you’ll have a <strong>stable, repeatable setup</strong> that just works — even after system restarts.</p><h3>Install and setup python</h3><h4>Step 1: Download Python Installer</h4><p>Go to the official Python website:<a href="https://www.python.org/downloads/windows/">https://www.python.org/downloads/windows/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*yn4rGCWGS2gHUKrvx5XSKg.png" /></figure><p>Click “Download Python” (or latest version)</p><h4>Step 2: Run the Installer (IMPORTANT SETTINGS)</h4><p>When the installer opens:</p><p>Check these boxes before clicking “Install”:</p><ul><li>Add Python to PATH (very important!)</li><li>Click Customize installation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*zITMkpzYkPvN6FPncimP7w.png" /></figure><p>Then, in the next screens:</p><ul><li>Keep everything checked</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*PzhJP1WjSJyn4XO8foHhyQ.png" /></figure><ul><li>Enable:<br> “Install for all users”<br> “Precompile standard library”</li><li>Choose install location: Example: C:\Python312 (or leave the default)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Wv1mXeud7dUazvdLIT97LA.png" /></figure><p>Click Install</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*xKizcfjg3jCMCW7-uMQtnA.png" /></figure><h4>Step 3: Verify Installation</h4><p>After install finishes:</p><p>Open Command Prompt</p><p>Run: <strong><em>where python</em></strong></p><p>You should now see something like:</p><p><strong><em>C:\Python312\python.exe</em></strong></p><p><strong><em>C:\Python312\Scripts\python.exe</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*vv5qS45aftOMf_AODQ2esA.png" /></figure><p>This means Python is now properly installed.</p><p>Install Necessary Modules</p><p>Run this in Command Prompt</p><p><strong><em>python -m pip install watchdog</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*bv52wrxBnjzkPvV5mzBSLg.png" /></figure><p>This ensures you’re installing watchdog into <strong>that exact Python</strong> which Task Scheduler is using.</p><p><strong><em>python -m pip install pandas</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*0OKSeJjy7xyMacIpJvhLtg.png" /></figure><p>Verify it is installed</p><p><strong><em>python -m pip show watchdog</em></strong></p><p>You should see:</p><p><strong><em>Name: watchdog</em></strong></p><p><strong><em>Version: x.y.z</em></strong></p><p><strong><em>Location: C:\Python312\Lib\site-packages</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*HDigy0nWcbsbq3QfA1cZCw.png" /></figure><p><strong><em>python -m pip show pandas</em></strong></p><p>You should see:</p><p><strong><em>Name: pandas</em></strong></p><p><strong><em>Version: x.y.z</em></strong></p><p><strong><em>Location: C:\Python312\Lib\site-packages</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*QJcjPh9x5HVhLjkhCxhTMw.png" /></figure><h3>Update the paths in Python File to Run the Script</h3><h4>Update the below path in the scripts</h4><p><strong>run_script.bat</strong></p><p><strong>@echo off</strong></p><p><strong>cd /d </strong>C:\Script</p><p><strong>echo Running script at %date% %time% &gt;&gt; run_script.log</strong></p><p><strong>python script.py &gt;&gt; run_script.log 2&gt;&amp;1</strong></p><p><strong>echo Finished at %date% %time% &gt;&gt; run_script.log</strong></p><h3>Set Up Task Scheduler on Windows</h3><h4>Open Task Scheduler</h4><ul><li>Press Win + R → type taskschd.msc → Enter</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*DiD0ma23iLm0AiA8SPSnjg.png" /></figure><h4>Create a New Task</h4><ul><li>In the right pane, click <strong>“Create Task…”</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*Y5it2rYpEKhSwBL6R8hq9g.png" /></figure><h4>General Tab</h4><ul><li><strong>Name</strong>: ScheduleScript</li><li><strong>Description</strong>: description</li><li><strong>Run whether user is logged on or not</strong></li><li><strong>Run with highest privileges</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*qicjYY-sIRP_4tkhou3rCw.png" /></figure><h4>Triggers Tab</h4><ul><li>Click <strong>New…</strong></li><li><strong>Begin the task</strong>: At startup</li><li><strong>Enabled</strong>: tick</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*PhHu89iKQBmbJ-h2RveKlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*OkZ288EwhtzqzZkJHQmeUg.png" /></figure><p>Click OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*ASPkzRnJ064bygHIabAsoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*t1l9KsM9-RQxovTwY3ScMw.png" /></figure><h4>Actions Tab</h4><ul><li>Click <strong>New…</strong></li><li><strong>Action</strong>: Start a program</li><li><strong>Program/script</strong>: C:\Path\To\Your\run_script.bat</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*mZNAvj3UKbUACgmRwUtY6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*1JE9Z4tlMWW_j-n_dEoEDA.png" /></figure><p>Click OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*00TE0LPaF70t6Iiy-hxgoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*6ix8zmFIpb7eVQdwSYejHw.png" /></figure><h4>Conditions Tab</h4><ul><li>Uncheck Start the task only if the computer is on AC power and Start the task only if idle</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*s84TdZJTkwLS7rJYieXZ2g.png" /></figure><h4>Settings Tab</h4><ul><li>Check:Allow task to be run on demand</li><li>Allow task to be run on demand</li><li>Restart if fails</li><li>If the task is already running, then the following rule applies: Do not start a new instance</li></ul><p>Click OK</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*P_c9_ahtV0IHE8lVLVCs_Q.png" /></figure><h4>Enter Admin Password (if prompted)</h4><p>Task will be saved and ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*4zg72uNoO9LJHOgywvN6kQ.png" /></figure><p>Restart the System</p><p>Setting up Python correctly on Windows is less about clicking “Install” and more about <strong>doing it the right way once</strong>.</p><p>In this guide, we:</p><ul><li>Installed Python with the correct PATH and system-wide settings</li><li>Ensured all required libraries were installed in the same Python environment</li><li>Fixed known package issues that can break automation</li><li>Configured Windows Task Scheduler for reliable, background execution</li></ul><p>This setup is ideal for <strong>data extraction jobs, monitoring scripts, ETL pipelines, and long-running background tasks</strong> that must run without manual intervention.</p><p>Once configured, you can focus on <strong>what your script does</strong>, not on why it stopped working.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4febdbc74fd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Data Ingestion on AWS: Build a Serverless Pipeline from S3 to RDS MySQL Using Lambda]]></title>
            <link>https://medium.com/@drishigupta/automating-data-ingestion-on-aws-build-a-serverless-pipeline-from-s3-to-rds-mysql-using-lambda-f9aee7419a67?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9aee7419a67</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rds]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 05:30:11 GMT</pubDate>
            <atom:updated>2025-10-03T05:30:11.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3BJdhtule2itD6-a" /></figure><p>In today’s data-driven world, automation has become the backbone of modern analytics and cloud infrastructure. Whether you’re building dashboards, machine learning pipelines, or data warehouses, the first and most critical step is <strong>getting your data in efficiently and securely</strong>.</p><p>In this article, we’ll walk through a <strong>step-by-step guide</strong> to building an <strong>automated data ingestion pipeline on AWS</strong> — one that fetches Excel files from Amazon S3, processes them with AWS Lambda, and loads the data directly into an Amazon RDS MySQL database. Along the way, you’ll also learn how to configure <strong>VPCs, subnets, security groups, and NAT gateways</strong> to ensure a secure and production-ready setup.</p><p>By the end, you’ll have a <strong>fully automated, serverless ingestion architecture</strong> that can scale, adapt, and keep your data flow running without manual intervention.</p><h3><strong>Step 1: Create an Amazon RDS MySQL Database</strong></h3><ul><li>Go to the <strong>AWS Management Console</strong> → <strong>RDS</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*RVFs0YTIDeB8KLpNxq3tSw.png" /></figure><ul><li>Click <strong>Create database</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*5ivzUMftJLc4FPnSY5FLoA.png" /></figure><ul><li>Select <strong>Standard create</strong>.</li><li>Engine options: Engine type: <strong>MySQL </strong>and<strong> </strong>Version: Choose the latest <strong>MySQL</strong> version.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*7Py45JncL9PexYticQF1Fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*oNg7yp-2vhTIcN_6hczkPw.png" /></figure><ul><li>Templates: Select <strong>Production</strong> or <strong>Dev/Test</strong> based on your needs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*zsuNt95yTwNmS4K6rm7Xfw.png" /></figure><ul><li>Settings: DB Instance Identifier: &lt;name of db instance&gt; Master username: dbuser and Master password: <strong>(Set a secure password)</strong></li><li>DB instance size: Choose an instance type based on your workload (e.g., <strong>t3.micro</strong> for testing).</li><li>Storage: Set required storage size (minimum 20GB).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*tAIkSPh3lPMF95jLPoc_PA.png" /></figure><ul><li>Connectivity: Virtual Private Cloud (VPC): <strong>Select your VPC</strong>.</li><li>Subnet group: <strong>Create a new subnet group or select an existing one</strong>.</li><li>Public access: <strong>No</strong> (for security).</li><li>VPC security group: <strong>Create or select an existing security group</strong>.</li><li>Additional Configuration: Initial database name: &lt;name of db&gt;</li><li>Click <strong>Create Database</strong>.</li></ul><h3>Steps to Launch an EC2 Instance as a Bastion Host for RDS Access</h3><p>Since your RDS instance is inside a <strong>VPC</strong>, you need an <strong>EC2 instance</strong> inside the same <strong>VPC &amp; subnet</strong> to act as a <strong>bastion host</strong>. You’ll connect to the EC2 instance via SSH and then connect to RDS from there.</p><h4>Step 1: Create an Internet Gateway (IGW)</h4><h4>Understanding Internet Gateway and Database Connectivity</h4><p>Why are we adding an Internet Gateway (IGW)?</p><p>An <strong>Internet Gateway (IGW)</strong> is required to provide internet access <strong>to instances inside a VPC</strong>. Without an IGW:</p><ul><li>Your <strong>EC2 instance will not have internet access</strong>.</li><li>You <strong>cannot SSH</strong> into the instance from your local machine.</li><li>You <strong>cannot connect</strong> to external services (e.g., downloading updates from the internet).</li></ul><p>Before launching the EC2 instance, ensure that your <strong>VPC has internet access</strong>.</p><ul><li>Go to <strong>AWS Console</strong> → <strong>VPC Dashboard</strong></li><li>Click <strong>Internet Gateways</strong> → <strong>Create Internet Gateway</strong></li><li>Enter a <strong>Name</strong></li><li>Click <strong>Create Internet Gateway</strong></li><li>Select the newly created <strong>Internet Gateway</strong></li><li>Click <strong>Actions</strong> → <strong>Attach to VPC</strong></li><li>Choose your <strong>VPC</strong> and click <strong>Attach</strong></li></ul><h3>Step 2: Update the Route Table</h3><p>To allow public internet access to your EC2 instance:</p><p>1️ Go to <strong>VPC Dashboard</strong> → <strong>Route Tables</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1XEByAtg-XnzXH1Y" /></figure><p>2️ Find the <strong>Route Table</strong> associated with your <strong>Public Subnet</strong></p><ul><li>If unsure, go to <strong>Subnets</strong> → Select your <strong>Public Subnet</strong> → Note the <strong>Route Table ID</strong></li></ul><p>3️ Click <strong>Routes</strong> → <strong>Edit Routes</strong></p><p>4️ Click <strong>Add Route</strong>:</p><ul><li><strong>Destination</strong>: 0.0.0.0/0</li><li><strong>Target</strong>: Select your <strong>Internet Gateway</strong></li></ul><p>5️ Click <strong>Save Changes</strong></p><h3>Key Pair in AWS EC2 (For SSH Access)</h3><p>A <strong>Key Pair</strong> is required to securely connect to your EC2 instance via <strong>SSH</strong>. It consists of:</p><ul><li><strong>Public Key</strong> (Stored on the EC2 instance)</li><li><strong>Private Key</strong> (You download and keep securely on your local machine)</li></ul><h3>Step 1: Launch an EC2 Instance</h3><p>1️ <strong>Go to AWS Console</strong> → Navigate to <strong>EC2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gi_QvXx7zuUKw_qP" /></figure><p>2️ Click <strong>Launch Instance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0L0IRDYBxs8le82" /></figure><p>3️ <strong>Set Instance Details</strong>:</p><ul><li><strong>Name</strong></li><li><strong>AMI</strong>: Choose <strong>Amazon Linux 2</strong> or <strong>Ubuntu</strong></li><li><strong>Instance Type</strong>: t2.micro (Free Tier)</li><li><strong>Key Pair</strong>: Select or create a new key pair (you’ll need this for SSH)</li></ul><p>4️ Set the following options:</p><ul><li><strong>Key pair name</strong></li><li><strong>Key pair type</strong>: RSA (default)</li><li><strong>Private key format</strong>: Choose <strong>.pem</strong> (for Linux/macOS)</li><li>Choose <strong>.ppk</strong> (for Windows PuTTY users)</li></ul><p>5️ Click <strong>Create Key Pair<br></strong>6️ <strong>Download the key file (.pem or .ppk) and keep it safe</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_nJEw-rBnnS0X8U-" /></figure><ul><li><strong>VPC</strong>: Choose the <strong>same VPC as RDS</strong></li><li><strong>Subnet</strong>: Choose a <strong>public subnet</strong> (important for internet access)</li><li><strong>Choose a Public Subnet instead of a Private Subnet.</strong></li></ul><p>Private subnets do not allow direct internet access.</p><p>A <strong>public subnet</strong> is required for a Bastion Host to allow external SSH access.</p><ul><li><strong>Ensure “Auto-Assign Public IP” is Enabled.</strong></li></ul><p>Public subnets allow EC2 instances to have public IPs for external access.</p><p>If the instance is in a <strong>private subnet</strong>, it will not get a public IP, and you won’t be able to SSH into it directly.</p><h3>How to Fix It:</h3><h4>Option 1: Select an Existing Public Subnet</h4><ul><li>When selecting a subnet, look for one named <strong>“Public_Subnet”</strong> or similar.</li><li>Confirm that the subnet’s <strong>Route Table</strong> is attached to an <strong>Internet Gateway</strong>.</li></ul><h4>Option 2: Create a New Public Subnet (If No Public Subnet Exists)</h4><ul><li><strong>Go to VPC Dashboard → Subnets → Create Subnet</strong></li><li>VPC</li><li>Subnet Name</li><li>CIDR Block: Choose a different range, e.g., 10.0.2.0/24</li><li><strong>Availability Zone:</strong> Choose the same as your private subnet.</li><li><strong>Auto-assign Public IP</strong>: Enabled (so you can connect to it)</li></ul><p><strong>Auto-assign Public IP</strong>: Enabled (so you can connect to it)</p><p><strong>Security Group (SG)</strong>:</p><p><strong>Allow SSH (port 22) from your IP</strong>:</p><ul><li><strong>Protocol</strong>: SSH</li><li><strong>Port Range</strong>: 22</li><li><strong>Source</strong>: My IP</li></ul><p><strong>Allow MySQL (port 3306) from EC2 to RDS</strong>:</p><ul><li><strong>Protocol</strong>: MySQL/Aurora</li><li><strong>Port Range</strong>: 3306</li><li><strong>Source</strong>: Select your <strong>RDS Security Group</strong></li></ul><h3>Step 6: Assign an Elastic IP</h3><p>1️ Go to <strong>EC2 Dashboard</strong> → <strong>Elastic IPs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZIrub8KVGcO1-GN" /></figure><p>2️ Click <strong>Allocate Elastic IP Address<br></strong> 3️ Click <strong>Allocate</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mRHnYAMTLj25R7m2" /></figure><p>4️ Select the allocated <strong>Elastic IP<br></strong> 5️ Click <strong>Associate Elastic IP Address<br></strong> 6️ Choose your <strong>EC2 instance<br></strong> 7️ Click <strong>Associate</strong></p><h3>Connect to the EC2</h3><ul><li><strong>Open PuTTY:</strong> Launch PuTTY.</li><li><strong>Go to SSH Authentication:</strong> Navigate to “Connection” -&gt; “SSH” -&gt; “Auth”.</li><li><strong>Select Private Key File:</strong> Click “Browse” and select the .ppk file you created in the previous step.</li><li><strong>Connect to the Instance:</strong> Enter the hostname or IP address of your AWS instance and click “Open”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*mg254X_83DqchWYO" /></figure><h3>Install MySQL Client on EC2</h3><p>Once connected to EC2, install the MySQL client:</p><h3>Step 1: Install MySQL Client</h3><p>Run the following command:</p><blockquote>sudo dnf install mariadb105 -yl</blockquote><p>This will install the MySQL client, allowing you to connect to your <strong>RDS MySQL database</strong>.</p><h3>Step 2: Verify Installation</h3><p>After installation, verify that MySQL client is installed by running:</p><blockquote>mysql — version</blockquote><h3>Step 4: Connect to RDS from EC2</h3><ul><li><strong>Get your RDS endpoint</strong> from AWS Console → RDS → Your DB → <strong>Connectivity &amp; Security</strong></li><li>Run this command on EC2 to connect to RDS:</li></ul><blockquote>mysql -h <strong>&lt;RDS-ENDPOINT&gt; </strong>-u user -p</blockquote><ul><li><strong>Replace &lt;RDS-ENDPOINT&gt;</strong> with your actual RDS endpoint</li><li><strong>Enter your MySQL password when prompted</strong></li></ul><h3>Step 5: Create the Database &amp; Schema in RDS</h3><p>Once connected to MySQL, run:</p><p>Run the following SQL command to check databases:</p><blockquote>SHOW DATABASES;</blockquote><blockquote>USE `db`;</blockquote><blockquote>CREATE SCHEMA schema;</blockquote><p>You now have a <strong>database and a schema </strong>inside RDS.</p><h3>Step 6: Verify Everything</h3><p>1 Check if the schema was created:</p><blockquote>SHOW SCHEMAS;</blockquote><blockquote>Create tables in schema</blockquote><blockquote>CREATE TABLE tests (</blockquote><blockquote>registration_date NVARCHAR(255),</blockquote><blockquote>test_name NVARCHAR(255),</blockquote><blockquote>result NVARCHAR(255)</blockquote><blockquote>);</blockquote><p>Exit MySQL:</p><blockquote>EXIT;</blockquote><h3>Step 3: Create an S3 Bucket for Data Storage</h3><ul><li>Go to <strong>AWS S3</strong>.</li><li>Click <strong>Create Bucket</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7rZ2wZ1d87aRUvWC" /></figure><ul><li>Set the bucket name:</li><li>Choose the same <strong>AWS region</strong> as your RDS and Lambda.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tRnuOe1_qZ1djpl3" /></figure><ul><li>Click <strong>Create Bucket</strong>.</li></ul><h3>Attach Lambda to the VPC</h3><ul><li>Go to <strong>AWS Lambda</strong>.</li><li>Click <strong>Create function</strong>.</li><li>Select <strong>Author from scratch</strong>.</li><li>Function name: upload-to-rds</li><li>Runtime: <strong>Python 3.x</strong>.</li><li>Permissions: Attach an <strong>IAM Role</strong> with permissions for <strong>S3, Lambda, and RDS</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ll1Y5E1MU0zQhDG_" /></figure><ul><li>In the <strong>VPC</strong> section:</li><li>Choose your <strong>VPC</strong>.</li><li>Select <strong>private subnets</strong> where RDS is located.</li><li>Attach a <strong>Security Group</strong> that allows access to RDS and S3.</li><li>Click <strong>Create Function</strong>.</li></ul><p>For your <strong>Lambda function</strong>, you should attach <strong>only the private subnets</strong> where your <strong>RDS instance is located</strong>.</p><h3>Here’s why:</h3><ol><li><strong>RDS is in a private subnet</strong> — To allow Lambda to connect to RDS, it should be in the same private subnet.</li><li><strong>Lambda doesn’t need a public IP</strong> — Since it will be interacting with RDS and S3 (which can be accessed through a VPC endpoint), it does not require internet access.</li><li><strong>NAT Gateway Consideration</strong> — If your Lambda function needs to access the internet (e.g., for downloading dependencies), the private subnet should be routed through a NAT Gateway in the public subnet.</li></ol><h3>Recommended Setup:</h3><ul><li><strong>Attach only private subnets</strong> to Lambda.</li><li><strong>Ensure proper security group rules</strong>:</li><li>Allow inbound connections from Lambda to RDS on the <strong>MySQL port (3306)</strong>.</li><li>Allow outbound access to <strong>S3 (if using VPC endpoints for S3)</strong>.</li></ul><p>If Lambda needs internet access (for external API calls or package installations), make sure the private subnet has a <strong>NAT Gateway</strong> configured in the public subnet.</p><h3>Step 5: Add an S3 Trigger to Lambda</h3><ul><li>Go to the <strong>Lambda function</strong>.</li><li>Click <strong>Add Trigger</strong> → <strong>Select S3</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s1hHkbAs2x4_gu16" /></figure><ul><li>Choose the <strong>bucket</strong>: my-data.</li><li>Event Type: <strong>PUT</strong> (Triggers when a file is uploaded).</li><li>Leave <strong>prefix empty</strong> (it will trigger for all folders).</li><li>Click <strong>Add</strong>.</li></ul><h3>Step 6: Write the Lambda Function</h3><p>The Lambda function will:</p><ul><li>Read the CSV from S3.</li><li>Create the table if it doesn’t exist.</li><li>Insert data into RDS.</li></ul><h3>Lambda Code (upload-to-rds)</h3><pre>import pymysql<br>import boto3<br>import pandas as pd<br>from io import BytesIO<br>import os<br><br># Configuration<br>RDS_CONFIG = {<br>&quot;host&quot;: &quot;&quot;,<br>&quot;user&quot;: &quot;&quot;,<br>&quot;password&quot;: &quot;&quot;,<br>&quot;database&quot;: &quot;&quot;,<br>&quot;port&quot;: 3306<br>}<br><br># Initialize clients<br>s3 = boto3.client(&#39;s3&#39;)<br><br>def connect_rds():<br>  &quot;&quot;&quot;Connect to MySQL RDS instance&quot;&quot;&quot;<br>  return pymysql.connect(<br>  cursorclass=pymysql.cursors.DictCursor,<br>  **RDS_CONFIG<br>  )<br><br>def process_excel(bucket, key):<br>    &quot;&quot;&quot;Process Excel file from S3&quot;&quot;&quot;<br>    response = s3.get_object(Bucket=bucket, Key=key)<br>    excel_file = BytesIO(response[&#39;Body&#39;].read())<br>    return pd.read_excel(excel_file, engine=&#39;openpyxl&#39;)<br>   <br>def insert_data(conn, table_name, data, headers):<br>    &quot;&quot;&quot;Insert data into RDS&quot;&quot;&quot;<br>    with conn.cursor() as cursor:<br>    placeholders = &#39;, &#39;.join([&#39;%s&#39;] * len(headers))<br>    query = f&quot;&quot;&quot;<br>    INSERT INTO {table_name} ({&#39;, &#39;.join(headers)})<br>    VALUES ({placeholders})<br>    &quot;&quot;&quot;<br>    for row in data:<br>        try:<br>        cursor.execute(query, row)<br>        except pymysql.Error as e:<br>        print(f&quot;Database error: {e}&quot;)<br>        continue<br>        def lambda_handler(event, context):<br>        for record in event[&#39;Records&#39;]:<br>        bucket = record[&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>        key = record[&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br>        print(f&quot;Processing {key} from {bucket}&quot;)<br>        try:<br>        # Determine file type<br>        file_ext = os.path.splitext(key)[1].lower()<br>        if file_ext not in (&#39;.xls&#39;, &#39;.xlsx&#39;):<br>        print(f&quot;Skipping non-Excel file: {key}&quot;)<br>        continue<br>        # Get table name from folder structure<br>        table_name = key.split(&#39;/&#39;)[0]<br>        # Process Excel file<br>        df = process_excel(bucket, key)<br>        headers = df.columns.tolist()<br>        data = [tuple(x) for x in df.to_records(index=False)]<br>        # Insert into RDS<br>        with connect_rds() as conn:<br>        insert_data(conn, table_name, data, headers)<br>        conn.commit()<br>        print(f&quot;Successfully processed Excel file: {key}&quot;)<br>        except Exception as e:<br>        print(f&quot;Error processing {key}: {str(e)}&quot;)<br>        raise<br>        return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: f&quot;Processed {len(event[&#39;Records&#39;])} Excel files&quot;<br>        }</pre><p>Check VPC Endpoints: Ensure you have a VPC endpoint for S3 configured in your VPC.</p><ul><li>Go to VPC Dashboard → Endpoints</li><li>Create an endpoint for S3 if it doesn’t exist</li><li>Type: Gateway</li></ul><p>Allow Outbound Traffic to S3 (HTTPS, Port 443):</p><ul><li>Type: HTTPS</li><li>Protocol: TCP</li><li>Port Range: 443</li><li>Destination: S3 Endpoint (You can use a VPC Endpoint for S3, or keep it as 0.0.0.0/0 if using NAT Gateway).</li></ul><p>Allow Outbound Traffic to RDS (MySQL, Port 3306):</p><ul><li>Type: MySQL/Aurora</li><li>Protocol: TCP</li><li>Port Range: 3306</li><li>Destination: RDS Security Group (Select the security group associated with your RDS instance).</li><li>Type: HTTP, Destination: 0.0.0.0/0</li></ul><p>Remove “All Traffic” Rule:</p><ul><li>Delete the existing “All Traffic” rule to restrict unnecessary access.</li></ul><h3>Steps to Update Security Group</h3><ul><li>Go to the AWS Management Console → EC2 → Security Groups.</li><li>Select the security group attached to your Lambda function.</li><li>Click on the Outbound Rules tab → Edit Rules.</li><li>Add the above rules and remove any unnecessary ones (like “All Traffic”).</li><li>Create a NAT Gateway:</li><li>Go to VPC Dashboard &gt; NAT Gateways &gt; Create NAT Gateway</li><li>Name: “Lambda-NAT”</li><li>Subnet: Choose your public subnet</li><li>Connectivity type: Public</li><li>Elastic IP allocation: Allocate Elastic IP</li></ul><h3>Create Route Tables</h3><ul><li>Go to VPC Dashboard &gt; Route Tables &gt; Create route table</li><li>Create two route tables: “Public-RT” and “Private-RT”</li><li>Associate “Public-RT” with the public subnet</li><li>Associate “Private-RT” with the private subnet</li><li>Configure Route Tables:</li><li>Public-RT:</li><li>Add route: Destination 0.0.0.0/0, Target Internet Gateway</li><li>Private-RT:</li><li>Add route: Destination 0.0.0.0/0, Target NAT Gateway</li></ul><h3>Create a Lambda Layer for PyMySQL</h3><ul><li>Install PyMySQL Locally:</li><li>Open your terminal and create a folder named python:</li></ul><blockquote>mkdir python</blockquote><ul><li>Install the pymysql library into the python folder:</li></ul><blockquote>pip install pymysql -t python</blockquote><ul><li>Package the Layer:</li><li>Compress the python folder into a .zip file</li></ul><blockquote>zip -r pymysql.zip python</blockquote><ul><li>Upload the Layer to AWS:</li><li>Go to the AWS Management Console → Lambda → Layers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6OG6C-bC3wzZ1Bt3" /></figure><ul><li>Click Create layer.</li><li>Provide a name (e.g., PyMySQLLayer), upload the pymysql.zip file, and choose compatible runtimes (e.g., Python 3.x).</li><li>Click Create.</li></ul><h3>Attach the Layer to Your Lambda Function</h3><ul><li>Navigate to your Lambda function in the AWS console.</li><li>Under the <em>Layers</em> section, click Add a layer.</li><li>Select your newly created layer (PyMySQLLayer) and save changes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BuunH9sifYjoL9e6" /></figure><p>With this setup, you now have a <strong>fully automated AWS data ingestion pipeline</strong> that securely moves Excel data from <strong>S3 to RDS MySQL</strong>, triggered seamlessly by <strong>AWS Lambda</strong>. This architecture not only eliminates manual effort but also enhances <strong>scalability, reliability, and security</strong> — key aspects of any modern cloud data solution.</p><p>From here, you can extend the pipeline to:</p><ul><li>Support <strong>CSV or JSON</strong> formats,</li><li>Incorporate <strong>data validation or transformation layers</strong>,</li><li>Connect with <strong>AWS Glue or Redshift</strong> for advanced analytics,</li><li>Or integrate monitoring through <strong>CloudWatch</strong>.</li></ul><p>Automation is not just about saving time — it’s about enabling consistency and freeing your team to focus on insights, not infrastructure. With this foundation, you’re well on your way to building robust, production-grade data workflows on AWS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9aee7419a67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Synchronization of SQLite Data from a Local Client to AWS]]></title>
            <link>https://medium.com/@drishigupta/real-time-synchronization-of-sqlite-data-from-a-local-client-to-aws-7b6a69cb381a?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6a69cb381a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 11:23:57 GMT</pubDate>
            <atom:updated>2025-06-16T11:23:57.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sYrEuu-WobR7Rju7MctqdQ.png" /></figure><p>To synchronize data from a local SQLite database on a client laptop to AWS in near real-time, a combination of change detection, data transfer, and automation techniques can be used. This article outlines various approaches for detecting new data in SQLite, transferring it to AWS, and automating the end-to-end pipeline.</p><h3>Detecting Changes in SQLite Database</h3><p>Since modifying the SQLite database schema or using database-level triggers is not feasible in many cases, especially when dealing with third-party systems or sensors, we explore three practical approaches for change detection.</p><h4>Option 1: SQLite Triggers with Audit Log (Not Feasible for Immutable DBs)</h4><p>This method involves creating an audit log table and using SQLite triggers to capture INSERT, UPDATE, and DELETE operations.</p><p><strong>Steps:</strong></p><ul><li>Create an audit_log table.</li><li>Use triggers to log each change to this table.</li><li>Sync the entries from audit_log to AWS.</li></ul><blockquote><strong><em>Limitation:</em></strong><em> This approach requires altering the database schema, which may not be possible in systems with fixed DB structures.</em></blockquote><h4>Option 2: Event-Based Monitoring Using Watchdog</h4><p>Use Python’s watchdog library to listen for file changes in the .db file. This script is event-driven and activates only when the database is modified.</p><p><strong>How It Works:</strong></p><ul><li>Monitors the .db file for any changes.</li><li>On modification, fetches new records based on the last processed ID.</li><li>Stores the last processed ID locally to prevent duplicates.</li><li>Sends the new data to AWS (e.g., S3, RDS, API Gateway).</li></ul><p><strong>Pros:</strong></p><ul><li>Real-time detection.</li><li>Low CPU usage.</li><li>Efficient, as it only runs on actual changes.</li></ul><p><strong>Cons:</strong></p><ul><li>Relies on OS-level file monitoring.</li><li>May miss subtle or optimized writes (e.g., journal mode in SQLite).</li></ul><h4>Option 3: Polling for Changes at Intervals</h4><p>If event-based monitoring proves unreliable, periodic polling is a reliable fallback. The script queries the database at fixed intervals (e.g., every 5 seconds) to check for new data.</p><p><strong>How It Works:</strong></p><ul><li>Runs a loop to check for new records.</li><li>Compares the latest row ID with the last known ID.</li><li>Stores and updates the last ID to prevent duplicates.</li><li>Sends data to AWS.</li></ul><p><strong>Pros:</strong></p><ul><li>Guaranteed detection.</li><li>Independent of file system behavior.</li><li>Simple and easy to implement.</li></ul><p><strong>Cons:</strong></p><ul><li>Slight delay based on polling interval.</li><li>Higher CPU usage due to frequent checks.</li><li>Redundant reads when no new data exists.</li></ul><h3>Transferring Data to AWS</h3><p>Once new data is identified, it needs to be sent to AWS for further processing and storage. Here are three practical methods:</p><h4>Option 1: S3 + Lambda (Recommended for Batches)</h4><p>Upload the extracted data (in CSV or JSON) to an S3 bucket and use S3 event triggers to invoke a Lambda function that loads the data into AWS RDS or DynamoDB.</p><p><strong>Steps:</strong></p><ol><li>Extract new records as CSV/JSON.</li><li>Upload to an S3 bucket.</li><li>Use S3 event notifications to trigger a Lambda function.</li><li>Lambda parses and inserts the data into RDS or DynamoDB.</li></ol><p><strong>Use Case:</strong> Cost-effective for batch uploads and serverless workflows.</p><h4>Option 2: AWS IoT Core (Not Feasible without IoT Device)</h4><p>If the device supports IoT protocols, data can be published using MQTT to AWS IoT Core, which can trigger a Lambda for ingestion.</p><blockquote><strong><em>Limitation:</em></strong><em> Only viable if the source data is IoT-enabled, which is not the case here.</em></blockquote><h4>Option 3: Direct API Push via API Gateway + Lambda</h4><p>Build a REST API using AWS API Gateway, which invokes a Lambda function to store the data. The local script sends real-time updates to this endpoint.</p><p><strong>Steps:</strong></p><ol><li>Create an API using AWS API Gateway + Lambda.</li><li>Local script pushes new records as JSON.</li><li>Lambda inserts the records into RDS or DynamoDB.</li></ol><p><strong>Use Case:</strong> Ideal for real-time, low-latency data transmission.</p><h3>Automating and Optimizing the Pipeline</h3><p>To ensure consistent and reliable execution, the data extraction and transfer script should run automatically.</p><h4>Automation on Local Machine</h4><ul><li><strong>Option 1: Cron Job (Linux/macOS):</strong> Schedule the script to run at regular intervals (e.g., every 5 minutes).</li><li><strong>Option 2: systemd Service:</strong> For continuous background execution, systemd provides robust service management.</li></ul><h4>AWS-Side Optimization</h4><p>For further processing and transformation, AWS provides services tailored to both batch and real-time needs.</p><p><strong>Option 1: AWS Glue (Batch ETL)</strong></p><ul><li>Extracted data is uploaded to S3.</li><li>AWS Glue jobs read and transform the data.</li><li>Output is stored in RDS or DynamoDB.</li></ul><p><strong>Option 2: AWS Kinesis (Real-Time Streaming)</strong></p><ul><li>The local script pushes new records to Kinesis Data Streams.</li><li>A Lambda function reads from Kinesis and writes to RDS/DynamoDB.</li></ul><h3>Final Thoughts</h3><p>For real-time or near-real-time synchronization of local SQLite databases with AWS, a hybrid strategy of periodic polling (or event-based detection) and serverless processing on AWS offers a scalable, cost-efficient solution. Choose between batch (S3 + Glue) or real-time (API Gateway/Kinesis) integration depending on your latency and data volume requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6a69cb381a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Setting Up and Running Apache Kafka on Windows OS]]></title>
            <link>https://medium.com/@drishigupta/comprehensive-guide-to-setting-up-and-running-apache-kafka-on-windows-os-5dbe834df955?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dbe834df955</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 11:13:48 GMT</pubDate>
            <atom:updated>2025-04-24T11:13:48.265Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setting Up and Running Apache Kafka on Windows OS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MURGA7GGGCiDgcmL" /></figure><p>Apache Kafka is a distributed streaming platform, and setting it up on Windows requires specific steps. Follow this guide carefully to ensure proper installation and setup.</p><p><strong>Step 1:</strong>Check if the Java has been installed successfully on your system by running the below command</p><pre>java -version</pre><p>If your command prompt somewhat looks like the image above, you are good to go. Otherwise, you need to recheck whether your setup version matches the correct OS architecture (x86, x64), or if the environment variables path is correct.</p><p>Please find the below output for the reference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*XGFeYGMbRp557bnV" /></figure><p><strong>Step 2</strong>: Download Server JRE according to your OS and CPU architecture</p><p>Navigate to <a href="https://www.oracle.com/in/java/technologies/downloads/">https://www.oracle.com/in/java/technologies/downloads/</a> and <a href="https://www.java.com/en/download/manual.jsp">https://www.java.com/en/download/manual.jsp</a> and select the java version as per your requirements</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMNFKsu-iz3X2h25X2h2UQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*eCxXsgfWSIbJ4rDeICyebg.png" /></figure><p><strong>Step 3: </strong>Setup JRE</p><p>Change the installation directory to any path without spaces in the folder name. E.g. C:\Java\jre1.8.0_xx\. (By default it will be C:\Program Files\Java\jre1.8.0_xx), then click ‘Next.’</p><p><strong>If we don’t change the path we will get the error “<em>\Java\jre1.8.0_231 was unexpected at this time</em>.” while running zookeeper</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*mVEk9iOcpTwIYlGSMTD8GA.png" /></figure><p><strong>Step 4: </strong>Setting up the system environment variables</p><p>Set a variable “<em>JAVA_HOME</em>” with the value as “path to java directory till JRE”.By default it will be C:\Program Files\Java\jre1.8.0_xx</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jm4mmz8Tb7iKKxTQ" /></figure><p><strong>Step 5:</strong>Edit the path in system environment variables</p><p>Search for a Path variable in the “System Variable” section in the “Environment Variables” dialogue box you just opened. Edit the path and add “%JAVA_HOME%\bin” at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eqeNVSb2vO4tZvHX" /></figure><p><strong>Step 6: </strong>Download and extract ZooKeeper using 7-zip from <a href="http://zookeeper.apache.org/releases.html">http://zookeeper.apache.org/releases.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNEqOwGoIY1xm8749URI8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HioCjEoLbcHIJG7AOO9kcg.png" /></figure><p><strong>Step 7:</strong> Go to your ZooKeeper config directory and make the below changes</p><ul><li>Go to your ZooKeeper config directory and rename file “zoo_sample.cfg” to “<em>zoo.cfg”</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXp1syVAg9brJe-0lJBDIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pT-4jeSzxQR4yg1-DFkHUw.png" /></figure><ul><li>Open zoo.cfg in any text editor. Find and edit dataDir=/tmp/zookeeper to &lt;path to zookeeper&gt;\data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*hLhMRYJca715YAqh" /></figure><p><strong>Step 8 : </strong>Add an entry in the System Environment Variables as we did for Java</p><p>Add ZOOKEEPER_HOME = C:\zookeeper-3.4.7 to the System Variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FUF9E2QdgxlMCYWM" /></figure><p>Edit the System Variable named “Path” and add %ZOOKEEPER_HOME%\bin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WFStGYyaxXWmPvi5" /></figure><p><strong>Step 9(optional) : </strong>You can change the default Zookeeper port in zoo.cfg file (Default port 2181).</p><p><strong>Step 10: </strong>Run ZooKeeper by opening a new cmd and type zkserver.</p><p>You will see the command prompt with some details, like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wah-NNvbNsrp0rJp" /></figure><p><strong>Step 11: </strong>Download and unzip the kafka from <a href="http://kafka.apache.org/downloads.html">http://kafka.apache.org/downloads.html</a>.</p><ul><li><strong><em>Download kafka version 2.11 or less.Only these versions are compatible with windows otherwise while running Kafka you can face the issues.</em></strong></li><li><strong><em>Unzip the file and don’t keep the folder’s name too big otherwise while starting the kafka an error “the input line is too long. the syntax of the command is incorrect” is observed</em></strong></li></ul><p><strong>Step 12</strong>: Set the properties in the config directory</p><ul><li>Go to your Kafka config directory.</li><li>Edit the file “server.properties.”</li><li>Find and edit the line<em> </em>log.dirs=/tmp/kafka-logs” to “log.dir= C:\kafka_2.11–0.9.0.0\kafka-logs<em>.</em></li></ul><p>If your ZooKeeper is running on some other machine or cluster you can edit <em>“zookeeper.connect:2181”</em> to your custom IP and port. For this demo, we are using the same machine so there’s no need to change. Also the Kafka port and broker.id are configurable in this file. Leave other settings as is.</p><p>Your Kafka will run on default port 9092 and connect to ZooKeeper’s default port 2181.</p><p><strong>Step 13: </strong>Running a Kafka Server</p><p><strong><em>Important: Please ensure that your ZooKeeper instance is up and running before starting a Kafka server.</em></strong></p><ul><li>Go to your Kafka installation directory: <em>C:\kafka_2.11–0.9.0.0\</em></li><li>Open a command prompt here</li><li>Now type kafka-server-start.bat ../../config/server.properties and press Enter.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4sUXqo2MysGZKZzI" /></figure><p><strong>Please find the resolutions for the errors (if faced) while running kafka</strong></p><p><strong>Error 1: <em>the input line is too long. the syntax of the command is incorrect</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_-ExsYer7WeJ4JCC" /></figure><p><strong><em>Resolution : Don’t keep the folder’s name too big</em></strong></p><p><strong>Error 2: missing `server’ JVM at `C:\java\jre\bin\server\jvm.dll’.</strong></p><p><strong>Please install or use the JRE or JDK that contains these missing components.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/0*02PNOkDN7dWcTl2u" /></figure><p><strong><em>Resolution : Change the Java home path from JRE to JDK and restart the system</em></strong></p><p><strong>Error 3: Disk error while writing log start offsets checkpoint in directory C:\kafka\kafkakafka-logs: Error while writing to checkpoint file C:\kafka\kafkakafka-logs\log-start-offset-checkpoint</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ry9VgPwzGYiV2XbE" /></figure><p><strong><em>Resolution : Windows doesn’t support kafka version 2.13 and 2.12,Try installing the kafka version 2.11 or less and you should not face the above issue.</em></strong></p><p><strong>Step 14:</strong> Creating Topics</p><p>Now create a topic with the name <em>“test”</em> and a replication factor of 1, as we have only one Kafka server running. If you have a cluster with more than one Kafka server running, you can increase the replication-factor accordingly, which will increase the data availability and act like a fault-tolerant system.</p><ul><li>Open a new command prompt in the locatio <em>C:\kafka_2.11–0.9.0.0\bin\windows.</em></li><li>Type the following command and hit Enter</li></ul><p><em>Command:kafka-topics.bat — create — zookeeper localhost:2181 — replication-factor 1 — partitions 1 — topic test</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aOCncfyPl5Xr_rR2" /></figure><p><strong>Step 15:</strong> Creating a Producer and Consumer to Test Server</p><ul><li>Open a new command prompt in the location where you have place kafka folder for eg: <em>C:\kafka_2.11–0.9.0.0\bin\windows</em></li><li>To start a producer type the following command:</li></ul><pre>kafka-console-producer.bat — broker-list localhost:9092 — topic test</pre><ul><li>Again open a new command prompt in the same location as <em>C:\kafka_2.11–0.9.0.0\bin\windows</em></li><li>Now start a consumer by typing the following command:</li></ul><p>Before kafka version 2.0 (&lt;2.0)</p><pre>kafka-console-consumer.bat — zookeeper localhost:2181 — topic test</pre><p>After kafka version 2.0 (&gt;= 2.0):</p><pre>kafka-console-consumer.bat — bootstrap-server localhost:9092 — topic test</pre><p>Now you will have two command prompt then try sending some message from producer to consumer like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/0*MM9juVocoUc013Lq" /></figure><p>If you are getting the output in consumer from the producer then your kafka is working as expected.</p><p>With these steps completed, your Apache Kafka setup on Windows OS should be fully functional. Enjoy streaming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dbe834df955" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Great Expectations in Action: Building a Custom Expectation for Data Consistency]]></title>
            <link>https://medium.com/@drishigupta/great-expectations-in-action-building-a-custom-expectation-for-data-consistency-2c71899a8364?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c71899a8364</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[great-expectations]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 07:21:05 GMT</pubDate>
            <atom:updated>2025-02-10T07:21:05.077Z</atom:updated>
            <content:encoded><![CDATA[<h4>Custom Expectation — Great Expectation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*zKlZfdofPukO-lkWiunm_A.png" /></figure><h3>Overview of Great Expectations</h3><p>Great Expectations (GE) is an open-source framework designed for data quality checks. It enables users to define expectations about their data, validate these expectations, and generate documentation. While GE includes many built-in expectations, it also allows users to create custom ones tailored to specific needs. This article focuses on building custom expectations to ensure data consistency in SQL databases.</p><h3>Sample Data</h3><p>The article uses a sample dataset with the following schema:</p><h4>Create Statement</h4><pre>CREATE TABLE `sample_data_university` (<br>  `National_Identification_Number` int DEFAULT NULL,<br>  `Sex` text,<br>  `the_college` text,<br>  `Specialization` text,<br>  `Degree` text,<br>  `Cumulative_average` double DEFAULT NULL,<br>  `Student_appreciation` text,<br>  `school_system` text,<br>  `Start_date_of_the_first_semester` text,<br>  `Graduation_Date` text,<br>  `Graduation_class` int DEFAULT NULL,<br>  `University_name` text<br>)<br><br>CREATE TABLE table1 (<br>    id INT PRIMARY KEY,<br>    date DATE<br>);<br><br>CREATE TABLE table2 (<br>    id INT PRIMARY KEY,<br>    date DATE<br>);</pre><h4>Insert Statement</h4><pre>INSERT INTO `sample_db`.`sample_data_university`<br>(`National_Identification_Number`,<br>`Sex`,<br>`the_college`,<br>`Specialization`,<br>`Degree`,<br>`Cumulative_average`,<br>`Student_appreciation`,<br>`school_system`,<br>`Start_date_of_the_first_semester`,<br>`Graduation_Date`,<br>`Graduation_class`,<br>`University_name`)<br>VALUES<br>(&lt;{National_Identification_Number: }&gt;,<br>&lt;{Sex: }&gt;,<br>&lt;{the_college: }&gt;,<br>&lt;{Specialization: }&gt;,<br>&lt;{Degree: }&gt;,<br>&lt;{Cumulative_average: }&gt;,<br>&lt;{Student_appreciation: }&gt;,<br>&lt;{school_system: }&gt;,<br>&lt;{Start_date_of_the_first_semester: }&gt;,<br>&lt;{Graduation_Date: }&gt;,<br>&lt;{Graduation_class: }&gt;,<br>&lt;{University_name: }&gt;);<br><br><br>INSERT INTO table1 (id, date) VALUES<br>(1, &#39;2024-01-01&#39;),<br>(2, &#39;2024-02-01&#39;),<br>(3, &#39;2024-03-01&#39;);<br><br>INSERT INTO table2 (id, date) VALUES<br>(1, &#39;2024-01-01&#39;),<br>(2, &#39;2024-02-02&#39;),  -- This date is different from table1 for id 2<br>(3, &#39;2024-03-01&#39;); <br></pre><h4>Custom Expectation: Consistency Across Groups</h4><p>The first custom expectation ensures that column values are consistent across grouped records.</p><p><strong>SQL Query</strong></p><pre>Select col1,count(distinct col1) from table group by col1 having count(*)&gt;1</pre><p><strong>Expectation</strong> <strong>Code</strong></p><pre>from typing import Dict, Optional<br>import sqlalchemy as sa<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from great_expectations.execution_engine import (<br>    ExecutionEngine,<br>)<br>from great_expectations.expectations.registry import (<br>    register_expectation,<br>    register_metric,<br>)<br>from great_expectations.validator.metric_configuration import MetricConfiguration<br>from great_expectations.validator.validator import ValidationDependencies<br>from great_expectations.expectations.expectation import (<br>    InvalidExpectationConfigurationError,<br>    ColumnExpectation,<br>)<br>from great_expectations.execution_engine import SqlAlchemyExecutionEngine<br>from great_expectations.expectations.metrics.metric_provider import metric_value, MetricProvider<br><br>class ColumnDistinctValuesByGroup(MetricProvider):<br>    &quot;&quot;&quot;<br>    This metric calculates the distinct values for each group.<br>    &quot;&quot;&quot;<br><br>    metric_name = &quot;column.distinct_values_by_group&quot;<br><br>    @metric_value(engine=SqlAlchemyExecutionEngine)<br>    def _sqlalchemy(cls, metrics, **kwargs):<br>        column = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;column&#39;)<br>        groupby = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;groupby&#39;)<br>        table = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;table&#39;)  # Get the table name from metric_domain_kwargs<br>        batch_identifiers = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;batch_identifiers&#39;)<br>        if column is None or groupby is None or table is None:<br>            raise ValueError(&quot;Both &#39;column&#39;, &#39;groupby&#39;, and &#39;table&#39; must be provided&quot;)<br>        groupby_columns = [sa.column(g) for g in groupby]<br><br>        agg_func = sa.func.group_concat(sa.distinct(sa.column(column))).label(&#39;distinct_values&#39;)<br>        # Use group_concat to get distinct values<br><br>        query = (<br>            sa.select(*groupby_columns, agg_func)  # Use * to unpack the list of groupby_columns<br>            .select_from(sa.table(table))  # Use the dynamic table name<br>        )<br><br>        if batch_identifiers:<br>            for key, value in batch_identifiers.items():<br>                query = query.where(sa.text(value))<br><br>        query = query.group_by(*groupby_columns)<br><br>        return query<br><br><br>register_metric(<br>    metric_name=ColumnDistinctValuesByGroup.metric_name,<br>    metric_domain_keys=(&quot;column&quot;, &quot;groupby&quot;),<br>    metric_value_keys=(&quot;sqlalchemy&quot;,),<br>    execution_engine=SqlAlchemyExecutionEngine,<br>    metric_class=ColumnDistinctValuesByGroup,<br>    metric_provider=ColumnDistinctValuesByGroup._sqlalchemy<br>)<br><br><br>class ExpectColumnValuesToBeConsistentByGroup(ColumnExpectation):<br>    &quot;&quot;&quot;<br>    This expectation checks if column values are consistent across records for each group.<br>    &quot;&quot;&quot;<br><br>    library_metadata = {<br>        &quot;maturity&quot;: &quot;Experimental&quot;,<br>        &quot;package&quot;: &quot;great_expectations_experimental&quot;,<br>        &quot;tags&quot;: [&quot;experimental&quot;],<br>        &quot;contributors&quot;: [&quot;@drishi_gupta&quot;],<br>    }<br><br>    @classmethod<br>    def from_config(cls, config, **kwargs):<br>        return cls(configuration=config)<br><br>    def get_validation_dependencies(<br>            self,<br>            configuration: Optional[ExpectationConfiguration] = None,<br>            execution_engine: Optional[ExecutionEngine] = None,<br>            runtime_configuration: Optional[dict] = None,<br>    ) -&gt; ValidationDependencies:<br>        dependencies = super().get_validation_dependencies(<br>            configuration, execution_engine, runtime_configuration<br>        )<br>        column = configuration.kwargs.get(&quot;column&quot;)<br>        groupby = configuration.kwargs.get(&quot;groupby&quot;)<br>        table = configuration.kwargs.get(&quot;table&quot;)<br>        batch_identifiers = configuration.kwargs.get(&quot;batch_identifiers&quot;)<br>        if not groupby:<br>            raise InvalidExpectationConfigurationError(<br>                &quot;groupby must be provided&quot;<br>            )<br>        if not table:<br>            raise InvalidExpectationConfigurationError(&quot;table must be provided&quot;)<br>        if not column:<br>            raise InvalidExpectationConfigurationError(&quot;column must be provided&quot;)<br>        metric_configuration = MetricConfiguration(<br>            &quot;column.distinct_values_by_group&quot;,<br>            metric_domain_kwargs={&quot;column&quot;: column, &quot;groupby&quot;: groupby, &quot;table&quot;: table,<br>                                  &quot;batch_identifiers&quot;: batch_identifiers},<br>        )<br>        dependencies.metric_configurations[<br>            &quot;column.distinct_values_by_group&quot;<br>        ] = metric_configuration<br>        return dependencies<br><br>    @classmethod<br>    def _validate(<br>            self,<br>            configuration: dict,<br>            metrics: Dict,<br>            runtime_configuration: dict = None,<br>            execution_engine: ExecutionEngine = None,<br>    ):<br>        groups = []<br>        distinct_value = []<br>        query = metrics[&quot;column.distinct_values_by_group&quot;]<br>        result = execution_engine.execute_query(query).fetchall()<br>        distinct_values_by_group = {row[0]: set(row[1].split(&#39;,&#39;)) for row in result}<br>        for group, distinct_values in distinct_values_by_group.items():<br>            if len(distinct_values) &gt; 1:<br>                groups.append(group)<br>                distinct_value.append(list(distinct_values))<br>        if len(distinct_value) &gt;= 1 and len(groups) &gt;= 1:<br>            return {<br>                &quot;success&quot;: False,<br>                &quot;result&quot;: {<br>                    &quot;unexpected_index_list&quot;: groups,<br>                    &quot;unexpected_list&quot;: distinct_value,<br>                },<br>            }<br>        else:<br>            return {&quot;success&quot;: True}<br><br><br>register_expectation(ExpectColumnValuesToBeConsistentByGroup)</pre><p>This Python code is part of a data validation framework called Great Expectations. It defines a custom metric and a custom expectation that work with SQL databases via SQLAlchemy.</p><p>The `ColumnDistinctValuesByGroup` class is a custom metric provider. It calculates the distinct values for each group in a given column of a table. The `_sqlalchemy` method builds a SQL query to get the distinct values for each group.</p><p>The `ExpectColumnValuesToBeConsistentByGroup` class is a custom expectation. It checks if column values are consistent across records for each group. The `_validate` method executes the SQL query built by the `ColumnDistinctValuesByGroup` metric provider and checks if there are any groups with more than one distinct value. If such groups exist, the expectation fails.</p><p>Both the metric provider and the expectation are registered with Great Expectations using the `register_metric` and `register_expectation` functions, respectively. This makes them available for use in data validation.</p><p>The code uses several concepts from Great Expectations, including:</p><ul><li><strong>MetricProvider</strong>: A class that calculates a metric.</li><li><strong>ColumnExpectation</strong>: A class that defines an expectation for a column.</li><li><strong>ExpectationConfiguration</strong>: A class that holds the configuration for an expectation.</li><li><strong>MetricConfiguration</strong>: A class that holds the configuration for a metric.</li><li><strong>ValidationDependencies</strong>: A class that holds the dependencies for a validation.</li><li><strong>SqlAlchemyExecutionEngine</strong>: A class that executes SQL queries using SQLAlchemy.</li><li><strong>register_metric </strong>and <strong>register_expectation</strong>: Functions that register a metric provider and an expectation, respectively.</li></ul><p><strong>Validator Code (on full table):</strong></p><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from plugins.expectations.consistency import ExpectColumnValuesToBeConsistentByGroup<br><br># Get the context<br>context = ge.get_context()<br><br># Define your datasources<br>datasource_name = &quot;sample_data_university&quot;<br># Define your assets<br>asset_name = &quot;sample_data_university_asset&quot;<br># Get the datasource<br>datasource = context.get_datasource(datasource_name)<br># Get the asset<br>datasource_asset = datasource.get_asset(asset_name=asset_name)<br><br># Build the batch request<br>datasource_batch_request = datasource_asset.build_batch_request()<br><br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;university&quot;)<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>   expectation_type=&quot;expect_column_values_to_be_consistent_by_group&quot;,<br>   kwargs={<br>       &quot;groupby&quot;:[&quot;National_Identification_Number&quot;],<br>       &quot;column&quot;:&quot;sex&quot;,<br>       &quot;table&quot;:&quot;sample_data_university&quot;<br>   },<br>)<br>suite.add_expectation(expectation_config)<br><br>context._save_expectation_suite(expectation_suite_name=&quot;university&quot;, expectation_suite=suite)<br><br># Get the validator<br>validator = context.get_validator(<br>   batch_request=datasource_batch_request,<br>   expectation_suite_name=&quot;university&quot;,<br>)<br>print(validator.head(100))<br><br>res = validator.validate()<br><br># Save the expectation suite<br>validator.save_expectation_suite(discard_failed_expectations=False)<br># Define the checkpoint configuration<br>checkpoint_config = {<br>    &quot;class_name&quot;: &quot;SimpleCheckpoint&quot;,<br>    &quot;validations&quot;: [<br>        {<br>            &quot;batch_request&quot;: datasource_batch_request,<br>            &quot;expectation_suite_name&quot;: &quot;university&quot;<br>        }<br>    ]<br>}<br># Add or update the checkpoint<br>checkpoint_name = &quot;my_checkpoint&quot;<br>context.add_or_update_checkpoint(name=checkpoint_name, **checkpoint_config)<br># Run the checkpoint<br>checkpoint_result = context.run_checkpoint(checkpoint_name)<br># Build data docs<br>context.build_data_docs()</pre><p>This Python code is using the Great Expectations library to validate data. Here’s a brief explanation of what each part does:</p><ul><li><strong>Import necessary libraries</strong>: The code imports the necessary libraries and modules, including Great Expectations and a custom expectation ExpectColumnValuesToBeConsistentByGroup.</li><li><strong>Get the Great Expectations context</strong>: The get_context function is used to get the current Great Expectations context.</li><li><strong>Define the datasource and asset</strong>: The code defines the datasource and asset names.</li><li><strong>Get the datasource and asset</strong>: The code retrieves a datasource and an asset from the context.</li><li><strong>Build the batch request</strong>: The code builds a batch request for the datasource asset.</li><li><strong>Add or update the expectation suite</strong>: The code adds or updates an expectation suite in the context.</li><li><strong>Define the custom expectation configuration</strong>: The code defines a custom expectation configuration and adds it to the suite.</li><li><strong>Save the expectation suite</strong>: The code saves the updated expectation suite to the context.</li><li><strong>Get the validator</strong>: The code gets a validator for the batch request and the expectation suite.</li><li><strong>Print the head of the validator</strong>: The code prints the first 100 records of the batch that the validator will validate.</li><li><strong>Validate the data</strong>: The code validates the data using the validator.</li><li><strong>Save the expectation suite</strong>: The code saves the expectation suite after validation.</li><li><strong>Define the checkpoint configuration</strong>: The code defines a checkpoint configuration. A checkpoint is a list of validations to run.</li><li><strong>Add or update the checkpoint</strong>: The code adds or updates the checkpoint in the context.</li><li><strong>Run the checkpoint</strong>: The code runs the checkpoint, which will validate the data again.</li><li><strong>Build data docs</strong>: The code builds data docs, which are a visual representation of the validation results.</li></ul><p><strong>Validator Code (on filtered data):</strong></p><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.batch import BatchRequest<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from plugins.expectations.consistency import ExpectColumnValuesToBeConsistentByGroup<br><br>import pandas as pd<br><br># Set the maximum number of columns to display<br>pd.set_option(&#39;display.max_columns&#39;, None)<br><br># Set the maximum width of each column<br>pd.set_option(&#39;display.max_colwidth&#39;, None)<br><br>context = ge.get_context()<br>datasource_name = &quot;sample_data_university_batches&quot;<br>asset_name = &quot;sample_data_university_batches_asset&quot;<br><br># Get the datasource<br>datasource = context.get_datasource(datasource_name)<br># Get the asset<br>datasource_asset = datasource.get_asset(asset_name=asset_name)<br><br># Add the splitter and sorters<br>datasource_asset.add_splitter_year_and_month(column_name=&quot;Graduation_Date&quot;)<br><br># Build the batch request<br>datasource_batch_request = datasource_asset.build_batch_request(options= {&quot;year&quot;: 2007})<br><br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;university_batches&quot;)<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>   expectation_type=&quot;expect_column_values_to_be_consistent_by_group&quot;,<br>   kwargs={<br>       &quot;groupby&quot;:[&quot;National_Identification_Number&quot;],<br>       &quot;column&quot;:&quot;sex&quot;,<br>       &quot;table&quot;:&quot;sample_data_university&quot;,<br>       &quot;batch_identifiers&quot;: {&quot;Graduation_Date&quot;: &quot;YEAR(Graduation_Date) = 2007&quot;}<br>   },<br>)<br>suite.add_expectation(expectation_config)<br><br>context._save_expectation_suite(expectation_suite_name=&quot;university_batches&quot;, expectation_suite=suite)<br><br># Get the validator<br>validator = context.get_validator(<br>   batch_request=datasource_batch_request,<br>   expectation_suite_name=&quot;university_batches&quot;,<br>)<br><br>print(validator.head())<br><br>res = validator.validate()<br><br># Save the expectation suite<br>validator.save_expectation_suite(discard_failed_expectations=False)<br># Define the checkpoint configuration<br>checkpoint_config = {<br>    &quot;class_name&quot;: &quot;SimpleCheckpoint&quot;,<br>    &quot;validations&quot;: [<br>        {<br>            &quot;batch_request&quot;: datasource_batch_request,<br>            &quot;expectation_suite_name&quot;: &quot;university_batches&quot;<br>        }<br>    ]<br>}<br># Add or update the checkpoint<br>checkpoint_name = &quot;my_checkpoint&quot;<br>context.add_or_update_checkpoint(name=checkpoint_name, **checkpoint_config)<br># Run the checkpoint<br>checkpoint_result = context.run_checkpoint(checkpoint_name)<br># Build data docs<br>context.build_data_docs()</pre><p>This Python code is using the Great Expectations library to validate data. Here’s a brief explanation of what each part does:</p><ul><li><strong>Import necessary libraries</strong>: The code imports the necessary libraries and modules, including Great Expectations and a custom expectation `ExpectColumnValuesToBeConsistentByGroup`.</li><li><strong>Set pandas display options</strong>: The code sets the maximum number of columns to display and the maximum width of each column in pandas.</li><li><strong>Get the Great Expectations context</strong>: The `get_context` function is used to get the current Great Expectations context.</li><li><strong>Get the datasource and asset</strong>: The code retrieves a datasource and an asset from the context.</li><li><strong>Add the splitter and sorters</strong>: The code adds a splitter to the asset.</li><li><strong>Build the batch request</strong>: The code builds a batch request for the datasource asset.</li><li><strong>Add or update the expectation suite</strong>: The code adds or updates an expectation suite in the context.</li><li><strong>Define the custom expectation configuration</strong>: The code defines a custom expectation configuration and adds it to the suite.</li><li><strong>Save the expectation suite</strong>: The code saves the updated expectation suite to the context.</li><li><strong>Get the validator</strong>: The code gets a validator for the batch request and the expectation suite.</li><li><strong>Print the head of the validator</strong>: The code prints the first few records of the batch that the validator will validate.</li><li><strong>Validate the data</strong>: The code validates the data using the validator.</li><li><strong>Save the expectation suite</strong>: The code saves the expectation suite after validation.</li><li><strong>Define the checkpoint configuration</strong>: The code defines a checkpoint configuration. A checkpoint is a list of validations to run.</li><li><strong>Add or update the checkpoint</strong>: The code adds or updates the checkpoint in the context.</li><li><strong>Run the checkpoint</strong>: The code runs the checkpoint, which will validate the data again.</li><li><strong>Build data docs</strong>: The code builds data docs, which are a visual representation of the validation results.</li></ul><h4>Custom Expectation: Cross-Table Value Comparison</h4><p>Another custom expectation ensures that values in specific columns across two tables match.</p><p><strong>SQL Query</strong></p><pre>SELECT <br>    t1.id, <br>    t1.date AS date_table1, <br>    t2.date AS date_table2, <br>    CASE <br>        WHEN t1.date = t2.date THEN &#39;Match&#39; <br>        ELSE &#39;No Match&#39; <br>    END AS MatchStatus<br>FROM <br>    table1 t1<br>INNER JOIN <br>    table2 t2 <br>ON <br>    t1.id = t2.id;</pre><p><strong>Expectation Code</strong></p><pre>from typing import Dict<br>from great_expectations.execution_engine import SqlAlchemyExecutionEngine, ExecutionEngine<br>from great_expectations.expectations.expectation import Expectation<br>import sqlalchemy as sa<br><br>class ExpectColumnValuesToBeEqualInDifferentTables(Expectation):<br>    success_keys = (<br>        &quot;column_compare_1&quot;,<br>        &quot;column_compare_2&quot;,<br>        &quot;column_against_1&quot;,<br>        &quot;column_against_2&quot;,<br>        &quot;table_1&quot;,<br>        &quot;table_2&quot;,<br>    )<br><br>    def _validate(self,<br>                  configuration: dict,<br>                  metrics: Dict,<br>                  runtime_configuration: dict = None,<br>                  execution_engine: ExecutionEngine = None, **kwargs):<br>        if not isinstance(execution_engine, SqlAlchemyExecutionEngine):<br>            raise ValueError(&quot;This expectation is only supported for SQL backends.&quot;)<br><br>        table_1 = configuration.kwargs.get(&quot;table_1&quot;)<br>        table_2 = configuration.kwargs.get(&quot;table_2&quot;)<br>        column_compare_1 = configuration.kwargs.get(&quot;column_compare_1&quot;)<br>        column_compare_2 = configuration.kwargs.get(&quot;column_compare_2&quot;)<br>        column_against_1 = configuration.kwargs.get(&quot;column_against_1&quot;)<br>        column_against_2 = configuration.kwargs.get(&quot;column_against_2&quot;)<br><br>        # Get the batch identifiers<br>        batch_identifiers = configuration.kwargs.get(&quot;batch_identifiers&quot;)<br><br>        # Create the base query<br>        query = sa.text(<br>            f&quot;&quot;&quot;<br>                 SELECT t1.{column_against_1}, t1.{column_compare_1} AS date_table1, t2.{column_compare_2} AS date_table2,<br>                 CASE WHEN t1.{column_compare_1} = t2.{column_compare_2} THEN &#39;Match&#39; ELSE &#39;No Match&#39; END AS MatchStatus<br>                 FROM {table_1} t1<br>                 INNER JOIN {table_2} t2<br>                 ON t1.{column_against_1} = t2.{column_against_2}<br>                 &quot;&quot;&quot;<br>        )<br><br>        if batch_identifiers is not None:<br>            # Create a WHERE clause based on the batch identifiers<br>            where_clause = &#39; AND &#39;.join([f&quot;{k} &gt; {v}&quot; for k, v in batch_identifiers.items()])<br><br>            # Add the WHERE clause to the query<br>            query = query + sa.text(f&quot; WHERE {where_clause}&quot;)<br><br>        # Get a connection from the engine<br>        connection = execution_engine.engine.connect()<br>        # Use the connection to execute the query<br>        result = connection.execute(query)<br>        # Use an integer index to access the &quot;MatchStatus&quot; field<br>        match_status = [row[3] for row in result]<br>        success = match_status.count(&quot;Match&quot;) == len(match_status)<br><br>        return {<br>            &quot;success&quot;: success,<br>            &quot;result&quot;: {<br>                &quot;observed_value&quot;: {<br>                    &quot;match_count&quot;: match_status.count(&quot;Match&quot;),<br>                    &quot;total_count&quot;: len(match_status),<br>                }<br>            },<br>        }</pre><p>This Python code defines a custom expectation for the Great Expectations data testing and validation library. The expectation is named ExpectColumnValuesToBeEqualInDifferentTables and it checks if the values in a specific column of two different tables are equal.</p><p>Here’s a step-by-step explanation of the code:</p><ul><li>The ExpectColumnValuesToBeEqualInDifferentTables class is defined, inheriting from the Expectation class provided by Great Expectations. The success_keys tuple defines the keys that will be used in the configuration dictionary to specify the columns and tables to compare.</li><li>The _validate method is defined. This is where the actual expectation logic is implemented. It takes several arguments, including a configuration dictionary, a metrics dictionary, a runtime configuration dictionary, and an execution engine.</li><li>The method first checks if the execution engine is an instance of SqlAlchemyExecutionEngine. If not, it raises a ValueError, because this expectation is only supported for SQL backends.</li><li>The method then retrieves the table names and column names from the configuration dictionary.</li><li>It constructs a SQL query that selects the relevant columns from the two tables and compares the values. If the values are equal, the query returns ‘Match’, otherwise it returns ‘No Match’.</li><li>If there are any batch identifiers in the configuration, the method adds a WHERE clause to the query to filter the data.</li><li>The method executes the query using the execution engine’s connection and fetches the results.</li><li>It counts the number of ‘Match’ results and compares it to the total number of results. If all results are ‘Match’, the expectation is successful.</li><li>Finally, the method returns a dictionary containing the success status and the observed values (the number of matches and the total count).</li></ul><p><strong>Validator Code</strong></p><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from gx.plugins.expectations.ExpectColumnValuesToBeEqualInTwoTables import ExpectColumnValuesToBeEqualInDifferentTables<br><br># Get the context<br>context = ge.get_context()<br><br># Define your datasources<br>datasource_name1 = &quot;table1&quot;<br># Define your assets<br>asset_name1 = &quot;table1_asset&quot;<br># Get the datasource<br>datasource1 = context.get_datasource(datasource_name1)<br># Get the asset<br>datasource_asset1 = datasource1.get_asset(asset_name=asset_name1)<br><br># Define your datasources<br>datasource_name2 = &quot;table2&quot;<br># Define your assets<br>asset_name2 = &quot;table2_asset&quot;<br># Get the datasource<br>datasource2 = context.get_datasource(datasource_name2)<br># Get the asset<br>datasource_asset2 = datasource2.get_asset(asset_name=asset_name2)<br><br># Build the batch request<br>datasource_batch_request = datasource_asset1.build_batch_request()<br><br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;date_id_check&quot;)<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>    expectation_type=&quot;expect_column_values_to_be_equal_in_different_tables&quot;,<br>    kwargs={<br>        &quot;column_compare_1&quot;: &quot;date&quot;,<br>        &quot;column_compare_2&quot;: &quot;date&quot;,<br>        &quot;column_against_1&quot;: &quot;id&quot;,<br>        &quot;column_against_2&quot;: &quot;id&quot;,<br>        &quot;table_1&quot;: &quot;table1&quot;,<br>        &quot;table_2&quot;: &quot;table2&quot;,<br>    },<br>)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=&quot;date_id_check&quot;, expectation_suite=suite)<br><br># Get the validator<br>validator = context.get_validator(<br>    batch_request=datasource_batch_request,<br>    expectation_suite_name=&quot;date_id_check&quot;,<br>)<br><br>print(validator.head(10))<br><br>res = validator.validate()<br><br>print(res)</pre><p>This Python script uses the Great Expectations library to validate data across two different tables in a database. It uses a custom expectation ExpectColumnValuesToBeEqualInDifferentTables to check if the values in a specific column of two different tables are equal.</p><p>Here’s a step-by-step explanation of the code:</p><ul><li>The necessary libraries and modules are imported.</li><li>The Great Expectations context is obtained using ge.get_context().</li><li>The names of the two data sources (tables) and their corresponding assets are defined.</li><li>The data sources and assets are retrieved from the context.</li><li>A batch request is built for the first data source asset using datasource_asset1.build_batch_request().</li><li>An expectation suite named “date_id_check” is added or updated in the context.</li><li>The custom expectation configuration is defined using ExpectationConfiguration. The expectation type is set to “expect_column_values_to_be_equal_in_different_tables” and the necessary arguments are provided in the kwargs dictionary.</li><li>The custom expectation is added to the suite using suite.add_expectation(expectation_config).</li><li>The expectation suite is saved in the context using context._save_expectation_suite().</li><li>A validator is obtained from the context using context.get_validator(). The batch request and the name of the expectation suite are provided as arguments.</li><li>The first 10 rows of the validator’s data are printed using validator.head(10).</li><li>The validation is performed using validator.validate() and the result is printed.</li></ul><p>The result of the validation will be a dictionary containing the success status and the observed values (the number of matches and the total count) for each expectation in the suite.</p><h3>Advanced Custom Expectations</h3><h4>Cross-Table Row Count Validation</h4><p>A more complex expectation validates whether row counts in different tables are equal after performing unions and joins.</p><p><strong>SQL Query</strong></p><pre>SELECT COUNT(*)<br>FROM (<br>    SELECT <br>        CASE <br>            WHEN col1 = col2 THEN &#39;Match&#39; <br>            ELSE &#39;No Match&#39; <br>        END AS MatchStatus<br>    FROM (<br>        SELECT col1, col2, col3<br>        FROM table t1<br>        JOIN table2 t2 ON col2 = col4<br>    ) t1<br>    INNER JOIN (<br>        SELECT col1, col2<br>        FROM table3<br>        UNION<br>        SELECT col1, col2<br>        FROM table4<br>    ) t2 ON t1.col2 = t2.col2 AND t1.col3 = t2.col3<br>) t3<br>WHERE MatchStatus = &#39;No Match&#39;;</pre><p><strong>Expectation Code</strong></p><pre><br>from typing import Dict, Optional<br>from great_expectations.core import ExpectationConfiguration<br>from great_expectations.exceptions import InvalidExpectationConfigurationError<br>from great_expectations.execution_engine import SqlAlchemyExecutionEngine, ExecutionEngine<br>from great_expectations.expectations.expectation import Expectation<br>from great_expectations.expectations.metrics.metric_provider import metric_value, MetricProvider<br>from great_expectations.expectations.registry import register_metric<br>from great_expectations.validator.metric_configuration import MetricConfiguration<br>from great_expectations.validator.validator import ValidationDependencies<br>from sqlalchemy import text, inspect<br><br><br>class ColumnTotalCount(MetricProvider):<br>    &quot;&quot;&quot;<br>    This metric calculates the total count of rows in the table.<br>    &quot;&quot;&quot;<br><br>    metric_name = &quot;column.total_count&quot;<br><br>    @metric_value(engine=SqlAlchemyExecutionEngine)<br>    def _sqlalchemy(cls, metrics, execution_engine, **kwargs):<br>        table = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;table&#39;)<br>        batch_identifiers = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;batch_identifiers&#39;)<br><br>        if table is None:<br>            raise ValueError(&quot;&#39;table&#39; must be provided&quot;)<br><br>        # Access the engine from the SqlAlchemyExecutionEngine instance<br>        engine = execution_engine.engine<br><br>        # Check if the table exists<br>        inspector = inspect(engine)<br>        if not inspector.has_table(table):<br>            raise ValueError(f&quot;The table &#39;{table}&#39; does not exist&quot;)<br><br>        if batch_identifiers is not None:<br>            where_clause = &#39; AND &#39;.join([f&quot;{k} = {v}&quot; for k, v in batch_identifiers.items()])<br>            query = text(<br>                f&#39;SELECT count(*) FROM {table} WHERE {where_clause}&#39;)<br>        else:<br>            query = text(<br>                f&#39;SELECT count(*) FROM {table}&#39;)<br>        return query<br><br>register_metric(<br>    metric_name=ColumnTotalCount.metric_name,<br>    metric_domain_keys=(&quot;table&quot;,),<br>    metric_value_keys=(&quot;sqlalchemy&quot;,),<br>    execution_engine=SqlAlchemyExecutionEngine,<br>    metric_class=ColumnTotalCount,<br>    metric_provider=ColumnTotalCount._sqlalchemy<br>)<br><br>class ExpectColumnValuesToBeEqualInDifferentTables(Expectation):<br><br>    def get_validation_dependencies(<br>            self,<br>            configuration: Optional[ExpectationConfiguration] = None,<br>            execution_engine: Optional[ExecutionEngine] = None,<br>            runtime_configuration: Optional[dict] = None,<br>    ) -&gt; ValidationDependencies:<br>        dependencies = super().get_validation_dependencies(<br>            configuration, execution_engine, runtime_configuration<br>        )<br>        table = configuration.kwargs.get(&quot;table&quot;)<br>        batch_identifiers = configuration.kwargs.get(&quot;batch_identifiers&quot;)<br>        if not table:<br>            raise InvalidExpectationConfigurationError(&quot;table must be provided&quot;)<br>        metric_configuration = MetricConfiguration(<br>            &quot;column.total_count&quot;,<br>            metric_domain_kwargs={&quot;table&quot;: table,&quot;batch_identifiers&quot;: batch_identifiers},<br>        )<br>        dependencies.metric_configurations[<br>            &quot;column.total_count&quot;<br>        ] = metric_configuration<br>        return dependencies<br><br>    def generate_union_query(self, union_tables, union_columns):<br>        if len(union_tables) != len(union_columns):<br>            raise ValueError(&quot;The number of tables and columns must be the same.&quot;)<br><br>        select_statements = []<br>        for table, columns in zip(union_tables, union_columns):<br>            # Split the table string into database, schema, and table name<br>            database, schema, table_name = table.split(&#39;.&#39;)<br>            # Format the table string correctly<br>            table_str = f&quot;[{database}].[{schema}].[{table_name}]&quot;<br>            columns_str = &quot;, &quot;.join(f&quot;{table_str}.[{col}]&quot; for col in columns)<br>            select_statements.append(f&quot;SELECT {columns_str} FROM {table_str}&quot;)<br><br>        union_query = &quot; UNION &quot;.join(select_statements)<br>        return union_query<br><br>    def generate_join_query(self, join_tables, join_columns, join_conditions, collation, batch_identifiers):<br>        if len(join_tables) == 1:<br>            join_query = &quot;&quot;<br>            table1 = join_tables[0]<br>            columns_str1 = &quot;, &quot;.join([f&quot;{table1}.[{col}]&quot; for col in join_columns[0]])<br>            join_query = f&quot;SELECT {columns_str1} FROM {table1}&quot;<br>            if batch_identifiers is not None and table1 == &#39;UNIVERSITY&#39;:<br>                where_clause = &#39; AND &#39;.join([f&quot;{k} = {v}&quot; for k, v in batch_identifiers.items()])<br>                join_query += f&quot; WHERE {where_clause}&quot;<br>        else:<br>            # Generate a SELECT statement for each pair of tables<br>            select_statements = []<br>            for i in range(len(join_tables) - 1):<br>                table1 = join_tables[i]<br>                table2 = join_tables[i + 1]<br>                columns_str1 = &quot;, &quot;.join([f&#39;{table1}.[{col}]&#39; for col in join_columns[i]])<br>                columns_str2 = &quot;, &quot;.join([f&#39;{table2}.[{col}]&#39; for col in join_columns[i + 1]])<br>                conditions_str = &quot; AND &quot;.join(<br>                    [<br>                        f&#39;{table1}.[{join_conditions[i][0]}] COLLATE {collation} = {table2}.[{join_conditions[i + 1][0]}] COLLATE {collation}&#39;<br>                        for _ in<br>                        range(len(join_conditions[i]))])<br>                select_statement = f&quot;SELECT {columns_str1}, {columns_str2} FROM {table1} JOIN {table2} ON {conditions_str}&quot;<br>                if batch_identifiers is not None and table1 == &#39;UNIVERSITY&#39;:<br>                    where_clause = &#39; AND &#39;.join([f&quot;{k} = {v}&quot; for k, v in batch_identifiers.items()])<br>                    select_statement += f&quot; WHERE {where_clause}&quot;<br>                select_statements.append(select_statement)<br>            join_query = &quot; JOIN &quot;.join(select_statements)<br>        return join_query<br><br>    def _validate(self,<br>                  configuration: dict,<br>                  metrics: Dict,<br>                  runtime_configuration: dict = None,<br>                  execution_engine: ExecutionEngine = None, **kwargs):<br>        union_tables = configuration.kwargs.get(&quot;union_tables&quot;)<br>        union_columns = configuration.kwargs.get(&quot;union_columns&quot;)<br>        join_tables = configuration.kwargs.get(&quot;join_tables&quot;)<br>        join_columns = configuration.kwargs.get(&quot;join_columns&quot;)<br>        join_conditions = configuration.kwargs.get(&quot;join_conditions&quot;)<br>        compare_against = configuration.kwargs.get(&quot;compare_against&quot;)<br>        compare_columns = configuration.kwargs.get(&quot;compare_columns&quot;)<br>        batch_identifiers = configuration.kwargs.get(&quot;batch_identifiers&quot;)<br>        union_query = self.generate_union_query(union_tables, union_columns)<br>        join_query = self.generate_join_query(join_tables, join_columns, join_conditions<br>                                              ,&#39;SQL_Latin1_General_CP1_CI_AS&#39;,batch_identifiers)<br>        case_conditions = f&quot;t1.[{compare_columns[0]}] COLLATE SQL_Latin1_General_CP1_CI_AS = &quot; \<br>                          f&quot;t2.[{compare_columns[1]}] COLLATE SQL_Latin1_General_CP1_CI_AS&quot;<br>        on_conditions = &quot; AND &quot;.join(<br>            [f&#39;t1.[{col1}] COLLATE SQL_Latin1_General_CP1_CI_AS = t2.[{col2}] COLLATE SQL_Latin1_General_CP1_CI_AS&#39; for<br>             col1, col2 in zip(compare_against[0], compare_against[1])])<br>        final_query = text(f&quot;&quot;&quot;<br>            SELECT COUNT(*) FROM (<br>            SELECT CASE WHEN {case_conditions} THEN &#39;Match&#39; ELSE &#39;No Match&#39; END AS MatchStatus<br>            FROM ({join_query}) t1<br>            INNER JOIN ({union_query}) t2<br>            ON {on_conditions} ) t3<br>            WHERE MatchStatus=&#39;No Match&#39;<br>            &quot;&quot;&quot;)<br>        result = execution_engine.execute_query(final_query).fetchone()[0]<br><br>        total_count = metrics[&quot;column.total_count&quot;]<br>        total_count_result = execution_engine.execute_query(total_count).fetchone()[0]<br><br>        element_count = total_count_result<br>        unexpected_count = result<br>        unexpected_percent = (unexpected_count / element_count) * 100 if element_count &gt; 0 else 0<br>        result_dict = {<br>            &quot;element_count&quot;: element_count,<br>            &quot;unexpected_count&quot;: unexpected_count,<br>            &quot;unexpected_percent&quot;: unexpected_percent,<br>            &quot;unexpected_percentage_total&quot;: unexpected_percent<br>        }<br>        if result&gt;0:<br>            return {<br>                &quot;success&quot;: False,<br>                &quot;result&quot;: result_dict<br>            }<br>        else:<br>            return {<br>                &quot;success&quot;: True,<br>                &quot;result&quot;: result_dict<br>            }<br></pre><ul><li>This code defines a custom expectation for the Great Expectations data quality library. The expectation is named ExpectColumnValuesToBeEqualInDifferentTables.</li><li>The expectation checks if the values of specific columns in different tables are equal. It does this by generating SQL queries that join and union the tables, and then compares the values of the specified columns.</li><li>The expectation uses a custom metric ColumnTotalCount which calculates the total count of rows in the table. This metric is used to calculate the percentage of rows that do not meet the expectation.</li><li>The expectation is defined in a class that inherits from Expectation. The main logic of the expectation is implemented in the _validate method. This method generates the SQL queries, executes them, and calculates the result. The result is a dictionary that includes the total number of elements, the number and percentage of unexpected elements, and the overall success status of the expectation.</li><li>The ExpectColumnValuesToBeEqualInDifferentTables class also includes methods to generate the SQL queries (generate_union_query and generate_join_query), and a method to get the validation dependencies (get_validation_dependencies).</li><li>The ColumnTotalCount metric is defined in a separate class that inherits from MetricProvider. The metric is registered with the register_metric function. The metric is calculated by executing a SQL query that counts the number of rows in the table.</li></ul><p><strong>Validator</strong></p><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from gx.plugins.expectations.ExpectColumnValuesToBeEqualInDifferentTables import ExpectColumnValuesToBeEqualInDifferentTables<br><br># Get the context<br>context = ge.get_context()<br><br># Define your datasources<br>datasource_name = &quot;University&quot;<br># Define your assets<br>asset_name = &quot;University_asset&quot;<br># Get the datasource<br>datasource = context.get_datasource(datasource_name)<br># Get the asset<br>datasource_asset1 = datasource.get_asset(asset_name=asset_name)<br><br># Build the batch request<br>datasource_batch_request = datasource_asset1.build_batch_request()<br><br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;testing&quot;)<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>   expectation_type=&quot;expect_column_values_to_be_equal_in_different_tables&quot;,<br>   kwargs={<br>       &quot;union_tables&quot;: [&quot;deem_test.dbo.001UniversityNINs&quot;, &quot;deem_test2.dbo.MOEPubulationV4&quot;],<br>       &quot;union_columns&quot;: [[&quot;NIN&quot;,&quot;collegeNameAr&quot;,&quot;degreeNameAr&quot;,&quot;graduationDateGregorian&quot;,&quot;instituteNameAr&quot;],<br>                         [&quot;NIN&quot;,&quot;collegeNameAr&quot;,&quot;degreeNameAr&quot;,&quot;graduationDateGregorian&quot;,&quot;instituteNameAr&quot;]],<br>       &quot;join_tables&quot; : [&#39;UNIVERSITY&#39;, &#39;deem_test1.dbo.UniversityCode&#39;],<br>       &quot;join_columns&quot;: [[&#39;National_Identification_Number&#39;,&#39;Degree&#39;,&#39;College&#39;,&#39;Graduation_date&#39;],[&#39;University Name&#39;]],<br>       &quot;join_conditions&quot;: [[&#39;university_name&#39;],[&#39;University Code&#39;]],<br>       &quot;compare_columns&quot; : [&#39;Graduation_date&#39;,&#39;graduationDateGregorian&#39;],<br>       &quot;compare_against&quot; : [[&#39;National_Identification_Number&#39;,&#39;Degree&#39;,&#39;College&#39;,&#39;University Name&#39;]<br>           ,[&#39;NIN&#39;,&#39;degreeNameAr&#39;,&#39;collegeNameAr&#39;,&#39;instituteNameAr&#39;]],<br>       &quot;table&quot;:&quot;UNIVERSITY&quot;,<br>       &quot;batch_identifiers&quot; : {&quot;YEAR(Load_date)&quot;: 2023, &quot;MONTH(Load_date)&quot;: 10}<br>   },<br>)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=&quot;testing&quot;, expectation_suite=suite)<br><br># Get the validator<br>validator = context.get_validator(<br>    batch_request=datasource_batch_request,<br>    expectation_suite_name=&quot;testing&quot;,<br>)<br><br>res = validator.validate()<br><br>print(res)</pre><p>This code uses the Great Expectations library to validate data quality by using a custom expectation named ExpectColumnValuesToBeEqualInDifferentTables.</p><p>Here’s a step-by-step description of what the code does:</p><ul><li>Import the necessary libraries and the custom expectation ExpectColumnValuesToBeEqualInDifferentTables.</li><li>Get the Great Expectations context, which is the main object for configuring and managing data quality checks.</li><li>Define the datasource and asset names. A datasource in Great Expectations represents a source of data, while an asset is a specific dataset within a datasource.</li><li>Get the datasource and asset from the context.</li><li>Build a batch request. A batch in Great Expectations represents a slice of data to validate.</li><li>Add or update an expectation suite. An expectation suite is a collection of expectations to validate against a batch of data.</li><li>Define the configuration for the custom expectation. This includes the names of the tables and columns to compare, the join conditions, and the batch identifiers.</li><li>Add the custom expectation to the suite and save the suite.</li><li>Get a validator. A validator in Great Expectations is an object that checks whether a batch of data meets the expectations in a suite.</li><li>Validate the data and print the result. The validate method checks whether the data in the batch meets the expectations in the suite, and returns a dictionary with the results.</li></ul><p><strong>SQL Query</strong></p><pre>SELECT COUNT(*) <br>FROM (<br>    SELECT <br>        CASE <br>            WHEN t1.count_1 = t2.count_2 THEN &#39;Match&#39; <br>            ELSE &#39;No Match&#39; <br>        END AS MatchStatus<br>    FROM (<br>        SELECT <br>            t1.col1, <br>            t1.col2, <br>            t1.col3, <br>            COUNT(DISTINCT t1.col4) AS count_1<br>        FROM (<br>            SELECT <br>                table4.col1, <br>                table4.col2, <br>                table4.col3, <br>                table3.UniversityCode.col4<br>            FROM table4<br>            JOIN table3 ON table4.col5 = table3.col6<br>        ) t1<br>        GROUP BY t1.[Degree], t1.[College], t1.[University Name]<br>    ) t1<br>    INNER JOIN (<br>        SELECT <br>            t2.col1, <br>            t2.col2, <br>            t2.col3, <br>            COUNT(DISTINCT t2.col4) AS count_2<br>        FROM (<br>            SELECT col1, col2, col3, col4 FROM table2<br>            UNION<br>            SELECT col1, col2, col3, col4 FROM table1<br>        ) t2<br>        GROUP BY t2.col1, t2.col2, t2.col3<br>    ) t2 ON t1.col1 = t2.col1 <br>         AND t1.col2 = t2.col2 <br>         AND t1.col3 = t2.col3<br>) t3 <br>WHERE MatchStatus = &#39;No Match&#39;;</pre><p><strong>Expectation Code</strong></p><pre>from typing import Dict, Optional<br>from great_expectations.core import ExpectationConfiguration<br>from great_expectations.exceptions import InvalidExpectationConfigurationError<br>from great_expectations.execution_engine import SqlAlchemyExecutionEngine, ExecutionEngine<br>from great_expectations.expectations.expectation import Expectation<br>from great_expectations.expectations.metrics.metric_provider import metric_value, MetricProvider<br>from great_expectations.expectations.registry import register_metric<br>from great_expectations.validator.metric_configuration import MetricConfiguration<br>from great_expectations.validator.validator import ValidationDependencies<br>from sqlalchemy import text, inspect<br><br>class ColumnTotalCount(MetricProvider):<br>    &quot;&quot;&quot;<br>    This metric calculates the total count of rows in the table.<br>    &quot;&quot;&quot;<br>    metric_name = &quot;column.total_count&quot;<br>    @metric_value(engine=SqlAlchemyExecutionEngine)<br>    def _sqlalchemy(cls, metrics, execution_engine, **kwargs):<br>        table = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;table&#39;)<br>        batch_identifiers = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;batch_identifiers&#39;)<br><br>        if table is None:<br>            raise ValueError(&quot;&#39;table&#39; must be provided&quot;)<br><br>        # Access the engine from the SqlAlchemyExecutionEngine instance<br>        engine = execution_engine.engine<br><br>        # Check if the table exists<br>        inspector = inspect(engine)<br>        if not inspector.has_table(table):<br>            raise ValueError(f&quot;The table &#39;{table}&#39; does not exist&quot;)<br><br>        if batch_identifiers is not None:<br>            where_clause = &#39; AND &#39;.join([f&quot;{k} = {v}&quot; for k, v in batch_identifiers.items()])<br>            query = text(<br>                f&#39;SELECT count(*) FROM {table} WHERE {where_clause}&#39;)<br>        else:<br>            query = text(<br>                f&#39;SELECT count(*) FROM {table}&#39;)<br>        return query<br><br>register_metric(<br>    metric_name=ColumnTotalCount.metric_name,<br>    metric_domain_keys=(&quot;table&quot;,),<br>    metric_value_keys=(&quot;sqlalchemy&quot;,),<br>    execution_engine=SqlAlchemyExecutionEngine,<br>    metric_class=ColumnTotalCount,<br>    metric_provider=ColumnTotalCount._sqlalchemy<br>)<br><br>class ExpectColumnCountToBeEqualInDifferentTables(Expectation):<br><br>    def get_validation_dependencies(<br>            self,<br>            configuration: Optional[ExpectationConfiguration] = None,<br>            execution_engine: Optional[ExecutionEngine] = None,<br>            runtime_configuration: Optional[dict] = None,<br>    ) -&gt; ValidationDependencies:<br>        dependencies = super().get_validation_dependencies(<br>            configuration, execution_engine, runtime_configuration<br>        )<br>        table = configuration.kwargs.get(&quot;table&quot;)<br>        batch_identifiers = configuration.kwargs.get(&quot;batch_identifiers&quot;)<br>        if not table:<br>            raise InvalidExpectationConfigurationError(&quot;table must be provided&quot;)<br>        metric_configuration = MetricConfiguration(<br>            &quot;column.total_count&quot;,<br>            metric_domain_kwargs={&quot;table&quot;: table,&quot;batch_identifiers&quot;: batch_identifiers},<br>        )<br>        dependencies.metric_configurations[<br>            &quot;column.total_count&quot;<br>        ] = metric_configuration<br>        return dependencies<br><br>    def generate_union_query(self, union_tables, union_columns):<br>        if len(union_tables) != len(union_columns):<br>            raise ValueError(&quot;The number of tables and columns must be the same.&quot;)<br><br>        select_statements = []<br>        for table, columns in zip(union_tables, union_columns):<br>            # Split the table string into database, schema, and table name<br>            database, schema, table_name = table.split(&#39;.&#39;)<br>            # Format the table string correctly<br>            table_str = f&quot;[{database}].[{schema}].[{table_name}]&quot;<br>            columns_str = &quot;, &quot;.join(f&quot;{table_str}.[{col}]&quot; for col in columns)<br>            select_statements.append(f&quot;SELECT {columns_str} FROM {table_str}&quot;)<br><br>        union_query = &quot; UNION &quot;.join(select_statements)<br>        return union_query<br><br>    def generate_join_query(self, join_tables, join_columns, join_conditions, collation, batch_identifiers):<br>        if len(join_tables) == 1:<br>            join_query = &quot;&quot;<br>            table1 = join_tables[0]<br>            columns_str1 = &quot;, &quot;.join([f&quot;{table1}.[{col}]&quot; for col in join_columns[0]])<br>            join_query = f&quot;SELECT {columns_str1} FROM {table1}&quot;<br>            if batch_identifiers is not None and table1 == &#39;UNIVERSITY&#39;:<br>                where_clause = &#39; AND &#39;.join([f&quot;{k} = {v}&quot; for k, v in batch_identifiers.items()])<br>                join_query += f&quot; WHERE {where_clause}&quot;<br>        else:<br>            # Generate a SELECT statement for each pair of tables<br>            select_statements = []<br>            for i in range(len(join_tables) - 1):<br>                table1 = join_tables[i]<br>                table2 = join_tables[i + 1]<br>                columns_str1 = &quot;, &quot;.join([f&#39;{table1}.[{col}]&#39; for col in join_columns[i]])<br>                columns_str2 = &quot;, &quot;.join([f&#39;{table2}.[{col}]&#39; for col in join_columns[i + 1]])<br>                conditions_str = &quot; AND &quot;.join(<br>                    [<br>                        f&#39;{table1}.[{join_conditions[i][0]}] COLLATE {collation} = {table2}.[{join_conditions[i + 1][0]}] COLLATE {collation}&#39;<br>                        for _ in<br>                        range(len(join_conditions[i]))])<br>                select_statement = f&quot;SELECT {columns_str1}, {columns_str2} FROM {table1} JOIN {table2} ON {conditions_str}&quot;<br>                if batch_identifiers is not None and table1 == &#39;UNIVERSITY&#39;:<br>                    where_clause = &#39; AND &#39;.join([f&quot;{k} = {v}&quot; for k, v in batch_identifiers.items()])<br>                    select_statement += f&quot; WHERE {where_clause}&quot;<br>                select_statements.append(select_statement)<br>            join_query = &quot; JOIN &quot;.join(select_statements)<br>        return join_query<br><br>    def _validate(self,<br>                  configuration: dict,<br>                  metrics: Dict,<br>                  runtime_configuration: dict = None,<br>                  execution_engine: ExecutionEngine = None, **kwargs):<br>        union_tables = configuration.kwargs.get(&quot;union_tables&quot;)<br>        union_columns = configuration.kwargs.get(&quot;union_columns&quot;)<br>        join_tables = configuration.kwargs.get(&quot;join_tables&quot;)<br>        join_columns = configuration.kwargs.get(&quot;join_columns&quot;)<br>        join_conditions = configuration.kwargs.get(&quot;join_conditions&quot;)<br>        compare_against = configuration.kwargs.get(&quot;compare_against&quot;)<br>        compare_columns = configuration.kwargs.get(&quot;compare_columns&quot;)<br>        batch_identifiers = configuration.kwargs.get(&quot;batch_identifiers&quot;)<br>        union_query = self.generate_union_query(union_tables, union_columns)<br>        join_query = self.generate_join_query(join_tables, join_columns, join_conditions<br>                                              ,&#39;SQL_Latin1_General_CP1_CI_AS&#39;,batch_identifiers)<br>        on_conditions = &quot; AND &quot;.join(<br>            [f&#39;t1.[{col1}] COLLATE SQL_Latin1_General_CP1_CI_AS = t2.[{col2}] COLLATE SQL_Latin1_General_CP1_CI_AS&#39; for<br>             col1, col2 in zip(compare_against[0], compare_against[1])])<br><br>        columns_str1=&#39;&#39;<br>        columns_str2=&#39;&#39;<br>        case_condition1 = f&quot;count(distinct t1.[{compare_columns[0]}])&quot;<br>        group_by_lst1=join_columns<br>        for sublist in group_by_lst1:<br>            if compare_columns[0] in sublist:<br>                sublist.remove(compare_columns[0])<br>        for i in range(len(join_tables) - 1):<br>            columns_str1 = &quot;, &quot;.join([f&#39;t1.[{col}]&#39; for col in group_by_lst1[i]])<br>            columns_str2 = &quot;, &quot;.join([f&#39;t1.[{col}]&#39; for col in group_by_lst1[i + 1]])<br>        query1 = text(f&quot;&quot;&quot;<br>            SELECT {columns_str1},{columns_str2},{case_condition1} as count_1<br>            FROM ({join_query}) t1<br>            group by {columns_str1}, {columns_str2}<br>            &quot;&quot;&quot;)<br><br>        case_condition2 = f&quot;count(distinct t2.[{compare_columns[1]}])&quot;<br>        columns_str=&#39;&#39;<br>        group_by_lst2 = union_columns<br>        for sublist in group_by_lst2:<br>            if compare_columns[1] in sublist:<br>                sublist.remove(compare_columns[1])<br>        for columns in group_by_lst2:<br>            columns_str = &quot;, &quot;.join(f&quot;t2.[{col}]&quot; for col in columns)<br>        query2 = text(f&quot;&quot;&quot;<br>                    SELECT {columns_str},{case_condition2} as count_2 FROM ({union_query}) t2 group by {columns_str}<br>                    &quot;&quot;&quot;)<br><br>        final_query = text(f&quot;&quot;&quot;<br>                    SELECT COUNT(*) FROM (<br>                    SELECT CASE WHEN t1.count_1=t2.count_2 THEN &#39;Match&#39; ELSE &#39;No Match&#39; END AS MatchStatus<br>                    from ({query1}) t1<br>                    INNER JOIN ({query2}) t2<br>                    ON {on_conditions} ) t3<br>                    WHERE MatchStatus=&#39;No Match&#39;<br>                    &quot;&quot;&quot;)<br><br>        result = execution_engine.execute_query(final_query).fetchone()[0]<br><br>        total_count = metrics[&quot;column.total_count&quot;]<br>        total_count_result = execution_engine.execute_query(total_count).fetchone()[0]<br><br>        element_count = total_count_result<br>        unexpected_count = result<br>        unexpected_percent = (unexpected_count / element_count) * 100 if element_count &gt; 0 else 0<br>        result_dict = {<br>            &quot;element_count&quot;: element_count,<br>            &quot;unexpected_count&quot;: unexpected_count,<br>            &quot;unexpected_percent&quot;: unexpected_percent,<br>            &quot;unexpected_percentage_total&quot;: unexpected_percent<br>        }<br>        if result&gt;0:<br>            return {<br>                &quot;success&quot;: False,<br>                &quot;result&quot;: result_dict<br>            }<br>        else:<br>            return {<br>                &quot;success&quot;: True,<br>                &quot;result&quot;: result_dict<br>            }</pre><ul><li>This Python code is part of a data validation framework using Great Expectations, a Python-based open-source library for validating, documenting, and profiling your data. It defines custom metrics and expectations for validating data in SQL databases using SQLAlchemy.</li><li>The ColumnTotalCount class is a custom metric provider that calculates the total count of rows in a table. It uses SQLAlchemy to execute a SQL query that counts the number of rows in a specified table.</li><li>The ExpectColumnCountToBeEqualInDifferentTables class is a custom expectation that validates whether the count of rows in different tables is equal. It generates SQL queries to perform unions and joins on tables, and then compares the counts of rows in the resulting tables.</li><li>The _validate method in ExpectColumnCountToBeEqualInDifferentTables is the main validation method. It generates SQL queries for unions and joins, executes them, and then compares the counts of rows in the resulting tables. If the counts are not equal, it returns a dictionary with the validation result and some statistics about the validation.</li><li>The register_metric function registers the ColumnTotalCount metric with the Great Expectations framework, so it can be used in expectations.</li><li>The get_validation_dependencies method in ExpectColumnCountToBeEqualInDifferentTables specifies that this expectation depends on the ColumnTotalCount metric.</li><li>The generate_union_query and generate_join_query methods in ExpectColumnCountToBeEqualInDifferentTables generate SQL queries for unions and joins, respectively.</li></ul><p><strong>Validator:</strong></p><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from gx.plugins.expectations.ExpectColumnCountToBeEqualInDifferentTables import ExpectColumnCountToBeEqualInDifferentTables<br><br># Get the context<br>context = ge.get_context()<br><br># Define your datasources<br>datasource_name = &quot;University&quot;<br># Define your assets<br>asset_name = &quot;University_asset&quot;<br># Get the datasource<br>datasource = context.get_datasource(datasource_name)<br># Get the asset<br>datasource_asset1 = datasource.get_asset(asset_name=asset_name)<br><br># Build the batch request<br>datasource_batch_request = datasource_asset1.build_batch_request()<br><br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;testing&quot;)<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>   expectation_type=&quot;expect_column_count_to_be_equal_in_different_tables&quot;,<br>   kwargs={<br>       &quot;union_tables&quot;: [&quot;deem_test.dbo.001UniversityNINs&quot;, &quot;deem_test2.dbo.MOEPubulationV4&quot;],<br>       &quot;union_columns&quot;: [[&quot;NIN&quot;,&quot;collegeNameAr&quot;,&quot;degreeNameAr&quot;,&quot;instituteNameAr&quot;],<br>                         [&quot;NIN&quot;,&quot;collegeNameAr&quot;,&quot;degreeNameAr&quot;,&quot;instituteNameAr&quot;]],<br>       &quot;join_tables&quot; : [&#39;UNIVERSITY&#39;, &#39;deem_test1.dbo.UniversityCode&#39;],<br>       &quot;join_columns&quot;: [[&#39;National_Identification_Number&#39;,&#39;Degree&#39;,&#39;College&#39;],[&#39;University Name&#39;]],<br>       &quot;join_conditions&quot;: [[&#39;university_name&#39;],[&#39;University Code&#39;]],<br>       &quot;compare_columns&quot; : [&#39;National_Identification_Number&#39;,&#39;NIN&#39;],<br>       &quot;compare_against&quot; : [[&#39;Degree&#39;,&#39;College&#39;,&#39;University Name&#39;],[&#39;degreeNameAr&#39;,&#39;collegeNameAr&#39;,&#39;instituteNameAr&#39;]],<br>       &quot;table&quot;:&quot;UNIVERSITY&quot;<br>   },<br>)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=&quot;testing&quot;, expectation_suite=suite)<br><br># Get the validator<br>validator = context.get_validator(<br>    batch_request=datasource_batch_request,<br>    expectation_suite_name=&quot;testing&quot;,<br>)<br><br>res = validator.validate()<br><br>print(res)</pre><p>This Python script uses the Great Expectations library to validate data in a SQL database. It defines an expectation suite and adds a custom expectation to it, which checks if the count of rows in different tables is equal.</p><p>Here’s a brief description of the code:</p><ul><li>It imports the necessary libraries and the custom expectation ExpectColumnCountToBeEqualInDifferentTables.</li><li>It gets the Great Expectations context, which is the main object for configuring and managing data validation.</li><li>It defines the datasource and asset names, and retrieves them from the context.</li><li>It builds a batch request for the asset. A batch is a subset of data from a datasource that Great Expectations validates.</li><li>It adds or updates an expectation suite named “testing”. An expectation suite is a collection of expectations.</li><li>It defines the configuration for the custom expectation. The configuration includes the names of the tables to union and join, the columns to use in the unions and joins, the conditions for the joins, the columns to compare, and the table to validate.</li><li>It adds the custom expectation to the suite and saves the suite.</li><li>It gets a validator for the batch and the expectation suite. A validator applies an expectation suite to a batch and produces a validation result.</li><li>It validates the data and prints the result. The result includes information about whether each expectation was met and some statistics about the validation.</li></ul><h3>Great Expectations Workflow</h3><h4>1. Define Data sources</h4><p>Set up connections to data sources such as SQL databases or files.</p><h4>2. Create Expectation Suites</h4><p>Organize related expectations into suites for modular validation.</p><h4>3. Validate Data</h4><p>Use validators to apply expectation suites to batches of data.</p><h4>4. Generate Data Docs</h4><p>Build interactive documentation summarizing validation results for stakeholders.</p><h3>Conclusion</h3><p>Custom expectations in Great Expectations provide flexibility for complex data validation scenarios. By leveraging SQLAlchemy and Python, users can enforce data quality standards tailored to their specific requirements, ensuring consistency and reliability in their datasets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c71899a8364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing the Date Columns — Great Expectation]]></title>
            <link>https://medium.com/@drishigupta/comparing-the-date-columns-great-expectation-55a3f38bf4bf?source=rss-67eca4b1a168------2</link>
            <guid isPermaLink="false">https://medium.com/p/55a3f38bf4bf</guid>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[great-expectations]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Drishi Gupta]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 10:27:00 GMT</pubDate>
            <atom:updated>2025-01-24T10:27:00.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparing the Date Columns — Great Expectation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WtmBvAVUggl4L0Xq" /></figure><p>Data validation is a critical step in ensuring data quality for analysis and decision-making. When working with datasets containing date columns, one common requirement is to verify that the values in one column (e.g., start dates) are earlier than those in another column (e.g., end dates). Great Expectations, a robust data validation framework, allows you to define custom expectations to validate such rules efficiently.</p><p>In this article, we’ll guide you through creating a custom expectation in Great Expectations to compare date columns and ensure that the end date is always greater than the start date. This step-by-step guide includes defining a custom metric, implementing the expectation, and validating sample data.</p><h3>Install Great Expectations</h3><p>If you haven’t already, install Great Expectations in your Python environment. You can do this using pip:</p><pre>pip install great_expectations</pre><h3><strong>Define the Custom Expectation</strong></h3><p>Create a new Python file in your project directory. In this file, define your custom expectation. Here’s the code for the custom expectation ExpectEndColumnValuesToBeGreaterThanStart:</p><pre>from datetime import datetime<br>from typing import Optional, Dict<br>from great_expectations.core import ExpectationConfiguration<br>from great_expectations.exceptions import InvalidExpectationConfigurationError<br>from great_expectations.execution_engine import ExecutionEngine, SqlAlchemyExecutionEngine<br>from great_expectations.expectations.expectation import Expectation<br>from great_expectations.expectations.metrics.metric_provider import MetricProvider, metric_value<br>from great_expectations.expectations.registry import register_metric<br>from great_expectations.validator.metric_configuration import MetricConfiguration<br>from great_expectations.validator.validator import ValidationDependencies<br>from sqlalchemy import text<br><br>class ColumnDistinctValuesByRowID(MetricProvider):<br>&quot;&quot;&quot;<br>This metric calculates the distinct values for each group.<br>&quot;&quot;&quot;<br>metric_name = &quot;column.distinct_values_by_row_id&quot;<br><br>@metric_value(engine=SqlAlchemyExecutionEngine)<br>def _sqlalchemy(cls, metrics, execution_engine, **kwargs):<br>column_A = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;column_A&#39;)<br>column_B = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;column_B&#39;)<br>table = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;table&#39;)<br>batch_identifiers = kwargs[&#39;metric_domain_kwargs&#39;].get(&#39;batch_identifiers&#39;)<br>if column_A is None or column_B is None or table is None:<br>raise ValueError(&quot;Both &#39;column_A&#39;, &#39;column_B&#39; and &#39;table&#39; must be provided&quot;)<br>if batch_identifiers is not None:<br>  where_clause = &#39; AND &#39;.join([f&quot;{k} = {v}&quot; for k, v in batch_identifiers.items()])<br>  query = text(<br>  f&#39;SELECT row_number() over (order by {column_A}) as row_id, {column_A}, {column_B} FROM {table} WHERE {where_clause}&#39;)<br>else:<br>  query = text(<br>  &#39;SELECT row_number() over (order by {}) as row_id, {}, {} FROM {}&#39;.format(column_A, column_A,<br>  column_B,table))<br># Create a connection from the engine and execute the query<br>with execution_engine.engine.connect() as connection:<br>  result = connection.execute(query)<br>  rows = result.fetchall()<br>return rows<br><br>register_metric(<br>metric_name=ColumnDistinctValuesByRowID.metric_name,<br>metric_domain_keys=(&quot;column&quot;,),<br>metric_value_keys=(&quot;sqlalchemy&quot;,),<br>execution_engine=SqlAlchemyExecutionEngine,<br>metric_class=ColumnDistinctValuesByRowID,<br>metric_provider=ColumnDistinctValuesByRowID._sqlalchemy<br>)<br><br>class ExpectEndColumnValuesToBeGreaterThanStart(Expectation):<br>library_metadata = {<br>&quot;maturity&quot;: &quot;experimental&quot;,<br>&quot;package&quot;: &quot;great_expectations&quot;,<br>&quot;tags&quot;: [&quot;custom expectation&quot;, &quot;date&quot;],<br>&quot;contributors&quot;: [&quot;@drishi_gupta&quot;],<br>}<br><br>@classmethod<br>def from_config(cls, config, **kwargs):<br>return cls(configuration=config)<br><br>def get_validation_dependencies(<br>self,<br>configuration: Optional[ExpectationConfiguration] = None,<br>execution_engine: Optional[ExecutionEngine] = None,<br>runtime_configuration: Optional[dict] = None,<br>) -&gt; ValidationDependencies:<br>dependencies = super().get_validation_dependencies(<br>configuration, execution_engine, runtime_configuration<br>)<br>column_A = configuration.kwargs.get(&quot;column_A&quot;)<br>column_B = configuration.kwargs.get(&quot;column_B&quot;)<br>table = configuration.kwargs.get(&quot;table&quot;)<br>batch_identifiers = configuration.kwargs.get(&quot;batch_identifiers&quot;)<br>if not table:<br>raise InvalidExpectationConfigurationError(&quot;table not provided&quot;)<br>if not column_A:<br>raise InvalidExpectationConfigurationError(&quot;column_A not provided&quot;)<br>if not column_B:<br>raise InvalidExpectationConfigurationError(&quot;column_B not provided&quot;)<br>metric_configuration = MetricConfiguration(<br>&quot;column.distinct_values_by_row_id&quot;,<br>metric_domain_kwargs={&quot;column_A&quot;: column_A, &quot;column_B&quot;: column_B, &quot;table&quot;: table,<br>&quot;batch_identifiers&quot;: batch_identifiers}<br>)<br>dependencies.metric_configurations[&quot;column_A_and_B.distinct_values_by_row_id&quot;] = metric_configuration<br>return dependencies<br><br>@classmethod<br>def _validate(<br>self,<br>configuration: ExpectationConfiguration,<br>metrics: Dict,<br>runtime_configuration: dict = None,<br>execution_engine: ExecutionEngine = None,<br>) -&gt; Dict:<br># Get the data from the metrics<br>rows = metrics[&quot;column_A_and_B.distinct_values_by_row_id&quot;]<br>unexpected_data_dict = {}<br># Check if each end date is greater than its corresponding start date<br>for row_id, start_date, end_date in rows:<br>start_date = datetime.strptime(str(start_date), &quot;%Y-%m-%d&quot;)<br>end_date = datetime.strptime(str(end_date), &quot;%Y-%m-%d&quot;)<br>if end_date &lt;= start_date:<br>unexpected_data_dict[start_date] = end_date<br>if len(unexpected_data_dict) &gt; 0:<br>return {&quot;success&quot;: False, &quot;unexpected_index_list&quot;: [unexpected_data_dict]}<br>else:<br>return {&quot;success&quot;: True}</pre><p>This Python code is using the Great Expectations library, which is a tool for testing, documenting, and profiling your data to ensure it meets your expectations. The code defines two classes: ColumnDistinctValuesByRowID and ExpectEndColumnValuesToBeGreaterThanStart.</p><ul><li><strong>ColumnDistinctValuesByRowID </strong>is a custom metric provider. It calculates the distinct values for each group in a SQL database. The _sqlalchemy method constructs a SQL query based on the provided column names and table, executes the query, and returns the result. This metric is registered with the Great Expectations library using the register_metric function.</li><li><strong>ExpectEndColumnValuesToBeGreaterThanStart </strong>is a custom expectation. It checks if the value in column_B (end date) is greater than the value in column_A (start date) for each row in a table. The get_validation_dependencies method sets up the dependencies for this expectation, including the custom metric column.distinct_values_by_row_id. The _validate method retrieves the data from the metrics, checks if each end date is greater than its corresponding start date, and returns a dictionary indicating whether the expectation was met and any unexpected data.</li></ul><p>This code is a good example of how you can extend the Great Expectations library with custom metrics and expectations to suit your specific data validation needs.</p><h3>Use the Expectation</h3><p>Now you can use this expectation in your data validation. Here’s how you might do it:</p><h4>On Full Data</h4><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from gx.plugins.expectations.ExpectEndColumnValuesToBeGreaterThanStart import ExpectEndColumnValuesToBeGreaterThanStart<br><br># Get the context<br>context = ge.get_context()<br><br># Define your datasources<br>datasource_name = &quot;DateTable&quot;<br><br># Define your assets<br>asset_name = &quot;DateTable_asset&quot;<br><br># Get the datasource<br>datasource = context.get_datasource(datasource_name)<br><br># Get the asset<br>datasource_asset = datasource.get_asset(asset_name=asset_name)<br><br># Build the batch request<br>datasource_batch_request = datasource_asset.build_batch_request()<br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;date_ce&quot;)<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>expectation_type=&quot;expect_end_column_values_to_be_greater_than_start&quot;,<br>kwargs={<br>&quot;column_A&quot;: &quot;start_date&quot;,<br>&quot;column_B&quot;: &quot;end_date&quot;,<br>&quot;table&quot;: &quot;DateTable&quot;<br>},<br>)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=&quot;date_ce&quot;, expectation_suite=suite)<br><br># Get the validator<br>validator = context.get_validator(<br>batch_request=datasource_batch_request,<br>expectation_suite_name=&quot;date_ce&quot;,<br>)<br>print(validator.head(10))<br>res = validator.validate()<br><br># Save the expectation suite<br>validator.save_expectation_suite(discard_failed_expectations=False)<br><br># Define the checkpoint configuration<br>checkpoint_config = {<br>&quot;class_name&quot;: &quot;SimpleCheckpoint&quot;,<br>&quot;validations&quot;: [<br>{<br>&quot;batch_request&quot;: datasource_batch_request,<br>&quot;expectation_suite_name&quot;: &quot;date_ce&quot;<br>}<br>]<br>}<br><br># Add or update the checkpoint<br>checkpoint_name = &quot;my_checkpoint&quot;<br>context.add_or_update_checkpoint(name=checkpoint_name, **checkpoint_config)<br><br># Run the checkpoint<br>checkpoint_result = context.run_checkpoint(checkpoint_name)<br><br># Build data docs<br>context.build_data_docs()</pre><p>This Python script uses the Great Expectations library to validate data in a SQL database. Here’s a brief description of what each part of the script does:</p><ul><li><strong>Imports</strong>: The script imports necessary libraries and classes, including the custom expectation ExpectEndColumnValuesToBeGreaterThanStart.</li><li><strong>Context and Datasource Setup</strong>: The script gets the Great Expectations context, defines the datasource and asset names, and retrieves the datasource and asset.</li><li><strong>Batch Request</strong>: The script builds a batch request for the datasource asset.</li><li><strong>Expectation Suite</strong>: The script creates or updates an expectation suite named “date_ce”.</li><li><strong>Expectation Configuration</strong>: The script defines a custom expectation configuration that checks if the end date is greater than the start date in the “DateTable”. This expectation is added to the suite.</li><li><strong>Validator</strong>: The script gets a validator for the batch request and expectation suite, prints the first 10 rows of the data, and validates the data.</li><li><strong>Save Expectation Suite</strong>: The script saves the expectation suite, keeping any failed expectations.</li><li><strong>Checkpoint Configuration</strong>: The script defines a checkpoint configuration that includes the batch request and expectation suite, adds or updates the checkpoint, and runs the checkpoint.</li><li><strong>Data Docs</strong>: Finally, the script builds data docs, which are a set of HTML pages that describe the data validation results.</li></ul><p>This script is a good example of how to use Great Expectations to validate data, including using custom expectations, and how to save and document the validation results.</p><h4>On Filtered Data</h4><pre># Import necessary libraries<br>import great_expectations as ge<br>from great_expectations.core.expectation_configuration import ExpectationConfiguration<br>from gx.plugins.expectations.col_comparison import ExpectEndColumnValuesToBeGreaterThanStart<br><br># Get the context<br>context = ge.get_context()<br><br># Define your datasources<br>datasource_name = &quot;DateTable&quot;<br><br># Define your assets<br>asset_name = &quot;DateTable_asset&quot;<br><br># Get the datasource<br>datasource = context.get_datasource(datasource_name)<br><br># Get the asset<br>datasource_asset = datasource.get_asset(asset_name=asset_name)<br><br># Add the splitter and sorters<br>datasource_asset.add_splitter_year_and_month(column_name=&quot;end_date&quot;)<br>datasource_asset = datasource_asset.add_sorters([&quot;+year&quot;, &quot;-month&quot;])<br><br># Build the batch request<br>datasource_batch_request = datasource_asset.build_batch_request(options={&quot;year&quot;: 2020, &quot;month&quot;: 9})<br><br># Get the validator<br>validator = context.get_validator(<br>batch_request=datasource_batch_request,<br>expectation_suite_name=&quot;date_ce_batch&quot;,<br>)<br>print(validator.head(10))<br>suite = context.add_or_update_expectation_suite(expectation_suite_name=&quot;date_ce_batch&quot;)<br><br># Define the custom expectation configuration<br>expectation_config = ExpectationConfiguration(<br>expectation_type=&quot;expect_end_column_values_to_be_greater_than_start&quot;,<br>kwargs={<br>&quot;column_A&quot;: &quot;start_date&quot;,<br>&quot;column_B&quot;: &quot;end_date&quot;,<br>&quot;table&quot;: &quot;DateTable&quot;,<br>&quot;batch_identifiers&quot; : {&quot;YEAR(end_date)&quot;: 2020, &quot;MONTH(end_date)&quot;: 9}<br>},<br>)<br>suite.add_expectation(expectation_config)<br>context._save_expectation_suite(expectation_suite_name=&quot;date_ce_batch&quot;, expectation_suite=suite)<br>res = validator.validate()<br><br># Save the expectation suite<br>validator.save_expectation_suite(discard_failed_expectations=False)<br><br># Define the checkpoint configuration<br>checkpoint_config = {<br>&quot;class_name&quot;: &quot;SimpleCheckpoint&quot;,<br>&quot;validations&quot;: [<br>{<br>&quot;batch_request&quot;: datasource_batch_request,<br>&quot;expectation_suite_name&quot;: &quot;date_ce_batch&quot;<br>}<br>]<br>}<br><br># Add or update the checkpoint<br>checkpoint_name = &quot;my_checkpoint&quot;<br>context.add_or_update_checkpoint(name=checkpoint_name, **checkpoint_config)<br><br># Run the checkpoint<br>checkpoint_result = context.run_checkpoint(checkpoint_name)<br><br># Build data docs<br>context.build_data_docs()</pre><p>This Python script uses the Great Expectations library to validate data in a SQL database. Here’s a brief description of what each part of the script does:</p><ul><li><strong>Imports</strong>: The script imports necessary libraries and classes, including the custom expectation ExpectEndColumnValuesToBeGreaterThanStart.</li><li><strong>Context and Datasource Setup</strong>: The script gets the Great Expectations context, defines the datasource and asset names, and retrieves the datasource and asset.</li><li><strong>Splitter and Sorters</strong>: The script adds a splitter to the asset that splits the data by year and month based on the “end_date” column. It also adds sorters that sort the data by year in ascending order and by month in descending order.</li><li><strong>Batch Request</strong>: The script builds a batch request for the datasource asset for data from September 2020.</li><li><strong>Validator</strong>: The script gets a validator for the batch request and an expectation suite named “date_ce_batch”, and prints the first 10 rows of the data.</li><li><strong>Expectation Suite</strong>: The script creates or updates the expectation suite.</li><li><strong>Expectation Configuration</strong>: The script defines a custom expectation configuration that checks if the end date is greater than the start date in the “DateTable” for data from September 2020. This expectation is added to the suite.</li><li><strong>Validation</strong>: The script validates the data.</li><li><strong>Save Expectation Suite</strong>: The script saves the expectation suite, keeping any failed expectations.</li><li><strong>Checkpoint Configuration</strong>: The script defines a checkpoint configuration that includes the batch request and expectation suite, adds or updates the checkpoint, and runs the checkpoint.</li><li><strong>Data Docs</strong>: Finally, the script builds data docs, which are a set of HTML pages that describe the data validation results.</li></ul><p>This script is a good example of how to use Great Expectations to validate data, including using custom expectations, and how to save and document the validation results. It also shows how to use splitters and sorters to partition and order the data.</p><h3>Sample Data</h3><p>Use the following SQL to create a sample table for testing:</p><pre>CREATE TABLE DateTable (<br>id INT AUTO_INCREMENT,<br>start_date DATE,<br>end_date DATE,<br>PRIMARY KEY (id)<br>);<br><br>INSERT INTO DateTable (start_date, end_date)<br>VALUES<br> - Positive test cases (end_date is greater than start_date)<br>(&#39;2020–06–01&#39;, &#39;2020–06–02&#39;), - end_date is 1 day after start_date<br>(&#39;2020–07–01&#39;, &#39;2020–07–31&#39;), - end_date is 30 days after start_date<br>(&#39;2020–08–01&#39;, &#39;2021–08–01&#39;), - end_date is 1 year after start_date<br> - Negative test cases (end_date is not greater than start_date)<br>(&#39;2020–09–01&#39;, &#39;2020–09–01&#39;), - end_date is the same as start_date<br>(&#39;2020–10–01&#39;, &#39;2020–09–30&#39;), - end_date is 1 day before start_date<br>(&#39;2020–11–01&#39;, &#39;2019–11–01&#39;); - end_date is 1 year before start_date</pre><h3>Conclusion</h3><p>In this article, we demonstrated how to define and implement a custom expectation in Great Expectations to validate date column relationships. By following these steps, you can ensure the integrity of your data and identify inconsistencies early in your data pipeline.</p><p>Using custom expectations not only improves data quality but also provides a reusable and automated way to enforce data validation rules tailored to your specific requirements. With this approach, you can confidently work with clean, validated data for analytics and decision-making.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55a3f38bf4bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>