Good day Monks. I have been using a little subroutine to do inserts on MySQL (via DBI and Pg) and get the inserted id:
sub insertsql {
my ($dbh,$table,$data,$ignore) = @_;
my @qm;
my @keys;
my @values;
my $i = -1;
foreach my $k (keys %$data) {
if (defined($data->{$k})) {
$i++;
$keys[$i] = $k;
$values[$i] = $data->{$k};
$qm[$i] = '?';
}
}
my $keylist = join(",",@keys);
my $qlist = join(",",@qm);
my $sqlstatement = "insert into $table ($keylist) values ($qlist)"
+;
if ($ignore) {
my $sqlstatement = "insert ignore into $table ($keylist) value
+s ($qlist)";
}
my $sth = $dbh->prepare($sqlstatement);
#$sth->execute(@values) || die "putsql could not execute MySQL sta
+tement: $sqlstatement $sth->errstr";
$sth->execute(@values) || die $sth->errstr;
$sth->finish();
return $dbh->{'mysql_insertid'};
}
I'm now working with Postgres and, alas, there is no 'mysql_insertid' for postgres, and it doesn't provide such an easy way to get the inserted id.
I found this thread on Stack Overflow where somebody suggests using a separate statement SELECT currval(pg_get_serial_sequence('[tablename]','id')) but that returns nothing. They also suggest adding returning id to the end of the insert statement. But I can't figure out how to make that work in the context of the subroutine.
Can anyone help?