I have been recently porting a Perl application form Oracle to Postgres (my first time with Postgres) and I am stumped by a small issue which I was able to reduce to the following sample code:
use strict;
use warnings;
use DBI;
my @db_params = qw (dbi:Pg:host=127.0.0.1;database=test test test);
my $dbh = DBI->connect(@db_params, {AutoCommit => 0 } ) or die ;
while (1) {
my $sth = $dbh->prepare_cached('SELECT localtimestamp ') or die;
$sth->execute() or die;
my $result = $sth->fetchall_arrayref();
print $result->[0][0] , "\n";
sleep(5);
}
This outputs :
2011-11-27 16:46:25.94291
2011-11-27 16:46:25.94291
2011-11-27 16:46:25.94291
I am getting the same time stamp all the time unless I disconnect and reconnect to the database.
How can I make sure that ever time I select localtimestamp from the database I get the value corresponding to the time when the sql is executed?
Because you are not using autocommit, you are always in the same transaction, and localtimestamp gets the timestamp at the start of that transaction in Postgres. I.e. you will need to create individual transactions for your queries, using
$dbh->begin_workand$dbh->commit.