|
1 from django.core.management.base import NoArgsCommand, CommandError |
|
2 from django.core.management.color import no_style |
|
3 from optparse import make_option |
|
4 |
|
5 class Command(NoArgsCommand): |
|
6 option_list = NoArgsCommand.option_list + ( |
|
7 make_option('--verbosity', action='store', dest='verbosity', default='1', |
|
8 type='choice', choices=['0', '1', '2'], |
|
9 help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'), |
|
10 make_option('--noinput', action='store_false', dest='interactive', default=True, |
|
11 help='Tells Django to NOT prompt the user for input of any kind.'), |
|
12 ) |
|
13 help = "Executes ``sqlflush`` on the current database." |
|
14 |
|
15 def handle_noargs(self, **options): |
|
16 from django.conf import settings |
|
17 from django.db import connection, transaction, models |
|
18 from django.dispatch import dispatcher |
|
19 from django.core.management.sql import sql_flush, emit_post_sync_signal |
|
20 |
|
21 verbosity = int(options.get('verbosity', 1)) |
|
22 interactive = options.get('interactive') |
|
23 |
|
24 self.style = no_style() |
|
25 |
|
26 # Import the 'management' module within each installed app, to register |
|
27 # dispatcher events. |
|
28 for app_name in settings.INSTALLED_APPS: |
|
29 try: |
|
30 __import__(app_name + '.management', {}, {}, ['']) |
|
31 except ImportError: |
|
32 pass |
|
33 |
|
34 sql_list = sql_flush(self.style, only_django=True) |
|
35 |
|
36 if interactive: |
|
37 confirm = raw_input("""You have requested a flush of the database. |
|
38 This will IRREVERSIBLY DESTROY all data currently in the %r database, |
|
39 and return each table to the state it was in after syncdb. |
|
40 Are you sure you want to do this? |
|
41 |
|
42 Type 'yes' to continue, or 'no' to cancel: """ % settings.DATABASE_NAME) |
|
43 else: |
|
44 confirm = 'yes' |
|
45 |
|
46 if confirm == 'yes': |
|
47 try: |
|
48 cursor = connection.cursor() |
|
49 for sql in sql_list: |
|
50 cursor.execute(sql) |
|
51 except Exception, e: |
|
52 transaction.rollback_unless_managed() |
|
53 raise CommandError("""Database %s couldn't be flushed. Possible reasons: |
|
54 * The database isn't running or isn't configured correctly. |
|
55 * At least one of the expected database tables doesn't exist. |
|
56 * The SQL was invalid. |
|
57 Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run. |
|
58 The full error: %s""" % (settings.DATABASE_NAME, e)) |
|
59 transaction.commit_unless_managed() |
|
60 |
|
61 # Emit the post sync signal. This allows individual |
|
62 # applications to respond as if the database had been |
|
63 # sync'd from scratch. |
|
64 emit_post_sync_signal(models.get_models(), verbosity, interactive) |
|
65 |
|
66 # Reinstall the initial_data fixture. |
|
67 from django.core.management import call_command |
|
68 call_command('loaddata', 'initial_data', **options) |
|
69 |
|
70 else: |
|
71 print "Flush cancelled." |