PostgreSQL / 系统课时
使用 pg_restore 恢复备份
使用 pg_restore 恢复备份
自定义格式备份不是 SQL 文本,需要由 pg_restore 解析。本课将查看归档目录、恢复到目标数据库、选择指定对象,并在安全条件下使用并行恢复提升速度。
学习目标
- 使用
pg_restore检查并恢复自定义格式备份 - 按 schema、表或目录清单选择对象
- 正确使用清理与并行参数
先检查归档目录
恢复前先读取 TOC 目录,确认备份数据库名、对象数量和关键表是否存在。
bash
pg_restore --list appdb.dump > appdb.list
head -n 12 appdb.list
grep -E "TABLE DATA public orders|TABLE public orders" appdb.list预期输出
text
;
; Archive created at <TIME>
; dbname: appdb
; TOC Entries: <COUNT>
;
<TID>; <OID> <OID> TABLE public orders <OWNER>
<TID>; <OID> <OID> TABLE DATA public orders <OWNER>动态值会因备份而变化。目录可读取只证明归档结构没有明显损坏,仍需实际恢复验证。
恢复到新数据库
先创建空库,再将归档恢复进去。--no-owner 避免要求目标环境存在原始属主,--exit-on-error 在首个错误处停止。
bash
createdb -h <HOST> -p <PORT> -U postgres --owner=app_owner appdb_restore
pg_restore -h <HOST> -p <PORT> -U postgres -d appdb_restore --no-owner --exit-on-error --verbose appdb.dump > pg_restore.log 2>&1
echo $?
tail -n 5 pg_restore.log预期输出
text
0
pg_restore: <RESTORE_MESSAGE>退出码为 0 后,还要执行对象、数据和权限校验。日志内容与对象数量有关,不能只匹配某一条固定文本。
选择部分对象
可使用 --schema 或 --table 限定恢复范围。表名建议写全限定名,并在恢复后检查依赖对象是否齐全。
bash
pg_restore -h <HOST> -p <PORT> -U postgres -d appdb_restore --no-owner --exit-on-error --table=public.orders --table=public.order_items appdb.dump预期结果
text
归档中的 public.orders 与 public.order_items 相关对象被恢复;未选择的业务表不会被装载。复杂选择可以编辑 pg_restore --list 生成的目录文件,删除不需要的行,再用 --use-list=appdb.list 恢复。目录顺序影响依赖关系,修改后必须在空库中验证。
清理已有对象
--clean 会在创建对象前执行删除,--if-exists 可减少对象不存在时的报错。该组合会破坏目标库现有对象,只能在明确允许覆盖的环境中使用。
bash
pg_restore -h <HOST> -p <PORT> -U postgres -d appdb_restore --clean --if-exists --no-owner --exit-on-error appdb.dump预期结果
text
归档涉及的现有对象先被删除,再按备份内容重新创建和装载。不要把 --clean 当作所有恢复失败的通用修复手段。目标库若承载其他对象,应改用新库恢复或更精确的对象选择。
使用并行恢复
自定义格式支持 -j 并行执行可并行任务。并行度应结合 CPU、磁盘、网络和目标实例连接上限确定,不是越大越快。
bash
pg_restore -h <HOST> -p <PORT> -U postgres -d appdb_restore --no-owner --exit-on-error -j 4 appdb.dump预期结果
text
最多使用 4 个并行作业恢复可并行对象;依赖项仍按归档要求排序执行。并行恢复期间多个错误可能同时出现,因此仍应保存完整日志,并以退出码和最终校验结果为准。
按自己的节奏,确认真正理解。