虽然我已经看到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;
我做错了什么?