Skip to content

Instantly share code, notes, and snippets.

@rightfold
Created August 25, 2013 20:09
Show Gist options
  • Save rightfold/99d9ac0436ef3d49e810 to your computer and use it in GitHub Desktop.
Save rightfold/99d9ac0436ef3d49e810 to your computer and use it in GitHub Desktop.
BEGIN;
CREATE FUNCTION put_item(collection_id_arg integer, key_arg bytea, value_arg bytea) RETURNS void
AS $$
BEGIN
LOOP
UPDATE items
SET value = value_arg
WHERE collection_id = collection_id_arg
AND key = key_arg;
IF FOUND THEN
RETURN;
END IF;
BEGIN
INSERT INTO items
(collection_id, key, value)
VALUES
(collection_id_arg, key_arg, value_arg);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- loop
END;
END LOOP;
END;
$$ LANGUAGE plpgsql;
COMMIT;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment