summaryrefslogtreecommitdiff
path: root/docs/schema-evolution.txt
blob: 38794900f29cfd19a3093ae59d3a8707ff7a8045 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
= Schema Evolution Documentation =

== Introduction ==

Schema evolution is the function of updating an existing Django generated database schema to a newer/modified version based upon a newer/modified set of Django models.

=== Limitations ===

I feel it important to note that is an automated implementation designed to handle schema ''evolution'', not ''revolution''.  No tool, other than storing DBA written SQL scripts and auto-applying them via schema versioning or DB fingerprinting (which is a trivial solution - I have a Java implementation if anyone wants it), can handle the full scope of possible database changes.  Once you accept this fact, the following becomes self-evident:

 * There is a trade off between ease of use and the scope of coverable problems.

Combine that with:

 * The vast majority of database changes are minor, evolutionary tweaks. (*)
 * Very few people are DBAs.

And I believe the ideal solution is in easing the life of common Django developer, not in appeasing the DBA's or power-developer's desire for an all-in-one-comprehensive solution.  Massive schema changes (w/ data retention) are always going to require someone with database skill, but we can empower the people to do the simple things for themselves.

(*) By this I mean adding/removing/renaming tables and adding/removing/renaming/changing-attributes-of columns.

== Downloading / Installing ==

This functionality is not yet in Django/trunk, but in a separate schema-evolution branch.  To download this branch, run the following:

{{{
svn co http://code.djangoproject.com/svn/django/schema-evolution/ django_se_src
ln -s `pwd`/django_se_src/django SITE-PACKAGES-DIR/django
}}}

Or, if you're currently running Django v0.96, run the following:

{{{
cd /<path_to_python_dir>/site-packages/django/
wget http://kered.org/blog/wp-content/uploads/2007/07/django_schema_evolution-v096patch.txt
patch -p1 < django_schema_evolution-v096patch.txt
}}}

The last command will produce the following output:

{{{
patching file core/management.py
patching file db/backends/mysql/base.py
patching file db/backends/mysql/introspection.py
patching file db/backends/postgresql/base.py
patching file db/backends/postgresql/introspection.py
patching file db/backends/sqlite3/base.py
patching file db/backends/sqlite3/introspection.py
patching file db/models/fields/__init__.py
patching file db/models/options.py}}}
}}}

== How To Use ==

For the most part, schema evolution is designed to be automagic via introspection.  Make changes to your models, run syncdb, and you're done.  But like all schema changes, it's wise to preview what is going to be run.  To do this, run the following:

{{{
./manage sqlevolve app_name
}}}

This will output to the command line the SQL to be run to bring your database schema up to date with your model structure.

However not everything can be handled through introspection.  A small amount of metadata is used in the cases of model or field renames, so that the introspection code can match up the old field to the new field. (therefore preserving your data)

For renaming a column, use an "aka" attribute:

{{{
    # this field used to be called pub_date
    publish_date = models.DateTimeField('date published', aka='pub_date')
}}}

If you have renamed this twice and still wish to support migration from both older schemas, "aka"s can be tuples:

{{{
    # this field used to be called pub_date
    publish_date = models.DateTimeField('date published', aka=('pub_date','other_old_field_name'))
}}}

For renaming a model, add an "aka" field to the Meta section:

{{{
# the original name for this model was 'Choice'
class Option(models.Model):
    [...]
    class Meta:
        aka = 'Choice'
}}}

For further examples...

== Usage Examples ==

The following documentation will take you through several common model changes and show you how Django's schema evolution handles them. Each example provides the pre and post model source code, as well as the SQL output.

=== Adding / Removing Fields ===

Model: version 1

{{{
    from django.db import models
    
    class Poll(models.Model):
        question = models.CharField(maxlength=200)
        pub_date = models.DateTimeField('date published')
        author = models.CharField(maxlength=200)
        def __str__(self):
            return self.question
        
    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)
        votes = models.IntegerField()
        def __str__(self):
            return self.choice
}}}

Model: version 2

{{{	
    from django.db import models
    
    class Poll(models.Model):
        question = models.CharField(maxlength=200)
        pub_date = models.DateTimeField('date published')
        author = models.CharField(maxlength=200)
        def __str__(self):
            return self.question
    
        # new fields
        pub_date2 = models.DateTimeField('date published')

    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)
        votes = models.IntegerField()
        def __str__(self):
            return self.choice
    
        # new fields
        votes2 = models.IntegerField()
        hasSomething = models.BooleanField()
        creatorIp = models.IPAddressField()
}}}

Output: v1⇒v2 	

{{{
    BEGIN;
    ALTER TABLE `case01_add_field_poll` ADD COLUMN `pub_date2` datetime NOT NULL;
    ALTER TABLE `case01_add_field_choice` ADD COLUMN `votes2` integer NOT NULL;
    ALTER TABLE `case01_add_field_choice` ADD COLUMN `hasSomething` bool NOT NULL;
    ALTER TABLE `case01_add_field_choice` ADD COLUMN `creatorIp` char(15) NOT NULL;
    COMMIT;
}}}

Output: v2⇒v1 	

{{{
    -- warning: as the following may cause data loss, it/they must be run manually
    -- ALTER TABLE `case01_add_field_poll` DROP COLUMN `pub_date2`;
    -- end warning
    -- warning: as the following may cause data loss, it/they must be run manually
    -- ALTER TABLE `case01_add_field_choice` DROP COLUMN `votes2`;
    -- ALTER TABLE `case01_add_field_choice` DROP COLUMN `creatorIp`;
    -- ALTER TABLE `case01_add_field_choice` DROP COLUMN `hasSomething`;
    -- end warning
}}}

