Have “select for update” block on nonrexisting rows

前端 未结 3 605
深忆病人
深忆病人 2021-02-07 03:24

we have some persistent data in an application, that is queried from a server and then stored in a database so we can keep track of additional information. Because we do not wan

3条回答
  •  心在旅途
    2021-02-07 03:28

    Example solution (i haven't found better :/)

    Thread A:

    BEGIN;
    SELECT pg_advisory_xact_lock(42); -- database semaphore arbitrary ID
    SELECT * FROM t WHERE id = 1;
    DELETE FROM t WHERE id = 1;
    INSERT INTO t (id, value) VALUES (1, 'thread A');
    SELECT 1 FROM pg_sleep(10); -- only for race condition simulation
    COMMIT;
    

    Thread B:

    BEGIN;
    SELECT pg_advisory_xact_lock(42); -- database semaphore arbitrary ID
    SELECT * FROM t WHERE id = 1;
    DELETE FROM t WHERE id = 1;
    INSERT INTO t (id, value) VALUES (1, 'thread B');
    SELECT 1 FROM pg_sleep(10); -- only for race condition simulation
    COMMIT;
    

    Causes always correct order of transactions execution.

提交回复
热议问题