私の関数new_customerは、Webアプリケーションによって1秒あたり数回(ただし、セッションごとに1回)呼び出されます。最初に行うことは、customerテーブルをロックすることです(「存在しない場合は挿入」、つまりの単純なバリアントupsert)。
ドキュメントの私の理解は、他の呼び出しは、new_customer以前の呼び出しがすべて終了するまで単純にキューに入れる必要があるということです:
LOCK TABLEは、テーブルレベルのロックを取得し、競合するロックが解放されるのを必要に応じて待機します。
代わりにデッドロックが発生することがあるのはなぜですか?
定義:
create function new_customer(secret bytea) returns integer language sql 
                security definer set search_path = postgres,pg_temp as $$
  lock customer in exclusive mode;
  --
  with w as ( insert into customer(customer_secret,customer_read_secret)
              select secret,decode(md5(encode(secret, 'hex')),'hex') 
              where not exists(select * from customer where customer_secret=secret)
              returning customer_id )
  insert into collection(customer_id) select customer_id from w;
  --
  select customer_id from customer where customer_secret=secret;
$$;ログからのエラー:
2015-07-28 08:02:58 BST詳細:プロセス12380は、データベース12141のリレーション16438でExclusiveLockを待機します。プロセス12379によってブロックされました。
        プロセス12379は、データベース12141の関係16438でExclusiveLockを待ちます。プロセス12380によってブロックされました。
        プロセス12380:new_customer(decode($ 1 :: text、 'hex'))を選択します
        プロセス12379:new_customer(decode($ 1 :: text、 'hex'))を選択
2015-07-28 08:02:58 BSTヒント:クエリの詳細については、サーバーログを参照してください。
2015-07-28 08:02:58 BST CONTEXT:SQL関数 "new_customer"ステートメント1
2015-07-28 08:02:58 BST STATEMENT:select new_customer(decode($ 1 :: text、 'hex'))
関係:
postgres=# select relname from pg_class where oid=16438;
┌──────────┐
│ relname  │
├──────────┤
│ customer │
└──────────┘編集:
シンプルで再現可能なテストケースを取得できました。私には、これはある種の競合状態によるバグのように見えます。
スキーマ:
create table test( id serial primary key, val text );
create function f_test(v text) returns integer language sql security definer set search_path = postgres,pg_temp as $$
  lock test in exclusive mode;
  insert into test(val) select v where not exists(select * from test where val=v);
  select id from test where val=v;
$$;bashスクリプトは2つのbashセッションで同時に実行されます。
for i in {1..1000}; do psql postgres postgres -c "select f_test('blah')"; doneエラーログ(通常、1000回の呼び出しで発生する少数のデッドロック):
2015-07-28 16:46:19 BST ERROR:  deadlock detected
2015-07-28 16:46:19 BST DETAIL:  Process 9394 waits for ExclusiveLock on relation 65605 of database 12141; blocked by process 9393.
        Process 9393 waits for ExclusiveLock on relation 65605 of database 12141; blocked by process 9394.
        Process 9394: select f_test('blah')
        Process 9393: select f_test('blah')
2015-07-28 16:46:19 BST HINT:  See server log for query details.
2015-07-28 16:46:19 BST CONTEXT:  SQL function "f_test" statement 1
2015-07-28 16:46:19 BST STATEMENT:  select f_test('blah')編集2:
@ypercube はlock table、関数の外側にあるバリアントを提案しました:
for i in {1..1000}; do psql postgres postgres -c "begin; lock test in exclusive mode; select f_test('blah'); end"; done興味深いことに、これによりデッドロックが解消されます。
customer、より弱いロックを取得する方法で使用されていますか?次に、ロックアップグレードの問題である可能性があります。