|
1 from django.core.management.base import AppCommand, CommandError |
|
2 from django.core.management.color import no_style |
|
3 from optparse import make_option |
|
4 |
|
5 class Command(AppCommand): |
|
6 option_list = AppCommand.option_list + ( |
|
7 make_option('--noinput', action='store_false', dest='interactive', default=True, |
|
8 help='Tells Django to NOT prompt the user for input of any kind.'), |
|
9 ) |
|
10 help = "Executes ``sqlreset`` for the given app(s) in the current database." |
|
11 args = '[appname ...]' |
|
12 |
|
13 output_transaction = True |
|
14 |
|
15 def handle_app(self, app, **options): |
|
16 from django.db import connection, transaction |
|
17 from django.conf import settings |
|
18 from django.core.management.sql import sql_reset |
|
19 |
|
20 app_name = app.__name__.split('.')[-2] |
|
21 |
|
22 self.style = no_style() |
|
23 |
|
24 sql_list = sql_reset(app, self.style) |
|
25 |
|
26 if options.get('interactive'): |
|
27 confirm = raw_input(""" |
|
28 You have requested a database reset. |
|
29 This will IRREVERSIBLY DESTROY any data for |
|
30 the "%s" application in the database "%s". |
|
31 Are you sure you want to do this? |
|
32 |
|
33 Type 'yes' to continue, or 'no' to cancel: """ % (app_name, settings.DATABASE_NAME)) |
|
34 else: |
|
35 confirm = 'yes' |
|
36 |
|
37 if confirm == 'yes': |
|
38 try: |
|
39 cursor = connection.cursor() |
|
40 for sql in sql_list: |
|
41 cursor.execute(sql) |
|
42 except Exception, e: |
|
43 transaction.rollback_unless_managed() |
|
44 raise CommandError("""Error: %s couldn't be reset. Possible reasons: |
|
45 * The database isn't running or isn't configured correctly. |
|
46 * At least one of the database tables doesn't exist. |
|
47 * The SQL was invalid. |
|
48 Hint: Look at the output of 'django-admin.py sqlreset %s'. That's the SQL this command wasn't able to run. |
|
49 The full error: %s""" % (app_name, app_name, e)) |
|
50 transaction.commit_unless_managed() |
|
51 else: |
|
52 print "Reset cancelled." |