DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • Streamlining Event Data in Event-Driven Ansible

Trending

  • Spring and PersistenceContextType.EXTENDED
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  • Role of Cloud Architecture in Conversational AI
  1. DZone
  2. Data Engineering
  3. Databases
  4. Notify Events From PostgreSQL to External Listeners

Notify Events From PostgreSQL to External Listeners

What happens when you need to call external programs from a PostgreSQL database? Read on for a solution.

By 
Gonzalo Ayuso user avatar
Gonzalo Ayuso
·
Jul. 06, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
29.9K Views

Join the DZone community and get the full member experience.

Join For Free

Sometimes, we need to call external programs from our PostgreSQL database. We can send sockets from SQL statements. I've written about it. The problem with this approach is if the user rolls back the transaction. The socket has been already emitted. That's a problem (or not, depending on our application). Also, nobody guarantees that the process behind the socket server has access to the data of the transaction. If we're very fast, maybe the transaction isn't committed yet. We can use a sleep function, but sleep functions are always a bad idea. PostgreSQL gives us another tool to decouple processes: LISTEN and NOTIFY.

Let me show you and example. First we create a table:

CREATE TABLE PUBLIC.TBLEXAMPLE
(
    KEY1 CHARACTER VARYING(10) NOT NULL,
    KEY2 CHARACTER VARYING(14) NOT NULL,

    VALUE1 CHARACTER VARYING(20),
    VALUE2 CHARACTER VARYING(20) NOT NULL,

    CONSTRAINT TBLEXAMPLE_PKEY PRIMARY KEY (KEY1, KEY2)
)


Now we add an "after insert" trigger to our table:

CREATE TRIGGER TBLEXAMPLE_AFTER
AFTER INSERT
ON PUBLIC.TBLEXAMPLE
FOR EACH ROW
EXECUTE PROCEDURE PUBLIC.NOTIFY();


And now, within the trigger function, we send a notify event ("myEvent" in this case) with the row information. We need to send plain text in the notify event so we'll use JSON to encode our row data.

CREATE OR REPLACE FUNCTION PUBLIC.NOTIFY() RETURNS trigger AS
$BODY$
BEGIN
    PERFORM pg_notify('myEvent', row_to_json(NEW)::text);
    RETURN new;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE COST 100;


Now we're going to build a server side example that connects to our PostgreSQL database and listen to the event. In this case, we're going to use Node.js to build the prototype. This example also will enqueue events into a gearman server.

var pg = require('pg'),
    gearmanode = require('gearmanode'),
    gearmanClient,
    conString = 'tcp://username:password@localhost:5432/gonzalo',
    pgClient;

gearmanode.Client.logger.transports.console.level = 'error';

gearmanClient = gearmanode.client();

console.log('LISTEN myEvent');
pgClient = new pg.Client(conString);
pgClient.connect();
pgClient.query('LISTEN myEvent');
pgClient.on('notification', function (data) {
    console.log("\033[34m" + new Date + '-\033[0m payload', data.payload);
    gearmanClient.submitJob('sms.sender.one', data.payload);
});


And that's all. Now we only need to perform an INSERT statement in our table. This process will trigger our event and our Node.js will enqueue the process into a gearman queue.

INSERT INTO PUBLIC.TBLEXAMPLE(KEY1, KEY2, VALUE1, VALUE2) VALUES ('k1', 'k2', 'v1', 'v2');


It's good to note  that if our insert statement is inside a transaction and we roll it back, notify won't send any message.

Event PostgreSQL

Published at DZone with permission of Gonzalo Ayuso, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • Streamlining Event Data in Event-Driven Ansible

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!