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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • How Much Signal Differential Privacy Takes From Your Dashboards, in Events
  • Consumer Lag Is the Wrong Finish Line

Trending

  • DuckDB for Python Developers
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices
  • Replay, Scheduling, and Throttling: Engineering a Self-Service Kafka Streaming Tool at Scale
  • Why AI Agents Need a Shared Enterprise Ontology

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jul. 06, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
30.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • How Much Signal Differential Privacy Takes From Your Dashboards, in Events
  • Consumer Lag Is the Wrong Finish Line

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook