2

我有 PostgreSQL 函数,用于计算用户对“项目”的使用情况。计数器值保存到表中:

users_items

user_id - integer (fk)
item_id - integer (fk)
counter - integer

有最大值。每个用户每个项目 1 个计数器(唯一键)。

这是我的功能:

CREATE OR REPLACE FUNCTION increment_favorite_user_item (item integer, userid integer) RETURNS integer AS 
$BODY$
    DECLARE
        new_count  integer;   -- Usage counter
    BEGIN
        IF NOT EXISTS(SELECT 1 FROM users_items WHERE user_id = userid AND item_id = itemid) 
        THEN
            INSERT INTO users_items ("user_id", "item_id", "counter") VALUES (userid, itemid, 1); -- First usage - create new counter
            new_amount = 1;
        ELSE
            UPDATE users_items SET count = count + 1 WHERE (user_id = userid AND item_id = itemid); -- Increment counter
            SELECT counter INTO new_count FROM users_items WHERE (user_id = userid AND item_id = itemid);
        END IF;

        RETURN new_count;
    END;
$BODY$
LANGUAGE 'plpgsql'
VOLATILE;

它由应用程序使用,可能会多次调用它。一切正常,直到我们为同一个用户和项目一个接一个地调用该函数,当项目对于特定用户是新的(users_items 表中的记录不存在)。

对于第二个函数调用,我得到唯一的违规:“Key (user_id, item_id)=(1, 7912) 已经存在”。似乎“如果不存在”检查无法正常工作,第二个函数调用没有看到第一个插入的记录,并尝试插入同一行,导致 uq 检查失败。

我能做些什么来解决这个问题?

每个函数调用都在另一个事务中运行。

4

1 回答 1

2

There is a) race condition, b) you should to LOCK table if you would to ensure INSERT

DECLARE rc int;
BEGIN
  LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE;
  UPDATE users SET counter = counter + 1 WHERE user_id = $1;
  GET DIAGNOSTICS rc = ROW_COUNT;
  IF rc = 0 THEN
    INSERT INTO users(id, counter) VALUES($1, 1)
  END IF;
END;

or more complex code, but with less locking

DECLARE rc int;
BEGIN
  -- fast path
  UPDATE users SET counter  = counter + 1 WHERE user_id = $1;
  GET DIAGNOSTICS rc = ROW_COUNT;
  IF rc = 0 THEN
    LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE;
    UPDATE users SET counter  = counter + 1 WHERE user_id = $1;
    GET DIAGNOSTICS rc = ROW_COUNT;
    IF rc = 0 THEN
      INSERT INTO users(id, counter) VALUES($1, 1)
    END IF;
  END IF;
END;
于 2013-06-11T14:38:08.763 回答