23

I am using pg_dump and pg_restore for backup and restore of postgres database.

Here is some information from documentation that will be relevant for this question For Pg_restore, -C option is described as follows

-C

--create

Create the database before restoring into it. If --clean is also specified, > > drop and recreate the target database before connecting to it. When this option is used, the database named with -d is used only to issue the initial DROP DATABASE and CREATE DATABASE commands. All data is restored into the database name that appears in the archive.

However even when I use this option with pg_restore, I get following error

pg_restore: [archiver (db)] connection to database "test" failed: FATAL: > database "test" does not exist

As per the description the -C option should have created the missing database. However it does not in my case.

Following are the steps that I did for backup and restore:

  1. Use pg_dump to backup database
pg_dump -N backup -d test --format custom -v -h xxhostxx -p 5432 -U xxuserxx --lock-wait-timeout 300000 -f test_pg_dump.dmp

Note: not using -C option since it is meaningful for the plain-text formats only

  1. Deleted the test database

  2. use pg_resore to restore database

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

I cannot understand what is the issue here! Am I doing anything wrong ? Let me know if more information is needed.

4

3 回答 3

20

就像@Eelke 所说的那样-您在文件中写入了“创建数据库”,因此当您运行脚本时该数据库不存在……这就是始终存在“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”的身份运行它。

于 2016-11-24T11:23:27.560 回答
13

它从来没有为我工作所以这个命令创建数据库

createdb -h HOST -U USER -W DB_NAME

然后执行 pg restore

pg_restore -d DB_NAME -v -h HOST -p PORT -U USER DUMP_FILE.dump**

故事结局

于 2019-01-04T04:58:44.087 回答
11

以下引用并不意味着您可能认为它意味着什么。在意识到他们在说什么之前,我还必须阅读三次。

使用此选项时,以 -d 命名的数据库仅用于发出初始 DROP DATABASE 和 CREATE DATABASE 命令。所有数据都恢复到存档中出现的数据库名称中。

这意味着 pg_restore 最初将连接到用 -d 指定的数据库。它不会创建该数据库。它使用您正在恢复的存档中的名称创建一个数据库,并将数据恢复到该数据库中。

于 2016-11-24T11:14:49.447 回答