hikaru’s diary

Django Engineer

【PostgreSQL】バックアップとリストア

バックアップ
例
pg_dump -U ユーザー名 --format=出力形式 --file=出力先 バックアップを取るDB名

私の環境
pg_dump -U postgres --format=p --file=C:\Users\省略\20220427.db postgres

パスワード聞かれる

出力されたファイルはメモ帳で内容が分かる

リストア
createdb -U postgres newdb  # 今回はnewdbを作成 

psql -h ホスト名 -U ユーザー名 -d リストア先のDB -f .sqlファイルのパス
psql -h localhost -U postgres -d newdb -f C:\Users\省略\20220427.db postgres


確認

psql -U postgres

\c newdb

\dt


newdbは使わないので削除

DROP DATABASE newdb;


以上、お疲れさまでした。


追記:5/3
ちょっとわかりづらかったのでまとめる

# 退避や削除してから行う
ALTER DATABASE postgres rename to postgres_bk_date;
DROP DATABASE postgres;

# 移行
CREATE DATABASE -U postgres postgres
psql -h localhost -U postgres -d newdb -f 20220427.db postgres

# 確認
\l


追記:5/16
リストアするのがすごく面倒くさいので

CREATE DATABASE postgres_bk_20220516 TEMPLATE postgres;