问题
I'm making a CRUD with php and postgres, and I want to know if there a way to rollback the transaction if there is a error. actually if I get an error in the transaction the id (primary key) get increased, then I lose one id for the future use.
How can I prevent it? I mean, if the Insert's Query fails, don't make the auto increment in the table.
Im using a class for execute the querys:
public function insertRecord ($data){
$campos =$this->getTableFields();
$data =implode ("', '", $data);
$sql ="INSERT INTO {$this->table} ($campos) VALUES (";
$sysData =$this->getDefaultValues();
if($sysData){
$sysData .= ",";
$sql .="$sysData ";
}
$sql .="'$data') RETURNING {$this->campoId};";
echo $sql;
pg_query($this->linkid,$sql);
return $this->validateOperation();
}
回答1:
The transaction is rolled back. But it will still use up a number from a sequence, on which automatically incrementing values are based. This is by design and prevents long lasting locks, which would kill parallel execution performance.
There are some workarounds:
- postgresql generate sequence with no gap
来源:https://stackoverflow.com/questions/42737177/php-postgresql-how-i-can-rollback-a-query-if-is-returning-error