使用pg_restore创建或覆盖表

时间:2017-04-21 15:15:34

标签: sql database postgresql pg-dump pg-restore

我知道这是一个奇怪的请求,但由于一些我无法避免的hacky原因,我希望能够始终如一地将一些表从一个数据库同步到另一个数据库。我知道我可以在脚本中自己写出功能,但我认为pg_dumppg_restore会对我不了解的过程应用很多优化。

我想知道的是,是否有办法让pg_restore覆盖现有的表格。基本上,在伪代码中就像:

-- pseudo code
begin;
drop table to_restore;
drop table to_restore2;
drop table to_restore3;

-- etc

restore table to_restore;
restore table to_restore2;
restore table to_restore3;

-- etc
commit;

如果不是那么好的话,我也会采取其他方式来做这件事。

2 个答案:

答案 0 :(得分:2)

好像你想要pg_restore documentation

中指定的-c选项
  

-c

     

- 清洁

     

在重新创建数据库对象之前清理(删除)它们。 (除非使用--if-exists,否则如果目标数据库中不存在任何对象,则可能会生成一些无害的错误消息。)

您可以使用-1标志在一个事务中执行所有操作

  

-1

     

- 单交易

     

将恢复作为单个事务执行(即,将发出的命令包装在BEGIN / COMMIT中)。这可确保所有命令成功完成,或者不应用任何更改。此选项意味着--exit-on-error。

答案 1 :(得分:1)

这只是可能解决方案的一个例子:

将这些表从第一个db复制到csv。并在交易中使用极快的副本:

begin;
truncate table to_restore;
truncate table to_restore2;
truncate table to_restore3;
  set commit_delay to 100000;
  set synchronous_commit to off;
copy to_restore from 'to_restore.csv';
copy to_restore2 from 'to_restore2.csv';
copy to_restore3 from 'to_restore3.csv';
commit;