pg_dump和pg_restore(DROP IF EXISTS)

lol*_*ter 11 postgresql

我想要一个完全基于shell的解决方案来测试我的数据库,允许我通过运行终端命令将其恢复到一致状态.

我像这样转储我的数据库:

pg_dump -F c -b -f -i -h domain.edu -p 5432 -n myschema -U me mydatabase -W -f mydump.sql
Run Code Online (Sandbox Code Playgroud)

然后我想恢复它:

pg_restore -h domain.edu -p 5432 -U me -d mydatabase -W mydump.sql
Run Code Online (Sandbox Code Playgroud)

但它没有用,因为我遇到了很多这样的错误:

pg_restore: [archiver (db)] could not execute query: ERROR:  constraint "settings_person_id_fkey" for relation "settings" already exists
    Command was: ALTER TABLE ONLY settings
    ADD CONSTRAINT settings_learner_id_fkey FOREIGN KEY (person_id) REFERENCES pe...
Run Code Online (Sandbox Code Playgroud)

基本上只有很多东西需要在重新添加之前先删除(DROP TABLE <whatever> IF EXISTS与类型相同).

我怎么能用Postgres做到这一点?我不想使用psql控制台,只有linux终端.

Mat*_*sOl 20

如果要将数据库还原到一致状态,建议您在还原转储之前删除并重新创建它:

dropdb -h domain.edu -U me mydatabase
createdb -h domain.edu -U me -T template0 mydatabase # adjust encoding/locale if necessary
pg_restore -h domain.edu -p 5432 -U me -d mydatabase -W mydump.sql
Run Code Online (Sandbox Code Playgroud)


not*_*vvy 12

--clean --if-exists恢复数据时可以使用。

然后,您不需要删除并重新创建整个数据库,也不需要--clean在备份中使用过该数据库。

pg_restore -h domain.edu -p 5432 -U me --clean --if-exists -d mydatabase -W mydump.sql
Run Code Online (Sandbox Code Playgroud)

--clean使 pg_restoredrop首先恢复所有对象,并--if-exists防止不存在的对象导致失败。

请注意,在pg_restore 的 postgres 文档--if-exists中没有将其列为单独的选项,但在选项的描述中提到了它:--clean

-c
--clean
Run Code Online (Sandbox Code Playgroud)

在重新创建数据库对象之前清理(删除)它们。(除非使用 --if-exists,否则如果目标数据库中不存在任何对象,则可能会生成一些无害的错误消息。)


Cas*_*rin 10

您可以在 pg_dump 中使用 --clean 来首先删除对象。

pg_dump --clean

备份

pg_dump --clean -U 用户数据库> database.sql

恢复

psql -U 用户 -d 数据库 -f 数据库.sql