PostgreSQL: Auto-increment based on multi-column unique constraint

前端 未结 3 1038
自闭症患者
自闭症患者 2020-12-02 21:02

One of my tables has the following definition:

CREATE TABLE incidents
(
  id serial NOT NULL,
  report integer NOT NULL,
  year integer NOT NULL,
  month int         


        
3条回答
  •  萌比男神i
    2020-12-02 21:51

    I think this will help: http://www.varlena.com/GeneralBits/130.php

    Note that in MySQL it is for MyISAM tables only.

    PP I have tested advisory locks and found them useless for more than 1 transaction in same time. I am using 2 windows of pgAdmin. First is as simple as possible:

    BEGIN;
    INSERT INTO animals (grp,name) VALUES ('mammal','dog');
    COMMIT;
    
    BEGIN;
    INSERT INTO animals (grp,name) VALUES ('mammal','cat');
    COMMIT;
    
    ERROR: duplicate key violates unique constraint "animals_pkey"
    

    Second:

    BEGIN;
    INSERT INTO animals (grp,name) VALUES ('mammal','dog');
    INSERT INTO animals (grp,name) VALUES ('mammal','cat');
    COMMIT;
    
    ERROR: deadlock detected
    SQL state: 40P01
    Detail: Process 3764 waits for ExclusiveLock on advisory lock [46462,46496,2,2]; blocked by process 2712.
    Process 2712 waits for ShareLock on transaction 136759; blocked by process 3764.
    Context: SQL statement "SELECT  pg_advisory_lock( $1 ,  $2 )"
    PL/pgSQL function "animals_id_auto" line 15 at perform
    

    And database is locked and can not be unlocked - it is unknown what to unlock.

提交回复
热议问题