2009-12-22 23:18:51 +08:00
from optparse import make_option
2007-08-16 14:06:55 +08:00
from django . core . management . base import AppCommand , CommandError
from django . core . management . color import no_style
2009-12-22 23:18:51 +08:00
from django . core . management . sql import sql_reset
from django . db import connections , transaction , DEFAULT_DB_ALIAS
2007-08-16 14:06:55 +08:00
class Command ( AppCommand ) :
2007-09-10 05:57:59 +08:00
option_list = AppCommand . option_list + (
make_option ( ' --noinput ' , action = ' store_false ' , dest = ' interactive ' , default = True ,
help = ' Tells Django to NOT prompt the user for input of any kind. ' ) ,
2009-12-22 23:18:51 +08:00
make_option ( ' --database ' , action = ' store ' , dest = ' database ' ,
default = DEFAULT_DB_ALIAS , help = ' Nominates a database to reset. '
' Defaults to the " default " database. ' ) ,
2007-09-10 05:57:59 +08:00
)
2007-08-16 14:06:55 +08:00
help = " Executes ``sqlreset`` for the given app(s) in the current database. "
2007-09-10 05:57:59 +08:00
args = ' [appname ...] '
2007-08-16 14:06:55 +08:00
output_transaction = True
def handle_app ( self , app , * * options ) :
2010-12-13 06:58:25 +08:00
# This command breaks a lot and should be deprecated
import warnings
warnings . warn (
' This command has been deprecated. The command ``flush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually. ' ,
2011-04-02 16:37:53 +08:00
DeprecationWarning
2010-12-13 06:58:25 +08:00
)
2009-12-22 23:18:51 +08:00
using = options . get ( ' database ' , DEFAULT_DB_ALIAS )
connection = connections [ using ]
2007-08-16 14:06:55 +08:00
app_name = app . __name__ . split ( ' . ' ) [ - 2 ]
self . style = no_style ( )
2009-12-22 23:18:51 +08:00
sql_list = sql_reset ( app , self . style , connection )
2007-08-16 14:06:55 +08:00
if options . get ( ' interactive ' ) :
confirm = raw_input ( """
You have requested a database reset .
This will IRREVERSIBLY DESTROY any data for
the " %s " application in the database " %s " .
Are you sure you want to do this ?
2009-12-22 23:18:51 +08:00
Type ' yes ' to continue , or ' no ' to cancel : """ % (app_name, connection.settings_dict[ ' NAME ' ]))
2007-08-16 14:06:55 +08:00
else :
confirm = ' yes '
if confirm == ' yes ' :
try :
cursor = connection . cursor ( )
for sql in sql_list :
cursor . execute ( sql )
except Exception , e :
transaction . rollback_unless_managed ( )
raise CommandError ( """ Error: %s couldn ' t be reset. Possible reasons:
* The database isn ' t running or isn ' t configured correctly .
* At least one of the database tables doesn ' t exist.
* The SQL was invalid .
Hint : Look at the output of ' django-admin.py sqlreset %s ' . That ' s the SQL this command wasn ' t able to run .
The full error : % s """ % (app_name, app_name, e))
transaction . commit_unless_managed ( )
else :
print " Reset cancelled. "