Skip to content

Instantly share code, notes, and snippets.

@peterli888
Created December 13, 2016 19:37
Show Gist options
  • Save peterli888/807435aab3e60cee83962035b6c99778 to your computer and use it in GitHub Desktop.
Save peterli888/807435aab3e60cee83962035b6c99778 to your computer and use it in GitHub Desktop.
pgjson.upsert
CREATE OR REPLACE FUNCTION pgjson.upsert(
key text,
data jsonb)
RETURNS void AS
$BODY$
BEGIN
LOOP
UPDATE pgjson.main SET doc = data WHERE id = key;
IF found THEN
RETURN;
END IF;
BEGIN
INSERT INTO pgjson.main(id, doc) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
END;
END LOOP;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION pgjson.upsert(text, jsonb)
OWNER TO liyong;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment