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/ 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 script like this, so you can create a new migration in just one command:
./ "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
./ compare_model_to_db rcl.model.metadata

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

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

# --- manually edit 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
./ 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
./ upgrade

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

# remove temporary file

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