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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Data Engineering
  3. Databases
  4. Sending Sockets from PostgreSQL Triggers with Python

Sending Sockets from PostgreSQL Triggers with Python

Gonzalo Ayuso user avatar by
Gonzalo Ayuso
·
Dec. 02, 12 · Interview
Like (0)
Save
Tweet
Share
6.60K Views

Join the DZone community and get the full member experience.

Join For Free

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
$body$
  import _socket
  try:
    s = _socket.socket(_socket.af_inet, _socket.sock_stream)
    s.connect((host, port))
    s.sendall(msg)
    s.close()
    return 1
  except:
    return 0
$body$
  language plpython volatile
  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
$body$
   import json
   stmt = plpy.prepare("select dummy.sendsocket($1, $2, $3)", ["text", "text", "int"])
   rv = plpy.execute(stmt, [json.dumps(td), "host", 26200])
$body$
language plpython volatile
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)

create trigger mytrigger
  after insert or update or delete
  on dummy.mytable
  for each row
  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:

node.js:

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
        pass

class myserverfactory(protocol.factory):
    def buildprotocol(self, addr):
        return myserver()

reactor.listentcp(port, myserverfactory(), interface=host)
reactor.run()

(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 ):

<?php
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);
$loop->run();

you also can use xinet.d to handle the tcp inbound connections.



Python (language) PostgreSQL Database

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Secrets Management
  • Why It Is Important To Have an Ownership as a DevOps Engineer
  • Type Variance in Java and Kotlin
  • Explainer: Building High Performing Data Product Platform

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: