【PostgreSQL】バックアップ・リストア ~ pg_dump / pg_restore ~

■ はじめに

PostgreSQL の データのバックアップ・リストア で
 pg_dump / pg_restore について取り上げる

【0】PostgreSQL の データのバックアップ・リストア

バックアップ/リストアについて、困ったら、以下の公式を読みといいかも。

https://www.postgresql.jp/document/9.4/html/backup.html

また、注意事項も含めて、以下を一読しておくといいかも。

http://www.atmarkit.co.jp/ait/articles/0810/24/news135_2.html

【1】pg_dump

*  データのバックアップ

http://www.postgresql.jp/document/9.4/html/app-pgdump.html
http://wp.tech-style.info/archives/563
http://developpp.blog.jp/archives/814136.html

1)構文

pg_dump.exe -b -Fc -U 【ユーザ名】 【DB名】 > 【出力ダンプ・ファイル名】

# -b  : ラージオブジェクトをダンプに含める
# -Fc : カスタム形式でのダンプ(-Ftとするとtar形式)

2)サンプル

Windowsの場合

pg_dump.exe -b -Fc -U postgres sampledb > c:\temp\sample.backup.dump

pg_dump -s --schema=public -U postgres sample_db > out.sql

【2】pg_dumpall

* 全データベースのバックアップをとる

1)サンプル

Linuxの場合

# postgresユーザーにスイッチ
sudo -u postgres -i

postgres@debian:~$ pg_dumpall > sample.sql

【注意】 -Fオプションは使えない

* 復元する際に、pg_restoreを使えない

~~~~~~
pg_restore: [アーカイバ] 入力ファイルがテキスト形式のダンプのようです。
psqlを使用してください
~~~~~~

【3】pg_restore

* データの復元(リストア)

https://www.postgresql.jp/document/9.4/html/app-pgrestore.html
http://www.desknets.com/neo/download/doc/install/dneo_winpg92_mainte.html

1)構文

pg_restore.exe -U 【ユーザ名】 -c -Fc 【入力ダンプ・ファイル名】 -d 【DB名】

# -c : データベースの作成前にテーブルなどをドロップする。
# -F : カスタム形式でのダンプ(-Ftとするとtar形式、-Fpがテキスト)
# -d : データベース名を指定
#
#[その他]
# -v : 進捗状況を詳細表示

2)サンプル

pg_restore.exe -U postgres -c -Fc c:\temp\sample.backup.dump

関連記事

ER図生成ツール ~ SchemaSpy ~
https://dk521123.hatenablog.com/entry/2023/06/29/234745
PostgreSQLをエクスポート/インポートするスクリプト
https://dk521123.hatenablog.com/entry/2018/03/02/232623
外部プログラム/コマンドを実行するには ~ ProcessBuilder ~