Database migrations on django production

前端 未结 5 402
自闭症患者
自闭症患者 2021-01-31 10:20

From someone who has a django application in a non-trivial production environment, how do you handle database migrations? I know there is south, but it seems like t

5条回答
  •  伪装坚强ぢ
    2021-01-31 10:58

    If your database is non-trivial and Postgresql you have a whole bunch of excellent options SQL-wise, including:

    • snapshotting and rollback
    • live replication to a backup server
    • trial upgrade then live

    The trial upgrade option is nice (but best done in collaboration with a snapshot)

    su postgres
    pg_dump  > $(date "+%Y%m%d_%H%M").sql
    psql template1
    # create database upgrade_test template current_db
    # \c upgradetest
    # \i upgrade_file.sql
    ...assuming all well...
    # \q
    pg_dump  > $(date "+%Y%m%d_%H%M").sql # we're paranoid
    psql 
    # \i upgrade_file.sql
    

    If you like the above arrangement, but you are worried about the time it takes to run upgrade twice, you can lock db for writes and then if the upgrade to upgradetest goes well you can then rename db to dbold and upgradetest to db. There are lots of options.

    If you have an SQL file listing all the changes you want to make, an extremely handy psql command \set ON_ERROR_STOP 1. This stops the upgrade script in its tracks the moment something goes wrong. And, with lots of testing, you can make sure nothing does.

    There are a whole host of database schema diffing tools available, with a number noted in this StackOverflow answer. But it is basically pretty easy to do by hand ...

    pg_dump --schema-only production_db > production_schema.sql
    pg_dump --schema-only upgraded_db > upgrade_schema.sql
    vimdiff production_schema.sql upgrade_schema.sql
    or
    diff -Naur production_schema.sql upgrade_schema.sql > changes.patch
    vim changes.patch (to check/edit)
    

提交回复
热议问题