Some documentation on how to write database migrations.
[mediagoblin.git] / docs / source / devel / migrations.rst
CommitLineData
4436fbcd
CAW
1.. MediaGoblin Documentation
2
3 Written in 2011, 2012 by MediaGoblin contributors
4
5 To the extent possible under law, the author(s) have dedicated all
6 copyright and related and neighboring rights to this software to
7 the public domain worldwide. This software is distributed without
8 any warranty.
9
10 You should have received a copy of the CC0 Public Domain
11 Dedication along with this software. If not, see
12 <http://creativecommons.org/publicdomain/zero/1.0/>.
13
14==========
15Migrations
16==========
17
18So, about migrations. Every time we change the way the database
19structure works, we need to add a migration so that people running
20older codebases can have their databases updated to the new structure
21when they run `./bin/gmg dbupdate`.
22
23There's a few things you need to know:
24
25- We use `sqlalchemy-migrate
26 <http://code.google.com/p/sqlalchemy-migrate/>`_.
27 See `their docs <https://sqlalchemy-migrate.readthedocs.org/>`_.
28- `Alembic <https://bitbucket.org/zzzeek/alembic>`_ might be a better
29 choice than sqlalchemy-migrate now or in the future, but we
30 originally decided not to use it because it didn't have sqlite
31 support. It's not clear if that's changed.
32- SQLAlchemy has two parts to it, the ORM and the "core" interface.
33 We DO NOT use the ORM when running migrations. Think about it: the
34 ORM is set up with an expectation that the models already reflect a
35 certain pattern. But if a person is moving from their old patern
36 and are running tools to *get to* the current pattern, of course
37 their current database structure doesn't match the state of the ORM!
38- How to write migrations? Maybe there will be a tutorial here in the
39 future... in the meanwhile, look at existing migrations in
40 `mediagoblin/db/migrations.py` and look in
41 `mediagoblin/tests/test_sql_migrations.py` for examples.
42- Common pattern: use `inspect_table` to get the current state
43 of the table before we run alterations on it.
44- Make sure you set the RegisterMigration to be the next migration in
45 order.
46- What happens if you're adding a *totally new* table? In this case,
47 you should copy the table in entirety as it exists into
48 migrations.py then create the tables based off of that... see
49 add_collection_tables. This is easier than reproducing the SQL by
50 hand.
51- If you're writing a feature branch, you don't need to keep adding
52 migrations every time you change things around if your database
53 structure is in flux. Just alter your migrations so that they're
54 correct for the merge into master.
55
56That's it for now! Good luck!