I am using pg-promise to run my SQL queries. The queries themselves are stored in external .sql files.
When I execute a transaction, Postgres will abort the transaction if an error occurs (as expected). The problem that I'm running into is any separate queries I try to run after the transaction is aborted are not run and I instead get this message: "current transaction is aborted, commands ignored until end of transaction block". If the queries were being run in the psql console, I could solve this problem by issuing a ROLLBACK after the failed query. I don't think that's an option here since the SQL used by my application is located in an external file. I also don't think Savepoints are an option because the entire transaction should be thrown out if something fails.
How would I rollback in the SQL file if this error occurs?
Here's the SQL for reference:
BEGIN;
DELETE
FROM tournament_tossup_values
WHERE tournament_id = $1 AND
NOT EXISTS
(
SELECT id
FROM tournament_match
WHERE tournament_id = $1
);
UPDATE tournament
SET bonus_point_value = $5, parts_per_bonus = $6
WHERE id = $1 AND NOT EXISTS (
SELECT id
FROM tournament_match
WHERE tournament_id = $1
)
RETURNING bonus_point_value, parts_per_bonus; <-- Any subsequent accesses to the database by the application fail if this transaction fails
COMMIT; <-- I want to rollback everything if this fails
Thank you in advance!
tx? In this case we can't be sure what is going on, as you do not show the complete code of what you are doing. Perhaps it is best that you use methodtx, and execute queries in it as shown in all examples. See Transactions. This will make your code more predictable, since you do not provide a properROLLBACKlogic in your SQL anyway.