Login

post_migrate handler to load initial SQL after migrating with south

Author:
stingydrone
Posted:
January 6, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

I found that South doesn't execute initial sql file after a migration, like what Django can do after syncdb. So here's the workaround by using post_migrate signal.

Usage: Put your SQL files the same way as you would if you were to use Django to load your initial SQL file (follow Django doc). The only difference is that, the SQL filename needs to in this format: <app_label>.sql OR <app_label>.<backend>.sql This is done this way since the migration is run per app.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def run_initial_sql(sender, **kwargs):
    app_label = kwargs.get('app')
    import os
    from django.db import connection, transaction
    app_dir = os.path.normpath(os.path.join(os.path.dirname(models.get_app(app_label).__file__), 'sql'))
    backend_name = connection.settings_dict['ENGINE'].split('.')[-1]
    sql_files = [os.path.join(app_dir, "%s.%s.sql" % (app_label, backend_name)),
                 os.path.join(app_dir, "%s.sql" % app_label)]
    cursor = connection.cursor()
    for sql_file in sql_files:
        try:
            if os.path.exists(sql_file):
                print "Loading initial SQL data from '%s'" % sql_file
                f = open(sql_file)
                sql = f.read()
                f.close()
                cursor.execute(sql)
        except Exception, e:
            sys.stderr.write("Failed to install custom SQL file '%s': %s\n" % \
                                (sql_file, e))
            import traceback
            traceback.print_exc()
            transaction.rollback_unless_managed()
        else:
            transaction.commit_unless_managed()
post_migrate.connect(run_initial_sql)                                                                   

More like this

  1. Generate and render HTML Table by LLyaudet 5 days, 8 hours ago
  2. My firs Snippets by GutemaG 1 week, 1 day ago
  3. FileField having auto upload_to path by junaidmgithub 1 month, 2 weeks ago
  4. LazyPrimaryKeyRelatedField by LLyaudet 1 month, 3 weeks ago
  5. CacheInDictManager by LLyaudet 1 month, 3 weeks ago

Comments

mmoya (on January 25, 2011):

Hi,

Before south.. i use a lot of sql files in the form sql/modelname.sql

Now, i need tu put only one file with all the sql statements? Thay is, only one file appname.sql whit the content of the old modelname.sql files?

#

Please login first before commenting.