将pg_dump的结果用作pg_restore的输入

18

我需要在同一台服务器上克隆一个数据库(只复制架构)。我想使用从pg_dump获取的输入,并将其导入到pg_restore中。我知道可以使用psql完成此操作,但是psql没有"-c clean"选项。

这是否可能使用pg_restore实现?

 pg_dump --schema public dbName | psql dbNameTest

1
你尝试过使用 pg_dump --format=c ... | pg_restore ... 吗? - user330315
1
使用 pg_dump --schema-only (-c -C ... 更多选项 ...) databasename >myfile.sql,并在使用 psql 提交之前编辑输出文件。--schema-only 的输出不是很大。 - wildplasser
使用psql有什么问题吗? - Scott Marlowe
pg_restore带有“--jobs”选项,可以让您使用所有CPU来恢复备份,从而使恢复速度更快。 - EAmez
2个回答

27
以下内容较接近:
pg_dump --schema-only --format c dbName | \
  pg_restore --schema-only --clean --dbname=dbNameTest

除非dbNameTest已经存在,否则它是不起作用的。以下代码可以解决这个问题(虽然如果dbNameTest已经存在会报错,但我可以接受)。
createdb dbNameTest
pg_dump --schema-only --format c dbName | \
  pg_restore --schema-only --clean --dbname=dbNameTest

一个带有短选项的单行代码可以是:
createdb dbNameTest ; pg_dump -s -F c dbName | pg_restore -s -c -d dbNameTest

一个名为 pg_copy_schema 的 sh 脚本可能是这样的:
#!/bin/sh
if [ -z "$2" ] ; then echo "Usage: `basename $0` original-db new-db" ; exit 1 ; fi
echo "Copying schema of $1 to $2"
createdb "$2" 2> /dev/null
pg_dump --schema-only --format c "$1" | pg_restore --schema-only --clean --dbname="$2"

这个答案做得很好,代码看起来非常干净和有用。但是为什么要使用 --schema-only 呢? - Nico Brenner
4
操作者希望仅复制数据库架构。 - artm
请注意,pg_restore不能被导向到pg_dump的输出。如果这样做,会出现类似于“不支持从stdin并行还原”的错误提示。至少在v12版本中是如此。 - EAmez

2

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