pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Rodrigo De León <rdeleonp@gmail.com>
To: pgsql-sql@postgresql.org
Cc: Markus Holzer <holli.holzer@googlemail.com>
Subject: Re: Doing a conditional insert/update
Date: Thu, 19 Apr 2007 13:58:59 -0500
Message-ID: <a55915760704191158l278c760bg3b95296535a79e07@mail.gmail.com> (raw)
In-Reply-To: <978075550704191127g781a4a26i400f4fc80d491df6@mail.gmail.com>
References: <978075550704191127g781a4a26i400f4fc80d491df6@mail.gmail.com>

On 4/19/07, Markus Holzer <holli.holzer@googlemail.com> wrote:
> Hello.
>
> I'm currently developing my first web app with Postgres and I have a
> question.
>
> How do I perform a conditional insert/update?
>
> To clarify: I need to insert data into a table when the primary key is not
> already in the table, or an update if it is. I have currently solved this by
> SELECTing for the primary key, then looking if there is a row, and if there
> is I do an UPDATE otherwise I do an INSERT. But since this is a web app this
> way of course leaves a big race condition.
>
> Is there a way to get around that? Like the ON DUPLICATE KEY UPDATE
> statement in MySQL?
>
>
> Thanks for your time,
>
> Holli

--------------------------------------------------

CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
    LOOP
        UPDATE db SET b = data WHERE a = key;
        IF found THEN
            RETURN;
        END IF;

        BEGIN
            INSERT INTO db(a,b) VALUES (key, data);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- do nothing
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');

--------------------------------------------------

Straight from the docs:

http://www.postgresql.org/docs/8.2/static/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING



view thread (3+ messages)

Message-ID: <a55915760704191158l278c760bg3b95296535a79e07@mail.gmail.com>
Permalink:  ../a55915760704191158l278c760bg3b95296535a79e07@mail.gmail.com/
Also on:    postgresql.org/message-id/a55915760704191158l278c760bg3b95296535a79e07@mail.gmail.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: rdeleonp@gmail.com, holli.holzer@googlemail.com
  Subject: Re: Doing a conditional insert/update
  In-Reply-To: <a55915760704191158l278c760bg3b95296535a79e07@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox