Django

Code

Show
Ignore:
Timestamp:
08/06/07 09:19:27 (1 year ago)
Author:
danderson
Message:

schema-evolution:
added support for custom migration scripts

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/branches/schema-evolution/django/core/management.py

    r5793 r5821  
    483483    return output 
    484484     
     485def get_sql_fingerprint(app): 
     486    "Returns the fingerprint of the current schema, used in schema evolution." 
     487    from django.db import get_creation_module, models, backend, get_introspection_module, connection 
     488    # This should work even if a connecton isn't available 
     489    try: 
     490        cursor = connection.cursor() 
     491    except: 
     492        cursor = None 
     493    introspection = get_introspection_module() 
     494    app_name = app.__name__.split('.')[-2] 
     495    schema_fingerprint = introspection.get_schema_fingerprint(cursor, app) 
     496    try: 
     497        # is this a schema we recognize? 
     498        app_se = __import__(app_name +'.schema_evolution').schema_evolution 
     499        schema_recognized = schema_fingerprint in app_se.fingerprints 
     500        if schema_recognized: 
     501            sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (recognized)\n" % (app_name, schema_fingerprint))) 
     502        else: 
     503            sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (unrecognized)\n" % (app_name, schema_fingerprint))) 
     504    except: 
     505        sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (no schema_evolution module found)\n" % (app_name, schema_fingerprint))) 
     506    return 
     507get_sql_fingerprint.help_doc = "Returns the fingerprint of the current schema, used in schema evolution." 
     508get_sql_fingerprint.args = APP_ARGS 
     509 
    485510def get_sql_evolution(app): 
     511    "Returns SQL to update an existing schema to match the existing models." 
     512    return get_sql_evolution_detailed(app)[2] 
     513 
     514def get_sql_evolution_detailed(app): 
    486515    "Returns SQL to update an existing schema to match the existing models." 
    487516    import schema_evolution 
     
    508537    _check_for_validation_errors() 
    509538 
     539    # This should work even if a connecton isn't available 
     540    try: 
     541        cursor = connection.cursor() 
     542    except: 
     543        cursor = None 
     544 
     545    introspection = get_introspection_module() 
     546    app_name = app.__name__.split('.')[-2] 
     547 
    510548    final_output = [] 
     549 
     550    schema_fingerprint = introspection.get_schema_fingerprint(cursor, app) 
     551    try: 
     552        # is this a schema we recognize? 
     553        app_se = __import__(app_name +'.schema_evolution').schema_evolution 
     554        schema_recognized = schema_fingerprint in app_se.fingerprints 
     555        if schema_recognized: 
     556            sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (recognized)\n" % (app_name, schema_fingerprint))) 
     557            available_upgrades = [] 
     558            for (vfrom, vto), upgrade in app_se.evolutions.iteritems(): 
     559                if vfrom == schema_fingerprint: 
     560                    try: 
     561                        distance = app_se.fingerprints.index(vto)-app_se.fingerprints.index(vfrom) 
     562                        available_upgrades.append( ( vfrom, vto, upgrade, distance ) ) 
     563                        sys.stderr.write(style.NOTICE("\tan upgrade from %s to %s is available (distance: %i)\n" % ( vfrom, vto, distance ))) 
     564                    except: 
     565                        available_upgrades.append( ( vfrom, vto, upgrade, -1 ) ) 
     566                        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 ))) 
     567            if len(available_upgrades): 
     568                best_upgrade = available_upgrades[0] 
     569                for an_upgrade in available_upgrades: 
     570                    if an_upgrade[3] > best_upgrade[3]: 
     571                        best_upgrade = an_upgrade 
     572                final_output.extend( best_upgrade[2] ) 
     573                return schema_fingerprint, False, final_output 
     574        else: 
     575            sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (unrecognized)\n" % (app_name, schema_fingerprint))) 
     576    except: 
     577        # sys.stderr.write(style.NOTICE("Notice: Current schema fingerprint for '%s' is '%s' (no schema_evolution module found)\n" % (app_name, schema_fingerprint))) 
     578        pass # ^^^ lets not be chatty 
    511579 
    512580    # stolen and trimmed from syncdb so that we know which models are about  
     
    526594        created_models.add(model) 
    527595        table_list.append(model._meta.db_table) 
    528  
    529     introspection = get_introspection_module() 
    530     # This should work even if a connecton isn't available 
    531     try: 
    532         cursor = connection.cursor() 
    533     except: 
    534         cursor = None 
    535596 
    536597    # get the existing models, minus the models we've just created 
     
    557618        final_output.extend(output) 
    558619         
    559     return final_output 
     620    return schema_fingerprint, True, final_output 
    560621     
    561622get_sql_evolution.help_doc = "Returns SQL to update an existing schema to match the existing models." 
     
    649710                        cursor.execute(statement) 
    650711 
    651         for sql in get_sql_evolution(app): 
    652             print sql 
    653 #            cursor.execute(sql) 
     712        # keep evolving until there is nothing left to do 
     713        schema_fingerprint, introspected_upgrade, evolution = get_sql_evolution_detailed(app) 
     714        last_schema_fingerprint = None 
     715        while evolution and schema_fingerprint!=last_schema_fingerprint: 
     716            for sql in evolution: 
     717                if introspected_upgrade: 
     718                    print sql 
     719                else:  
     720                    cursor.execute(sql) 
     721            last_schema_fingerprint = schema_fingerprint 
     722            if not introspected_upgrade: # only do one round of introspection generated upgrades 
     723                schema_fingerprint, introspected_upgrade, evolution = get_sql_evolution_detailed(app) 
    654724 
    655725    transaction.commit_unless_managed() 
     
    16031673    'sqlsequencereset': get_sql_sequence_reset, 
    16041674    'sqlevolve': get_sql_evolution, 
     1675    'sqlfingerprint': get_sql_fingerprint, 
    16051676    'startapp': startapp, 
    16061677    'startproject': startproject, 
  • django/branches/schema-evolution/django/db/backends/mysql/introspection.py

    r5735 r5821  
    110110    # print table_name, column_name, dict 
    111111    return dict 
     112 
     113def get_schema_fingerprint(cursor, app): 
     114    """it's important that the output of these methods don't change, otherwise the hashes they 
     115    produce will be inconsistent (and detection of existing schemas will fail.  unless you are  
     116    absolutely sure the outout for ALL valid inputs will remain the same, you should bump the version by creating a new method""" 
     117    return get_schema_fingerprint_fv1(cursor, app) 
     118 
     119def get_schema_fingerprint_fv1(cursor, app): 
     120    from django.db import models 
     121    app_name = app.__name__.split('.')[-2] 
     122 
     123    schema = ['app_name := '+ app_name] 
     124 
     125    cursor.execute('SHOW TABLES;') 
     126    for table_name in [row[0] for row in cursor.fetchall()]: 
     127        if not table_name.startswith(app_name): 
     128            continue    # skip tables not in this app 
     129        schema.append('table_name := '+ table_name) 
     130        cursor.execute("describe %s" % quote_name(table_name)) 
     131        for row in cursor.fetchall(): 
     132            tmp = [] 
     133            for x in row: 
     134                tmp.append(str(x)) 
     135            schema.append( '\t'.join(tmp) ) 
     136        cursor.execute("SHOW INDEX FROM %s" % quote_name(table_name)) 
     137        for row in cursor.fetchall(): 
     138            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]), ]) ) 
     139         
     140    return 'fv1:'+ str('\n'.join(schema).__hash__()) 
     141 
    112142     
    113143DATA_TYPES_REVERSE = { 
  • django/branches/schema-evolution/docs/schema-evolution.txt

    r5781 r5821  
    33== Introduction == 
    44 
    5 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. 
    6  
    7 === Limitations === 
    8  
    9 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: 
    10  
    11  * There is a trade off between ease of use and the scope of coverable problems. 
    12  
    13 Combine that with: 
    14  
    15  * The vast majority of database changes are minor, evolutionary tweaks. (*) 
    16  * Very few people are DBAs. 
    17  
    18 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. 
    19  
    20 (*) By this I mean adding/removing/renaming tables and adding/removing/renaming/changing-attributes-of columns. 
     5Schema 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. 
     6 
     7It'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: 
     8 
     9 1. users who trust introspection and never want to touch/see SQL (Malcolm) 
     10 1. users who mostly trust introspection but want the option of auto-applied upgrades for specific situations (Wash) 
     11 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) 
     12 1. users who hate introspection and just want auto-application of their own scripts (Zoe) 
     13 
     14who wish to perform different combinations of the two basic subtasks of schema evolution: 
     15 
     16 1. generation of SQL via magical introspection 
     17 1. storage and auto-application of upgrade SQL 
     18 
     19This 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. 
    2120 
    2221== Downloading / Installing == 
     
    2524 
    2625{{{ 
    27 svn co http://code.djangoproject.com/svn/django/schema-evolution/ django_se_src 
     26svn co http://code.djangoproject.com/svn/django/branches/schema-evolution/ django_se_src 
    2827ln -s `pwd`/django_se_src/django SITE-PACKAGES-DIR/django 
    2928}}} 
     
    5150}}} 
    5251 
    53 == How To Use == 
    54  
    55 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: 
    56  
    57 {{{ 
    58 ./manage sqlevolve app_name 
     52== How To Use: Malcolm == 
     53 
     54For 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: 
     55 
     56{{{ 
     57$ ./manage sqlevolve app_name 
    5958}}} 
    6059 
     
    8786}}} 
    8887 
    89 For further examples... 
    90  
    91 == Usage Examples == 
    92  
    93 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. 
     88And 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. 
     89 
     90For further examples, scroll down to the Introspection Examples section. 
     91 
     92== How To Use: Wash == 
     93 
     94Note 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. 
     95 
     96All Wash has to do is store a little bit of extra metadata.  Namely two things: 
     97 
     98 1. a fingerprint of the known schema 
     99 1. an sql script 
     100 
     101in the file 'app_name/schema_evolution.py'.  (conveniently next to models.py) 
     102 
     103This module looks as follows: 
     104 
     105{{{ 
     106# list of all known schema fingerprints, in order 
     107fingerprints = [ 
     108    'fv1:1742830097', 
     109    'fv1:907953071', 
     110    # add future fingerprints here 
     111
     112 
     113# all of your evolution scripts, mapping the from_version and to_version  
     114# to a list if sql commands 
     115evolutions = { 
     116    # ('from_fingerprint','to_fingerprint'): ['-- some sql'], 
     117    ('fv1:1742830097','fv1:907953071'): [ 
     118        '-- some list of sql statements, constituting an upgrade', 
     119        '-- some list of sql statements, constituting an upgrade', 
     120    ], 
     121
     122}}} 
     123 
     124To create this file, he would first fingerprint his schema with the following command: 
     125 
     126{{{ 
     127$ ./manage sqlfingerprint app_name 
     128Notice: Current schema fingerprint for 'app_name' is 'fv1:1742830097' (unrecognized) 
     129}}} 
     130 
     131He 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. 
     132 
     133Later, 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) 
     134 
     135'''Note:''' Manually defined upgrade scripts always are prioritized over introspected scripts.  And introspected scripts are never applied recursively. 
     136 
     137This 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. 
     138 
     139== How To Use: Kaylee == 
     140 
     141Kaylee, 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. 
     142 
     143== How To Use: Zoe == 
     144 
     145Zoe 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. 
     146 
     147== Introspection Examples == 
     148 
     149The 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. 
    94150 
    95151=== Adding / Removing Fields === 
     
    368424Correct, 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. 
    369425 
     426''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.'' 
     427 
     428It does not matter how you get from v1 => v3, as long as you get there with minimum theoretical information loss.  The following: 
     429 
     430'''v1 => v2 => v3''' 
     431 1. // v1 t1:{A} 
     432 1. add_field(B); 
     433 1. add_field(C); 
     434 1. del_field(A); 
     435 1. rename_table(t1,t2); 
     436 1. // v2 t2{B,C} 
     437 1. add_field(A); 
     438 1. del_field(C); 
     439 1. // v3 t2:{A,B} 
     440 
     441is functionally equivalent to: 
     442 
     443'''v1 => v3''' 
     444 1. // v1 t1:{A} 
     445 1. add_field(B); 
     446 1. rename_table(t1,t2); 
     447 1. // v3 t2:{A,B} 
     448 
     449And 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. 
     450 
     451A 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. 
     452 
    370453== Future Work == 
    371454 
     
    384467Schema 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. 
    385468 
     469The second biggest missing piece is foreign/m2m key support. 
     470 
     471Lastly, 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. 
     472 
    386473== Conclusion == 
    387474 
    388 That's pretty much it. If you can suggest additional examples or test cases you 
    389 think would be of value, please email me at public@kered.org. 
    390  
     475That'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. 
     476