PostgreSQL:upsert函数重试无限插入

时间:2015-05-28 19:48:04

标签: postgresql infinite-loop upsert postgresql-9.4

虽然我已经看到upsert将成为Postgresql 9.5的一部分,但我正在尝试写我的(我与PostgreSQL 9.4合作)并且我不明白我得到了什么无限递归:函数重试无限地插入行。

当我尝试返回unique violation时已经存在的行的id时出现问题(即如果我返回VOID,则它有效)。

这是功能:

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;

我做错了什么?

0 个答案:

没有答案