从heroku postgresql更新本地数据库,停机时间最短

时间:2014-11-26 17:15:41

标签: postgresql heroku

我想每晚从我的Heroku Postgres数据库更新我的本地posgres数据库。

我当时可能有连接到本地数据库的应用程序。我不想记得关闭并重新启动它们。我不想继续更改我的应用程序的数据库名称。

如何以最少的干预和停机时间恢复数据库?

1 个答案:

答案 0 :(得分:0)

将它放在一个bash文件中,并在你不介意从你下面更改数据库时,从一个cron作业中调用它:

# copy local db from server into a file
curl -o fresh.db `heroku pgbackups:url --app myapp`

# make a new local database with a temporary name
psql -c 'CREATE DATABASE freshdb;'

# restore the fresh database from the file
pg_restore --verbose --clean --no-acl --no-owner -h localhost -d freshdb fresh.db

# kill all connections to the local postgres server so we can rename the database
# from http://stackoverflow.com/a/13023189/596939
cat <<-EOF | psql  
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
where pg_stat_activity.datname = 'workingdb'
EOF

# make the fresh database the active one, drop the old one
psql -c 'ALTER DATABASE workingdb RENAME to olddb;'
psql -c 'ALTER DATABASE freshdb RENAME to workingdb;'
psql -c 'DROP DATABASE olddb;'

# clean up temporary files
rm fresh.db

您的应用应设置为在注意到丢失连接时自动重新连接到数据库;你一切都准备好了!下次在本地使用您的应用程序时,它将拥有数据库的更新副本。