D
D
DoggoTheKing2018-03-31 20:06:37
PostgreSQL
DoggoTheKing, 2018-03-31 20:06:37

How to check for the existence of a pair of columns (ManyToMany) in asynchronous code?

There is a code that makes requests to the API and makes changes to the database. Initially, it was synchronous and worked without errors. When I rewrote it for use in workers, it began to fall with an error:

> "INSERT INTO main_user_groups (group_id, user_id)"
psycopg2.IntegrityError: duplicate key value violates unique constraint "main_user_groups_user_id_group_id_dce92137_uniq
DETAIL:  Key (user_id, group_id)=(1623, 2) already exists.

Here is the piece of code that crashes:
if row:
    user_id_rel = row[0]
    cur.execute(  # psycopg2.cursor 
         f"INSERT INTO main_user_groups (group_id, user_id) "
         f"VALUES ('{group_ID_rel}', '{user_id_rel}');"
    )
else:
    ...

All other threads crash with the following error:
> "UPDATE main_group "
psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block

I tried to fix it with try/except + cursor.rollback()and INSERT + ON CONFLICT UPDATE, it didn't work.
Apparently, the code falls due to the coincidence of the current pair with the one already existing in the database. Is it possible to fix this without making requests to check the existence of the pair, because are they slow?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question