[eb20dc8] | 1 | ZODB migrations |
---|
| 2 | =============== |
---|
| 3 | |
---|
| 4 | This directory contains the migrations applied to the database when the app |
---|
| 5 | is starting. |
---|
| 6 | |
---|
| 7 | .. contents:: |
---|
| 8 | |
---|
| 9 | |
---|
| 10 | Adding a new migration |
---|
| 11 | ---------------------- |
---|
| 12 | |
---|
| 13 | Migrations are named numerically, before adding a new migration look at the |
---|
| 14 | biggest number already available (look at **.py** files), then create a new |
---|
| 15 | **.py** file containing your migration. |
---|
| 16 | |
---|
| 17 | For example, if the last migration is **11.py**, create a file called **12.py** |
---|
| 18 | with your migration code inside. |
---|
| 19 | |
---|
| 20 | The migration file needs a **migrate** function in it, that accepts one |
---|
| 21 | parameter, the **root** of the pyramid application. There is where your code |
---|
| 22 | should modify whatever needs to be modified in the database. |
---|
| 23 | |
---|
| 24 | For example, this migration adds a new attribute to all objects in the |
---|
| 25 | database:: |
---|
| 26 | |
---|
| 27 | from BTrees.OOBTree import OOTreeSet |
---|
| 28 | |
---|
| 29 | def migrate(root): |
---|
| 30 | """ |
---|
| 31 | Adds some_new_attribute to all objects that do not have such attribute |
---|
| 32 | |
---|
| 33 | >>> from models.root import Root, Child |
---|
| 34 | >>> root = Root() |
---|
| 35 | >>> child = Child() |
---|
| 36 | >>> delattr(child, 'some_new_attr') |
---|
| 37 | >>> assert getattr(child, 'some_new_attr', None) is None |
---|
| 38 | True |
---|
| 39 | >>> root.add(child) |
---|
| 40 | >>> c = root.values()[0] |
---|
| 41 | >>> assert getattr(c, 'some_new_attr', None) is None |
---|
| 42 | True |
---|
| 43 | >>> migrate(root) |
---|
| 44 | >>> c = root.values()[0] |
---|
| 45 | >>> assert getattr(c, 'some_new_attr', None) is None |
---|
| 46 | False |
---|
| 47 | """ |
---|
| 48 | for child in root.values(): |
---|
| 49 | if getattr(child, 'some_new_attr', None) is None: |
---|
| 50 | child.some_new_attr = OOTreeSet() |
---|
| 51 | |
---|
| 52 | |
---|
| 53 | It is important that you add a proper doctest for the migration, because: |
---|
| 54 | |
---|
| 55 | 1. The first paragraph of the migration will be shown on the app logs, letting |
---|
| 56 | us known which kind of changes have been made to the database on start. |
---|
| 57 | |
---|
| 58 | 2. Doctests there allow us to keep code coverage high and test those migrations |
---|
| 59 | separately |
---|
| 60 | |
---|
| 61 | **Please use previous migrations for reference when in doubt on how to write |
---|
| 62 | a new migration** |
---|