取消用户定义函数中的先前操作

时间:2013-05-22 12:03:09

标签: postgresql transactions plpgsql rollback postgresql-9.2

是否可以取消用户定义函数中的先前操作?

例如:

CREATE OR REPLACE FUNCTION transact_test () RETURNS BOOLEAN
AS $$
    BEGIN

        UPDATE table1 SET ...

        UPDATE table2 SET ...

        IF some_condition THEN
            --Here is  possible to cancel  all above operations?
            RETURN FALSE; 
        END IF;

        RETURN TRUE;
    END;
$$
LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:3)

到目前为止,这两个答案都是不正确的 如果您尝试启动事务或在plpgsql函数中使用SAVEPOINT,则会收到如下错误消息:

ERROR:  cannot begin/end transactions in PL/pgSQL
HINT:  Use a BEGIN block with an EXCEPTION clause instead.
CONTEXT:  PL/pgSQL function "f_savepoint" line 6 at SQL statement

如果在普通SQL函数中尝试SAVEPOINT

ERROR:  SAVEPOINT is not allowed in a SQL function
CONTEXT:  SQL function "f_savepoint2" during startup

如错误消息所示,请在plpgsql函数内使用BEGIN block。您的演示可能如下所示:

CREATE OR REPLACE FUNCTION transact_test(boolean)
  RETURNS boolean AS
$func$
BEGIN -- start a nested BEGIN block
    UPDATE t SET i = i+1 WHERE i = 1;
    UPDATE t SET i = i+1 WHERE i = 3;
    IF $1 THEN
        RAISE EXCEPTION 'foo';  -- cancels all of the above
    END IF;

    RETURN TRUE;

EXCEPTION WHEN OTHERS THEN
    RETURN FALSE; 
    -- do nothing
END
$func$ LANGUAGE plpgsql;

-> SQLfiddle证明这一切。