有没有办法用pg_restore自动解压缩?

时间:2014-05-09 10:44:19

标签: python python-3.x postgresql unzip pg-restore

我有一个程序可以进行PostgreSQL备份,并为用户提供压缩这些备份的机会:

if bkp_type == 'gz':
   command = 'pg_dumpall -U {} -h {} -p {} | gzip > {}'.format(user, server, port, file)
elif bkp_type == 'bz2':
   command = 'pg_dumpall -U {} -h {} -p {} | bzip2 > {}'.format(user, server, port, file)
elif bkp_type == 'zip':
   command = 'pg_dumpall -U {} -h {} -p {} | zip > {}'.format(user, server, port, file)
else:
   command = 'pg_dumpall -U {} -h {} -p {} > {}'.format(user, server, port, file)

result = subprocess.call(command, shell=True)

现在,我正在使用pg_restore来恢复它们,但如果文件被压缩,我无法做到。有没有办法直接使用pg_restore(比如在pg_dump或pg_dumpall中)或者我是否必须检查使用的压缩类型并用Python解压缩它们?

1 个答案:

答案 0 :(得分:1)

最后我管理这个解决方案来恢复pg_dump生成的备份(还没有pg_dumpall):

if ext == 'gz':
   command = 'gunzip -c {} -k | pg_restore -U {} -h {} -p {}' \
             '-d {}'.format(file, user, server, port, new_dbname)
elif ext == 'bz2':
   command = 'bunzip2 -c {} -k | pg_restore -U {} -h {} -p {}' \
             '-d {}'.format(file, user, server, port, new_dbname)
elif ext == 'zip':
   command = 'unzip -p {} | pg_restore -U {} -h {} -p {} ' \
             '-d {}'.format(file, user, server, port, new_dbname)
else:
   command = 'pg_restore -U {} -h {} -p {} -d {} {}'.format(user,
                server, port, new_dbname, file)