LoginSignup
1
0

PostgreSQLのAccessShareLockにおけるALTER文の挙動

Last updated at Posted at 2024-03-29

先日、オンライン処理からAurora(PostgreSQL)に対してAccessShareLockをかけた状態で、バッチ処理からテーブルのリネームを実行しようとしてバッチ処理がアベンドする事象が発生したので、自宅PCで再現してみました。

前提

ターミナルを二つ立ち上げ(以下、端末A、端末Bと呼称)、それぞれでposgreSQLにpsqlでログインしていること。

※PostgreSQLの環境を構築する方法は別記事で解説しているのでご参照ください。

1. 端末Aでロックをかける

BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
LOCK TABLE customers IN ACCESS SHARE MODE;

2. 端末Bでロックの状態を確認

SELECT * FROM pg_stat_activity WHERE query LIKE '%customers%';

実行結果

datid | datname  | pid | leader_pid | usesysid | usename  | application_name | client_addr | client_hostname | client_port |         backend_start         |          xact_start           |          query_start          |         state_change          | wait_event_type | wait_event |        state        | backend_xid | backend_xmin | query_id |                             query                              |  backend_type  
-------+----------+-----+------------+----------+----------+------------------+-------------+-----------------+-------------+-------------------------------+-------------------------------+-------------------------------+-------------------------------+-----------------+------------+---------------------+-------------+--------------+----------+----------------------------------------------------------------+----------------
     5 | postgres | 106 |            |       10 | postgres | psql             |             |                 |          -1 | 2024-03-29 12:30:24.877979+00 | 2024-03-29 13:32:56.536604+00 | 2024-03-29 13:32:56.536604+00 | 2024-03-29 13:32:56.536608+00 |                 |            | active              |             |          739 |          | SELECT * FROM pg_stat_activity WHERE query LIKE '%customers%'; | client backend
     5 | postgres |  76 |            |       10 | postgres | psql             |             |                 |          -1 | 2024-03-29 12:23:53.778779+00 | 2024-03-29 13:32:36.815987+00 | 2024-03-29 13:32:36.82352+00  | 2024-03-29 13:32:36.824537+00 | Client          | ClientRead | idle in transaction |             |              |          | LOCK TABLE customers IN ACCESS SHARE MODE;                     | client backend
(2 rows)

customersテーブルに対してロック(AccessShareLock)がかかっていることを確認

3. 端末Bでテーブルのリネームを実行

ALTER TABLE customers RENAME TO customers_tmp;

応答待ち状態になる

4. 端末Aでロックを開放する

COMMIT;

5. 端末Bの処理が走行してリネームが完了する

postgres=# ALTER TABLE customers RENAME TO customers_tmp;
ALTER TABLE
postgres=#

これで、PostgreSQLのAccessShareLockの挙動についての実験を再現し、結果を確認しました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0