當你這個負責任的資料庫管理員已經做好備份,接下來就是關鍵時刻啦:資料還原。這時候主角 pg_restore 就要登場了。如果 pg_dump 是你做備份的超級英雄,那 pg_restore 就是他的好夥伴,專門把備份檔案裡的資料救回來。
pg_restore 是用來還原那些用 pg_dump 以 binary 格式(custom 或 directory)產生的檔案。如果你的資料庫哪天壞掉,或是你想把資料搬到新伺服器,這個工具就是你的神隊友啦。
為什麼你需要 pg_restore:
- 它可以還原整個資料庫,也可以只還原部分(像 schema、table、data)。
- 這是個很強大的工具,適合需要細節控制的複雜還原情境。
基本指令語法
用 pg_restore 的第一步,就是搞懂它的基本語法:
pg_restore -U username -d database_name backup_file.dump
指令參數說明:
-U username:指定要連線的 PostgreSQL 使用者名稱。-d database_name:要還原到哪個資料庫。backup_file.dump:之前用pg_dump產生的備份檔(custom或directory格式)
舉例來說,如果你想用 postgres 這個使用者,把 backup.dump 還原到 university 這個資料庫,指令會長這樣:
pg_restore -U postgres -d university backup.dump
執行這個指令後,pg_restore 就會開始還原流程,把資料救回來!
備份類型與相容性
不是所有備份都一樣。你可能還記得,用 pg_dump 備份時可以選不同格式。有些格式 pg_restore 支援,有些就不行。
| 備份格式 | 說明 | pg_restore 支援嗎 |
|---|---|---|
plain(純文字) |
包含還原指令的 SQL script。 | ❌ 不支援 |
custom |
PostgreSQL 專屬格式的壓縮備份。 | ✅ 支援 |
directory |
以資料夾方式儲存的多檔案備份。 | ✅ 支援 |
tar |
TAR 格式的壓縮檔。 | ✅ 支援 |
注意,對於純文字備份(plain),你不能用 pg_restore。這種檔案要用 psql 手動還原。例如:
psql -U username -d database_name -f backup.sql
pg_restore 的彈性:還原參數
pg_restore 之所以這麼受歡迎,最大原因就是它很彈性。你可以還原整個資料庫,也可以只還原部分內容。
只還原資料結構。 如果你只想還原資料庫的結構(像 table schema、index、trigger 等),用 --schema-only:
pg_restore -U postgres -d university --schema-only backup.dump
這很適合你想分析資料庫結構,或是做一個「空殼」的複本。
只還原資料。 如果你只想還原資料(不包含結構),用 --data-only:
pg_restore -U postgres -d university --data-only backup.dump
這種情境很適合結構已經有了,只想把 table 裡的內容補回來。
還原前先清空。 有時候 table 或 schema 已經存在。想在還原前先刪掉,用 --clean:
pg_restore -U postgres -d university --clean backup.dump
加這個參數,pg_restore 會先把現有物件刪掉,再從備份還原。
物件過濾。 pg_restore 可以讓你挑要還原哪些物件。用 --table:
pg_restore -U postgres -d university --table=students backup.dump
這個例子只會還原 students 這張 table。
把 SQL 輸出到 console
如果你想先看看會執行哪些 SQL,不想馬上動到資料庫,可以用 --list:
pg_restore -l backup.dump
想看更詳細的 SQL 指令,加上 --verbose:
pg_restore -U postgres --verbose --schema-only backup.dump
還原範例
- 完整還原資料庫。
最常見的情境:你想把整個資料庫從備份救回來:
pg_restore -U postgres -d university backup.dump
- 還原特定 table。
比如你只遺失 courses 這張 table 的資料,就只還原它:
pg_restore -U postgres -d university --table=courses backup.dump
- 還原資料庫 schema。
只想還原 table 結構(不含資料):
pg_restore -U postgres -d university --schema-only backup.dump
- 還原時重建物件。
如果你想覆蓋現有資料:
pg_restore -U postgres -d university --clean backup.dump
還原常見錯誤與預防方法
版本不相容。 如果你用一個版本的 PostgreSQL 備份,卻想還原到另一個(尤其是更舊的),可能會遇到相容性錯誤。解法:盡量用同一版本的 PostgreSQL 來備份和還原。
錯誤 "Role does not exist"。 如果備份裡有用到某些 role(使用者),但還原的伺服器沒有這些 role,就會出錯。解法:先在新伺服器建立好需要的 role。
錯誤 "Table already exists"。 如果你還原時 table 已經存在,就會出現這個錯誤。用
--clean可以避免衝突。
GO TO FULL VERSION