Login

post_migrate handler to load initial SQL after migrating with south

Author:
stingydrone
Posted:
January 6, 2011
Language:
Python
Version:
1.2
Tags:
custom-sql south initial-data post_migrate
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. Loading initial data per model at table creation (useful with migrations) by GigiusB 10 months, 2 weeks ago
  2. Proper fixtures loading in south data migrations by JustDelight 2 years, 2 months ago
  3. South unran migration check by rednaw 1 year, 10 months ago
  4. Load customized SQL by roppert 6 years, 2 months ago
  5. immitating 'real' post_syncdb signal by jango 5 years, 1 month 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.