Does Postgres support nested or autonomous transactions?

后端 未结 2 1277
醉酒成梦
醉酒成梦 2020-11-28 12:18

I have situation in which I have to commit a portion of code as transaction of its own.
I have created a table subtransaction_tbl:

CREATE TA         


        
2条回答
  •  清酒与你
    2020-11-28 12:30

    There are no autonomous transactions in Postgres before Postgres 11, where SQL procedures were added. Everything that's done in a function is rolled back with the transaction.

    Here is a discussion of the feature:

    • http://wiki.postgresql.org/wiki/Autonomous_subtransactions

    In Postgres 10 or older a workaround could be to (ab-)use dblink:

    • dblink can't update a table on the same database in an after UPDATE trigger
    • How do I do large non-blocking updates in PostgreSQL?

    There is also the related concept of a SAVEPOINT. (Not the same thing!):

    plpython

    plpython has subtransactions (with plpy.subtransaction():), but that's not the same as autonomous transactions. There is no separate COMMIT. All it does, is bundle a couple of statements together to make them atomic. Without that, if an exception occurs somewhere in the middle, and you catch that exception, only the code up to this exception would be executed. If you wrap it into a subtransaction, it's all or nothing. This is like using a SAVEPOINT, not an autonomous transaction. Per documentation:

    The subtransaction context manager does not trap errors, it only assures that all database operations executed inside its scope will be atomically committed or rolled back.

提交回复
热议问题