Engineering

How to Automate PostgreSQL Trigger to Slack message

November 11, 2023

Setup guide to get notified on Slack from your Postgres database

Automating PostgreSQL triggers to Slack can be a valuable way to keep your team informed of important events in your database. These triggers can help business simplify their process and make them more efficient. Timely notifications to Slack can help teams quickly respond to changes or issues. Suppose you're managing an e-commerce platform and want to get Slack notifications for every new order above a certain value. This real-time alerting could be essential for high-priority customer engagement or inventory management.

In this detailed guide, we’ll walk you through how to automate Postgres triggers to send Slack messages:

  1. Method #1: Using PostgreSQL NOTIFY/LISTEN with Python
  2. Method #2: Automating Trigger through Locale

Method #1: Using PostgreSQL NOTIFY/LISTEN with Python

When dealing with real-time event notifications in PostgreSQL, NOTIFY and LISTEN commands can be quite powerful. In this method, the NOTIFY clause announces a message whenever a significant event occurs, and the LISTEN clause receives the messages and acts upon them. Let's see how we can configure them:

Setting up a Slack Webhook URL

Before you can start sending notifications to Slack, you need to set up an incoming webhook:

  1. Go to your Slack workspace's App Directory.
  2. Search for and select Incoming WebHooks.
  3. Click Add to Slack to create a new webhook.
  4. Choose the channel to which you want the notifications to be posted.
  5. Click the Add Incoming WebHooks integration button.
  6. Copy the Webhook URL provided — you'll use this in your Python script to send notifications to Slack.
Activating incoming webhook on Slack

Remember to keep your webhook URL secure; it's a key that allows messages to be sent to your Slack workspace.

Setting up the PostgreSQL trigger

Next, we set up a trigger in PostgreSQL. This trigger will NOTIFY a channel whenever a new order that meets our criteria is inserted into the orders table:


CREATE OR REPLACE FUNCTION notify_new_order() RETURNS TRIGGER AS $$
BEGIN
  IF NEW.total_amount > 500 THEN
    NOTIFY high_value_orders, row_to_json(NEW)::text;
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER high_value_order_after_insert
AFTER INSERT ON orders
FOR EACH ROW EXECUTE FUNCTION notify_new_order();

In this SQL snippet, row_to_json(NEW) converts the newly inserted row into a JSON format, making it easy to extract data points in our Python script. This is a very handy JSON function provided by PostgreSQL, you can read up more about it here.

When the trigger fires, the NEW record is transformed into JSON, encapsulating all the column values of the new order. This JSON is sent as a string payload with the NOTIFY command.

Sending the Slack message

Next, we need a Python script that listens for these notifications and sends a message to a Slack channel using a webhook. In this script, we are first setting up a connection our PostgreSQL server that will listen for incoming NOTIFY payloads of the function high_value_orders . Once we receive the payload, we use its data to create a Slack message body and send it using the Slack Webhook URL we previously obtained.


import select
import psycopg2
import requests
import json

# Set up PostgreSQL connection and listen for notifications
conn = psycopg2.connect(database="your_db", user="your_user", password="your_password")
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute("LISTEN high_value_orders;")

print("Waiting for notifications on channel 'high_value_orders'")

while True:
    if select.select([conn],[],[],5) == ([],[],[]):
        print("Timeout")
    else:
        conn.poll()
        while conn.notifies:
            notify = conn.notifies.pop(0)
            payload = json.loads(notify.payload)

            # Send Slack notification
            slack_data = {
                'text': f"New high-value order received: Order ID {payload['id']} with total amount {payload['total_amount']}."
            }
            response = requests.post(
                'your_slack_webhook_url',
                data=json.dumps(slack_data),
                headers={'Content-Type': 'application/json'}
            )
            if response.status_code != 200:
                raise ValueError(f"Request to Slack returned an error {response.status_code}, the response is:\n{response.text}")

With this setup, when a new high-value order is placed, the trigger sends a notification, the Python script catches it, and a detailed Slack message is posted. It's a neat solution for real-time alerts, but it requires continuous script running and careful handling of the webhook URL security. It comes with a set of limitations which can make the whole process complex for you:

  • This becomes less efficient as the scale of data increases leading to bottlenecks in high-traffic databases.
  • Implementing and maintaining triggers for multiple tables and operations can be complex and error-prone, and requires constant monitoring.
  • NOTIFY does not support built-in filtering or aggregation of notifications. This means that listeners receive all messages leading to an overwhelming amount of noise.
  • It relies on the Slack Webhook being correctly configured and secured.

Let’s look at the other method, which can help you avoid these issues and is easy to set up.

Method #2: Automating Trigger through Locale

Locale is a no-code platform which significantly simplifies the process of PostgreSQL query runs.  Automating PostgreSQL query through locale is an easy deal, With just a few clicks you can automate the PostgreSQL query results to Slack. Let’s see how you can automate through Locale.

Step 1: Login to Locale, Go to Org Setting and Connect your Postgres database from the data source.

Step 2: Now go to Alerts → Create New Alerts. Choose your database → Click on Setup data to be monitored.

Database Connection setup on Locale platform

Step 3:  Write your own SQL Query and click Run to verify the data. Once you are satisfied, click Done.

SQL Query to set the alert condition that will trigger alerts about high value orders

In the above example, if you want to get notified about large orders, you can use the below SQL script:


SELECT id, total_amount 
FROM orders
WHERE total_amount > 500
ORDER BY created_at DESC

Step 4: Now Setup your schedule based on your requirement, this would automatically run the query based on the frequency you set. Click on Run the query at frequency and choose your schedule

Scheduling alert runs in Locale by setting alert frequency

Step 5: With Locale, you can also customize the Slack message to get the better idea. To configure the Slack message, Click on Configure incidents and enter your message in the Incident Title.

Configure incidents on Locale to provide better context to the users receiving alerts

Step 6: Set up whom or on which channel the Slack alert should be sent. Go to the Setup Notification section and click on Add Notification then select Send Slack Message. Select whether you want the Slack message to be sent to a channel or a user. You can also preview and send test notifications.

Configuring Slack alerts to define whom to send alerts on Locale

Save the alert. It will automatically run itself on the pre-set schedule and trigger a Slack notification.

Sample Slack alerts for high value orders from Locale

Conclusion

Automating PostgreSQL triggers to Slack helps your team to be notified on their preferred channel so that they can quickly response to changes or issues. In this detailed guide, we looked at two methods which can help you to automate Slack alerts for PostgreSQL query results.

However, while Method 1 (using PostgreSQL NOTIFY/LISTEN with Python) is a viable option, it can be complex and error-prone to implement, especially if you need to handle complex notification scenarios. Additionally, you need to keep your Python script up to date with any changes to your PostgreSQL database or Slack configuration.

Locale’s no-code platform makes it easy to automate PostgreSQL triggers to Slack with minimal one-time setup. Locale helps you to:

  • Easy automation of PostgreSQL triggers to Slack
  • Choose a schedule for sending notifications based on your requirements.
  • Dynamically choose people to send Slack message based on the query result allowing alerts only go to the person it needs.
  • Group the notifications ensuring less noise to the users.
  • Set up and provide a clear playbook for users to follow in case of any issue so that it can be resolved efficiently.
  • Set up an escalation rule to ensure issues are being resolved.
  • Moreover, if you want to expand sending reports/data to other destinations like Gmail, WhatsApp, MS Teams etc, you get to do that with 100+ integration options.

If you are looking for a simple and reliable way to automate PostgreSQL triggers to Slack, Try Locale. It takes less than 10 minutes to get all things set up:  Try for free

Receive Latest InsideOps Updates

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.