PHP、PDO和Postgres中的事务错误回滚处理方法

4
我有一个基于PHP/Yii的非常广泛的PHP更新脚本,用于更新不同数据库类型(MSSQL、Postgres和MySQL)的数据库。
整个脚本在事务中运行。然而,有些语句会导致查询错误(例如如果某个表上已经存在某个关键字)。我用 try/catch 语句包围了这些语句,在MySQL中这样做很好。
但是在Postgres上,一旦发生无效查询,事务就会自动失败。对于所有后续语句,都会显示以下错误消息:
CDbCommand failed to execute the SQL statement: SQLSTATE[25P02]: In failed sql transaction: ERROR: current transaction is aborted, commands ignored until end of transaction block

但我需要Postgres继续事务,因为我想在应用程序中决定何时回滚 - 或者有一种清除错误并继续事务的方法。
如何做到这一点?

如果脚本检测到“重复键错误”,下一步该怎么办? - wildplasser
@wildplasser:一些其他无关的声明。 - Deckard
1个回答

5

为此目的使用保存点:

BEGIN; -- transaction starts here

-- do things if you want

SAVEPOINT my_savepoint;

-- failing statement here
-- all other statements are ignored

ROLLBACK TO SAVEPOINT my_savepoint;

-- continue your transaction starting from my_savepoint

COMMIT;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接