1. 备份/还原
Pg数据库的备份/还原对象可以是数据库、模式或表,他们的备份/还原命令基本一样,仅仅只是个别参数的区别。
备份共有四种方式,Custom、Tar、Directory以及Plain,使用--format参数进行区分。还原时不需要指定该参数,工具会自行判断。对于Direcotry方式,备份出来是一个文件夹,还原时路径也是指定到该文件夹。对于Plain方式,备份出来是一个SQL文件,不能使用还原工具(pg_restore)进行恢复,但是可以用psql命令进行。
表:对于表,使用 --table 参数即是备份指定表,例如:--table "public.tab" ,public为模式名,tab为表名。
模式:对于模式,使用 --schema 参数即是备份指定模式,例如:--schema "public"
数据库:对于数据库,不加 --table 或 --schema 参数,即是备份整个数据库。
如下所示,为表的备份和还原:
# 备份:
pg_dump --file "/tmp/tab.backup" --host "localhost" --port "5432" --username "postgres" --verbose --format=c --blobs --table "public.tab" "postgres"
# 还原:
pg_restore --host "localhost" --port "5432" --username "postgres" --dbname "postgres" --verbose --schema "public" --table "tab" "/tmp/tab.backup"
# 使用psql还原plain方式的备份
psql --host "localhost" --port "5432" --username "postgres" --dbname "postgres" --file "/tmp/tab.backup"
--format=c # Custom方式
--format=t # Tar方式
--format=p # Plain方式
--format=d # Diretory方式
2. 导出/导入
导出/导入只针对表(数据),都使用psql命令进行操作。导出与导入命令格式基本一致,区别仅在于导出使用"copy to",而导入使用"copy from"。默认导出格式为text,若要导出CSV格式,则需要加上CSV相关参数,如下所示。
# 导出text格式
psql --port 5432 --username postgres --dbname postgres --command "\copy public.tab (id, name) TO '/tmp/tab.text';"
# 导入text格式
psql --port 5432 --username postgres --dbname postgres --command "\copy public.tab (id, name) FROM '/tmp/tab.text';"
# 导出CSV格式
psql --port 5432 --username postgres --dbname postgres --command "\copy public.tab (id, name) TO '/tmp/tab.csv' CSV QUOTE '\"' ESCAPE '\"';"
# 导入CSV格式
psql --port 5432 --username postgres --dbname postgres --command "\copy public.tab (id, name) FROM '/tmp/tab.csv' CSV QUOTE '\"' ESCAPE '\"';"