4 ms·
I built the pgscript version of the some upsert example and use it as a stored function. I'm no pgsql pro, so sorry if this is total shit. Works for what I need
by SDGT 13y ago
I built the pgscript version of the some upsert example and use it as a stored function. I'm no pgsql pro, so sorry if this is total shit. Works for what I needed. This is controlling a list of access rules to different services for doling out access on the controller level globally, or down to an individual action inside that controller. If I rewrote this on newer PG, I'd store the permissions text as a JSON datatype.
CREATE OR REPLACE FUNCTION merge_privileges(key integer, data_controller text, data_permissions text)
RETURNS void AS
$BODY$
BEGIN
LOOP
-- first try to update the key
UPDATE privileges SET controller = data_controller, permissions = data_permissions WHERE user_id = key AND controller = data_controller;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO privileges(user_id, controller, permissions) VALUES (key, data_controller, data_permissions);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing, and loop to try the UPDATE again
END;
END LOOP;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;