I have a problem looks like that, it would be wonderful if you can give some instructions. I am using PostgreSQL
Table:
mytable(col1,col2,col3,count)
unique constraints on col1,col2,col3
I have a insertion statement,call it
insert into myTable
It sometimes fails, because the insertion violates the unique constraints But I want to catch this error and do a update if there is unique_violation,namely
update myTable
set count=count+1
where col1=.. and col2=.. and col3=..
How can I express this semantic exactly in the language of Postgresql?
I have tried (seems to be syntactically wrong):
BEGIN;
INSERT INTO knowledge (brand_id, brand, user_variant,score,count)
VALUES (%(brand_id)s, %(brand)s, %(user_variant)s,%(score)s,%(count)s);
EXCEPTION
WHEN unique_violation THEN
UPDATE knowledge
SET count=count+1
WHERE brand=%(brand)s AND user_variant=%(user_variant)s;
COMMIT;
And also python (I am using python, with psycopg2)
try:
...
except:
...
which does not work, because the try just passes the insertion error on to the exception which finally causes an error:
current transaction is aborted, commands ignored until end of transaction block
In except even the sql in except is fully correct.
I am now trying to use a pl/pgsql function, but it seems hard.