]> git.zarvox.org Git - imoo.git/blob - create_db_migrate_script.py
Fix misnamed parameter in log line
[imoo.git] / create_db_migrate_script.py
1 #!env/bin/python
2 # You have a model (A) that represents your current DBs.
3 # You want to transform that into a new model (B).
4 #
5 # To create the migration script:
6 # 1) Have (A) on the filesystem.
7 # 2) Populate the database with the schema described by version (A).
8 #    This will be done if you simply run the app, since it auto-applies all
9 #    migrations.
10 # 3) Edit models.py (A) into (B) on the filesystem.
11 # 4) Run this script with a description of the changes as argv[1].
12
13 import imp
14 import os.path
15 import sys
16
17 from migrate.versioning import api
18
19 from imoo import create_app, db, models
20
21 app = create_app()
22
23 SQLALCHEMY_DATABASE_URI = app.config['SQLALCHEMY_DATABASE_URI']
24 SQLALCHEMY_MIGRATE_REPO = app.config['SQLALCHEMY_MIGRATE_REPO']
25
26 # come up with a name for the migration
27 migration_description = "migration"
28 if len(sys.argv) > 1:
29     migration_description = sys.argv[1].replace(' ', '_')
30
31 # Pick the next filename for this script
32 current_db_version = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
33 new_migration_script = os.path.join(SQLALCHEMY_MIGRATE_REPO, "versions",
34         "{0:03d}_{1}.py".format(current_db_version + 1, migration_description))
35
36 # Get current model from DB, save into a temporary module
37 tmp_module = imp.new_module('old_model')
38 old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
39 exec old_model in tmp_module.__dict__
40
41 # Generate a new update script and save it to disk
42 script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, tmp_module.meta, db.metadata)
43 with open(new_migration_script, "wt") as f:
44     f.write(script)
45     print script
46
47 print "New migration saved as", new_migration_script
48 print "Current database version:", api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
49 print "Run update_db.py to update your database to the new version"