Atomicity of INSERT INTO ... SELECT ... WHERE NOT EXISTS ... - Mailing list pgsql-general

From Jim Garrison
Subject Atomicity of INSERT INTO ... SELECT ... WHERE NOT EXISTS ...
Date
Msg-id 391418bb91fe4570a2fe8bda3281b976@BN1PR06MB839.namprd06.prod.outlook.com
Whole thread Raw
Responses Re: Atomicity of INSERT INTO ... SELECT ... WHERE NOT EXISTS ...  (David G Johnston <david.g.johnston@gmail.com>)
Re: Atomicity of INSERT INTO ... SELECT ... WHERE NOT EXISTS ...  (Jerry Sievers <gsievers19@comcast.net>)
Re: Atomicity of INSERT INTO ... SELECT ... WHERE NOT EXISTS ...  (Craig Ringer <craig@2ndquadrant.com>)
List pgsql-general
Given (pseudocode)

    CREATE TABLE kvstore (
        k varchar primary key,
        v varchar);

    CREATE OR REPLACE FUNCTION store_key_value_pair(k varchar, v varchar) returns boolean as $$
    BEGIN
      INSERT INTO kvstore (k, v)
      SELECT :k, :v
      WHERE NOT EXISTS (select 1 from kvstore where k = :k);
      RETURN FOUND;
    END;
    $$ LANGUAGE plpgsql;

I have a few questions:

1) Does INSERT statement set FOUND based on whether or not the row was inserted?
2) If this is invoked without a transaction in progress, is there any guarantee of atomicity between checking the
EXISTSand attempting to insert the row?  If this is being executed in two (or more) sessions, can the SELECT succeed
butthen have the INSERT fail with a duplicate-key exception? 
3) Will the behavior be different if the invoking processes have a transaction in progress?



pgsql-general by date:

Previous
From: Adrian Klaver
Date:
Subject: Re: error restarting DB
Next
From: Rich Shepard
Date:
Subject: UPDATE table: Syntax to Remove Terminal '\n'