Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

PostgreSQLの教育にPostgres-WASMを使う

大量のデータをINSERTしようとするとエラーになる

600行くらいのINSERTを一気に実行しようとすると以下のエラーが出る。

psql:/mnt/test.sql:665: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
psql:/mnt/test.sql:665: fatal: connection to server was lostpsql:/mnt/test.sql:665: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
psql:/mnt/test.sql:665: fatal: connection to server was lost

1レコードごとにINSERTするのではなく、バルクインサートにすることでエラーが出ずに実行できる。

統計情報が更新されず、実行計画の値がおかしい

1000行あるテーブルに対して全件SELECTしているのに、実行計画でrowsが1000にならない。 統計情報を見ても、relpagesは0(未更新)、reltuplesは-1 (unknown)のままになっている。

postgres=# explain select * from staff;
                        QUERY PLAN                        
----------------------------------------------------------
 Seq Scan on staff  (cost=0.00..14.98 rows=98 width=1126)

postgres=# select relpages, reltuples FROM pg_class where relname = 'staff';
-[ RECORD 1 ]-
relpages  | 0
reltuples | -1

テーブルに対し明示的にANALYZEを実行してやれば統計情報が更新される。

postgres=# analyze staff;
ANALYZE
postgres=# select relpages, reltuples FROM pg_class where relname = 'staff';
-[ RECORD 1 ]---
relpages  | 14
reltuples | 1000

postgres=# explain select last_name from staff;
                       QUERY PLAN                        
---------------------------------------------------------
 Seq Scan on staff  (cost=0.00..24.00 rows=1000 width=7)
(1 row)

スロークエリログを取得したいがpg_stat_statementsを有効にできない

postgresql.confshared_preload_libraries = 'pg_stat_statements'を追加・再起動→CREATE EXTENSION pg_stat_statements;の順で実行すると、なぜかPostgreSQLが再起動に失敗したり、CREATE EXTENSIONが以下のエラーになったりする。

postgres=# CREATE EXTENSION pg_stat_statements;
server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
!?>

先にCREATE EXTENSIONしてから、postgresql.confshared_preload_libraries = 'pg_stat_statements'を追加・再起動すると問題なく実行できた。

postgres=# CREATE EXTENSION pg_stat_statements;
CREATE EXTENSION
postgres=# \q
# vi /var/lib/pgsql/postgresql.conf
----------------
※以下を追加
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.max = 1000
pg_stat_statements.track = top
pg_stat_statements.save = on
----------------
# /etc/init.d/S50postgresql restart
Stopping postgresql: waiting for server to shut down.... done
server stopped
OK
Starting postgresql: waiting for server to start.... done
server started
OK