除非所有行都被锁定,否则跳过锁定

时间:2017-04-10 19:25:34

标签: postgresql locking

有没有办法使用SKIP LOCKED使用PostgreSQL进行查询以避免已经锁定行,但同时如果所有内容都已锁定等待第一个未锁定的行?

在我的用例中,我希望在请求可用的电话号码时避免误报。但是在我将所有号码锁定的情况下,不太可能,但它仍然可能发生并应该解决。

SELECT plain_number FROM pool
  ORDER BY RANDOM()
  LIMIT 1
  FOR UPDATE
  SKIP LOCKED

1 个答案:

答案 0 :(得分:2)

这似乎有效:

WITH sl AS (
  SELECT plain_number FROM pool ORDER BY random() LIMIT 1 FOR UPDATE SKIP LOCKED
),
fu AS (
  SELECT plain_number FROM pool WHERE NOT EXISTS(SELECT 1 FROM sl) ORDER BY random() LIMIT 1 FOR UPDATE
)
SELECT * FROM sl FULL JOIN fu USING (plain_number);

然而,它等待随机plain_number释放其锁定。我不认为可以等待释放第一把锁。

设定:

create table pool(
  plain_number text primary key
);

insert into pool(plain_number)
select generate_series(1, 9)::text;

这是我为测试编写的一个小node.js脚本:

const pg = require("pg");
const options = {
    "user": "test",
    "password": "test",
    "database": "test"
};

function thread_ish() {
    const client = new pg.Client(options);
    const end = client.end.bind(client);
    const rollback = function (client) {
        client.query("ROLLBACK", end);
    };

    client.connect(function () {
        client.query("BEGIN", function (err) {
            if (err) {
                console.error(err);
                return rollback(client);
            }
            client.query(
                "WITH sl AS ("
                + "  SELECT plain_number FROM pool ORDER BY random() LIMIT 1 FOR UPDATE SKIP LOCKED"
                + "), fu AS ("
                + "  SELECT plain_number FROM pool WHERE NOT EXISTS(SELECT 1 FROM sl) ORDER BY random() LIMIT 1 FOR UPDATE"
                + ")"
                + "SELECT * FROM sl FULL JOIN fu USING (plain_number)",
                function (err, result) {
                    if (err) {
                        console.error(err);
                        return rollback(client);
                    }

                    console.log("Selected number is", result.rows);
                    setTimeout(function () {
                        client.query("COMMIT", end);
                    }, 1000);
                }
            );
        });
    });
}

for (var i = 0; i < 13; ++i) {
    setTimeout(thread_ish, Math.random() * 100);
}