Postgres automatically aborts transactions whenever any SQL statement terminates with an error, which includes any constraint violation. For example:
glyph=# create table foo (bar integer, constraint blug check(bar > 5));
CREATE TABLE
glyph=# begin;
BEGIN
glyph=# insert into foo values (10);
INSERT 0 1
glyph=# insert into foo values (1);
ERROR: new row for relation "foo" violates check constraint "blug"
STATEMENT: insert into foo values (1);
ERROR: new row for relation "foo" violates check constraint "blug"
No message has yet been issued to that effect, but the transaction is rolled back. My personal favorite line of this session is the following:
glyph=# commit;
ROLLBACK
... since "ROLLBACK
" seems like an odd success-message for COMMIT
. But, indeed, it's been rolled back, and there are no rows in the table:
glyph=# select * from foo;
bar
-----
(0 rows)
I know that I can create a ton of SAVEPOINT
s and handle errors in SQL that way, but that involves more traffic to the database, more latency (I might have to handle an error from the SAVEPOINT
after all), for relatively little benefit. I really just want to handle the error in my application language anyway (Python) with a try/except
, so the only behavior I want out of the SQL is for errors not to trigger automatic rollbacks. What can I do?
Explanation: This log event happens when a transaction fails due to a potentially unrelated error, and you try to run another query in the failed transaction.
Use COMMIT to successfully terminate a transaction. Issuing ABORT outside of a transaction block emits a warning and otherwise has no effect.
I'm extremely new to PostgreSQL, but one of the examples in the PostgreSQL documentation for triggers / server-side programming looks like it does exactly what you're looking for.
See: http://www.postgresql.org/docs/9.2/static/trigger-example.html
Snippet from the page: "So the trigger acts as a not-null constraint but doesn't abort the transaction."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With