3

I am creating procedures on a PostgreSQL database. I read about is not possible to use rollback inside these procedures.

Why?

Is it possible to use commit?

I guess that this is related with ACID properties, but what if we have two insert operations in a procedure. If the second fails the second one gets a rollback?

Thank you.

1
  • 1
    For one, because Postgres doesn't have procedures, only functions. Commented Feb 20, 2017 at 22:35

2 Answers 2

4

Postgres' overview gives a hint by explaining how their functions are different than traditional stored procedures:

Functions created with PL/pgSQL can be used anywhere that built-in functions could be used. For example, it is possible to create complex conditional computation functions and later use them to define operators or use them in index expressions.

This makes it awkward to support transactions within functions for every possible situation. From the docs:

Functions and trigger procedures are always executed within a transaction established by an outer query... However, a block containing an EXCEPTION clause effectively forms a subtransaction that can be rolled back without affecting the outer transaction.

If you were to have two INSERTs in a function, the first can be wrapped in an EXCEPTION block to catch any errors and decide if the second should be executed.

Sign up to request clarification or add additional context in comments.

Comments

1

You are correct. You cannot rollback transactions that were started prior to the procedure from within the procedure. In addition, a transaction cannot be created within the procedure either. You would receive this error:

ERROR: cannot begin/end transactions in PL/pgSQL
SQL state: 0A000
Hint: Use a BEGIN block with an EXCEPTION clause instead.

As this error states, and as Matt mentioned, you could use an exception block to essentially perform a rollback. From the help:

When an error is caught by an EXCEPTION clause, the local variables of the PL/pgSQL function remain as they were when the error occurred, but all changes to persistent database state within the block are rolled back.

Alternatively, you could call the procedure from within a transaction, and roll that back if necessary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.