views:

30

answers:

2

I maintain a Django project with a database that has several model constraints that have fallen out of sync with the actual database. So, for example, some model fields have null=False set, but the database permits NULLs for the corresponding database column.

I'm curious if there is a utility, either in Django or a third-party Python script, that will compare the SHOW CREATE TABLE output (in this case, using MySQL syntax) for each table and compare it with the python manage.py sql output, to highlight the discrepancies.

Granted, in an ideal situation, the database wouldn't fall out of sync with the Django model code in the first place, but since that's where I am, I'm curious if there's a solution to this problem before I write one myself or do the comparison manually.

A: 

./manage.py inspectdb generates the model file corresponding to the models that exist within the database.

You can diff it with your current model files using a standard unix diff or any other fancy diffing tool to find the difference and plan your migration strategy.

While the former seems simpler and better, you can also see the diff at the sql level. ./manage.py sqlall generates the sql for the current db schema and correspondingly show create table table-name shows the sql for the table creation.

You might want to refer http://code.google.com/p/django-evolution/ which once auto migrated the state of the db to the one in the current models. - Note however, that this project is old and seems abandoned.

Lakshman Prasad
Thanks, Lakshman. The diff utility works very well; indeed, that's what I'm using. I was looking for a utility that would run through all models in settings.INSTALLED_APPS and show the sql for each, and then the SHOW CREATE TABLE sql in the DB, yielding two outputs that are similar in structure that could easily be diffed. I know that might not be entirely possible to automate, but I was curious if anyone had solved the problem.
Jim McGaw
Jim, That's why I mentioned you to look at django-evolution.
Lakshman Prasad
Lakshman, I had a look at django-evolution. Looks very useful for database maintenance; thanks for sharing.
Jim McGaw
A: 

I did come up with a quick and dirty means of doing what I described. It's not perfect, but if you run ./manage.py testserver, the test database will be created based on the model code. Then (using MySQL-specific syntax), you can dump the schema for the regular database and the test database to files:

$ mysqldump -uroot -p [database_name] --no-data=true > schema.txt
$ mysqldump -uroot -p [test_database_name] --no-data=true > test_schema.txt

Then you can simply diff schema.txt and test_schema.txt and find the differences.

Jim McGaw