Postgresql 中文操作指南

44.10. Transaction Management #

在从顶层调用或从顶层调用的匿名代码块(DO 命令)中,可以控制事务。要提交当前事务,请调用 commit 命令。要回滚当前事务,请调用 rollback 命令。(请注意,无法通过 spi_exec 或类似方式运行 SQL 命令 COMMITROLLBACK。必须使用这些函数来完成。)在结束事务后,将自动启动一个新事务,因此没有为此提供单独的命令。

In a procedure called from the top level or an anonymous code block (DO command) called from the top level it is possible to control transactions. To commit the current transaction, call the commit command. To roll back the current transaction, call the rollback command. (Note that it is not possible to run the SQL commands COMMIT or ROLLBACK via spi_exec or similar. It has to be done using these functions.) After a transaction is ended, a new transaction is automatically started, so there is no separate command for that.

这是一个示例:

Here is an example:

CREATE PROCEDURE transaction_test1()
LANGUAGE pltcl
AS $$
for {set i 0} {$i < 10} {incr i} {
    spi_exec "INSERT INTO test1 (a) VALUES ($i)"
    if {$i % 2 == 0} {
        commit
    } else {
        rollback
    }
}
$$;

CALL transaction_test1();

在显式子事务处于活动状态时,无法结束事务。

Transactions cannot be ended when an explicit subtransaction is active.