diff --git includes/database/pgsql/database.inc includes/database/pgsql/database.inc index dbb3286..c4f948a 100644 --- includes/database/pgsql/database.inc +++ includes/database/pgsql/database.inc @@ -188,6 +188,30 @@ class DatabaseConnection_pgsql extends DatabaseConnection { return $id; } + + /** + * Overrides PDO::lastInsertId(). + * + * Catchs and handles the exception in case currval() fails. + */ + public function lastInsertId($name = null) { + try { + return parent::lastInsertId($name); + } catch(PDOException $e) { + if ($e->getCode() == 55000) { + // This fail if a value was inserted into the serial column and + // nextval() was never called. In that case, the last_insert_id is known + // by the caller and NULL is returned. + $last_insert_id = NULL; + } + else { + // If it is a different exception, re-throw it. + throw $e; + } + } + return $last_insert_id; + } + } /** diff --git includes/database/pgsql/query.inc includes/database/pgsql/query.inc index 8825229..5ed92ed 100644 --- includes/database/pgsql/query.inc +++ includes/database/pgsql/query.inc @@ -69,6 +69,16 @@ class InsertQuery_pgsql extends InsertQuery { } $last_insert_id = $this->connection->query($stmt, array(), $options); + // If a value was inserted into a serial column, update the sequence. + if (!empty($table_information->serial_fields)) { + foreach ($table_information->serial_fields as $index => $serial_field) { + if (in_array($serial_field, $this->insertFields)) { + $curval = $this->connection->query("SELECT MAX(" . $serial_field . ") FROM {" . $this->table . "}")->fetchField(); + $this->connection->query("SELECT SETVAL('" . $table_information->sequences[$index] . "', :curval)", array(':curval' => $curval)); + } + } + } + // Re-initialize the values array so that we can re-use this query. $this->insertValues = array();