Commits

Jean-Tiare LE BIGOT  committed 801a716 Draft

add migration example

  • Participants
  • Parent commits 29226e8

Comments (0)

Files changed (1)

File docs/api/migration.rst

 For complex use cases, you may consider freezing you application and running an
 EMR on it.
 
-Setting up a migration engine
-=============================
+Use case: Rename field 'mail' to 'email'
+========================================
 
 Migration engine
 ----------------
 
-(TODO)
+::
+
+    from dynamodb_mapper.migration import Migration
+
+    class UserMigration(Migration):
+        # Is it at least compatible with first revision ?
+        def check_1(self, raw_data):
+            field_count = 0
+            field_count += u"id" in raw_data and isinstance(raw_data[u"id"], unicode)
+            field_count += u"energy" in raw_data and isinstance(raw_data[u"energy"], int)
+            field_count += u"mail" in raw_data and isinstance(raw_data[u"mail"], unicode)
+
+            return field_count == len(raw_data)
+
+        #No migrator to version 1: in can not be older than version 1 !
+
+        # Is the object Up to date ?
+        def check_2(self, raw_data):
+            field_count = 0
+            field_count += u"id" in raw_data and isinstance(raw_data[u"id"], unicode)
+            field_count += u"energy" in raw_data and isinstance(raw_data[u"energy"], int)
+            field_count += u"email" in raw_data and isinstance(raw_data[u"email"], unicode)
+
+            return field_count == len(raw_data)
+
+        # migrate from previous revision (1) to this one (the latest)
+        def migrate_to_2(self, raw_data):
+            raw_data[u"email"] = raw_data[u"mail"]
+            del raw_data[u"mail"]
+            return raw_data
 
 Enable migrations in model
 --------------------------
 
-(TODO)
+::
+
+    from dynamodb_mapper.model import DynamoDBModel
+
+    class User(DynamoDBModel):
+        __table__ = "user"
+        __hash_key__ = "id"
+        __migrator__ = UserMigration # Single line to add !
+        __schema__ = {
+            "id": unicode,
+            "energy": int,
+            "email": unicode
+        }
 
 Example run
 -----------
 
-(TODO)
+Let's say you have an object at revision 1 in the db. It will look like this:
 
+::
+
+    raw_data_version_1 = {
+        u"id": u"Jackson",
+        u"energy": 6742348,
+        u"mail": u"jackson@tldr-ludia.com",
+    }
+
+Now, migrate it:
+
+>>> jackson = User.get(u"Jackson")
+# Done, jackson is migrated, but let's check it
+>>> print jackson.email
+u"jackson@tldr-ludia.com" #Alright !
+>>> jackson.save(raise_on_conflict=True)
+# Should go fine if no concurrent access
 
 ``raise_on_conflict`` integration
 =================================