如何仅通过 运行 一条命令导入数据库?

how can I import a database by running just one command?

我尝试学习如何将 a database 导入 PostgreSQL。

我的尝试失败了,我使用 pg_restore -C ... -d ... 将新数据库的创建和从文件导入到新数据库的一个命令结合起来:

$ sudo -u postgres pg_restore -C -d postgres dvdrental.tar 
pg_restore: [archiver (db)] Error while PROCESSING TOC:
pg_restore: [archiver (db)] Error from TOC entry 2194; 1262 17355 DATABASE pagila postgres
pg_restore: [archiver (db)] could not execute query: ERROR:  invalid locale name: "English_United States.1252"
    Command was: CREATE DATABASE pagila WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252';            
pg_restore: [archiver (db)] could not execute query: ERROR:  database "pagila" does not exist
    Command was: ALTER DATABASE pagila OWNER TO postgres;        
pg_restore: [archiver (db)] could not reconnect to database: FATAL:  database "pagila" does not exist

我的问题是:

文档说:

-C --create

Create the database before restoring into it. If --clean is also specified, drop and recreate the target database before connecting to it.

甚至提供一个例子:

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.

谢谢。


更新:

再次感谢。我发现转储中的二进制文件 toc.dat 包含

CREATE DATABASE pagila WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252';`

是否可以修改它以使 sudo -u postgres pg_restore -C -d postgres dvdrental.tar 工作?


请注意,我有一个有效的解决方案:

psql中单独创建一个新数据库并从文件导入到新数据库:

template1=# CREATE DATABASE dvdrental;
CREATE DATABASE

$ sudo -u postgres pg_restore -d dvdrental dvdrental.tar
$

您的导入失败,因为您尝试导入转储的操作系统不知道区域设置 English_United States.1252。操作系统不是 Windows,或者 Windows 没有安装该语言环境。

pg_restore -C 尝试以与在原始系统上相同的方式创建数据库,这是不可能的。显式创建数据库是可行的,因为它使用了现有的语言环境。

没有办法使 CREATE DATABASE 命令成功,除非存在语言环境,因此如果不可能,您必须 运行 两个命令来恢复转储。