Okay, so I just started with pgSQL, and of course discovered there is no ON DUPLICATE KEY
like MySQL has. Developing in PHP.
I want to hear your opinion on this solution for upsert, good and bad things and possibly errors if there are any.
So I have an object (in PHP) which has been populated with data. If populate was made on edit, ID of object will also be there, else ID will be 0. When it comes to saving, firstly I check that ID, if it's > 0 then okay, else, I'm getting a new ID from my DB, using this:
$query = "SELECT NEXTVAL(PG_GET_SERIAL_SEQUENCE(?, ?)) id";
As I learned recently, there is a guarantee that ID's will be unique, which is normally the important thing (@IMSoP).
The next thing is the actual upsert, and the easiest method I found was this (@Craig Ringer also commented it has concurrency problems)
UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
And that's preety much it.
I would love to hear your opinions :)