Ticket #5099: django_schema_evolution-SVN5821-patch.txt

File django_schema_evolution-SVN5821-patch.txt, 87.5 KB (added by Derek Anderson <public@…>, 17 years ago)

patch against trunk/HEAD (current as of 5821)

Line 
1diff -x .svn -rN trunk/AUTHORS schema-evolution/AUTHORS
247a48
3> Derek Anderson <public@kered.org>
4diff -x .svn -rN trunk/django/core/management.py schema-evolution/django/core/management.py
57a8
6> from django.conf import settings
7172c173
8< if f.unique and (not f.primary_key or backend.allows_unique_and_pk):
9---
10> if (f.unique and (not f.primary_key or backend.allows_unique_and_pk)) or (f.primary_key and backend.pk_requires_unique):
11482a484,623
12>
13> def get_sql_fingerprint(app):
14> "Returns the fingerprint of the current schema, used in schema evolution."
15> from django.db import get_creation_module, models, backend, get_introspection_module, connection
16> # This should work even if a connecton isn't available
17> try:
18> cursor = connection.cursor()
19> except:
20> cursor = None
21> introspection = get_introspection_module()
22> app_name = app.__name__.split('.')[-2]
23> schema_fingerprint = introspection.get_schema_fingerprint(cursor, app)
24> try:
25> # is this a schema we recognize?
26> app_se = __import__(app_name +'.schema_evolution').schema_evolution
27> schema_recognized = schema_fingerprint in app_se.fingerprints
28> if schema_recognized:
29> sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (recognized)\n" % (app_name, schema_fingerprint)))
30> else:
31> sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (unrecognized)\n" % (app_name, schema_fingerprint)))
32> except:
33> sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (no schema_evolution module found)\n" % (app_name, schema_fingerprint)))
34> return
35> get_sql_fingerprint.help_doc = "Returns the fingerprint of the current schema, used in schema evolution."
36> get_sql_fingerprint.args = APP_ARGS
37>
38> def get_sql_evolution(app):
39> "Returns SQL to update an existing schema to match the existing models."
40> return get_sql_evolution_detailed(app)[2]
41>
42> def get_sql_evolution_detailed(app):
43> "Returns SQL to update an existing schema to match the existing models."
44> import schema_evolution
45> from django.db import get_creation_module, models, backend, get_introspection_module, connection
46> data_types = get_creation_module().DATA_TYPES
47>
48> if not data_types:
49> # This must be the "dummy" database backend, which means the user
50> # hasn't set DATABASE_ENGINE.
51> sys.stderr.write(style.ERROR("Error: Django doesn't know which syntax to use for your SQL statements,\n" +
52> "because you haven't specified the DATABASE_ENGINE setting.\n" +
53> "Edit your settings file and change DATABASE_ENGINE to something like 'postgresql' or 'mysql'.\n"))
54> sys.exit(1)
55>
56> try:
57> backend.get_add_column_sql
58> except:
59> # This must be an unsupported database backend
60> sys.stderr.write(style.ERROR("Error: Django doesn't know which syntax to use for your SQL statements, " +
61> "because schema evolution support isn't built into your database backend yet. Sorry!\n"))
62> sys.exit(1)
63>
64> # First, try validating the models.
65> _check_for_validation_errors()
66>
67> # This should work even if a connecton isn't available
68> try:
69> cursor = connection.cursor()
70> except:
71> cursor = None
72>
73> introspection = get_introspection_module()
74> app_name = app.__name__.split('.')[-2]
75>
76> final_output = []
77>
78> schema_fingerprint = introspection.get_schema_fingerprint(cursor, app)
79> try:
80> # is this a schema we recognize?
81> app_se = __import__(app_name +'.schema_evolution').schema_evolution
82> schema_recognized = schema_fingerprint in app_se.fingerprints
83> if schema_recognized:
84> sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (recognized)\n" % (app_name, schema_fingerprint)))
85> available_upgrades = []
86> for (vfrom, vto), upgrade in app_se.evolutions.iteritems():
87> if vfrom == schema_fingerprint:
88> try:
89> distance = app_se.fingerprints.index(vto)-app_se.fingerprints.index(vfrom)
90> available_upgrades.append( ( vfrom, vto, upgrade, distance ) )
91> sys.stderr.write(style.NOTICE("\tan upgrade from %s to %s is available (distance: %i)\n" % ( vfrom, vto, distance )))
92> except:
93> available_upgrades.append( ( vfrom, vto, upgrade, -1 ) )
94> sys.stderr.write(style.NOTICE("\tan upgrade from %s to %s is available, but %s is not in schema_evolution.fingerprints\n" % ( vfrom, vto, vto )))
95> if len(available_upgrades):
96> best_upgrade = available_upgrades[0]
97> for an_upgrade in available_upgrades:
98> if an_upgrade[3] > best_upgrade[3]:
99> best_upgrade = an_upgrade
100> final_output.extend( best_upgrade[2] )
101> return schema_fingerprint, False, final_output
102> else:
103> sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (unrecognized)\n" % (app_name, schema_fingerprint)))
104> except:
105> # sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (no schema_evolution module found)\n" % (app_name, schema_fingerprint)))
106> pass # ^^^ lets not be chatty
107>
108> # stolen and trimmed from syncdb so that we know which models are about
109> # to be created (so we don't check them for updates)
110> table_list = _get_table_list()
111> seen_models = _get_installed_models(table_list)
112> created_models = set()
113> pending_references = {}
114>
115> model_list = models.get_models(app)
116> for model in model_list:
117> # Create the model's database table, if it doesn't already exist.
118> if model._meta.db_table in table_list or model._meta.aka in table_list or len(set(model._meta.aka) & set(table_list))>0:
119> continue
120> sql, references = _get_sql_model_create(model, seen_models)
121> seen_models.add(model)
122> created_models.add(model)
123> table_list.append(model._meta.db_table)
124>
125> # get the existing models, minus the models we've just created
126> app_models = models.get_models(app)
127> for model in created_models:
128> if model in app_models:
129> app_models.remove(model)
130>
131> for klass in app_models:
132>
133> output, new_table_name = schema_evolution.get_sql_evolution_check_for_changed_model_name(klass)
134> final_output.extend(output)
135>
136> output = schema_evolution.get_sql_evolution_check_for_changed_field_flags(klass, new_table_name)
137> final_output.extend(output)
138>
139> output = schema_evolution.get_sql_evolution_check_for_changed_field_name(klass, new_table_name)
140> final_output.extend(output)
141>
142> output = schema_evolution.get_sql_evolution_check_for_new_fields(klass, new_table_name)
143> final_output.extend(output)
144>
145> output = schema_evolution.get_sql_evolution_check_for_dead_fields(klass, new_table_name)
146> final_output.extend(output)
147>
148> return schema_fingerprint, True, final_output
149>
150> get_sql_evolution.help_doc = "Returns SQL to update an existing schema to match the existing models."
151> get_sql_evolution.args = APP_ARGS
152543c684
153< if table_name_converter(model._meta.db_table) in table_list:
154---
155> if table_name_converter(model._meta.db_table) in table_list or table_name_converter(model._meta.aka) in table_list or len(set(model._meta.aka) & set(table_list))>0:
156570a712,724
157> # keep evolving until there is nothing left to do
158> schema_fingerprint, introspected_upgrade, evolution = get_sql_evolution_detailed(app)
159> last_schema_fingerprint = None
160> while evolution and schema_fingerprint!=last_schema_fingerprint:
161> for sql in evolution:
162> if introspected_upgrade:
163> print sql
164> else:
165> cursor.execute(sql)
166> last_schema_fingerprint = schema_fingerprint
167> if not introspected_upgrade: # only do one round of introspection generated upgrades
168> schema_fingerprint, introspected_upgrade, evolution = get_sql_evolution_detailed(app)
169>
1701524a1679,1680
171> 'sqlevolve': get_sql_evolution,
172> 'sqlfingerprint': get_sql_fingerprint,
173diff -x .svn -rN trunk/django/core/schema_evolution.py schema-evolution/django/core/schema_evolution.py
1740a1,153
175> import django
176> from django.core.exceptions import ImproperlyConfigured
177> from optparse import OptionParser
178> from django.utils import termcolors
179> from django.conf import settings
180> import os, re, shutil, sys, textwrap
181> import management
182>
183>
184> def get_sql_evolution_check_for_new_fields(klass, new_table_name):
185> "checks for model fields that are not in the existing data structure"
186> from django.db import backend, get_creation_module, models, get_introspection_module, connection
187> data_types = get_creation_module().DATA_TYPES
188> cursor = connection.cursor()
189> introspection = get_introspection_module()
190> opts = klass._meta
191> output = []
192> db_table = klass._meta.db_table
193> if new_table_name:
194> db_table = new_table_name
195> for f in opts.fields:
196> existing_fields = introspection.get_columns(cursor,db_table)
197> if f.column not in existing_fields and (not f.aka or f.aka not in existing_fields and len(set(f.aka) & set(existing_fields))==0):
198> rel_field = f
199> data_type = f.get_internal_type()
200> col_type = data_types.get(data_type)
201> if col_type is not None:
202> output.extend( backend.get_add_column_sql( klass._meta.db_table, f.column, management.style.SQL_COLTYPE(col_type % rel_field.__dict__), f.null, f.unique, f.primary_key, f.default ) )
203> return output
204>
205> def get_sql_evolution_check_for_changed_model_name(klass):
206> from django.db import backend, get_creation_module, models, get_introspection_module, connection
207> cursor = connection.cursor()
208> introspection = get_introspection_module()
209> table_list = introspection.get_table_list(cursor)
210> if klass._meta.db_table in table_list:
211> return [], None
212> if klass._meta.aka in table_list:
213> return backend.get_change_table_name_sql( klass._meta.db_table, klass._meta.aka), klass._meta.aka
214> elif len(set(klass._meta.aka) & set(table_list))==1:
215> return backend.get_change_table_name_sql( klass._meta.db_table, klass._meta.aka[0]), klass._meta.aka[0]
216> else:
217> return [], None
218>
219> def get_sql_evolution_check_for_changed_field_name(klass, new_table_name):
220> from django.db import backend, get_creation_module, models, get_introspection_module, connection
221> data_types = get_creation_module().DATA_TYPES
222> cursor = connection.cursor()
223> introspection = get_introspection_module()
224> opts = klass._meta
225> output = []
226> db_table = klass._meta.db_table
227> if new_table_name:
228> db_table = new_table_name
229> for f in opts.fields:
230> existing_fields = introspection.get_columns(cursor,db_table)
231> if f.column not in existing_fields and f.aka and (f.aka in existing_fields or len(set(f.aka) & set(existing_fields)))==1:
232> old_col = None
233> if isinstance( f.aka, str ):
234> old_col = f.aka
235> else:
236> old_col = f.aka[0]
237> rel_field = f
238> data_type = f.get_internal_type()
239> col_type = data_types[data_type]
240> if col_type is not None:
241> col_def = management.style.SQL_COLTYPE(col_type % rel_field.__dict__) +' '+ management.style.SQL_KEYWORD('%sNULL' % (not f.null and 'NOT ' or ''))
242> if f.unique:
243> col_def += management.style.SQL_KEYWORD(' UNIQUE')
244> if f.primary_key:
245> col_def += management.style.SQL_KEYWORD(' PRIMARY KEY')
246> output.extend( backend.get_change_column_name_sql( klass._meta.db_table, introspection.get_indexes(cursor,db_table), old_col, f.column, col_def ) )
247> return output
248>
249> def get_sql_evolution_check_for_changed_field_flags(klass, new_table_name):
250> from django.db import backend, get_creation_module, models, get_introspection_module, connection
251> from django.db.models.fields import CharField, SlugField
252> from django.db.models.fields.related import RelatedField, ForeignKey
253> data_types = get_creation_module().DATA_TYPES
254> cursor = connection.cursor()
255> introspection = get_introspection_module()
256> opts = klass._meta
257> output = []
258> db_table = klass._meta.db_table
259> if new_table_name:
260> db_table = new_table_name
261> for f in opts.fields:
262> existing_fields = introspection.get_columns(cursor,db_table)
263> # print existing_fields
264> cf = None # current field, ie what it is before any renames
265> if f.column in existing_fields:
266> cf = f.column
267> elif f.aka in existing_fields:
268> cf = f.aka
269> elif f.aka and len(set(f.aka) & set(existing_fields))==1:
270> cf = f.aka[0]
271> else:
272> continue # no idea what column you're talking about - should be handled by get_sql_evolution_check_for_new_fields())
273> data_type = f.get_internal_type()
274> if data_types.has_key(data_type):
275> column_flags = introspection.get_known_column_flags(cursor, db_table, cf)
276> # print db_table, cf, column_flags
277> if column_flags['allow_null']!=f.null or \
278> ( not f.primary_key and isinstance(f, CharField) and column_flags['maxlength']!=str(f.maxlength) ) or \
279> ( not f.primary_key and isinstance(f, SlugField) and column_flags['maxlength']!=str(f.maxlength) ) or \
280> ( column_flags['unique']!=f.unique and ( settings.DATABASE_ENGINE!='postgresql' or not f.primary_key ) ) or \
281> column_flags['primary_key']!=f.primary_key:
282> #column_flags['foreign_key']!=f.foreign_key:
283> # print 'need to change'
284> # print db_table, f.column, column_flags
285> # print "column_flags['allow_null']!=f.null", column_flags['allow_null']!=f.null
286> # print "not f.primary_key and isinstance(f, CharField) and column_flags['maxlength']!=str(f.maxlength)", not f.primary_key and isinstance(f, CharField) and column_flags['maxlength']!=str(f.maxlength)
287> # print "not f.primary_key and isinstance(f, SlugField) and column_flags['maxlength']!=str(f.maxlength)", not f.primary_key and isinstance(f, SlugField) and column_flags['maxlength']!=str(f.maxlength)
288> # print "column_flags['unique']!=f.unique", column_flags['unique']!=f.unique
289> # print "column_flags['primary_key']!=f.primary_key", column_flags['primary_key']!=f.primary_key
290> col_type = data_types[data_type]
291> col_type_def = management.style.SQL_COLTYPE(col_type % f.__dict__)
292> # col_def = style.SQL_COLTYPE(col_type % f.__dict__) +' '+ style.SQL_KEYWORD('%sNULL' % (not f.null and 'NOT ' or ''))
293> # if f.unique:
294> # col_def += ' '+ style.SQL_KEYWORD('UNIQUE')
295> # if f.primary_key:
296> # col_def += ' '+ style.SQL_KEYWORD('PRIMARY KEY')
297> output.extend( backend.get_change_column_def_sql( klass._meta.db_table, cf, col_type_def, f.null, f.unique, f.primary_key, f.default ) )
298> #print db_table, cf, f.maxlength, introspection.get_known_column_flags(cursor, db_table, cf)
299> return output
300>
301> def get_sql_evolution_check_for_dead_fields(klass, new_table_name):
302> from django.db import backend, get_creation_module, models, get_introspection_module, connection
303> from django.db.models.fields import CharField, SlugField
304> from django.db.models.fields.related import RelatedField, ForeignKey
305> data_types = get_creation_module().DATA_TYPES
306> cursor = connection.cursor()
307> introspection = get_introspection_module()
308> opts = klass._meta
309> output = []
310> db_table = klass._meta.db_table
311> if new_table_name:
312> db_table = new_table_name
313> suspect_fields = set(introspection.get_columns(cursor,db_table))
314> # print 'suspect_fields = ', suspect_fields
315> for f in opts.fields:
316> # print 'f = ', f
317> # print 'f.aka = ', f.aka
318> suspect_fields.discard(f.column)
319> suspect_fields.discard(f.aka)
320> if f.aka: suspect_fields.difference_update(f.aka)
321> if len(suspect_fields)>0:
322> output.append( '-- warning: the following may cause data loss' )
323> for suspect_field in suspect_fields:
324> output.extend( backend.get_drop_column_sql( klass._meta.db_table, suspect_field ) )
325> output.append( '-- end warning' )
326> return output
327>
328diff -x .svn -rN trunk/django/db/backends/ado_mssql/base.py schema-evolution/django/db/backends/ado_mssql/base.py
32993a94
330> pk_requires_unique = False
331diff -x .svn -rN trunk/django/db/backends/mysql/base.py schema-evolution/django/db/backends/mysql/base.py
332138a139
333> pk_requires_unique = False
334244a246,295
335> def get_change_table_name_sql( table_name, old_table_name ):
336> return ['ALTER TABLE '+ quote_name(old_table_name) +' RENAME TO '+ quote_name(table_name) + ';']
337>
338> def get_change_column_name_sql( table_name, indexes, old_col_name, new_col_name, col_def ):
339> # mysql doesn't support column renames (AFAIK), so we fake it
340> # TODO: only supports a single primary key so far
341> pk_name = None
342> for key in indexes.keys():
343> if indexes[key]['primary_key']: pk_name = key
344> output = []
345> output.append( 'ALTER TABLE '+ quote_name(table_name) +' CHANGE COLUMN '+ quote_name(old_col_name) +' '+ quote_name(new_col_name) +' '+ col_def + ';' )
346> return output
347>
348> def get_change_column_def_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
349> output = []
350> col_def = col_type +' '+ ('%sNULL' % (not null and 'NOT ' or ''))
351> if unique:
352> col_def += ' '+ 'UNIQUE'
353> if primary_key:
354> col_def += ' '+ 'PRIMARY KEY'
355> if default and str(default) != 'django.db.models.fields.NOT_PROVIDED':
356> col_def += ' '+ 'DEFAULT '+ quote_name(str(default))
357> output.append( 'ALTER TABLE '+ quote_name(table_name) +' MODIFY COLUMN '+ quote_name(col_name) +' '+ col_def + ';' )
358> return output
359>
360> def get_add_column_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
361> output = []
362> field_output = []
363> field_output.append('ALTER TABLE')
364> field_output.append(quote_name(table_name))
365> field_output.append('ADD COLUMN')
366> field_output.append(quote_name(col_name))
367> field_output.append(col_type)
368> field_output.append(('%sNULL' % (not null and 'NOT ' or '')))
369> if unique:
370> field_output.append(('UNIQUE'))
371> if primary_key:
372> field_output.append(('PRIMARY KEY'))
373> if default and str(default) != 'django.db.models.fields.NOT_PROVIDED':
374> field_output.append(('DEFAULT'))
375> field_output.append((quote_name(str(default))))
376> output.append(' '.join(field_output) + ';')
377> return output
378>
379> def get_drop_column_sql( table_name, col_name ):
380> output = []
381> output.append( 'ALTER TABLE '+ quote_name(table_name) +' DROP COLUMN '+ quote_name(col_name) + ';' )
382> return output
383>
384>
385diff -x .svn -rN trunk/django/db/backends/mysql/introspection.py schema-evolution/django/db/backends/mysql/introspection.py
38675a76,142
387> def get_columns(cursor, table_name):
388> try:
389> cursor.execute("describe %s" % quote_name(table_name))
390> return [row[0] for row in cursor.fetchall()]
391> except:
392> return []
393>
394> def get_known_column_flags( cursor, table_name, column_name ):
395> cursor.execute("describe %s" % quote_name(table_name))
396> dict = {}
397> for row in cursor.fetchall():
398> if row[0] == column_name:
399>
400> # maxlength check goes here
401> if row[1][0:7]=='varchar':
402> dict['maxlength'] = row[1][8:len(row[1])-1]
403>
404> # default flag check goes here
405> if row[2]=='YES': dict['allow_null'] = True
406> else: dict['allow_null'] = False
407>
408> # primary/foreign/unique key flag check goes here
409> if row[3]=='PRI': dict['primary_key'] = True
410> else: dict['primary_key'] = False
411> if row[3]=='FOR': dict['foreign_key'] = True
412> else: dict['foreign_key'] = False
413> if row[3]=='UNI': dict['unique'] = True
414> else: dict['unique'] = False
415>
416> # default value check goes here
417> # if row[4]=='NULL': dict['default'] = None
418> # else: dict['default'] = row[4]
419> dict['default'] = row[4]
420>
421> # print table_name, column_name, dict
422> return dict
423>
424> def get_schema_fingerprint(cursor, app):
425> """it's important that the output of these methods don't change, otherwise the hashes they
426> produce will be inconsistent (and detection of existing schemas will fail. unless you are
427> absolutely sure the outout for ALL valid inputs will remain the same, you should bump the version by creating a new method"""
428> return get_schema_fingerprint_fv1(cursor, app)
429>
430> def get_schema_fingerprint_fv1(cursor, app):
431> from django.db import models
432> app_name = app.__name__.split('.')[-2]
433>
434> schema = ['app_name := '+ app_name]
435>
436> cursor.execute('SHOW TABLES;')
437> for table_name in [row[0] for row in cursor.fetchall()]:
438> if not table_name.startswith(app_name):
439> continue # skip tables not in this app
440> schema.append('table_name := '+ table_name)
441> cursor.execute("describe %s" % quote_name(table_name))
442> for row in cursor.fetchall():
443> tmp = []
444> for x in row:
445> tmp.append(str(x))
446> schema.append( '\t'.join(tmp) )
447> cursor.execute("SHOW INDEX FROM %s" % quote_name(table_name))
448> for row in cursor.fetchall():
449> schema.append( '\t'.join([ str(row[0]), str(row[1]), str(row[2]), str(row[3]), str(row[4]), str(row[5]), str(row[9]), ]) )
450>
451> return 'fv1:'+ str('\n'.join(schema).__hash__())
452>
453>
454diff -x .svn -rN trunk/django/db/backends/mysql_old/base.py schema-evolution/django/db/backends/mysql_old/base.py
455153a154
456> pk_requires_unique = False
457259a261,305
458> def get_change_table_name_sql( table_name, old_table_name ):
459> return ['ALTER TABLE '+ quote_name(old_table_name) +' RENAME TO '+ quote_name(table_name) + ';']
460>
461> def get_change_column_name_sql( table_name, indexes, old_col_name, new_col_name, col_def ):
462> # mysql doesn't support column renames (AFAIK), so we fake it
463> # TODO: only supports a single primary key so far
464> pk_name = None
465> for key in indexes.keys():
466> if indexes[key]['primary_key']: pk_name = key
467> output = []
468> output.append( 'ALTER TABLE '+ quote_name(table_name) +' CHANGE COLUMN '+ quote_name(old_col_name) +' '+ quote_name(new_col_name) +' '+ col_def + ';' )
469> return output
470>
471> def get_change_column_def_sql( table_name, col_name, col_type, null, unique, primary_key ):
472> output = []
473> col_def = col_type +' '+ ('%sNULL' % (not null and 'NOT ' or ''))
474> if unique:
475> col_def += ' '+ 'UNIQUE'
476> if primary_key:
477> col_def += ' '+ 'PRIMARY KEY'
478> output.append( 'ALTER TABLE '+ quote_name(table_name) +' MODIFY COLUMN '+ quote_name(col_name) +' '+ col_def + ';' )
479> return output
480>
481> def get_add_column_sql( table_name, col_name, col_type, null, unique, primary_key ):
482> output = []
483> field_output = []
484> field_output.append('ALTER TABLE')
485> field_output.append(quote_name(table_name))
486> field_output.append('ADD COLUMN')
487> field_output.append(quote_name(col_name))
488> field_output.append(col_type)
489> field_output.append(('%sNULL' % (not null and 'NOT ' or '')))
490> if unique:
491> field_output.append(('UNIQUE'))
492> if primary_key:
493> field_output.append(('PRIMARY KEY'))
494> output.append(' '.join(field_output) + ';')
495> return output
496>
497> def get_drop_column_sql( table_name, col_name ):
498> output = []
499> output.append( 'ALTER TABLE '+ quote_name(table_name) +' DROP COLUMN '+ quote_name(col_name) + ';' )
500> return output
501>
502>
503diff -x .svn -rN trunk/django/db/backends/mysql_old/introspection.py schema-evolution/django/db/backends/mysql_old/introspection.py
50475a76,112
505> def get_columns(cursor, table_name):
506> try:
507> cursor.execute("describe %s" % quote_name(table_name))
508> return [row[0] for row in cursor.fetchall()]
509> except:
510> return []
511>
512> def get_known_column_flags( cursor, table_name, column_name ):
513> cursor.execute("describe %s" % quote_name(table_name))
514> dict = {}
515> for row in cursor.fetchall():
516> if row[0] == column_name:
517>
518> # maxlength check goes here
519> if row[1][0:7]=='varchar':
520> dict['maxlength'] = row[1][8:len(row[1])-1]
521>
522> # default flag check goes here
523> if row[2]=='YES': dict['allow_null'] = True
524> else: dict['allow_null'] = False
525>
526> # primary/foreign/unique key flag check goes here
527> if row[3]=='PRI': dict['primary_key'] = True
528> else: dict['primary_key'] = False
529> if row[3]=='FOR': dict['foreign_key'] = True
530> else: dict['foreign_key'] = False
531> if row[3]=='UNI': dict['unique'] = True
532> else: dict['unique'] = False
533>
534> # default value check goes here
535> # if row[4]=='NULL': dict['default'] = None
536> # else: dict['default'] = row[4]
537> dict['default'] = row[4]
538>
539> # print table_name, column_name, dict
540> return dict
541>
542diff -x .svn -rN trunk/django/db/backends/postgresql/base.py schema-evolution/django/db/backends/postgresql/base.py
543119a120
544> pk_requires_unique = False
545284a286,330
546> def get_change_table_name_sql( table_name, old_table_name ):
547> output = []
548> output.append('ALTER TABLE '+ quote_name(old_table_name) +' RENAME TO '+ quote_name(table_name) + ';')
549> return output
550>
551> def get_change_column_name_sql( table_name, indexes, old_col_name, new_col_name, col_def ):
552> # TODO: only supports a single primary key so far
553> pk_name = None
554> for key in indexes.keys():
555> if indexes[key]['primary_key']: pk_name = key
556> output = []
557> output.append( 'ALTER TABLE '+ quote_name(table_name) +' RENAME COLUMN '+ quote_name(old_col_name) +' TO '+ quote_name(new_col_name) +';' )
558> return output
559>
560> def get_change_column_def_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
561> output = []
562> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD COLUMN '+ quote_name(col_name+'_tmp') +' '+ col_type + ';' )
563> output.append( 'UPDATE '+ quote_name(table_name) +' SET '+ quote_name(col_name+'_tmp') +' = '+ quote_name(col_name) + ';' )
564> output.append( 'ALTER TABLE '+ quote_name(table_name) +' DROP COLUMN '+ quote_name(col_name) +';' )
565> output.append( 'ALTER TABLE '+ quote_name(table_name) +' RENAME COLUMN '+ quote_name(col_name+'_tmp') +' TO '+ quote_name(col_name) + ';' )
566> if default and str(default) != 'django.db.models.fields.NOT_PROVIDED':
567> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET DEFAULT '+ quote_name(str(default)) +';' )
568> if not null:
569> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET NOT NULL;' )
570> if unique:
571> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD CONSTRAINT '+ table_name +'_'+ col_name +'_unique_constraint UNIQUE('+ col_name +');' )
572>
573> return output
574>
575> def get_add_column_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
576> output = []
577> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD COLUMN '+ quote_name(col_name) +' '+ col_type + ';' )
578> if default and str(default) != 'django.db.models.fields.NOT_PROVIDED':
579> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET DEFAULT '+ quote_name(str(default)) +';' )
580> if not null:
581> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET NOT NULL;' )
582> if unique:
583> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD CONSTRAINT '+ table_name +'_'+ col_name +'_unique_constraint UNIQUE('+ col_name +');' )
584> return output
585>
586> def get_drop_column_sql( table_name, col_name ):
587> output = []
588> output.append( 'ALTER TABLE '+ quote_name(table_name) +' DROP COLUMN '+ quote_name(col_name) + ';' )
589> return output
590>
591diff -x .svn -rN trunk/django/db/backends/postgresql/introspection.py schema-evolution/django/db/backends/postgresql/introspection.py
59268a69,121
593> def get_columns(cursor, table_name):
594> try:
595> cursor.execute("SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$') AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum" % table_name)
596> return [row[0] for row in cursor.fetchall()]
597> except:
598> return []
599>
600> def get_known_column_flags( cursor, table_name, column_name ):
601> # print "SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$') AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum" % table_name
602> cursor.execute("SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$') AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum" % table_name)
603> dict = {}
604> dict['primary_key'] = False
605> dict['foreign_key'] = False
606> dict['unique'] = False
607> dict['default'] = ''
608> dict['allow_null'] = False
609>
610> for row in cursor.fetchall():
611> if row[0] == column_name:
612>
613> # maxlength check goes here
614> if row[1][0:17]=='character varying':
615> dict['maxlength'] = row[1][18:len(row[1])-1]
616>
617> # null flag check goes here
618> dict['allow_null'] = not row[3]
619>
620> # pk, fk and unique checks go here
621> # print "select pg_constraint.conname, pg_constraint.contype, pg_attribute.attname from pg_constraint, pg_attribute where pg_constraint.conrelid=pg_attribute.attrelid and pg_attribute.attnum=any(pg_constraint.conkey) and pg_constraint.conname~'^%s'" % table_name
622> unique_conname = None
623> shared_unique_connames = set()
624> cursor.execute("select pg_constraint.conname, pg_constraint.contype, pg_attribute.attname from pg_constraint, pg_attribute, pg_class where pg_constraint.conrelid=pg_class.oid and pg_constraint.conrelid=pg_attribute.attrelid and pg_attribute.attnum=any(pg_constraint.conkey) and pg_class.relname='%s'" % table_name )
625> for row in cursor.fetchall():
626> # print row
627> if row[2] == column_name:
628> if row[1]=='p': dict['primary_key'] = True
629> if row[1]=='f': dict['foreign_key'] = True
630> if row[1]=='u': unique_conname = row[0]
631> else:
632> if row[1]=='u': shared_unique_connames.add( row[0] )
633> if unique_conname and unique_conname not in shared_unique_connames:
634> dict['unique'] = True
635>
636> # default value check goes here
637> cursor.execute("select pg_attribute.attname, adsrc from pg_attrdef, pg_attribute WHERE pg_attrdef.adrelid=pg_attribute.attrelid and pg_attribute.attnum=pg_attrdef.adnum and pg_attrdef.adrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$')" % table_name )
638> for row in cursor.fetchall():
639> if row[0] == column_name:
640> if row[1][0:7] == 'nextval': continue
641> dict['default'] = row[1][1:row[1].index("'",1)]
642>
643> # print table_name, column_name, dict
644> return dict
645>
646diff -x .svn -rN trunk/django/db/backends/postgresql_psycopg2/base.py schema-evolution/django/db/backends/postgresql_psycopg2/base.py
64781a82
648> pk_requires_unique = False
649226a228,272
650> def get_change_table_name_sql( table_name, old_table_name ):
651> output = []
652> output.append('ALTER TABLE '+ quote_name(old_table_name) +' RENAME TO '+ quote_name(table_name) + ';')
653> return output
654>
655> def get_change_column_name_sql( table_name, indexes, old_col_name, new_col_name, col_def ):
656> # TODO: only supports a single primary key so far
657> pk_name = None
658> for key in indexes.keys():
659> if indexes[key]['primary_key']: pk_name = key
660> output = []
661> output.append( 'ALTER TABLE '+ quote_name(table_name) +' RENAME COLUMN '+ quote_name(old_col_name) +' TO '+ quote_name(new_col_name) +';' )
662> return output
663>
664> def get_change_column_def_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
665> output = []
666> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD COLUMN '+ quote_name(col_name+'_tmp') +' '+ col_type + ';' )
667> output.append( 'UPDATE '+ quote_name(table_name) +' SET '+ quote_name(col_name+'_tmp') +' = '+ quote_name(col_name) + ';' )
668> output.append( 'ALTER TABLE '+ quote_name(table_name) +' DROP COLUMN '+ quote_name(col_name) +';' )
669> output.append( 'ALTER TABLE '+ quote_name(table_name) +' RENAME COLUMN '+ quote_name(col_name+'_tmp') +' TO '+ quote_name(col_name) + ';' )
670> if default and str(default) != 'django.db.models.fields.NOT_PROVIDED':
671> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET DEFAULT '+ quote_name(str(default)) +';' )
672> if not null:
673> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET NOT NULL;' )
674> if unique:
675> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD CONSTRAINT '+ table_name +'_'+ col_name +'_unique_constraint UNIQUE('+ col_name +');' )
676>
677> return output
678>
679> def get_add_column_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
680> output = []
681> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD COLUMN '+ quote_name(col_name) +' '+ col_type + ';' )
682> if default and str(default) != 'django.db.models.fields.NOT_PROVIDED':
683> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET DEFAULT '+ quote_name(str(default)) +';' )
684> if not null:
685> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ALTER COLUMN '+ quote_name(col_name) +' SET NOT NULL;' )
686> if unique:
687> output.append( 'ALTER TABLE '+ quote_name(table_name) +' ADD CONSTRAINT '+ table_name +'_'+ col_name +'_unique_constraint UNIQUE('+ col_name +');' )
688> return output
689>
690> def get_drop_column_sql( table_name, col_name ):
691> output = []
692> output.append( 'ALTER TABLE '+ quote_name(table_name) +' DROP COLUMN '+ quote_name(col_name) + ';' )
693> return output
694>
695diff -x .svn -rN trunk/django/db/backends/postgresql_psycopg2/introspection.py schema-evolution/django/db/backends/postgresql_psycopg2/introspection.py
69665a66,118
697> def get_columns(cursor, table_name):
698> try:
699> cursor.execute("SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$') AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum" % table_name)
700> return [row[0] for row in cursor.fetchall()]
701> except:
702> return []
703>
704> def get_known_column_flags( cursor, table_name, column_name ):
705> # print "SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$') AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum" % table_name
706> cursor.execute("SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum, pg_catalog.col_description(a.attrelid, a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$') AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum" % table_name)
707> dict = {}
708> dict['primary_key'] = False
709> dict['foreign_key'] = False
710> dict['unique'] = False
711> dict['default'] = ''
712> dict['allow_null'] = False
713>
714> for row in cursor.fetchall():
715> if row[0] == column_name:
716>
717> # maxlength check goes here
718> if row[1][0:17]=='character varying':
719> dict['maxlength'] = row[1][18:len(row[1])-1]
720>
721> # null flag check goes here
722> dict['allow_null'] = not row[3]
723>
724> # pk, fk and unique checks go here
725> # print "select pg_constraint.conname, pg_constraint.contype, pg_attribute.attname from pg_constraint, pg_attribute where pg_constraint.conrelid=pg_attribute.attrelid and pg_attribute.attnum=any(pg_constraint.conkey) and pg_constraint.conname~'^%s'" % table_name
726> unique_conname = None
727> shared_unique_connames = set()
728> cursor.execute("select pg_constraint.conname, pg_constraint.contype, pg_attribute.attname from pg_constraint, pg_attribute, pg_class where pg_constraint.conrelid=pg_class.oid and pg_constraint.conrelid=pg_attribute.attrelid and pg_attribute.attnum=any(pg_constraint.conkey) and pg_class.relname='%s'" % table_name )
729> for row in cursor.fetchall():
730> # print row
731> if row[2] == column_name:
732> if row[1]=='p': dict['primary_key'] = True
733> if row[1]=='f': dict['foreign_key'] = True
734> if row[1]=='u': unique_conname = row[0]
735> else:
736> if row[1]=='u': shared_unique_connames.add( row[0] )
737> if unique_conname and unique_conname not in shared_unique_connames:
738> dict['unique'] = True
739>
740> # default value check goes here
741> cursor.execute("select pg_attribute.attname, adsrc from pg_attrdef, pg_attribute WHERE pg_attrdef.adrelid=pg_attribute.attrelid and pg_attribute.attnum=pg_attrdef.adnum and pg_attrdef.adrelid = (SELECT c.oid from pg_catalog.pg_class c where c.relname ~ '^%s$')" % table_name )
742> for row in cursor.fetchall():
743> if row[0] == column_name:
744> if row[1][0:7] == 'nextval': continue
745> dict['default'] = row[1][1:row[1].index("'",1)]
746>
747> # print table_name, column_name, dict
748> return dict
749>
750diff -x .svn -rN trunk/django/db/backends/sqlite3/base.py schema-evolution/django/db/backends/sqlite3/base.py
7514a5
752> from django.core import management
753104a106
754> pk_requires_unique = True # or else the constraint is never created
755216a219,308
756> def get_change_table_name_sql( table_name, old_table_name ):
757> return ['ALTER TABLE '+ quote_name(old_table_name) +' RENAME TO '+ quote_name(table_name) + ';']
758>
759> def get_change_column_name_sql( table_name, indexes, old_col_name, new_col_name, col_def ):
760> # sqlite doesn't support column renames, so we fake it
761> model = get_model_from_table_name(table_name)
762> output = []
763> output.append( '-- FYI: sqlite does not support renaming columns, so we create a new '+ quote_name(table_name) +' and delete the old (ie, this could take a while)' )
764>
765> tmp_table_name = table_name + '_1337_TMP' # unlikely to produce a namespace conflict
766> output.extend( get_change_table_name_sql( tmp_table_name, table_name ) )
767> output.extend( management._get_sql_model_create(model, set())[0] )
768>
769> old_cols = []
770> for f in model._meta.fields:
771> if f.column != new_col_name:
772> old_cols.append( quote_name(f.column) )
773> else:
774> old_cols.append( quote_name(old_col_name) )
775>
776> output.append( 'INSERT INTO '+ quote_name(table_name) +' SELECT '+ ','.join(old_cols) +' FROM '+ quote_name(tmp_table_name) +';' )
777> output.append( 'DROP TABLE '+ quote_name(tmp_table_name) +';' )
778>
779> return output
780>
781> def get_change_column_def_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
782> # sqlite doesn't support column modifications, so we fake it
783>
784> model = get_model_from_table_name(table_name)
785> if not model: return ['-- model not found']
786> output = []
787> output.append( '-- FYI: sqlite does not support changing columns, so we create a new '+ quote_name(table_name) +' and delete the old (ie, this could take a while)' )
788>
789> tmp_table_name = table_name + '_1337_TMP' # unlikely to produce a namespace conflict
790> output.extend( get_change_table_name_sql( tmp_table_name, table_name ) )
791> output.extend( management._get_sql_model_create(model, set())[0] )
792>
793> old_cols = []
794> for f in model._meta.fields:
795> old_cols.append( quote_name(f.column) )
796>
797> output.append( 'INSERT INTO '+ quote_name(table_name) +' SELECT '+ ','.join(old_cols) +' FROM '+ quote_name(tmp_table_name) +';' )
798> output.append( 'DROP TABLE '+ quote_name(tmp_table_name) +';' )
799>
800> return output
801>
802> def get_add_column_sql( table_name, col_name, col_type, null, unique, primary_key, default ):
803> output = []
804> field_output = []
805> field_output.append('ALTER TABLE')
806> field_output.append(quote_name(table_name))
807> field_output.append('ADD COLUMN')
808> field_output.append(quote_name(col_name))
809> field_output.append(col_type)
810> field_output.append(('%sNULL' % (not null and 'NOT ' or '')))
811> if unique or primary_key:
812> field_output.append(('UNIQUE'))
813> if primary_key:
814> field_output.append(('PRIMARY KEY'))
815> if default and str(default) != 'django.db.models.fields.NOT_PROVIDED':
816> field_output.append(('DEFAULT'))
817> field_output.append((quote_name(str(default))))
818> output.append(' '.join(field_output) + ';')
819> return output
820>
821> def get_drop_column_sql( table_name, col_name ):
822> model = get_model_from_table_name(table_name)
823> output = []
824> output.append( '-- FYI: sqlite does not support deleting columns, so we create a new '+ quote_name(col_name) +' and delete the old (ie, this could take a while)' )
825> tmp_table_name = table_name + '_1337_TMP' # unlikely to produce a namespace conflict
826> output.extend( get_change_table_name_sql( tmp_table_name, table_name ) )
827> output.extend( management._get_sql_model_create(model, set())[0] )
828> new_cols = []
829> for f in model._meta.fields:
830> new_cols.append( quote_name(f.column) )
831> output.append( 'INSERT INTO '+ quote_name(table_name) +' SELECT '+ ','.join(new_cols) +' FROM '+ quote_name(tmp_table_name) +';' )
832> output.append( 'DROP TABLE '+ quote_name(tmp_table_name) +';' )
833> return output
834>
835> def get_model_from_table_name(table_name):
836> from django.db import models
837> for app in models.get_apps():
838> app_name = app.__name__.split('.')[-2]
839> if app_name == table_name.split('_')[0] or app_name == '_'.join(table_name.split('_')[0:1]) or app_name == '_'.join(table_name.split('_')[0:2]):
840> for model in models.get_models(app):
841> if model._meta.db_table == table_name:
842> return model
843> return None
844>
845>
846diff -x .svn -rN trunk/django/db/backends/sqlite3/introspection.py schema-evolution/django/db/backends/sqlite3/introspection.py
84729,31d28
848< for info in _table_info(cursor, table_name):
849< indexes[info['name']] = {'primary_key': info['pk'] != 0,
850< 'unique': False}
85139,43c36,45
852< # Skip indexes across multiple fields
853< if len(info) != 1:
854< continue
855< name = info[0][2] # seqno, cid, name
856< indexes[name]['unique'] = True
857---
858> for x in info:
859> name = x[2] # seqno, cid, name
860> cursor.execute('PRAGMA table_info(%s)' % quote_name(table_name))
861> for row in cursor.fetchall():
862> if row[1]==name:
863> indexes[name] = {'primary_key': False, 'unique': False}
864> if row[2]=='integer':
865> indexes[name]['primary_key'] = True
866> else:
867> indexes[name]['unique'] = True
86845a48,101
869> def get_columns(cursor, table_name):
870> try:
871> cursor.execute("PRAGMA table_info(%s)" % quote_name(table_name))
872> return [row[1] for row in cursor.fetchall()]
873> except:
874> return []
875>
876> def get_known_column_flags( cursor, table_name, column_name ):
877> cursor.execute("PRAGMA table_info(%s)" % quote_name(table_name))
878> dict = {}
879> dict['primary_key'] = False
880> dict['foreign_key'] = False
881> dict['unique'] = False
882> dict['default'] = ''
883> dict['allow_null'] = True
884>
885> for row in cursor.fetchall():
886> # print row
887> if row[1] == column_name:
888> col_type = row[2]
889>
890> # maxlength check goes here
891> if row[2][0:7]=='varchar':
892> dict['maxlength'] = row[2][8:len(row[2])-1]
893>
894> # default flag check goes here
895> dict['allow_null'] = row[3]==0
896>
897> # default value check goes here
898> dict['default'] = row[4]
899>
900> cursor.execute("PRAGMA index_list(%s)" % quote_name(table_name))
901> index_names = []
902> for row in cursor.fetchall():
903> index_names.append(row[1])
904> for index_name in index_names:
905> cursor.execute("PRAGMA index_info(%s)" % quote_name(index_name))
906> for row in cursor.fetchall():
907> if row[2]==column_name:
908> if col_type=='integer': dict['primary_key'] = True # sqlite3 does not distinguish between unique and pk; all
909> else: dict['unique'] = True # unique integer columns are treated as part of the pk.
910>
911> # primary/foreign/unique key flag check goes here
912> #if row[3]=='PRI': dict['primary_key'] = True
913> #else: dict['primary_key'] = False
914> #if row[3]=='FOR': dict['foreign_key'] = True
915> #else: dict['foreign_key'] = False
916> #if row[3]=='UNI': dict['unique'] = True
917> #else: dict['unique'] = False
918>
919>
920> # print dict
921> return dict
922>
923diff -x .svn -rN trunk/django/db/models/fields/__init__.py schema-evolution/django/db/models/fields/__init__.py
92483c83
925< help_text='', db_column=None, db_tablespace=None):
926---
927> help_text='', db_column=None, aka=None, db_tablespace=None):
928103a104
929> self.aka = aka
930diff -x .svn -rN trunk/django/db/models/options.py schema-evolution/django/db/models/options.py
93118c18
932< 'order_with_respect_to', 'app_label', 'db_tablespace')
933---
934> 'order_with_respect_to', 'app_label', 'aka', 'db_tablespace')
93525a26
936> self.aka = ''
93778a80,87
938> if isinstance(self.aka, str):
939> self.aka = "%s_%s" % (self.app_label, self.aka.lower())
940> if isinstance(self.aka, tuple):
941> real_aka = []
942> for some_aka in self.aka:
943> real_aka.append( "%s_%s" % (self.app_label, some_aka.lower()) )
944> self.aka = tuple(real_aka)
945>
946diff -x .svn -rN trunk/django/test/simple.py schema-evolution/django/test/simple.py
947149c149
948<
949\ No newline at end of file
950---
951>
952diff -x .svn -rN trunk/docs/schema-evolution.txt schema-evolution/docs/schema-evolution.txt
9530a1,476
954> = Schema Evolution Documentation =
955>
956> == Introduction ==
957>
958> 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, and/or a set of developer written upgrade scripts.
959>
960> It's important to note that different developers wish to approach schema evolution in different ways. As detailed in the original SchemaEvolution document (and elsewhere), there are four basic categories of developers:
961>
962> 1. users who trust introspection and never want to touch/see SQL (Malcolm)
963> 1. users who mostly trust introspection but want the option of auto-applied upgrades for specific situations (Wash)
964> 1. users who use introspection-generated SQL, but don't trust it (they want it generated at development and stored for use in production - Kaylee)
965> 1. users who hate introspection and just want auto-application of their own scripts (Zoe)
966>
967> who wish to perform different combinations of the two basic subtasks of schema evolution:
968>
969> 1. generation of SQL via magical introspection
970> 1. storage and auto-application of upgrade SQL
971>
972> This implementation of schema evolution should satisfy all four groups, while keeping the complexities of the parts you don't use out of sight. Scroll down to the usage sections to see examples of how each developer would approach their jobs.
973>
974> == Downloading / Installing ==
975>
976> This functionality is not yet in Django/trunk, but in a separate schema-evolution branch. To download this branch, run the following:
977>
978> {{{
979> svn co http://code.djangoproject.com/svn/django/branches/schema-evolution/ django_se_src
980> ln -s `pwd`/django_se_src/django SITE-PACKAGES-DIR/django
981> }}}
982>
983> Or, if you're currently running Django v0.96, run the following:
984>
985> {{{
986> cd /<path_to_python_dir>/site-packages/django/
987> wget http://kered.org/blog/wp-content/uploads/2007/07/django_schema_evolution-v096patch.txt
988> patch -p1 < django_schema_evolution-v096patch.txt
989> }}}
990>
991> The last command will produce the following output:
992>
993> {{{
994> patching file core/management.py
995> patching file db/backends/mysql/base.py
996> patching file db/backends/mysql/introspection.py
997> patching file db/backends/postgresql/base.py
998> patching file db/backends/postgresql/introspection.py
999> patching file db/backends/sqlite3/base.py
1000> patching file db/backends/sqlite3/introspection.py
1001> patching file db/models/fields/__init__.py
1002> patching file db/models/options.py
1003> }}}
1004>
1005> == How To Use: Malcolm ==
1006>
1007> For the most part, schema evolution can be performed via introspection, as long as you're not doing anything too radical. If you have an established application the ''vast'' majority of changes are either additions or renames (either tables or columns). Or if you're new to SQL, introspection keeps things very simple for you. To use schema evolution as Malcolm just 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:
1008>
1009> {{{
1010> $ ./manage sqlevolve app_name
1011> }}}
1012>
1013> This will output to the command line the SQL to be run to bring your database schema up to date with your model structure.
1014>
1015> 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)
1016>
1017> For renaming a column, use an "aka" attribute:
1018>
1019> {{{
1020> # this field used to be called pub_date
1021> publish_date = models.DateTimeField('date published', aka='pub_date')
1022> }}}
1023>
1024> If you have renamed this twice and still wish to support migration from both older schemas, "aka"s can be tuples:
1025>
1026> {{{
1027> # this field used to be called pub_date
1028> publish_date = models.DateTimeField('date published', aka=('pub_date','other_old_field_name'))
1029> }}}
1030>
1031> For renaming a model, add an "aka" field to the Meta section:
1032>
1033> {{{
1034> # the original name for this model was 'Choice'
1035> class Option(models.Model):
1036> [...]
1037> class Meta:
1038> aka = 'Choice'
1039> }}}
1040>
1041> And after time you make a series of changes, run sqlevolve or syncdb and your schema changes will be either shown to you or applied for you.
1042>
1043> For further examples, scroll down to the Introspection Examples section.
1044>
1045> == How To Use: Wash ==
1046>
1047> Note that most Malcolm developers (likely new developers) will eventually run up against a limitation inherent in introspection. They love their incredibly intuitive tool but it can't do everything. But they don't want to give it up, because it's a great 90% solution. If only they can add a simple script without having to throw away all the convenient candy, past or future.
1048>
1049> All Wash has to do is store a little bit of extra metadata. Namely two things:
1050>
1051> 1. a fingerprint of the known schema
1052> 1. an sql script
1053>
1054> in the file 'app_name/schema_evolution.py'. (conveniently next to models.py)
1055>
1056> This module looks as follows:
1057>
1058> {{{
1059> # list of all known schema fingerprints, in order
1060> fingerprints = [
1061> 'fv1:1742830097',
1062> 'fv1:907953071',
1063> # add future fingerprints here
1064> ]
1065>
1066> # all of your evolution scripts, mapping the from_version and to_version
1067> # to a list if sql commands
1068> evolutions = {
1069> # ('from_fingerprint','to_fingerprint'): ['-- some sql'],
1070> ('fv1:1742830097','fv1:907953071'): [
1071> '-- some list of sql statements, constituting an upgrade',
1072> '-- some list of sql statements, constituting an upgrade',
1073> ],
1074> }
1075> }}}
1076>
1077> To create this file, he would first fingerprint his schema with the following command:
1078>
1079> {{{
1080> $ ./manage sqlfingerprint app_name
1081> Notice: Current schema fingerprint for 'app_name' is 'fv1:1742830097' (unrecognized)
1082> }}}
1083>
1084> He would add this fingerprint to the end of the 'fingerprints' list in the schema_evolution module, and it would become an automatically recognized schema, ripe for the upgrade. And then he would write an upgrade script, placing it in the 'evolutions' dictionary object, mapped against the current fingerprint and some fake/temporary fingerprint ('fv1:xxxxxxxx'). Finally, he would run his script (either manually or via syncdb), re-fingerprint and save it in both the fingerprints list and the 'to_fingerprint' part of the mapping.
1085>
1086> Later, when he runs sqlevolve (or syncdb) against his production database, sqlevolve will detect his current schema and attempt an upgrade using the upgrade script, and then verify it. If it succeeds, will continue applying all available upgrade scripts until one either fails or it reaches the latest database schema version. (more technically, syncdb will recursively apply all available scripts...sqlevolve since it simply prints to the console, only prints the next available script)
1087>
1088> '''Note:''' Manually defined upgrade scripts always are prioritized over introspected scripts. And introspected scripts are never applied recursively.
1089>
1090> This way Wash can continue using introspections for the majority of his tasks, only stopping to define fingerprints/scripts on those rare occasions he needs them.
1091>
1092> == How To Use: Kaylee ==
1093>
1094> Kaylee, like Wash and Malcolm, likes the time-saving features of automatic introspection, but likes much more control over deployments to "her baby". So she typically still uses introspection during development, but never in production. What she does is instead of saving the occasional "hard" migration scripts like Wash, she saves them all. This builds a neat chain of upgrades in her schema_evolution module which are then applied in series. Additionally, she likes the ability to automatically back out changes as well, so she stores revert scripts (also usually automatically generated at development) in the same module.
1095>
1096> == How To Use: Zoe ==
1097>
1098> Zoe simply doesn't like the whole idea of introspection. She's an expert SQL swinger and never wants to see it generated for her (much less have those ugly "aka" fields buggering up her otherwise pristine models. She simply writes her own SQL scripts and stores them all in her schema_evolution module.
1099>
1100> == Introspection Examples ==
1101>
1102> The following documentation will take you through several common model changes and show you how Django's schema evolution introspection handles them. Each example provides the pre and post model source code, as well as the SQL output.
1103>
1104> === Adding / Removing Fields ===
1105>
1106> Model: version 1
1107>
1108> {{{
1109> from django.db import models
1110>
1111> class Poll(models.Model):
1112> question = models.CharField(maxlength=200)
1113> pub_date = models.DateTimeField('date published')
1114> author = models.CharField(maxlength=200)
1115> def __str__(self):
1116> return self.question
1117>
1118> class Choice(models.Model):
1119> poll = models.ForeignKey(Poll)
1120> choice = models.CharField(maxlength=200)
1121> votes = models.IntegerField()
1122> def __str__(self):
1123> return self.choice
1124> }}}
1125>
1126> Model: version 2
1127>
1128> {{{
1129> from django.db import models
1130>
1131> class Poll(models.Model):
1132> question = models.CharField(maxlength=200)
1133> pub_date = models.DateTimeField('date published')
1134> author = models.CharField(maxlength=200)
1135> def __str__(self):
1136> return self.question
1137>
1138> # new fields
1139> pub_date2 = models.DateTimeField('date published')
1140>
1141> class Choice(models.Model):
1142> poll = models.ForeignKey(Poll)
1143> choice = models.CharField(maxlength=200)
1144> votes = models.IntegerField()
1145> def __str__(self):
1146> return self.choice
1147>
1148> # new fields
1149> votes2 = models.IntegerField()
1150> hasSomething = models.BooleanField()
1151> creatorIp = models.IPAddressField()
1152> }}}
1153>
1154> Output: v1⇒v2
1155>
1156> {{{
1157> BEGIN;
1158> ALTER TABLE `case01_add_field_poll` ADD COLUMN `pub_date2` datetime NOT NULL;
1159> ALTER TABLE `case01_add_field_choice` ADD COLUMN `votes2` integer NOT NULL;
1160> ALTER TABLE `case01_add_field_choice` ADD COLUMN `hasSomething` bool NOT NULL;
1161> ALTER TABLE `case01_add_field_choice` ADD COLUMN `creatorIp` char(15) NOT NULL;
1162> COMMIT;
1163> }}}
1164>
1165> Output: v2⇒v1
1166>
1167> {{{
1168> -- warning: as the following may cause data loss, it/they must be run manually
1169> -- ALTER TABLE `case01_add_field_poll` DROP COLUMN `pub_date2`;
1170> -- end warning
1171> -- warning: as the following may cause data loss, it/they must be run manually
1172> -- ALTER TABLE `case01_add_field_choice` DROP COLUMN `votes2`;
1173> -- ALTER TABLE `case01_add_field_choice` DROP COLUMN `creatorIp`;
1174> -- ALTER TABLE `case01_add_field_choice` DROP COLUMN `hasSomething`;
1175> -- end warning
1176> }}}
1177>
1178> === Renaming Fields ===
1179>
1180> Model: version 1
1181>
1182> {{{
1183> from django.db import models
1184>
1185> class Poll(models.Model):
1186> """this model originally had fields named pub_date and the_author. you can use
1187> either a str or a tuple for the aka value. (tuples are used if you have changed
1188> its name more than once)"""
1189> question = models.CharField(maxlength=200)
1190> pub_date = models.DateTimeField('date published', aka='publish_date')
1191> the_author = models.CharField(maxlength=200, aka='the_author')
1192> def __str__(self):
1193> return self.question
1194>
1195> class Choice(models.Model):
1196> poll = models.ForeignKey(Poll)
1197> choice = models.CharField(maxlength=200)
1198> votes = models.IntegerField(aka='votes')
1199> def __str__(self):
1200> return self.choice
1201> }}}
1202>
1203> Model: version 2
1204>
1205> {{{
1206> from django.db import models
1207>
1208> class Poll(models.Model):
1209> """this model originally had fields named pub_date and the_author. you can use
1210> either a str or a tuple for the aka value. (tuples are used if you have changed
1211> its name more than once)"""
1212> question = models.CharField(maxlength=200)
1213> published_date = models.DateTimeField('date published', aka=('pub_date', 'publish_date'))
1214> author = models.CharField(maxlength=200, aka='the_author')
1215> def __str__(self):
1216> return self.question
1217>
1218> class Choice(models.Model):
1219> poll = models.ForeignKey(Poll)
1220> choice = models.CharField(maxlength=200)
1221> number_of_votes = models.IntegerField(aka='votes')
1222> def __str__(self):
1223> return self.choice
1224> }}}
1225>
1226> Output: v1⇒v2
1227>
1228> {{{
1229> BEGIN;
1230> ALTER TABLE `case02_rename_field_poll` CHANGE COLUMN `pub_date` `published_date` datetime NOT NULL;
1231> ALTER TABLE `case02_rename_field_poll` CHANGE COLUMN `the_author` `author` varchar(200) NOT NULL;
1232> ALTER TABLE `case02_rename_field_choice` CHANGE COLUMN `votes` `number_of_votes` integer NOT NULL;
1233> COMMIT;
1234> }}}
1235>
1236> === Renaming Models ===
1237>
1238> Model: version 1
1239>
1240> {{{
1241> from django.db import models
1242>
1243> class Poll(models.Model):
1244> question = models.CharField(maxlength=200)
1245> pub_date = models.DateTimeField('date published')
1246> author = models.CharField(maxlength=200)
1247> def __str__(self):
1248> return self.question
1249>
1250> class Choice(models.Model):
1251> "the original name for this model was 'Choice'"
1252> poll = models.ForeignKey(Poll)
1253> choice = models.CharField(maxlength=200)
1254> number_of_votes = models.IntegerField()
1255> def __str__(self):
1256> return self.choice
1257> class Meta:
1258> aka = ('Choice', 'OtherBadName')
1259> }}}
1260>
1261> Model: version 2
1262>
1263> {{{
1264> from django.db import models
1265>
1266> class Poll(models.Model):
1267> question = models.CharField(maxlength=200)
1268> pub_date = models.DateTimeField('date published')
1269> author = models.CharField(maxlength=200)
1270> def __str__(self):
1271> return self.question
1272>
1273> class Option(models.Model):
1274> "the original name for this model was 'Choice'"
1275> poll = models.ForeignKey(Poll)
1276> choice = models.CharField(maxlength=200)
1277> # show that field name changes work too
1278> votes = models.IntegerField(aka='number_of_votes')
1279> def __str__(self):
1280> return self.choice
1281> class Meta:
1282> aka = ('Choice', 'BadName')
1283> }}}
1284>
1285> Output: v1⇒v2
1286>
1287> {{{
1288> BEGIN;
1289> ALTER TABLE `case03_rename_model_choice` RENAME TO `case03_rename_model_option`;
1290> ALTER TABLE `case03_rename_model_option` CHANGE COLUMN `number_of_votes` `votes` integer NOT NULL;
1291> COMMIT;
1292> }}}
1293>
1294> === Changing Flags ===
1295>
1296> Model: version 1
1297>
1298> {{{
1299> from django.db import models
1300>
1301> class Poll(models.Model):
1302> question = models.CharField(maxlength=200)
1303> pub_date = models.DateTimeField('date published')
1304> author = models.CharField(maxlength=200)
1305> def __str__(self):
1306> return self.question
1307>
1308> class Choice(models.Model):
1309> "the original name for this model was 'Choice'"
1310> poll = models.ForeignKey(Poll)
1311> choice = models.CharField(maxlength=200)
1312> votes = models.IntegerField()
1313> def __str__(self):
1314> return self.choice
1315>
1316> class Foo(models.Model):
1317> GENDER_CHOICES = (
1318> ('M', 'Male'),
1319> ('F', 'Female'),
1320> )
1321> gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
1322> }}}
1323>
1324> Model: version 2
1325>
1326> {{{
1327> from django.db import models
1328>
1329> class Poll(models.Model):
1330> question = models.CharField(maxlength=100)
1331> pub_date = models.DateTimeField('date published')
1332> author = models.CharField(maxlength=200)
1333> def __str__(self):
1334> return self.question
1335>
1336> class Choice(models.Model):
1337> "the original name for this model was 'Choice'"
1338> poll = models.ForeignKey(Poll)
1339> # make sure aka still works with a flag change
1340> option = models.CharField(maxlength=400, aka='choice')
1341> votes = models.IntegerField()
1342> votes2 = models.IntegerField() # make sure column adds still work
1343> def __str__(self):
1344> return self.choice
1345>
1346> class Foo(models.Model):
1347> GENDER_CHOICES = (
1348> ('M', 'Male'),
1349> ('F', 'Female'),
1350> )
1351> gender = models.CharField(maxlength=1, choices=GENDER_CHOICES, db_index=True)
1352> gender2 = models.CharField(maxlength=1, null=True, unique=True)
1353>
1354> }}}
1355>
1356> Output: v1⇒v2
1357>
1358> {{{
1359> BEGIN;
1360> ALTER TABLE `case04_change_flag_poll` MODIFY COLUMN `question` varchar(100) NOT NULL;
1361> ALTER TABLE `case04_change_flag_foo` ADD COLUMN `gender2` varchar(1) NULL UNIQUE;
1362> ALTER TABLE `case04_change_flag_choice` MODIFY COLUMN `choice` varchar(400) NOT NULL;
1363> ALTER TABLE `case04_change_flag_choice` CHANGE COLUMN `choice` `option` varchar(400) NOT NULL;
1364> ALTER TABLE `case04_change_flag_choice` ADD COLUMN `votes2` integer NOT NULL;
1365> COMMIT;
1366> }}}
1367>
1368> == Criticisms ==
1369>
1370> ''I _really_ don't like the aka representations in the model. The models file should always be a clean statement of the current state of the model. Migration is about
1371> getting an old database to match the currently required models - if I don't have a legacy database, I don't really want the cruft hanging around in my models. Migration plans or historical models really should be kept out of the core model file, IMHO.''
1372>
1373> We currently store all sorts of non-DB related metadata in the model that arguably should not be there, including presentation information. We do this for clarity and convenience - you would have to duplicate a lot of information otherwise in multiple locations without any obvious direct connection. So which paradigm is more critical here, DRY or MVC? Or do we continue with the status-quo of a common-sense balance? As far as cruft, if you don't have a legacy database, you wouldn't have any aka fields to begin with. And as you phase out legacy support, simply delete them.
1374>
1375> ''Unless I'm missing something, the aka approach doesn't track exactly which name versions correlate with other versions. Consider; your aka chain for one field could indicate a rename from 'foo' to 'bar' to 'foo' to 'bar'; a second field could indicate renames from 'whiz' to 'foo' to 'whiz', etc. A tuple of historical names doesn't tell me which sets of names were in use concurrently; so if I find a database with a field called 'foo' which requires migration, is 'foo' the first field or the second?''
1376>
1377> Correct, however I thought this to be a highly unlikely scenario, not warranting the extra notational complexity. But just as we support strings and tuples, there is nothing to say we can't extend it to support say a mapping of historical names to date ranges, if the need arises.
1378>
1379> ''The 'aka' approach is ambiguous for all but trivial use cases. It doesn't capture the idea that database changes occur in bulk, in sequence. For example, On Monday, I add two fields, remove 1 field, rename a table. That creates v2 of the database. On Tuesday, I bring back the deleted field, and remove one of the added fields, creating v3 of the database. This approach doesn't track which state a given database is in, and doesn't apply changes in blocks appropriate to versioned changes.''
1380>
1381> It does not matter how you get from v1 => v3, as long as you get there with minimum theoretical information loss. The following:
1382>
1383> '''v1 => v2 => v3'''
1384> 1. // v1 t1:{A}
1385> 1. add_field(B);
1386> 1. add_field(C);
1387> 1. del_field(A);
1388> 1. rename_table(t1,t2);
1389> 1. // v2 t2{B,C}
1390> 1. add_field(A);
1391> 1. del_field(C);
1392> 1. // v3 t2:{A,B}
1393>
1394> is functionally equivalent to:
1395>
1396> '''v1 => v3'''
1397> 1. // v1 t1:{A}
1398> 1. add_field(B);
1399> 1. rename_table(t1,t2);
1400> 1. // v3 t2:{A,B}
1401>
1402> And this can be supported completely through introspection + metadata about what tables and columns used to be called. If you load v2 or v3, the available information can get you there from v1, and if you load v3, the available information can get you there from v1 or v2.
1403>
1404> A more detailed breakdown of this critique is available [http://kered.org/blog/2007-08-03/schema-evolution-confusion-example-case/ here], complete with working code examples.
1405>
1406> == Future Work ==
1407>
1408> The biggest missing piece I believe to be changing column types. For instance, say you currently have:
1409>
1410> {{{
1411> ssn = models.IntegerField()
1412> }}}
1413>
1414> Which you want to change into:
1415>
1416> {{{
1417> ssn = models.CharField(maxlength=12)
1418> }}}
1419>
1420> Schema evolution should generate SQL to add the new column, push the data from the old to the new column, then delete the old column. Warnings should be provided for completely incompatible types or other loss-of-information scenarios.
1421>
1422> The second biggest missing piece is foreign/m2m key support.
1423>
1424> Lastly, for the migration scripts, sometimes it's easier to write python than it is to write sql. I intend for you to be able to interleave function calls in with the sql statements and have the schema evolution code just Do The Right Thing(tm). But this isn't coded yet.
1425>
1426> == Conclusion ==
1427>
1428> 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.
1429>
1430diff -x .svn -rN trunk/tests/modeltests/schema_evolution/models.py schema-evolution/tests/modeltests/schema_evolution/models.py
14310a1,313
1432> """
1433> Schema Evolution Tests
1434> """
1435>
1436> from django.db import models
1437> from django.conf import settings
1438>
1439> GENDER_CHOICES = (
1440> ('M', 'Male'),
1441> ('F', 'Female'),
1442> )
1443>
1444> class Person(models.Model):
1445> name = models.CharField(maxlength=20)
1446> gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
1447> gender2 = models.CharField(maxlength=1, choices=GENDER_CHOICES, aka='gender_old')
1448>
1449> def __unicode__(self):
1450> return self.name
1451>
1452> class Meta:
1453> aka = ('PersonOld', 'OtherBadName')
1454>
1455> class Muebles(models.Model):
1456> tipo = models.CharField(maxlength=40, default="woot")
1457> # new fields
1458> fecha_publicacion = models.DateTimeField('date published')
1459>
1460> __test__ = {'API_TESTS':"""
1461> >>> import django
1462> >>> from django.core import management
1463> >>> from django.db import backend, models
1464> >>> from django.db import connection, get_introspection_module
1465> >>> app = models.get_apps()[-1]
1466> >>> cursor = connection.cursor()
1467> """}
1468>
1469> if settings.DATABASE_ENGINE == 'mysql':
1470> __test__['API_TESTS'] += """
1471> # the table as it is supposed to be
1472> >>> create_table_sql = management.get_sql_all(app)
1473>
1474> # make sure we don't evolve an unedited table
1475> >>> management.get_sql_evolution(app)
1476> []
1477>
1478> # delete a column, so it looks like we've recently added a field
1479> >>> sql = backend.get_drop_column_sql( 'schema_evolution_person', 'gender' )
1480> >>> print sql
1481> ['ALTER TABLE `schema_evolution_person` DROP COLUMN `gender`;']
1482> >>> for s in sql: cursor.execute(s)
1483> 0L
1484> >>> management.get_sql_evolution(app)
1485> ['ALTER TABLE `schema_evolution_person` ADD COLUMN `gender` varchar(1) NOT NULL;']
1486>
1487> # reset the db
1488> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1489> 0L\n0L
1490>
1491> # add a column, so it looks like we've recently deleted a field
1492> >>> cursor.execute('ALTER TABLE `schema_evolution_person` ADD COLUMN `gender_nothere` varchar(1) NOT NULL;')
1493> 0L
1494> >>> management.get_sql_evolution(app)
1495> ['-- warning: the following may cause data loss', u'ALTER TABLE `schema_evolution_person` DROP COLUMN `gender_nothere`;', '-- end warning']
1496>
1497> # reset the db
1498> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1499> 0L\n0L
1500>
1501> # rename column, so it looks like we've recently renamed a field
1502> >>> cursor.execute('ALTER TABLE `schema_evolution_person` CHANGE COLUMN `gender2` `gender_old` varchar(1) NOT NULL;')
1503> 0L
1504> >>> management.get_sql_evolution(app)
1505> ['ALTER TABLE `schema_evolution_person` CHANGE COLUMN `gender_old` `gender2` varchar(1) NOT NULL;']
1506>
1507> # reset the db
1508> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1509> 0L\n0L
1510>
1511> # rename table, so it looks like we've recently renamed a model
1512> >>> cursor.execute('ALTER TABLE `schema_evolution_person` RENAME TO `schema_evolution_personold`')
1513> 0L
1514> >>> management.get_sql_evolution(app)
1515> ['ALTER TABLE `schema_evolution_personold` RENAME TO `schema_evolution_person`;']
1516>
1517> # reset the db
1518> >>> cursor.execute(create_table_sql[0])
1519> 0L
1520>
1521> # change column flags, so it looks like we've recently changed a column flag
1522> >>> cursor.execute('ALTER TABLE `schema_evolution_person` MODIFY COLUMN `name` varchar(10) NULL;')
1523> 0L
1524> >>> management.get_sql_evolution(app)
1525> ['ALTER TABLE `schema_evolution_person` MODIFY COLUMN `name` varchar(20) NOT NULL;']
1526>
1527> # reset the db
1528> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1529> 0L\n0L
1530>
1531> # delete a datetime column, so it looks like we've recently added a datetime field
1532> >>> for sql in backend.get_drop_column_sql( 'schema_evolution_muebles', 'fecha_publicacion' ): print sql; cursor.execute(sql)
1533> ALTER TABLE `schema_evolution_muebles` DROP COLUMN `fecha_publicacion`;
1534> 0L
1535> >>> management.get_sql_evolution(app)
1536> ['ALTER TABLE `schema_evolution_muebles` ADD COLUMN `fecha_publicacion` datetime NOT NULL;']
1537>
1538> # reset the db
1539> >>> cursor.execute('DROP TABLE schema_evolution_muebles;'); cursor.execute(create_table_sql[1])
1540> 0L\n0L
1541>
1542> # delete a column with a default value, so it looks like we've recently added a column
1543> >>> for sql in backend.get_drop_column_sql( 'schema_evolution_muebles', 'tipo' ): print sql; cursor.execute(sql)
1544> ALTER TABLE `schema_evolution_muebles` DROP COLUMN `tipo`;
1545> 0L
1546> >>> management.get_sql_evolution(app)
1547> ['ALTER TABLE `schema_evolution_muebles` ADD COLUMN `tipo` varchar(40) NOT NULL DEFAULT `woot`;']
1548>
1549> """
1550>
1551> if settings.DATABASE_ENGINE == 'postgresql' or settings.DATABASE_ENGINE == 'postgresql_psycopg2' :
1552> __test__['API_TESTS'] += """
1553> # the table as it is supposed to be
1554> >>> create_table_sql = management.get_sql_all(app)
1555>
1556> # make sure we don't evolve an unedited table
1557> >>> management.get_sql_evolution(app)
1558> []
1559>
1560> # delete a column, so it looks like we've recently added a field
1561> >>> for sql in backend.get_drop_column_sql( 'schema_evolution_person', 'gender' ): cursor.execute(sql)
1562> >>> management.get_sql_evolution(app)
1563> ['ALTER TABLE "schema_evolution_person" ADD COLUMN "gender" varchar(1);', 'ALTER TABLE "schema_evolution_person" ALTER COLUMN "gender" SET NOT NULL;']
1564>
1565> # reset the db
1566> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1567>
1568> # add a column, so it looks like we've recently deleted a field
1569> >>> for sql in backend.get_add_column_sql( 'schema_evolution_person', 'gender_nothere', 'varchar(1)', True, False, False, None ): cursor.execute(sql)
1570> >>> management.get_sql_evolution(app)
1571> ['-- warning: the following may cause data loss', u'ALTER TABLE "schema_evolution_person" DROP COLUMN "gender_nothere";', '-- end warning']
1572>
1573> # reset the db
1574> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1575>
1576> # rename column, so it looks like we've recently renamed a field
1577> >>> for sql in backend.get_change_column_name_sql( 'schema_evolution_person', {}, 'gender2', 'gender_old', 'varchar(1)' ): cursor.execute(sql)
1578> >>> management.get_sql_evolution(app)
1579> ['ALTER TABLE "schema_evolution_person" RENAME COLUMN "gender_old" TO "gender2";']
1580>
1581> # reset the db
1582> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1583>
1584> # rename table, so it looks like we've recently renamed a model
1585> >>> for sql in backend.get_change_table_name_sql( 'schema_evolution_personold', 'schema_evolution_person' ): cursor.execute(sql)
1586> >>> management.get_sql_evolution(app)
1587> ['ALTER TABLE "schema_evolution_personold" RENAME TO "schema_evolution_person";']
1588>
1589> # reset the db
1590> >>> cursor.execute(create_table_sql[0])
1591>
1592> # change column flags, so it looks like we've recently changed a column flag
1593> >>> for sql in backend.get_change_column_def_sql( 'schema_evolution_person', 'name', 'varchar(10)', True, False, False, None ): cursor.execute(sql)
1594> >>> management.get_sql_evolution(app)
1595> ['ALTER TABLE "schema_evolution_person" ADD COLUMN "name_tmp" varchar(20);', 'UPDATE "schema_evolution_person" SET "name_tmp" = "name";', 'ALTER TABLE "schema_evolution_person" DROP COLUMN "name";', 'ALTER TABLE "schema_evolution_person" RENAME COLUMN "name_tmp" TO "name";', 'ALTER TABLE "schema_evolution_person" ALTER COLUMN "name" SET NOT NULL;']
1596>
1597> # reset the db
1598> >>> cursor.execute('DROP TABLE schema_evolution_person;'); cursor.execute(create_table_sql[0])
1599>
1600> # delete a datetime column pair, so it looks like we've recently added a datetime field
1601> >>> for sql in backend.get_drop_column_sql( 'schema_evolution_muebles', 'fecha_publicacion' ): print sql; cursor.execute(sql)
1602> ALTER TABLE "schema_evolution_muebles" DROP COLUMN "fecha_publicacion";
1603> >>> management.get_sql_evolution(app)
1604> ['ALTER TABLE "schema_evolution_muebles" ADD COLUMN "fecha_publicacion" timestamp with time zone;', 'ALTER TABLE "schema_evolution_muebles" ALTER COLUMN "fecha_publicacion" SET NOT NULL;']
1605>
1606> # reset the db
1607> >>> cursor.execute('DROP TABLE schema_evolution_muebles;'); cursor.execute(create_table_sql[1])
1608>
1609> # delete a column with a default value, so it looks like we've recently added a column
1610> >>> for sql in backend.get_drop_column_sql( 'schema_evolution_muebles', 'tipo' ): print sql; cursor.execute(sql)
1611> ALTER TABLE "schema_evolution_muebles" DROP COLUMN "tipo";
1612> >>> management.get_sql_evolution(app)
1613> ['ALTER TABLE "schema_evolution_muebles" ADD COLUMN "tipo" varchar(40);', 'ALTER TABLE "schema_evolution_muebles" ALTER COLUMN "tipo" SET DEFAULT "woot";', 'ALTER TABLE "schema_evolution_muebles" ALTER COLUMN "tipo" SET NOT NULL;']
1614> """
1615>
1616> if settings.DATABASE_ENGINE == 'sqlite3':
1617> __test__['API_TESTS'] += """
1618> # the table as it is supposed to be
1619> >>> create_table_sql = management.get_sql_all(app)
1620>
1621> # make sure we don't evolve an unedited table
1622> >>> management.get_sql_evolution(app)
1623> []
1624>
1625> # delete a column, so it looks like we've recently added a field
1626> >>> cursor.execute( 'DROP TABLE "schema_evolution_person";' ).__class__
1627> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1628> >>> cursor.execute( 'CREATE TABLE "schema_evolution_person" ( "id" integer NOT NULL UNIQUE PRIMARY KEY, "name" varchar(20) NOT NULL, "gender" varchar(1) NOT NULL );' ).__class__
1629> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1630> >>> management.get_sql_evolution(app)
1631> ['ALTER TABLE "schema_evolution_person" ADD COLUMN "gender2" varchar(1) NOT NULL;']
1632>
1633> # reset the db
1634> >>> cursor.execute('DROP TABLE schema_evolution_person;').__class__
1635> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1636> >>> cursor.execute(create_table_sql[0]).__class__
1637> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1638>
1639> # add a column, so it looks like we've recently deleted a field
1640> >>> cursor.execute( 'DROP TABLE "schema_evolution_person";' ).__class__
1641> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1642> >>> cursor.execute( 'CREATE TABLE "schema_evolution_person" ( "id" integer NOT NULL UNIQUE PRIMARY KEY, "name" varchar(20) NOT NULL, "gender" varchar(1) NOT NULL, "gender2" varchar(1) NOT NULL, "gender_new" varchar(1) NOT NULL );' ).__class__
1643> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1644> >>> cursor.execute( 'insert into "schema_evolution_person" values (1,2,3,4,5);' ).__class__
1645> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1646> >>> sql = management.get_sql_evolution(app)
1647> >>> print sql
1648> ['-- warning: the following may cause data loss', u'-- FYI: sqlite does not support deleting columns, so we create a new "gender_new" and delete the old (ie, this could take a while)', 'ALTER TABLE "schema_evolution_person" RENAME TO "schema_evolution_person_1337_TMP";', 'CREATE TABLE "schema_evolution_person" (\\n "id" integer NOT NULL UNIQUE PRIMARY KEY,\\n "name" varchar(20) NOT NULL,\\n "gender" varchar(1) NOT NULL,\\n "gender2" varchar(1) NOT NULL\\n)\\n;', 'INSERT INTO "schema_evolution_person" SELECT "id","name","gender","gender2" FROM "schema_evolution_person_1337_TMP";', 'DROP TABLE "schema_evolution_person_1337_TMP";', '-- end warning']
1649> >>> for s in sql: cursor.execute(s).__class__
1650> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1651> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1652> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1653> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1654> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1655> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1656> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1657> >>> cursor.execute('select * from "schema_evolution_person";').__class__
1658> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1659> >>> cursor.fetchall()[0]
1660> (1, u'2', u'3', u'4')
1661>
1662> # reset the db
1663> >>> cursor.execute('DROP TABLE schema_evolution_person;').__class__
1664> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1665> >>> cursor.execute(create_table_sql[0]).__class__
1666> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1667>
1668> # rename column, so it looks like we've recently renamed a field
1669> >>> cursor.execute('DROP TABLE "schema_evolution_person"').__class__
1670> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1671> >>> cursor.execute('').__class__
1672> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1673> >>> cursor.execute('CREATE TABLE "schema_evolution_person" ("id" integer NOT NULL UNIQUE PRIMARY KEY, "name" varchar(20) NOT NULL, "gender" varchar(1) NOT NULL, "gender_old" varchar(1) NOT NULL );').__class__
1674> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1675> >>> cursor.execute( 'insert into "schema_evolution_person" values (1,2,3,4);' ).__class__
1676> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1677> >>> sql = management.get_sql_evolution(app)
1678> >>> print sql
1679> ['-- FYI: sqlite does not support renaming columns, so we create a new "schema_evolution_person" and delete the old (ie, this could take a while)', 'ALTER TABLE "schema_evolution_person" RENAME TO "schema_evolution_person_1337_TMP";', 'CREATE TABLE "schema_evolution_person" (\\n "id" integer NOT NULL UNIQUE PRIMARY KEY,\\n "name" varchar(20) NOT NULL,\\n "gender" varchar(1) NOT NULL,\\n "gender2" varchar(1) NOT NULL\\n)\\n;', 'INSERT INTO "schema_evolution_person" SELECT "id","name","gender","gender_old" FROM "schema_evolution_person_1337_TMP";', 'DROP TABLE "schema_evolution_person_1337_TMP";']
1680> >>> for s in sql: cursor.execute(s).__class__
1681> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1682> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1683> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1684> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1685> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1686> >>> cursor.execute('select * from "schema_evolution_person";').__class__
1687> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1688> >>> cursor.fetchall()[0]
1689> (1, u'2', u'3', u'4')
1690>
1691> # reset the db
1692> >>> cursor.execute('DROP TABLE schema_evolution_person;').__class__
1693> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1694> >>> cursor.execute(create_table_sql[0]).__class__
1695> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1696>
1697> # rename table, so it looks like we've recently renamed a model
1698> >>> for sql in backend.get_change_table_name_sql( 'schema_evolution_personold', 'schema_evolution_person' ): cursor.execute(sql).__class__
1699> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1700> >>> management.get_sql_evolution(app)
1701> ['ALTER TABLE "schema_evolution_personold" RENAME TO "schema_evolution_person";']
1702>
1703> # reset the db
1704> >>> cursor.execute('DROP TABLE schema_evolution_personold;').__class__
1705> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1706> >>> cursor.execute(create_table_sql[0]).__class__
1707> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1708>
1709> # change column flags, so it looks like we've recently changed a column flag
1710> >>> cursor.execute('DROP TABLE "schema_evolution_person";').__class__
1711> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1712> >>> cursor.execute('CREATE TABLE "schema_evolution_person" ( "id" integer NOT NULL UNIQUE PRIMARY KEY, "name" varchar(20) NOT NULL, "gender" varchar(1) NOT NULL, "gender2" varchar(1) NULL);').__class__
1713> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1714> >>> management.get_sql_evolution(app)
1715> ['-- FYI: sqlite does not support changing columns, so we create a new "schema_evolution_person" and delete the old (ie, this could take a while)', 'ALTER TABLE "schema_evolution_person" RENAME TO "schema_evolution_person_1337_TMP";', 'CREATE TABLE "schema_evolution_person" (\\n "id" integer NOT NULL UNIQUE PRIMARY KEY,\\n "name" varchar(20) NOT NULL,\\n "gender" varchar(1) NOT NULL,\\n "gender2" varchar(1) NOT NULL\\n)\\n;', 'INSERT INTO "schema_evolution_person" SELECT "id","name","gender","gender2" FROM "schema_evolution_person_1337_TMP";', 'DROP TABLE "schema_evolution_person_1337_TMP";']
1716>
1717> # reset the db
1718> >>> cursor.execute('DROP TABLE schema_evolution_person;').__class__
1719> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1720> >>> cursor.execute(create_table_sql[0]).__class__
1721> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1722>
1723> # delete a datetime column pair, so it looks like we've recently added a datetime field
1724> >>> for sql in ['DROP TABLE schema_evolution_muebles;','CREATE TABLE "schema_evolution_muebles" ("id" integer NOT NULL UNIQUE PRIMARY KEY,"tipo" varchar(40) NOT NULL);']: cursor.execute(sql).__class__
1725> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1726> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1727> >>> management.get_sql_evolution(app)
1728> ['ALTER TABLE "schema_evolution_muebles" ADD COLUMN "fecha_publicacion" datetime NOT NULL;']
1729>
1730> # reset the db
1731> >>> cursor.execute('DROP TABLE schema_evolution_muebles;').__class__
1732> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1733> >>> cursor.execute(create_table_sql[1]).__class__
1734> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1735>
1736> # delete a column with a default value, so it looks like we've recently added a column
1737> >>> for sql in ['DROP TABLE schema_evolution_muebles;','CREATE TABLE "schema_evolution_muebles" ("id" integer NOT NULL UNIQUE PRIMARY KEY,"fecha_publicacion" datetime NOT NULL);']: cursor.execute(sql).__class__
1738> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1739> <class 'django.db.backends.sqlite3.base.SQLiteCursorWrapper'>
1740> >>> management.get_sql_evolution(app)
1741> ['ALTER TABLE "schema_evolution_muebles" ADD COLUMN "tipo" varchar(40) NOT NULL DEFAULT "woot";']
1742>
1743> """
1744>
1745
Back to Top