=== Renaming Fields ===

Model: version 1

{{{
    from django.db import models

    class Poll(models.Model):
        """this model originally had fields named pub_date and the_author.  you can use 
        either a str or a tuple for the aka value.  (tuples are used if you have changed 
        its name more than once)"""
        question = models.CharField(maxlength=200)
        pub_date = models.DateTimeField('date published', aka='publish_date')
        the_author = models.CharField(maxlength=200, aka='the_author')
        def __str__(self):
            return self.question
        
    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)
        votes = models.IntegerField(aka='votes')
        def __str__(self):
            return self.choice
}}}

Model: version 2

{{{
    from django.db import models
    
    class Poll(models.Model):
        """this model originally had fields named pub_date and the_author.  you can use
        either a str or a tuple for the aka value.  (tuples are used if you have changed
        its name more than once)"""
        question = models.CharField(maxlength=200)
        published_date = models.DateTimeField('date published', aka=('pub_date', 'publish_date'))
        author = models.CharField(maxlength=200, aka='the_author')
        def __str__(self):
            return self.question
        
    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)
        number_of_votes = models.IntegerField(aka='votes')
        def __str__(self):
            return self.choice
}}}

Output: v1⇒v2 	

{{{
    BEGIN;
    ALTER TABLE `case02_rename_field_poll` CHANGE COLUMN `pub_date` `published_date` datetime NOT NULL;
    ALTER TABLE `case02_rename_field_poll` CHANGE COLUMN `the_author` `author` varchar(200) NOT NULL;
    ALTER TABLE `case02_rename_field_choice` CHANGE COLUMN `votes` `number_of_votes` integer NOT NULL;
    COMMIT;
}}}

=== Renaming Models ===

Model: version 1

{{{
    from django.db import models
    
    class Poll(models.Model):
        question = models.CharField(maxlength=200)
        pub_date = models.DateTimeField('date published')
        author = models.CharField(maxlength=200)
        def __str__(self):
            return self.question
        
    class Choice(models.Model):
        "the original name for this model was 'Choice'"
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)
        number_of_votes = models.IntegerField()
        def __str__(self):
            return self.choice
        class Meta:
            aka = ('Choice', 'OtherBadName')
}}}

Model: version 2

{{{
    from django.db import models
    
    class Poll(models.Model):
        question = models.CharField(maxlength=200)
        pub_date = models.DateTimeField('date published')
        author = models.CharField(maxlength=200)
        def __str__(self):
            return self.question
        
    class Option(models.Model):
        "the original name for this model was 'Choice'"
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)
        # show that field name changes work too
        votes = models.IntegerField(aka='number_of_votes')
        def __str__(self):
            return self.choice
        class Meta:
            aka = ('Choice', 'BadName')
}}}
    
Output: v1⇒v2 	

{{{
    BEGIN;
    ALTER TABLE `case03_rename_model_choice` RENAME TO `case03_rename_model_option`;
    ALTER TABLE `case03_rename_model_option` CHANGE COLUMN `number_of_votes` `votes` integer NOT NULL;
    COMMIT;
}}}

=== Changing Flags ===

Model: version 1

{{{
    from django.db import models
    
    class Poll(models.Model):
        question = models.CharField(maxlength=200)
        pub_date = models.DateTimeField('date published')
        author = models.CharField(maxlength=200)
        def __str__(self):
            return self.question
        
    class Choice(models.Model):
        "the original name for this model was 'Choice'"
        poll = models.ForeignKey(Poll)
        choice = models.CharField(maxlength=200)
        votes = models.IntegerField()
        def __str__(self):
            return self.choice

    class Foo(models.Model):
        GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )
        gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
}}}
    
Model: version 2

{{{
    from django.db import models
    
    class Poll(models.Model):
        question = models.CharField(maxlength=100)
        pub_date = models.DateTimeField('date published')
        author = models.CharField(maxlength=200)
        def __str__(self):
            return self.question
        
    class Choice(models.Model):
        "the original name for this model was 'Choice'"
        poll = models.ForeignKey(Poll)
        # make sure aka still works with a flag change
        option = models.CharField(maxlength=400, aka='choice')
        votes = models.IntegerField()
        votes2 = models.IntegerField() # make sure column adds still work
        def __str__(self):
            return self.choice
    
    class Foo(models.Model):
        GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )
        gender = models.CharField(maxlength=1, choices=GENDER_CHOICES, db_index=True)
        gender2 = models.CharField(maxlength=1, null=True, unique=True)
            
}}}

Output: v1⇒v2 	

{{{
    BEGIN;
    ALTER TABLE `case04_change_flag_poll` MODIFY COLUMN `question` varchar(100) NOT NULL;
    ALTER TABLE `case04_change_flag_foo` ADD COLUMN `gender2` varchar(1) NULL UNIQUE;
    ALTER TABLE `case04_change_flag_choice` MODIFY COLUMN `choice` varchar(400) NOT NULL;
    ALTER TABLE `case04_change_flag_choice` CHANGE COLUMN `choice` `option` varchar(400) NOT NULL;
    ALTER TABLE `case04_change_flag_choice` ADD COLUMN `votes2` integer NOT NULL;
    COMMIT;
}}}

== Conclusion ==

That's pretty much it. If you can suggest additional examples or test cases you
think would be of value, please email me at public@kered.org.