Live Database View

I have setup myself a NodeJS and socket.io server with the mysql node module and all works well.

Here is my script:

// create an http server listening on port 8100
var io = require('socket.io').listen(8100);
var mysql = require('mysql');

var connection = mysql.createConnection({
host     : '127.0.0.1',
user     : 'user',
password : 'password',
database : 'mybase'
});

connection.connect(function(e){
if(e)
{
    console.log('Database connection failed. ('+e+')') ;
}
else
{
    console.log('Database connection successful!') ;
}
})

connection.query('SELECT id, name FROM entity_details WHERE id = 4626', function(e, rows) {
if(e)
{

}
else
{
    console.log(decodeURIComponent(rows[0]['name'])) ;
}
 });

// listen on new connections
io.sockets.on('connection', function (socket) {

// listen on an event called "eventA"
socket.on('eventA', function(data) {
    // send "eventA" to all clients, except the sender
    io.sockets.emit('eventA', data);

});

});

My question is how do I get MySQL to "tell" nodeJS/Socket.io that values in the column have changed or new rows updated? So in effect I get a live view of whatever table, column etc I want in the database?

I figure I don't want to poll the database every second as that defeats the whole idea of socket.io and I might as well use setTimeout with ajax calls.


After some thinking I have come up with this process that I think would be the most efficient for a real-time view, please see attached. Please let me know what you think!enter image description here

I'm using postgresql but since mysql supports triggers, it should work the same.

Put a trigger in each table on update subscribe to the events for each trigger on your database module

for (notification in notifications) { var n =notifications[notification]; pgclient.on('updated', n.handler); pgclient.query("LISTEN "+n.channel); } send message back

socket.emit('eventA',dbMsg.payload);

This way you don't need to poll.