Yavanosta
Yavanosta

Reputation: 1670

PostgreSQL DEFERRED CONSTRAINTS and begin end block

I have a table with unique constraint that marked as DEFERRABLE INITIALLY DEFERRED;

Then I execute next query:

START TRANSACTION;
INSERT INTO "T" VALUES (1,2);
INSERT INTO "T" VALUES (1,2);
INSERT INTO "T" VALUES (1,2);
ROLLBACK;

And everything goes fine. But If i try to execute

START TRANSACTION;
BEGIN;
    INSERT INTO "T" VALUES (1,2);
    INSERT INTO "T" VALUES (1,2);
    INSERT INTO "T" VALUES (1,2);
END;
ROLLBACK;

I get an error. Why does Postgres force constraint check when exiting BEGIN END block? Shouldn't in check constraints at the end of transaction? How can I change this behavior?

Upvotes: 0

Views: 680

Answers (1)

user330315
user330315

Reputation:

END is a synonym for COMMIT as documented in the manual:

http://www.postgresql.org/docs/current/static/sql-end.html

So in the first example you start a transaction, insert the conflicting rows and do a rollback.

In the second example you start a transaction, then you start another one (because BEGIN is a synonym for START TRANSACTION) then you try to commit the inserts by running END, then you do a rollback.

Upvotes: 2

Related Questions