Skip to content

Instantly share code, notes, and snippets.

@krusynth
Created July 23, 2013 12:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krusynth/6062106 to your computer and use it in GitHub Desktop.
Save krusynth/6062106 to your computer and use it in GitHub Desktop.
Function to emulate ON DUPLICATE KEY UPDATE functionality in Postgresql
CREATE FUNCTION merge_kvstore(dkey character varying, ddata BYTEA) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
UPDATE kvstore SET value = ddata WHERE key = dkey;
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 kvstore(key,value) VALUES (dkey, ddata);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- Do nothing, and loop to try the UPDATE again.
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment