francs=> select pid,mode,relation,granted from pg_locks where relation='mv_test_1'::regclass; pid | mode | relation | granted -------+---------------------+----------+--------- 15936 | AccessShareLock | 16408 | t 15936 | ShareLock | 16408 | t 15936 | ExclusiveLock | 16408 | t 15936 | AccessExclusiveLock | 16408 | t (4 rows)
备注 : session B 用来查看物化视图 mv_test_1 上的锁情况, 这里刷新物化视图时获取的是 “AccessExclusiveLock”锁。
session C 查询 mv_test_1
1 2 3 4 5 6 7 8
francs=> select pg_backend_pid(); pg_backend_pid ---------------- 16125 (1 row) francs=> select * from mv_test_1 ; .. -- 此时 session C 处于等待状态.
session B 再次查看 pg_locks
1 2 3 4 5 6 7 8 9
francs=> select pid,mode,relation,granted from pg_locks where relation='mv_test_1'::regclass; pid | mode | relation | granted -------+---------------------+----------+--------- 16125 | AccessShareLock | 16408 | f 15936 | AccessShareLock | 16408 | t 15936 | ShareLock | 16408 | t 15936 | ExclusiveLock | 16408 | t 15936 | AccessExclusiveLock | 16408 | t (5 rows)
备注: 说明 session C 已经被 session A 阻塞了,因为 session A 获取的是 AccessExclusiveLock 锁。
在线刷新物化视图
接着测试 CONCURRENTLY 参数的在线刷新方式。
session A 在线刷新物化视图
1 2 3
francs=> refresh materialized view CONCURRENTLY mv_test_1 ; ERROR: cannot refresh materialized view "francs.mv_test_1" concurrently HINT: Create a UNIQUE index with no WHERE clause on one or more columns of the materialized view.
备注: 说是要创建不带 where 条件的 unique 索引.
创建索引
1 2
francs=> createuniqueindex idx_mv_test_1 on mv_test_1 using btree (id); CREATEINDEX