上面的答案很有帮助,但最终并没有让我 100% 了解我的情况,所以我想我会为与我自己有类似情况的人分享上面的迭代。
在我的场景中,我可能有具有不同名称和不同所有者的登台和生产数据库。我可能需要迁移临时数据库以替换生产数据库,但名称和所有者不同。
或者我可能需要恢复每日备份,但出于某种原因更改了名称或所有者。
我们的权限相当简单,因为每个应用程序都有自己的数据库/用户,因此这不会帮助具有复杂用户/角色/权限设置的人。
我尝试使用从模板创建方法来复制数据库,但如果源数据库上的任何用户/连接处于活动状态,这将失败,因此这不适用于实时源数据库。
使用基本的--no-owner 还原,还原/新数据库上的数据库/表所有者是执行命令的用户(例如 postgres)...因此您将有一个额外的步骤来修复所有数据库权限。由于我们有一个简单的单个应用程序特定用户每 db 设置,我们可以让事情变得更容易。
我希望我的应用程序特定用户拥有数据库/表,即使他们一开始没有创建数据库的权限。
设置一些变量...
DB_NAME_SRC="app_staging"
DB_NAME_TARGET="app_production"
DB_TARGET_OWNER="app_production_user"
DUMP_FILE="/tmp/$DB_NAME_SRC"
然后做备份/恢复
# backup clean/no-owner
sudo -i -u postgres pg_dump --format custom --clean --no-owner "$DB_NAME_SRC" > "$DUMP_FILE"
# drop target if exists - doesn't work for db with active users/connections
sudo -i -u postgres dropdb -U postgres --if-exists "$DB_NAME_TARGET"
# recreate target db, specifying owner to be the new owner/user (user must already exist in postgres, presumably setup by your app deploy/provisioning)
sudo -i -u postgres createdb -U postgres --owner "$DB_TARGET_OWNER" -T template0 "$DB_NAME_TARGET"
# do the restore to the target db as the target user so any created objects will be owned by our target user.
sudo -i -u postgres pg_restore --host localhost --port 5432 --username "$DB_TARGET_OWNER" --password --dbname "$DB_NAME_TARGET" --no-owner --no-privileges "$DUMP_FILE"
# now in this simple case I don't need an additional step of fixing all the owners/permissions because the db and everything in it will be owned by the specified user.
请注意,在恢复部分中,我使用密码而不是本地连接通过网络连接,因此我不必将 postgres 本地用户身份验证从对等更改为密码。无论如何,我的 db 应用程序特定用户都不是本地用户。