Skip to content

Instantly share code, notes, and snippets.

@mlavin
Created November 14, 2011 16:12
Show Gist options
  • Save mlavin/1364315 to your computer and use it in GitHub Desktop.
Save mlavin/1364315 to your computer and use it in GitHub Desktop.
Install DB views
import os
import sys
from django.conf import settings
from django.db import connections, models, transaction, DEFAULT_DB_ALIAS
from django.db.models.signals import post_syncdb
from django.dispatch import receiver
from south.signals import post_migrate
@receiver(post_syncdb)
@receiver(post_migrate)
def install_view_sql(sender, *args, **kwargs):
"""Generic signal handler for installing view sql."""
# post_syncdb and post_migrate both use the app keyword but
# post_syncdb returns the app module and
# post_migrate a string of the app name
db = DEFAULT_DB_ALIAS
connection = connections[db]
cursor = connection.cursor()
app = kwargs.pop('app')
if not hasattr(app, '__file__'):
app = models.get_app(app)
app_dir = os.path.dirname(app.__file__)
sql_dir = os.path.normpath(os.path.join(app_dir, 'sql', 'views'))
if os.path.exists(sql_dir):
for view_sql in os.listdir(sql_dir):
with open(os.path.join(sql_dir, view_sql), 'U') as f:
sql = f.read().decode(settings.FILE_CHARSET)
try:
cursor.execute(sql)
except Exception as e:
sys.stderr.write("Failed to install view SQL %s: %s\n" % (view_sql, e))
transaction.rollback_unless_managed(using=db)
else:
transaction.commit_unless_managed(using=db)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment