iburrell has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to solve a database portability problem in timestamp interval calculations. The basic problem is finding all the sessions older the current time minus the timeout interval in seconds. There are lots of different ways to code this calculation in SQL but I am having trouble finding one that is portable between multiple databases. I want to support both PostgreSQL and MySQL. Postgres specific (because MySQL doesn't support EPOCH type in EXTRACT):
SELECT * FROM session WHERE EXTRACT(EPOCH FROM lastop) < EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) - $ +timeout
MySQL specific:
SELECT * FROM session WHERE UNIX_TIMESTAMP(lastop) < UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - $timeout
It is possible to do the calculation directly with timestamp values. The following is SQL92 standard, only supported by MySQL:
SELECT * FROM session WHERE lastop < now() - interval $timeout second
PostgreSQL uses a slightly different syntax (which I think is the SQL99 standard):
SELECT * FROM session WHERE lastop < now() - interval '$timeout second'
Is there any way to do this portably?

Replies are listed 'Best First'.
Re: Portable database interval calculation
by perrin (Chancellor) on Oct 25, 2002 at 20:44 UTC
    Just give up and use DBIx::AnyDBD. Then you can supply separate SQL statements for this non-portable stuff.
      Although, if you look at the recent DBI source code it has support for this... he integrated Matt's idea into DBI proper. Just look thru the source code for DbType or DbSubType

      He hasn't documented it yet and was actually looking for volunteers to do so.

      To see DBIx::AnyDBD in action, download SQL::Catalog or PApp::Hinduism.