PHP - Postgresql How I can rollback a query if is returning error?

我与影子孤独终老i 提交于 2019-12-04 06:31:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!