如何从 Postgres Dump 文件中恢复单个表以及其架构?

7
我在恢复表的架构方面遇到了一些困难。我转储了我的Heroku Postgres数据库,并使用pg_restore将其中一个表还原到本地数据库中(它有超过20个表)。成功还原,但当我尝试插入新数据时遇到问题。
当我使用 psql 打开我的数据库时,我发现还原的表可用并包含所有数据,但其架构没有任何行。是否有办法从转储中导入表和其架构?非常感谢。
以下是我将表还原到本地数据库的方法:
pg_restore -U postgres --dbname my_db --table=message latest.dump

编辑:

我按照官方文档尝试了类似以下的操作,但是只是被阻止了,没有任何反应。我的数据库很小,不超过几兆字节,我正在尝试恢复的表结构也不超过100行。

pg_restore -U postgres --dbname mydb --table=message --schema=message_id_seq latest.dump

“Schema”指的是“表数据”,一个序列,还是由CREATE SCHEMA创建的对象? - Laurenz Albe
3个回答

14
作为一个更加通用的回答(我需要从一个巨大的备份中恢复一个单独的表),您可能想看一下这篇文章:https://thequantitative.medium.com/restoring-individual-tables-from-postgresql-pg-dump-using-pg-restore-options-ef3ce2b41ab6。请注意保留HTML标签。
# run the schema-only restore as root
pg_restore -U postgres --schema-only -d new_db /directory/path/db-dump-name.dump

# Restore per table data using something like
pg_restore -U postgres --data-only -d target-db-name -t table_name /directory/path/dump-name.dump

0

恢复一个带有模式限定的表

@Haroldo_OK的回答的基础上,要指定表所属的模式,请在恢复数据时使用--schema选项:

# Restore only the schema (data definitions), not data into the database new_db
# which is assumed to already exist
pg_restore -U postgres --schema-only -d new_db /directory/path/db-dump-name.dump

# Restore the data for the schema_name.table_name table in the new_db database
pg_restore -U postgres --data-only -d new_db --schema schema_name --table table_name /directory/path/dump-name.dump

如果您要恢复的Postgres集群与备份所在的集群不同,那么您要恢复的集群可能没有备份所在集群的组/登录角色。在这种情况下,您可以选择指定--no-owner--no-privileges选项,以防止恢复对象的所有权和访问权限(授予/撤销命令)。
请参考pg_restore文档

-3

来自Heroku DevCenter 这里

Heroku Postgres直接集成到Heroku CLI中,提供了许多有用的命令,简化了常见的数据库任务

您可以在这里检查您的环境是否正确配置。

通过使用Heroku CLI pg:pull命令,您可以将远程数据从Heroku Postgres数据库拉取到本地计算机上的本地数据库。

例如:

$ heroku pg:pull HEROKU_POSTGRESQL_MAGENTA mylocaldb --app sushi

这并没有回答具体的问题。使用 pg:pull 会在本地恢复整个数据库,而 OP 想要恢复单个表。 - RangerRanger
@RangerRanger 这是真的,但我建议直接使用Heroku工具有两个原因:1)数据库只有“几MB”,基本上没有区别 - 我不会建议其他方式 2)如果用户没有太多PG dump / restore的经验,这可能是更简单和更安全的方法。 - Andrea
@Andrea,我已经将远程数据库拉到了本地数据库中;我已经使用pg_restore恢复了所需的表格,但问题在于序列表格,它们不会自动随其表格一起恢复。我不得不手动编辑序列表格以匹配数据表格。虽然不是最好的方法,但它起作用了。感谢您的回答。 - coredumped0x

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