Skip to main content

This package help to implement realtime db notifications.

Project description

PgPigeon

This package will help to capture realtime postgreSQL table notification in python scripts.

📝 Table of Contents

🧐 About

This package can be used for capture PostgreSQL database table event at real time in python scripts.

🏁 Getting Started

  • Dependancy & prerequisite

    • Python >=3.6 should be installed.
    • "psycopg2>=2.9.3"
  • To Start experimenting this package you need to install it.

  • [Step - 1]


    pip install pgpigeon

  • [Step - 2]

    • To configure pigeon
    
    pigeon configure
    
    

    This will create the configuration file "pigeon.json" in "pigeon" folder. In this file you can see database related settings i.e. database , schema , tables and triggers.

  • [Step - 3]

    • [To generate the db scripts i.e. triggers run following command ]
    
    pigeon create-scripts
    
    

    This will create all the required scripts in "pigeon/scripts" folder. Two scripts files will be created on for trigger function and second trigger.

  • [Step - 4]

    • To create the triggers in database i.e. run following command
    
    
    pigeon create-triggers
    
    

    This will create required triggers in database.

  • [Step - 5]

    • To create sample code run following command
    
    pigeon sample-code
    
    

    This will create sample code in "pigeon.py".

Now you an hook "pigeon.py" sample code anywhere in your code logic. It will start notifying if any change happen in the target db tables.

  • Let's review "pigeon.json" configuration file.
    {
    "dbname": "postgres",
    "host": "localhost",
    "port": "5432",
    "user": "postgres",
    "password": "postgres",
    "schemas": [
        {
            "name": "public",
            "tables": [
                {
                    "name": "items",
                    "triggers": [
                        {
                            "name": "pg_pigeon_default_after_insert_update_delete_trigger",
                            "trigger_func": "pg_pigeon_default_after_insert_update_delete_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "INSERT OR UPDATE OR DELETE",
                            "trigger_on_statement": "INSERT OR UPDATE OR DELETE",
                            "on_condition": "AFTER",
                            "is_active": "True"
                        },
                        {
                            "name": "pg_pigeon_default_before_insert_update_delete_trigger",
                            "trigger_func": "pg_pigeon_default_before_insert_update_delete_trigger_func",
                            "channel_name": "pg_pigeon_default_channel_before",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "INSERT OR UPDATE OR DELETE",
                            "trigger_on_statement": "INSERT OR UPDATE OR DELETE",
                            "on_condition": "BEFORE",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_after_insert_update_trigger",
                            "trigger_func": "pg_pigeon_default_after_insert_update_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "INSERT OR UPDATE OR DELETE",
                            "trigger_on_statement": "INSERT OR UPDATE OR DELETE",
                            "on_condition": "AFTER",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_after_insert_trigger",
                            "trigger_func": "pg_pigeon_default_after_insert_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "INSERT",
                            "trigger_on_statement": "INSERT",
                            "on_condition": "AFTER",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_after_update_trigger",
                            "trigger_func": "pg_pigeon_default_after_update_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "UPDATE",
                            "trigger_on_statement": "UPDATE OF item_description",
                            "on_condition": "AFTER",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_after_delete_trigger",
                            "trigger_func": "pg_pigeon_default_after_delete_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "DELETE",
                            "trigger_on_statement": "DELETE",
                            "on_condition": "AFTER",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_before_insert_trigger",
                            "trigger_func": "pg_pigeon_default_before_insert_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "INSERT",
                            "trigger_on_statement": "INSERT",
                            "on_condition": "BEFORE",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_before_update_trigger",
                            "trigger_func": "pg_pigeon_default_before_update_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "UPDATE",
                            "trigger_on_statement": "UPDATE OF item_no , item_description",
                            "on_condition": "BEFORE",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_instead_of_insert_trigger",
                            "trigger_func": "pg_pigeon_default_instead_of_insert_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "INSERT",
                            "trigger_on_statement": "INSERT",
                            "on_condition": "INSTEAD OF",
                            "is_active": "False"
                        },
                        {
                            "name": "pg_pigeon_default_instead_of_update_trigger",
                            "trigger_func": "pg_pigeon_default_instead_of_update_trigger_func",
                            "channel_name": "pg_pigeon_default_channel",
                            "return_columns": "['item_no', 'item_description']",
                            "type": "ROW",
                            "trigger_on": "UPDATE",
                            "trigger_on_statement": "UPDATE OF item_no , item_description",
                            "on_condition": "INSTEAD OF",
                            "is_active": "False"
                        }
                    ]
                }
            ]
        }
    ]
}

Now you can see above json config file having all the details in order to create trigger for notification. i.e. database connection details for connectivity , schema , table and trigger info to create triggers.

Note -


"channel_name": "pg_pigeon_default_channel"

"channel_name" is the property responsible to communicate with python script.

"return_columns" is the json property responsible to send notification payload to python script. This property value should be look like below one.


"return_columns": "['item_no', 'item_description']"

