Sending sockets from PostgreSQL triggers with Python

Picture this: We want to notify to one external service each time that one record is inserted in the database. We can find the place where the insert statement is done and create a TCP client there, but: What happens if the application that inserts the data within the database is a legacy application?, or maybe it is too hard to do?. If your database is PostgreSQL it’s pretty straightforward. With the “default” procedural language of PostgreSQL (pgplsql) we cannot do it, but PostgreSQL allows us to use more procedural languages than plpgsql, for example Python. With plpython we can use sockets in the same way than we use it within Python scripts. It’s very simple. Let me show you how to do it.

First we need to create one plpython with our TCP client

CREATE OR REPLACE FUNCTION dummy.sendsocket(msg character varying, host character varying, port integer)
  RETURNS integer AS
  import _socket
    s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
    s.connect((host, port))
    return 1
    return 0
  COST 100;
ALTER FUNCTION dummy.sendsocket(character varying, character varying, integer)
  OWNER TO username;

Now we create the trigger that use our socket client.

CREATE OR REPLACE FUNCTION dummy.myTriggerToSendSockets()
RETURNS trigger AS
   import json
   stmt = plpy.prepare("select dummy.sendSocket($1, $2, $3)", ["text", "text", "int"])
   rv = plpy.execute(stmt, [json.dumps(TD), "host", 26200])
COST 100;

As you can see in my example we are sending all the record as a JSON string in the socket body.

And finally we attach the trigger to one table (or maybe we need to do it to more than one table)

  ON dummy.myTable
  EXECUTE PROCEDURE dummy.myTriggerToSendSockets();

And that’s all. Now we can use one simple TCP socket server to handle those requests. Let me show you different examples of TCP servers with different languages. As we can see all are different implementations of Reactor pattern. We can use, for example:


var net = require('net');

var host = 'localhost';
var port = 26200;

var server = net.createServer(function (socket) {
    socket.on('data', function(buffer) {
        // do whatever that we want with buffer

server.listen(port, host);

python (with Twisted):

from twisted.internet import reactor, protocol

HOST = 'localhost'
PORT = 26200

class MyServer(protocol.Protocol):
    def dataReceived(self, data):
        # do whatever that we want with data

class MyServerFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return MyServer()

reactor.listenTCP(PORT, MyServerFactory(), interface=HOST)

(I know that we can create the Python’s TCP server without Twisted, but if don’t use it maybe someone will angry with me. Probably he is angry right now because I put the node.js example first :))

php (with react):

include __DIR__ . '/vendor/autoload.php';

$host = 'localhost';
$port = 26200;

$loop   = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);

$socket->on('connection', function ($conn) {
    $conn->on('data', function ($data) {
        // do whatever we want with data

$socket->listen($port, $host);

You also can use xinet.d to handle the TCP inbound connections.

About Gonzalo Ayuso

Web Architect. PHP, Python, Node, Angular, ionic, PostgreSQL, Linux, ... Always learning.

Posted on November 26, 2012, in node.js, php, PostgreSQL, Python, Technology and tagged , , , , . Bookmark the permalink. 8 Comments.

  1. Great article,

    I’m curious does the indentation of the python code inside the BODY statement matter?

    some python code


    some python code

  2. I’m a bit late responding to an article 1.5 years after publishing, but its still relevant.

    Great article and great idea. I’ve done a number of similar functions and love using python functions inside postgres.

    However, using a trigger for this code means that if the connection is down at the moment, the message will never be sent. Also, the insert will not be committed until the socket connection is completed.

    What I have done in similar circumstances is added a staging table where I store the list of messages needing to be sent. On the trigger I add the row to my staging table and call Notify. I have a Listen process sitting on the server that calls a process messages function in the database, which goes through all the messages that have not been processed yet. I also call that function from a cron job every half an hour, in case the notify isn’t called.

    This works like an asynchronous trigger, in that the code is called on database action, but the commit isn’t dependent on the outside action.

  1. Pingback: Sending sockets from PostgreSQL triggers with Python « DbRunas – Noticias y Recursos sobre Bases de Datos

  2. Pingback: Notify events from PostgreSQL to external listeners | Gonzalo Ayuso | Web Architect

  3. Pingback: Notify Events From PostgreSQL to External Listeners – WordPress

  4. Pingback: Notify Events From PostgreSQL to External Listeners -

  5. Pingback: Notifique eventos do PostgreSQL para listeners externos -

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: