begin transaction;
-- start a transaction
-- first SQL command with savepoint
SAVEPOINT sp_1;
-- your first INSERT command goes here
-- if it fails, you can rollback to savepoint sp_1
INSERT INTO "table_name" ("id","owner_id") VALUES (1, 100);
EXCEPTION WHEN others THEN
ROLLBACK TO SAVEPOINT sp_1;
RAISE NOTICE 'The first INSERT failed: %', SQLERRM;
release savepoint sp_1;
-- second SQL command with savepoint
SAVEPOINT sp_2;
-- your second INSERT command goes here
-- if it fails, you can rollback to savepoint sp_2
INSERT INTO "table_name" ("id","owner_id")
VALUES (2, 200);
EXCEPTION WHEN others THEN
ROLLBACK TO SAVEPOINT sp_2;
RAISE NOTICE 'The second INSERT failed: %', SQLERRM;
-- and so on for other commands...
END;
-- if everything went fine, commit the transaction
COMMIT;
END
The above code works fine for the first time if a duplicate key error happens.
SQL Error [23505]: ERROR: duplicate key value violates unique constraint "pk_headend" Detail: Key (id)=(1) already exists.
when I try again, below error occurs
SQL Error [25P02]: ERROR: current transaction is aborted, commands ignored until end of transaction block
The duplicate key error shows up when I reconnect to database and execute the above code again but I still get the second error, SQL Error [25P02] when I execute the code second time with in the same second connection.
what is the issue? can someone help me understand this issue?