使用 -C 选项的 pg_restore 不会创建数据库。

31

我正在使用 pg_dump 和 pg_restore 进行 postgres 数据库的备份和还原。

以下是一些文档中与此问题相关的信息。对于 Pg_restore,-C 选项描述如下:

-C

--create

在还原之前创建数据库。如果也指定了 --clean,则在连接到目标数据库之前删除并重新创建目标数据库。当使用此选项时,使用 -d 指定的数据库仅用于发出最初的 DROP DATABASE 和 CREATE DATABASE 命令。所有数据都被还原到存档中显示的数据库名称。

然而,即使我在 pg_restore 中使用此选项,仍会出现以下错误:

pg_restore:[archiver (db)] 连接到数据库“test”失败: FATAL: 数据库“test”不存在

根据说明,-C 选项应该创建缺少的数据库。但在我的情况下并没有这样做。

以下是我进行备份和还原的步骤:

  1. 使用 pg_dump 备份数据库
pg_dump -N backup -d test --format custom -v -h xxhostxx -p 5432 -U xxuserxx --lock-wait-timeout 300000 -f test_pg_dump.dmp

注意:不使用-C选项,因为该选项仅针对纯文本格式有意义

  1. 删除了test数据库

  2. 使用pg_restore来恢复数据库

pg_restore -C -d test -v -h xxhostxx -p 5432 -U xxuserxx test_pg_dump.dmp**

我不明白问题出在哪里!我做错了什么吗? 如果需要更多信息,请告诉我。

4个回答

24

就像@Eelke说的那样 - 你在文件中写了'create database',所以当你运行脚本时这个数据库并不存在...这就是始终存在'postgres'数据库的原因。请尝试以下操作:

pg_restore -C -d postgres -v -h xxhostxx -p 5432 -U xxuserxx test_pg_dump.dmp**

并且这应该:

  1. 连接到Postgres数据库
  2. 创建测试数据库
  3. 断开与Postgres的连接并连接到测试数据库
  4. 将数据上传到数据库中

当然,要检查Postgres数据库的所有者是谁-在大多数情况下,您必须以用户“postgres”身份运行此操作。


1
这个命令中有一个拼写错误,有些人可能没有注意到:postgres-v 应该是 postgres -v。我不能在帖子中编辑少于6个字符。 - adamczi

16

它从未对我起作用,因此此命令会创建数据库

createdb -h HOST -U USER -W DB_NAME

然后执行pg恢复操作

pg_restore -d DB_NAME -v -h HOST -p PORT -U USER DUMP_FILE.dump**
故事完结了。

这是PG安装的一部分。取决于您的操作系统和PG版本。我使用的是Ubuntu 18.04和PG9。 - Andre Leon Rangel

15
以下引用并不是你所想象的意思。在我读了三遍之后,才明白他们的意思。
当使用此选项时,仅使用带有-d选项指定的数据库来发出初始的DROP DATABASE和CREATE DATABASE命令。所有数据都将恢复到出现在归档中的数据库名称中。
这意味着pg_restore将最初连接到使用-d指定的数据库。它不会创建那个数据库。它会创建一个名称来自你正在恢复的归档的数据库,并将数据恢复到该数据库中。

这是否意味着如果数据库不存在,您就无法还原它? 要进行还原,您需要先发出一个命令来创建一个空数据库,然后再进行还原? - Swapnil17
1
@Swapnil17:你总是有一个空的数据库:template1 - user330315
2
哇,我用这些工具太久了,才现在学到这个。这是一种奇怪的工作方式! - Ethan T

2

来自 man pg_restoreEXAMPLES 部分

Assume we have dumped a database called mydb into a custom-format dump file:

   $ pg_dump -Fc mydb > db.dump

To drop the database and recreate it from the dump:

   $ dropdb mydb
   $ pg_restore -C -d postgres db.dump

The database named in the -d switch can be any database existing in the cluster; pg_restore only uses it to issue the CREATE DATABASE command for mydb.
With -C, data is always restored into the database name that appears in the dump file.

To reload the dump into a new database called newdb:

   $ createdb -T template0 newdb
   $ pg_restore -d newdb db.dump

Notice we don't use -C, and instead connect directly to the database to be restored into. Also note that we clone the new database from template0 not
template1, to ensure it is initially empty.

因此在您的情况下:
$ createdb -h xxhostxx -p 5432 -U xxuserxx -T template0 test
$ pg_restore -h xxhostxx -p 5432 -U xxuserxx -d test db.dump

在同一部分中提到了 pg_restore -l db.dump > db.lis,它将显示原始数据库备份的名称。 - borracciaBlu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接