我正在使用heroku,我想从我的应用程序(heroku)下载数据库,所以我可以对其进行一些更改,我已经安装了pgbackups,但是使用heroku pgbackups:url
下载了一个.dump文件
如何下载postgresql文件或将.dump转换为postgresql文件?
如果您正在使用Heroku的pgbackup(您可能应该使用它):
$ heroku pg:backups capture
$ curl -o latest.dump `heroku pg:backups public-url`
将其翻译成postgres数据库
$ pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d mydb latest.dump
见https://devcenter.heroku.com/articles/heroku-postgres-import-export
在CLI中有一个命令 - heroku db:pull
将为您执行此操作。 db:pull
可能会有点慢,所以你可能会更好地使用下一个选项。
如果你正在使用复杂的postgress数据类型(hstore,数组等),那么你需要使用pgtransfer插件https://github.com/ddollar/heroku-pg-transfer,它基本上会在Heroku上进行备份并在本地恢复它。
更新:db:pull
和db:push
已被弃用,应更换为pg:pull
和pg:push
- 更多信息,请访问https://devcenter.heroku.com/articles/heroku-postgresql#pg-push-and-pg-pull
我发现在documentation pull/push中建议的第一种方法更容易。无需密码或用户名。
PG:拉
pg:pull可用于将远程数据从Heroku Postgres数据库提取到本地计算机上的数据库。该命令如下所示:
$ heroku pg:pull HEROKU_POSTGRESQL_MAGENTA mylocaldb --app sushi
此命令将创建一个名为“mylocaldb”的新本地数据库,然后从应用程序“sushi”中的
DATABASE_URL
数据库中提取数据。为了防止意外的数据覆盖和丢失,本地数据库不得存在。在继续之前,系统将提示您删除已存在的本地数据库。
起初我有一个错误:/bin/sh: createdb: command not found
;我在this SO post之后解决了。
文档中也有描述的替代方法(我还没有尝试过):
要从Heroku Postgres数据库导出数据,请创建一个新备份并下载它。
$ heroku pg:backups:capture $ heroku pg:backups:download
资料来源:Importing and Exporting Heroku Postgres Databases with PG Backups
我认为在本地服务器上下载和复制数据库的最简单方法是:
**PGUSER**=LOCAL_USER_NAME PGPASSWORD=LOCAL_PASSWORD heroku pg:pull --app APP_NAME HEROKU_POSTGRESQL_DB_NAME LOCAL_DB_NAME
浏览此文档了解更多信息:https://devcenter.heroku.com/articles/heroku-postgresql#pg-push-and-pg-pull
这是我喜欢使用的脚本。
namespace :heroku do
desc "Import most recent database dump"
task :import_from_prod => :environment do
puts 'heroku run pg:backups capture --app APPNAME'
restore_backup 'APPNAME'
end
def path_to_heroku
['/usr/local/heroku/bin/heroku', '/usr/local/bin/heroku'].detect {|path| File.exists?(path)}
end
def heroku(command, site)
`GEM_HOME='' BUNDLE_GEMFILE='' GEM_PATH='' RUBYOPT='' #{path_to_heroku} #{command} -a #{site}`
end
def restore_backup(site = 'APPNAME')
dump_file = "#{Rails.root}/tmp/postgres.dump"
unless File.exists?(dump_file)
pgbackups_url = heroku('pg:backups public-url -q', site).chomp
puts "curl -o #{dump_file} #{pgbackups_url}"
system "curl -o #{dump_file} '#{pgbackups_url}'"
end
database_config = YAML.load(File.open("#{Rails.root}/config/database.yml")).with_indifferent_access
dev_db = database_config[Rails.env]
system "pg_restore -d #{dev_db[:database]} -c #{dump_file}".gsub(/\s+/,' ')
puts
puts "'rm #{dump_file}' to redownload postgres dump."
puts "Done!"
end
end
要从Heroku Postgres数据库导出数据,请按照以下步骤操作
pg_dump --DATABASE_URL_COPIED_IN_STEP_3 > database_dump_file
请注意,这将提供postgresql文件或转储文件,您可以直接从postgres插件接口下载。