diff --git a/docs/changelog.md b/docs/changelog.md index 597260b12..c15e481d3 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -41,6 +41,8 @@ Older changelogs: [#967](https://github.com/ADOdb/ADOdb/issues/967) - pgsql: Fix PHP 8.1 deprecated warning [#956](https://github.com/ADOdb/ADOdb/issues/956) +- pgsql: avoid Insert_ID() failing when lastval() is not set + [#978](https://github.com/ADOdb/ADOdb/issues/978) ## [5.22.5] - 2023-04-03 diff --git a/drivers/adodb-postgres8.inc.php b/drivers/adodb-postgres8.inc.php index 911ec178c..58df47c63 100644 --- a/drivers/adodb-postgres8.inc.php +++ b/drivers/adodb-postgres8.inc.php @@ -45,13 +45,19 @@ class ADODB_postgres8 extends ADODB_postgres7 * @return int last inserted ID for given table/column, or the most recently * returned one if $table or $column are empty */ - protected function _insertID( $table = '', $column = '' ){ - $sql = 'SELECT '; - $sql .= empty($table) || empty($column) ? 'lastval()' : "currval(pg_get_serial_sequence('$table', '$column'))"; + protected function _insertID( $table = '', $column = '' ) + { + global $ADODB_GETONE_EOF; + + $sql = empty($table) || empty($column) + ? 'SELECT lastval()' + : "SELECT currval(pg_get_serial_sequence('$table', '$column'))"; + + // Squelch "ERROR: lastval is not yet defined in this session" (see #978) $result = @$this->GetOne($sql); - if( $result === false || $result == $ADODB_GETONE_EOF ){ - if( $this->debug ){ - ADOConnection::outp(__FUNCTION__ . "() failed : " . $this->errorMsg()); + if ($result === false || $result == $ADODB_GETONE_EOF) { + if ($this->debug) { + ADOConnection::outp(__FUNCTION__ . "() failed : " . $this->errorMsg()); } return false; }