Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell PostgreSQL not to abort the whole transaction when a single constraint has failed?

Tags:

postgresql

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 SAVEPOINTs 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?

like image 685
Glyph Avatar asked Feb 24 '12 18:02

Glyph


People also ask

What causes the current transaction to abort?

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.

Which syntax is used to abort the current transaction in PostgreSQL?

Use COMMIT to successfully terminate a transaction. Issuing ABORT outside of a transaction block emits a warning and otherwise has no effect.


1 Answers

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."

like image 143
Rob Swarbrick Avatar answered Oct 23 '22 21:10

Rob Swarbrick