tags:

views:

580

answers:

5

Is there a better way to watch for new entries in a table besides selecting from it every n ticks of time or something like that?

I have a table that an external program updates very often, and clients can watch for this new data as it arrive, how can I make that without having to set a fixed period of repeatable select statements?

A: 

if you know SQL enough... you could write Triggers and Alarms.

Mote
Can triggers dispatch to outside the database? I don't remember that they do this, can you explain more?
Augusto Radtke
Don't believe so for mysql.
itsmatt
Can triggers write to a file? If so, you could use inotify to watch the file and invoke a program when it's been updated.
Paul Tomblin
+2  A: 

Here's what I do: I've got some triggers set up for the table (insert, delete, update) and those triggers increment a counter in another table. My DB access code keeps a local counter and compares it to the returned value, ultimately sending a bool back to the caller, answering the question IsDataCurrent().

Our programs that use this DB access code either poll or check it on-request and then make the appropriate calls to keep themselves up to date.

I'm sure there are other ways to solve this. It worked for me pretty well, though.

itsmatt
So it still requires polling, only slightly better to poll: select * from lastupdatetable; versus select count(*) from datatable;
davr
I disagree. The query select count(*) might produce erroneous results. If I perform an add/ a delete/ and an add the count will be the same, right? So did the data change? You wouldn't know in that case. The last update table won't produce this situation.
itsmatt
But it still requires a select every n ticks, but that would be more low cost than selecting the actual data table, that's a way I'm considering too.
Augusto Radtke
+1  A: 

This is just a small improvement to your method. Write a trigger on the table(s) you are watching to update a Last_Changed table.

CheeZe5
+3  A: 

In MySQL there's no best way than to poll (you create a specific table to simplify the polling though), in other databases you can have triggers that have impact outside the database. In MySQL triggers can only do stuff inside the database itself (for instance, populating the helper table).

Vinko Vrsalovic
+2  A: 

Another similar approach would be to add

add column Last_Modified TIMESTAMP ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP

to each table and preface your select queries to compare the last request date/time with the max(Last_Modified).

Databases are typically pull sources and not push so you'll still need to programmatically probe for changes no matter what.

Rob Allen