postgresqlpsycopg2libpq

psycopg2: statement return codes


I have a Postgres query which I execute in Python like so

cursor.execute('INSERT INTO my_data(id, val, bonus) VALUES (1, 2, 3) ON CONFLICT (id) DO UPDATE SET val = ex.val;')

I'd like to be able to tell if a fresh insert is happening to decide some later logic on the calling side. Outside of doing an extra read before attempting the upsert, is there a way of doing this? For example, checking a return code/message on whether the conflict was triggered


Solution

  • After the execute, check cursor.rowcount to get the number of affected rows.

    If that is 1, a row was inserted. If it is 0, an existing row was updated.