For example - as mentioned in json config file. if we have a table "items" structure like

CREATE TABLE public.items (
	item_no int4 NULL,
	item_description varchar NULL
);

then this property should be look like

"return_columns": "['item_no', 'item_description']"

all the keys are table column names.

Let's review the sample code .

from pgpigeon.pgnest import PgNest
from pgpigeon.context_models import PigeonChannelContext,PigeonContext, PgExecutionStrategy

class PGPigeonClient:
    def callback_func(self, channel, payload):
        print(f"Channel : {channel}")
        print(f"Payload : {payload}")

    def get_pg_db_dict(self):
        pg_db_dict = {}
        pg_db_dict["dbname"] = "postgres"
        pg_db_dict["host"] = "localhost"
        pg_db_dict["port"] = "5432"
        pg_db_dict["user"] = "postgres"
        pg_db_dict["password"] = "postgres"
        return pg_db_dict

    def start_keep_eye_on_channels_and_notify(self):
        pg_contexts = []

        pg_context = PigeonContext("pg_pigeon_default_process")
        pg_context.execution_strategy = PgExecutionStrategy.IN_SEPARATE_PROCESS
        # If you set is_main_on_hold=True , main thread or process will be blocked.
        # If you set is_main_on_hold=False , main thread or process will keep running.
        pg_context.is_main_on_hold = True

        pg_channel = PigeonChannelContext("pg_pigeon_default_channel")
        pg_channel.callbacks.append(self.callback_func)

        pg_context.channels.append(pg_channel)
        pg_contexts.append(pg_context)

        pg_nest = PgNest()
        pg_db_dict = self.get_pg_db_dict()
        pg_nest.start_keep_eye_on_channels_and_notify(
            pg_db_dict, pg_contexts)


if __name__ == "__main__":
    client = PGPigeonClient()
    client.start_keep_eye_on_channels_and_notify()

From above sample code you can see the python script is listening the channel for notification. Once your script is successfully running you will see the logs.

:: Parent process id , name  : 23512:: Current process id , name  : 19768
:: Waiting for new messages payload ....

if you insert or update or delete any record in target db table you will see this logs.

:: Current process id , name  : 19768
:: Waiting for new messages payload ....
:: Message payload received from channel pg_pigeon_default_channel): {"item_no" : 1, "item_description" : "23523523", "action" : "INSERT"}
Channel : pg_pigeon_default_channel
Payload : {"item_no" : 1, "item_description" : "23523523", "action" : "INSERT"}
:: Parent process id , name  : 23512:: Current process id , name  : 19768
:: Waiting for new messages payload ....
:: Message payload received from channel pg_pigeon_default_channel): {"item_no" : 1, "item_description" : "dinesh kushwaha", "action" : "UPDATE"}
Channel : pg_pigeon_default_channel
Payload : {"item_no" : 1, "item_description" : "dinesh kushwaha", "action" : "UPDATE"}
:: Parent process id , name  : 23512:: Current process id , name  : 19768
:: Waiting for new messages payload ....
:: Message payload received from channel pg_pigeon_default_channel): {"item_no" : 1, "item_description" : "dinesh kushwaha", "action" : "DELETE"}
Channel : pg_pigeon_default_channel
Payload : {"item_no" : 1, "item_description" : "dinesh kushwaha", "action" : "DELETE"}
:: Parent process id , name  : 23512:: Current process id , name  : 19768
:: Waiting for new messages payload ....

Now you can dieselize the payload and you can do anything with it.

✍️ Authors

See also the list of contributors who participated in this project.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pgpigeon-1.1.5.tar.gz (13.9 kB view details)

Uploaded Source

Built Distribution

pgpigeon-1.1.5-py3-none-any.whl (15.5 kB view details)

Uploaded Python 3

File details

Details for the file pgpigeon-1.1.5.tar.gz.

File metadata

  • Download URL: pgpigeon-1.1.5.tar.gz
  • Upload date:
  • Size: 13.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.10

File hashes

Hashes for pgpigeon-1.1.5.tar.gz
Algorithm Hash digest
SHA256 492f9c11ebd4bac1c98ef6d04f04e39474965c37bae4b84299ba0203d83892c1
MD5 45d01ed46d62f30f5e33f4719fba7f97
BLAKE2b-256 54f910072bf9321f5308e0742f584d19cceeaec13bd73b01ee94da1bbfab99f9

See more details on using hashes here.

File details

Details for the file pgpigeon-1.1.5-py3-none-any.whl.

File metadata

  • Download URL: pgpigeon-1.1.5-py3-none-any.whl
  • Upload date:
  • Size: 15.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.10

File hashes

Hashes for pgpigeon-1.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 ab37578f6cf6133b7a90d9545088168783590f4e4645907f419ee0033075a7ad
MD5 c46a3fa17042f4ec4970683c4a67af35
BLAKE2b-256 50df94b163d127e0aa85fb83d523f662aa6ffe0cecc6833ab54e124dc401ceb3

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page