SQL continues query execution after double key violation

I have a situation where I want to insert a string if it does not exist, and not insert it if it is already running. I tried to create sql queries that prevented this from happening (see here ), but I was told that the solution is to create constraints and throw an exception when they are violated.

I already have limitations. My question is: how can I catch the exception and continue to execute more requests? If my code looks like this:

cur = transaction.cursor()

#execute some queries that succeed

try:
    cur.execute(fooquery, bardata)  #this query might fail, but that OK
except psycopg2.IntegrityError:
    pass

cur.execute(fooquery2, bardata2)

Then I get an error in the second run:

psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block

How can I tell the computer that I want it to continue to execute requests? I do not want transaction.commit(), because I may need to roll back the entire transaction (requests that were previously executed).

+2
2

, SAVEPOINT, , . , SAVEPOINT, .

, :

+4

SAVEPOINT-, , , .;)

, , ", ", ?

. , , SELECT-and-generic , ( ). , PostgreSQL, , CSV , :

CREATE TEMP TABLE input_file (LIKE target_table);

COPY input_file FROM '/path/to/file.csv' WITH CSV;

INSERT INTO target_table
SELECT * FROM input_file
WHERE (<unique key field list>) NOT IN (
    SELECT <unique key field list>
    FROM target_table
);

, , (, , Python, COPY STDIN, ..), , , , , , .

+1

Source: https://habr.com/ru/post/1751801/


All Articles