If you wish to abort a transaction within a function, then yes, raising an exception is a good choice.
You can use subtransactions within PL/PgSQL functions by using BEGIN ... EXCEPTION
blocks within the function. Use an inner BEGIN ... EXCEPTION
block and within it RAISE
an exception with a user defined SQLSTATE. Catch the exception in the EXCEPTION
block.
A RAISE
(of ERROR
or higher) within a BEGIN ... EXCEPTION
block will roll back work done within that block, as if you had used a SAVEPOINT
and ROLLBACK TO SAVEPOINT
.
Functions cannot force a rollback of the top level transaction; if you RAISE
an exception, an outer pl/pgsql function can catch the exception in a BEGIN ... EXCEPTION
block, or the client can use a ROLLBACK TO SAVEPOINT
.