wiki:DevelopingWithMigrations

Developing with Migrations

When you decide that you need to change the database schema (add/remove/change a table or column), you need to create a database migration which will enable both you and others to upgrade (and downgrade!) the database through those changes you want to make to the database schema.

  1. Make sure you've set up your database to record migration versions first!
  1. The first step is to change your model (model/main.py) so it matches the changes you want to make to the database. Then you need to follow the steps outlined in terminal commands below.
  1. Here is an  example migration (and other associated changes) which makes formerly plural table names singular. Below are the terminal commands used to create and execute the migration. (Do this in an activated virtualenv!)
  • The easy way to run the commands below is to run the all-in-one  new_migration.sh script like this, so you can create a new migration in just one command:
./new_migration.sh "Describe the new migration here"
  • If instead you want to enter each command separately yourself, you can run the following commands:
# Compare the model to the database to see what needs to change in the database
./manage.py compare_model_to_db rcl.model.metadata

# Create a declarative model file representing the current state of the database
./manage.py create_model > oldmodel.py

# Create an upgrade script and give it a meaningful name
./manage.py make_update_script_for_model --oldmodel=oldmodel:meta --model=rcl.model:metadata > migration/versions/002_make_singular.py

# --- manually edit 002_make_singular.py in case it does not do what you want it to do, then... ---

# optionally test upgrading & downgrading on an expendable copy of your database
cp devdata.db devdata.db.bak
./manage.py test
# then if all went well, restore your original database
rm devdata.db
mv devdata.db.bak devdata.db

# ------------------------------------------------------------------------------------------------------
# NOTE: !!! Start here if you're not creating a new migration, but only running a migration that another 
# developer created in order to get your database schema in sync with new code revisions you just pulled
# in via Bazaar !!!
# ------------------------------------------------------------------------------------------------------

# run the migration script to upgrade your database
./manage.py upgrade

# optionally test downgrading to the specified previous version
./manage.py downgrade 1

# remove temporary file
rm oldmodel.py

# commit new migration script to the repository
bzr commit -m "Describe new migration script here"