I have an application with PostgreSQL 9.4. Since the upsert is a feature of PostgreSQL 9.5, I need a workaround for that.
The task is additionally complicated by the necessity of returning the updated/inserted row.
At first I tried this:
BEGIN;
DO $$
DECLARE
_cursor CONSTANT refcursor := '_cursor';
BEGIN
LOOP
OPEN _cursor FOR
UPDATE uac.roles
SET parent_id = null,
PRIVILEGES = 'blablabla213',
autoload = 'blablabla2'
WHERE name = 'role_name2'
RETURNING *;
IF FOUND THEN
EXIT;
END IF;
CLOSE _cursor;
BEGIN
OPEN _cursor FOR
INSERT INTO uac.roles
(
parent_id,
name,
PRIVILEGES,
autoload
)
VALUES
(
null,
'role_name2',
'blablabla214',
'blabla21'
)
RETURNING *;
EXIT;
EXCEPTION
WHEN unique_violation THEN
END;
END LOOP;
END
$$;
FETCH ALL FROM _cursor;
COMMIT;
But the internal variable "FOUND" will always be false, because the execution of the cursor happens just before the very end of the transaction, so it always gonna insert values.
UPDATE: Is it even possible without functions?