title: PostgreSQL: upsert function retries to insert infinitely
body: <p>Although I have seen that <code>upsert</code> will be part of <code>Postgresql 9.5</code>, I'm trying to write mine (I work with <code>PostgreSQL 9.4</code>) and I don't understand what I get an infinite recursion: the function retry to insert the row infinitely.</p>
  
  <p>The problem appears when I try to return the id of the row that already exists in case of a <code>unique violation</code> (i.e. if I return <code>VOID</code>, it works).</p>
  
  <p>Here is the function:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION upsertAddress(
    geographicPointValue      VARCHAR(63),
    cityValue                 VARCHAR(127),
    zipValue                  VARCHAR(15),
    streetValue               VARCHAR)
    RETURNS INT AS
    $$
    DECLARE addressIdToReturn int;
    BEGIN
      LOOP
        UPDATE addresses
          SET geographicPoint = POINT(geographicPointValue), city = cityValue, zip = zipValue, street = streetValue
          WHERE city = cityValue AND zip = zipValue AND street = streetValue;
        IF found THEN
          SELECT addressId INTO addressIdToReturn
            FROM addresses
            WHERE city = cityValue AND zip = zipValue AND street = streetValue;
          RETURN addressIdToReturn;
        END IF;
        BEGIN
          INSERT INTO addresses (geographicPoint, city, zip, street)
            VALUES (POINT(geographicPointValue), cityValue, zipValue, streetValue)
            RETURNING addressId INTO addressIdToReturn;
          RETURN addressIdToReturn;
          EXCEPTION WHEN unique_violation THEN
        END;
      END LOOP;
    END;
    $$
  LANGUAGE plpgsql;
  </code></pre>
  
  <p>What I am doing wrong?</p>