vendredi 22 janvier 2016

Insert or update entry but fail on unique constraint violation

Imagine a table like this:

+-----+-------+
| id  | value |
+-----+-------+ 
| id1 | val1  |
| id2 | val2  |
+-----+-------+

whereas id is PRIMARY KEY and value has a UNIQUE constraint.

What I want to do is to use a query that inserts or updates an entry based on its primary key but fails if the unique constraint is violated.

As an example, if I try to insert id1, val2, i want the query to fail whereas inserting id1, val3 should update the first row.

What I however observed in sqlite3 is that if I use INSERT OR REPLACE to insert id1, val2 it will replace both existing entries. I also had a look at the ON CONFLICT clause of sqlite, but there doesn't seem to be a way to distinguish UNIQUE or PRIMARY KEY constraint violations.

Is there any way to do something like this with sqlite or is there maybe another way to deal with a situation like this?

Aucun commentaire:

Enregistrer un commentaire