Created
July 23, 2013 12:50
-
-
Save krusynth/6062106 to your computer and use it in GitHub Desktop.
Function to emulate ON DUPLICATE KEY UPDATE functionality in Postgresql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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