Esempio n. 1
0
    def handle_noargs(self, **options):
        db = options.get('database')
        connection = connections[db]
        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_migrate = options.get('inhibit_post_migrate', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to a fresh state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.commit_on_success_unless_managed():
                    cursor = connection.cursor()
                    for sql in sql_list:
                        cursor.execute(sql)
            except Exception as e:
                new_msg = (
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.\n"
                    "The full error: %s") % (connection.settings_dict['NAME'], e)
                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])

            if not inhibit_post_migrate:
                self.emit_post_migrate(verbosity, interactive, db)

            # Reinstall the initial_data fixture.
            if options.get('load_initial_data'):
                # Reinstall the initial_data fixture.
                call_command('loaddata', 'initial_data', **options)

        else:
            self.stdout.write("Flush cancelled.\n")
Esempio n. 2
0
    def handle(self, **options):
        database = options['database']
        connection = connections[database]
        verbosity = options['verbosity']
        interactive = options['interactive']
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_migrate = options.get('inhibit_post_migrate', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            with suppress(ImportError):
                import_module('.management', app_config.name)

        sql_list = sql_flush(self.style,
                             connection,
                             only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ %
                            connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.atomic(
                        using=database,
                        savepoint=connection.features.can_rollback_ddl):
                    with connection.cursor() as cursor:
                        for sql in sql_list:
                            cursor.execute(sql)
            except Exception as exc:
                raise CommandError(
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin sqlflush'. "
                    "That's the SQL this command wasn't able to run.\n" %
                    (connection.settings_dict['NAME'], )) from exc

            # Empty sql_list may signify an empty database and post_migrate would then crash
            if sql_list and not inhibit_post_migrate:
                # Emit the post migrate signal. This allows individual applications to
                # respond as if the database had been migrated from scratch.
                emit_post_migrate_signal(verbosity, interactive, database)
        else:
            self.stdout.write("Flush cancelled.\n")
    def flush_all_tables(self):
        """
        全テーブル内容を削除する。
        ToDo: そもそもDjangoに備わっているJSON形式のレストアバッチコマンドを流用してもよい。
        """
        #flush_cmd = flush.Command()
        #flush_cmd.execute()
        connection = connections[self._db]
        style = no_style()
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError:
                pass
        sql_list = sql_flush(style, connection, only_django=True)
        confirm = True
        if (confirm):
            try:
                cursor = connection.cursor()
                print "[Start Deleting]..."
                for sql in sql_list:
                    print "%s... " % sql,
                    cursor.execute(sql)
                    print "Done."
                print "[Done] delete tables completely!"
            except Exception, e:
                transaction.rollback_unless_managed(using=self._db)
                raise CommandError(
                    """Database %s couldn't be flushed. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: %s""" % (connection.settings_dict['NAME'], e))
            transaction.commit_unless_managed(using=self._db)
    def flush_all_tables(self):
        """
        全テーブル内容を削除する。
        ToDo: そもそもDjangoに備わっているJSON形式のレストアバッチコマンドを流用してもよい。
        """
        #flush_cmd = flush.Command()
        #flush_cmd.execute()
        connection = connections[self._db]
        style = no_style()
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError:
                pass
        sql_list = sql_flush(style, connection, only_django=True)
        confirm = True
        if ( confirm ):
            try:
                cursor = connection.cursor()
                print "[Start Deleting]..."
                for sql in sql_list:
                    print "%s... " % sql,
                    cursor.execute(sql)
                    print "Done."
                print "[Done] delete tables completely!"
            except Exception, e:
                transaction.rollback_unless_managed(using=self._db)
                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: %s""" % (connection.settings_dict['NAME'], e))
            transaction.commit_unless_managed(using=self._db)
Esempio n. 5
0
    def handle_noargs(self, **options):
        db = options.get('database')
        connection = connections[db]
        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')

        self.style = no_style()

        sql_list = sql_flush(self.style, connection, only_django=True)

        if interactive:
            confirm = raw_input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        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(using=db)
                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: %s""" % (connection.settings_dict['NAME'], e))
            transaction.commit_unless_managed(using=db)
Esempio n. 6
0
    def handle(self, **options):
        database = options['database']
        connection = connections[database]
        verbosity = options['verbosity']
        interactive = options['interactive']
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_migrate = options.get('inhibit_post_migrate', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            try:
                import_module('.management', app_config.name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.atomic(using=database,
                                        savepoint=connection.features.can_rollback_ddl):
                    with connection.cursor() as cursor:
                        for sql in sql_list:
                            cursor.execute(sql)
            except Exception as exc:
                raise CommandError(
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin sqlflush'. "
                    "That's the SQL this command wasn't able to run.\n" % (
                        connection.settings_dict['NAME'],
                    )
                ) from exc

            # Empty sql_list may signify an empty database and post_migrate would then crash
            if sql_list and not inhibit_post_migrate:
                # Emit the post migrate signal. This allows individual applications to
                # respond as if the database had been migrated from scratch.
                emit_post_migrate_signal(verbosity, interactive, database)
        else:
            self.stdout.write("Flush cancelled.\n")
Esempio n. 7
0
    def handle_noargs(self, **options):
        db = options.get('database')
        connection = connections[db]
        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_migrate = options.get('inhibit_post_migrate', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            try:
                import_module('.management', app_config.name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to a fresh state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.commit_on_success_unless_managed():
                    with connection.cursor() as cursor:
                        for sql in sql_list:
                            cursor.execute(sql)
            except Exception as e:
                new_msg = (
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.\n"
                    "The full error: %s") % (connection.settings_dict['NAME'], e)
                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])

            if not inhibit_post_migrate:
                self.emit_post_migrate(verbosity, interactive, db)

            # Reinstall the initial_data fixture.
            if options.get('load_initial_data'):
                # Reinstall the initial_data fixture.
                call_command('loaddata', 'initial_data', **options)

        else:
            self.stdout.write("Flush cancelled.\n")
Esempio n. 8
0
 def handle(self, **options):
     sql_statements = sql_flush(self.style,
                                connections[options["database"]],
                                only_django=True)
     if not sql_statements and options["verbosity"] >= 1:
         self.stderr.write("No tables found.")
     return "\n".join(sql_statements)
Esempio n. 9
0
 def handle(self, **options):
     sql_statements = sql_flush(self.style,
                                connections[options['database']],
                                only_django=True)
     if not sql_statements and options['verbosity'] >= 1:
         self.stderr.write('No tables found.')
     return '\n'.join(sql_statements)
Esempio n. 10
0
    def handle_noargs(self, **options):
        db = options.get('database', DEFAULT_DB_ALIAS)
        connection = connections[db]
        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True)

        if interactive:
            confirm = raw_input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        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(using=db)
                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: %s""" % (connection.settings_dict['NAME'], e))
            transaction.commit_unless_managed(using=db)

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            all_models = []
            for app in models.get_apps():
                all_models.extend([
                    m for m in models.get_models(app, include_auto_created=True)
                    if router.allow_syncdb(db, m)
                ])
            emit_post_sync_signal(set(all_models), verbosity, interactive, db)

            # Reinstall the initial_data fixture.
            kwargs = options.copy()
            kwargs['database'] = db
            call_command('loaddata', 'initial_data', **kwargs)
Esempio n. 11
0
    def handle_noargs(self, **options):
        from django.conf import settings
        from django.db import connection, transaction, models
        from django.dispatch import dispatcher
        from django.core.management.sql import sql_flush, emit_post_sync_signal

        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                __import__(app_name + '.management', {}, {}, [''])
            except ImportError:
                pass

        sql_list = sql_flush(self.style, only_django=True)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % settings.DATABASE_NAME)
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                cursor = connection.cursor()
                for sql in sql_list:
                    cursor.execute(sql)
            except Exception as e:
                transaction.rollback_unless_managed()
                raise CommandError(
                    """Database %s couldn't be flushed. Possible reasons:
      * The database isn't running or isn't configured correctly.
      * At least one of the expected database tables doesn't exist.
      * The SQL was invalid.
    Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
    The full error: %s""" % (settings.DATABASE_NAME, e))
            transaction.commit_unless_managed()

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            emit_post_sync_signal(models.get_models(), verbosity, interactive)

            # Reinstall the initial_data fixture.
            from django.core.management import call_command
            call_command('loaddata', 'initial_data', **options)

        else:
            print("Flush cancelled.")
Esempio n. 12
0
    def handle_noargs(self, **options):
        db = options.get('database', DEFAULT_DB_ALIAS)
        connection = connections[db]
        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True)

        if interactive:
            confirm = raw_input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        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(using=db)
                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: %s""" % (connection.settings_dict['NAME'], e))
            transaction.commit_unless_managed(using=db)

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            all_models = []
            for app in models.get_apps():
                all_models.extend([
                    m for m in models.get_models(app, include_auto_created=True)
                    if router.allow_syncdb(db, m)
                ])
            emit_post_sync_signal(set(all_models), verbosity, interactive, db)

            # Reinstall the initial_data fixture.
            kwargs = options.copy()
            kwargs['database'] = db
            call_command('loaddata', 'initial_data', **kwargs)
Esempio n. 13
0
    def handle_noargs(self, **options):
        from django.conf import settings
        from django.db import connection, transaction, models
        from django.core.management.sql import sql_flush, emit_post_sync_signal

        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive')

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                __import__(app_name + '.management', {}, {}, [''])
            except ImportError:
                pass

        sql_list = sql_flush(self.style, only_django=True)

        if interactive:
            confirm = raw_input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % settings.DATABASE_NAME)
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                cursor = connection.cursor()
                for sql in sql_list:
                    try:
                        cursor.execute(sql)
                    except Exception, e:
                        #print "error! %s %s" % (sql,e)
                        pass
            except Exception, e:
                transaction.rollback_unless_managed()
                raise CommandError("""Database %s couldn't be flushed. Possible reasons:
      * The database isn't running or isn't configured correctly.
      * At least one of the expected database tables doesn't exist.
      * The SQL was invalid.
    Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
    The full error: %s""" % (settings.DATABASE_NAME, e))
            transaction.commit_unless_managed()

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            emit_post_sync_signal(models.get_models(), verbosity, interactive)

            # Reinstall the initial_data fixture.
            from django.core.management import call_command
            call_command('loaddata', 'initial_data', **options)
Esempio n. 14
0
    def handle_noargs(self, **options):
        print(_(u"Resetting database %(database)s...") % {'database': settings.DATABASE_NAME})
        queries = sql_flush(no_style(), only_django=False)
        cursor = connection.cursor()

        for query in queries:
            cursor.execute(query)

        transaction.commit_unless_managed()
        print(_(u"done"))
Esempio n. 15
0
File: utils.py Progetto: 42/tddspry
def flush():
    from django.core.management.sql import sql_flush
    from django.db import connection, models, transaction

    sql_list = sql_flush(no_style(), only_django=True)

    try:
        cursor = connection.cursor()

        for sql in sql_list:
            cursor.execute(sql)
    except Exception, e:
        transaction.rollback_unless_managed()
        raise CommandError(ERROR_MESSAGE % (settings.DATABASE_NAME, e))
    def test_sql_flush_works(self):

        mock_style = Mock()
        ExampleModel.objects.create(id='1', created_at=datetime.now(),
                                    deleted=False)
        ExampleModel2.objects.create(id='3')

        self.assertEqual(ExampleModel.objects.count(), 1)
        self.assertEqual(ExampleModel2.objects.count(), 1)

        statements = sql_flush(mock_style, self.connection)
        self.assertEqual(statements, [])
        self.assertEqual(ExampleModel.objects.count(), 0)
        self.assertEqual(ExampleModel2.objects.count(), 0)
Esempio n. 17
0
    def run(self, **options):

        database = options.get("database", DEFAULT_DB_ALIAS)
        connection = connections[database]
        verbosity = options["verbosity"]
        interactive = False
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get("reset_sequences", True)
        allow_cascade = options.get("allow_cascade", False)
        inhibit_post_migrate = options.get("inhibit_post_migrate", False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            try:
                import_module(".management", app_config.name)
            except ImportError:
                pass

        sql_list = sql_flush(
            self.style,
            connection,
            only_django=True,
            reset_sequences=reset_sequences,
            allow_cascade=allow_cascade,
        )

        print("Flushing database!")
        connection.ops.execute_sql_flush(database, sql_list)
        if sql_list and not inhibit_post_migrate:
            # Emit the post migrate signal. This allows individual applications to
            # respond as if the database had been migrated from scratch.
            emit_post_migrate_signal(verbosity, interactive, database)

        corpora_file = os.path.abspath(settings.CORPORA_FILE)

        print(f"Done. Loading from {corpora_file}")

        # see https://code.djangoproject.com/ticket/8085
        if os.environ.get("RUN_MAIN", False):
            load_explorer_app()
            for corpus in Corpus.objects.all():
                if corpus.pdfs and not corpus.disabled:
                    os.environ["TESSDATA_PREFIX"] = settings.TESSDATA_PREFIX
                    load_tif_pdf_plaintext(corpus)
Esempio n. 18
0
def setUp(doctest):
    sql_list = sql_flush(no_style(), only_django=True)
    # Drop the current db
    cursor = connection.cursor()
    cursor.execute('SHOW statement_timeout')
    statement_timeout = cursor.fetchone()
    cursor.execute('SET statement_timeout TO 0')
    try:
        for sql in sql_list:
            # Tweak the sql so that tables can be dropped
            if sql.startswith('TRUNCATE '):
                sql = sql.strip(';') + ' CASCADE;'
                cursor.execute(sql)
                transaction.commit_unless_managed()
    finally:
        cursor.execute("SET statement_timeout TO '%s'" % statement_timeout)
    # Set up the test fixtures
    management.call_command('loaddata', 'test.json', verbosity=0)
Esempio n. 19
0
 def handle_noargs(self, **options):
     from django.core.management.sql import sql_flush
     return u'\n'.join(sql_flush(self.style, only_django=True)).encode('utf-8')
Esempio n. 20
0
 def flush(self, style, only_django=False):
     from django.core.management.sql import sql_flush
     sql_list = sql_flush(style, self.connection, only_django=True)
     cursor = self.connection.cursor()
     for sql in sql_list:
         cursor.execute(sql)
Esempio n. 21
0
 def handle(self, **options):
     return "\n".join(sql_flush(self.style, connections[options["database"]], only_django=True))
 def handle_noargs(self, **options):
     return u'\n'.join(
         sql_flush(self.style,
                   connections[options.get('database', DEFAULT_DB_ALIAS)],
                   only_django=True)).encode('utf-8')
Esempio n. 23
0
 def handle(self, **options):
     return '\n'.join(
         sql_flush(self.style,
                   connections[options['database']],
                   only_django=True))
Esempio n. 24
0
    def handle_noargs(self, **options):
        db = options.get('database')
        connection = connections[db]
        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        # 'reset_sequences' and 'allow_cascade' are stealth options
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module('.management', app_name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.commit_on_success_unless_managed():
                    cursor = connection.cursor()
                    for sql in sql_list:
                        cursor.execute(sql)
            except Exception as e:
                new_msg = (
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.\n"
                    "The full error: %s") % (connection.settings_dict['NAME'], e)
                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])
            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            all_models = []
            for app in models.get_apps():
                all_models.extend([
                    m for m in models.get_models(app, include_auto_created=True)
                    if router.allow_syncdb(db, m)
                ])
            emit_post_sync_signal(set(all_models), verbosity, interactive, db)

            # Reinstall the initial_data fixture.
            if options.get('load_initial_data'):
                # Reinstall the initial_data fixture.
                call_command('loaddata', 'initial_data', **options)

        else:
            self.stdout.write("Flush cancelled.\n")
Esempio n. 25
0
    def handle_noargs(self, **options):
        db = options.get("database")
        connection = connections[db]
        verbosity = int(options.get("verbosity"))
        interactive = options.get("interactive")
        # 'reset_sequences' is a stealth option
        reset_sequences = options.get("reset_sequences", True)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_name in settings.INSTALLED_APPS:
            try:
                import_module(".management", app_name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True, reset_sequences=reset_sequences)

        if interactive:
            confirm = input(
                """You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to the state it was in after syncdb.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """
                % connection.settings_dict["NAME"]
            )
        else:
            confirm = "yes"

        if confirm == "yes":
            try:
                with transaction.commit_on_success_unless_managed():
                    cursor = connection.cursor()
                    for sql in sql_list:
                        cursor.execute(sql)
            except Exception as e:
                raise CommandError(
                    """Database %s couldn't be flushed. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the expected database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.
The full error: %s"""
                    % (connection.settings_dict["NAME"], e)
                )

            # Emit the post sync signal. This allows individual
            # applications to respond as if the database had been
            # sync'd from scratch.
            all_models = []
            for app in models.get_apps():
                all_models.extend(
                    [m for m in models.get_models(app, include_auto_created=True) if router.allow_syncdb(db, m)]
                )
            emit_post_sync_signal(set(all_models), verbosity, interactive, db)

            # Reinstall the initial_data fixture.
            if options.get("load_initial_data"):
                # Reinstall the initial_data fixture.
                call_command("loaddata", "initial_data", **options)

        else:
            self.stdout.write("Flush cancelled.\n")
Esempio n. 26
0
    def handle(self, *args, **options):

        #~ from lino.core.kernel import analyze_models
        #~ analyze_models()

        #~ from lino.utils import dblogger

        #~ if not dblogger.logger.isEnabledFor(logging.INFO):
            #~ raise CommandError("System logger must be enabled for INFO")
        #~ dblogger.info(settings.SITE.welcome_text())
        #~ dblogger.info("FIXTURE_DIRS is %s",settings.FIXTURE_DIRS)
        using = options.get('database', DEFAULT_DB_ALIAS)
        dbname = settings.DATABASES[using]['NAME']
        if options.get('interactive'):
            if not confirm("""We are going to flush your database (%s).
Are you sure (y/n) ?""" % dbname):
                raise CommandError("User abort.")

        options.update(interactive=False)
        #~ dblogger.info("Lino initdb %s started on database %s.", args, dbname)

        if USE_DROP_CREATE:

            from django.db import connection
            cursor = connection.cursor()
            #~ cursor.execute("DROP DATABASE %s;", [connection.settings_dict['NAME']])
            #~ cursor.execute("CREATE DATABASE %s;", [connection.settings_dict['NAME']])
            cursor.execute("DROP DATABASE %s;" % dbname)
            cursor.execute("CREATE DATABASE %s;" % dbname)

        else:

            sql_list = []
            conn = connections[using]

            if AFTER17:
                # from django.apps import apps
                # print 20140913, apps
                # app_list = apps.get_app_configs()
                sql = sql_flush(no_style(), conn, only_django=False)
                sql_list.extend(sql)

            elif USE_SQLDELETE:
                #~ sql_list = u'\n'.join(sql_reset(app, no_style(), conn)).encode('utf-8')
                app_list = [models.get_app(app_label)
                            for app_label in app_labels()]
                for app in app_list:
                    # app_label = app.__name__.split('.')[-2]
                    sql_list.extend(sql_delete(app, no_style(), conn))
                    # print app_label, ':', sql_list
            else:
                #~ call_command('flush',verbosity=0,interactive=False)
                #~ call_command('flush',**options)
                sql_list.extend(sql_flush(no_style(), conn, only_django=False))

            #~ print sql_list

            try:
                cursor = conn.cursor()
                for sql in sql_list:
                    # print sql
                    cursor.execute(sql)
            except Exception:
                transaction.rollback_unless_managed(using=using)
                raise

            transaction.commit_unless_managed()

        #~ call_command('reset',*apps,**options)
        #~ call_command('syncdb',load_initial_data=False,**options)
        #~ if USE_SQLDELETE:

        #~ tried to call `syncdb` with `verbosity=0` to avoid the
        #~ irritating message "No fixtures found" (which comes because there
        #~ are no `initial_data` fixtures):
        #~ syncdb_options = dict(**options)
        #~ syncdb_options.update(verbosity=0)
        #~ call_command('syncdb',**syncdb_options)
        #~ not good because all other messages "Creating table..." also disappear.

        #~ """
        #~ When loading a full dump back into the database,
        #~ initdb must disable the post_syncdb signal emitted by syncdb
        #~ which would cause automatisms like
        #~ `django.contrib.auth.management.create_permissions`
        #~ `django.contrib.auth.management.create_superuser`
        #~ `django.contrib.sites.management.create_default_site`
        #~ """
        #~ if options.get('dumped'):
            #~ class NullSignal:
                #~ def connect(*args,**kw):
                    #~ pass
                #~ def send(*args,**kw):
                    #~ pass
            #~ models.signals.post_syncdb = NullSignal()

        settings.SITE._site_config = None  # clear cached instance

        call_command('syncdb', load_initial_data=False, **options)

        if len(args):
            call_command('loaddata', *args, **options)
Esempio n. 27
0
    def handle(self, **options):
        database = options["database"]
        connection = connections[database]
        verbosity = options["verbosity"]
        interactive = options["interactive"]
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get("reset_sequences", True)
        allow_cascade = options.get("allow_cascade", False)
        inhibit_post_migrate = options.get("inhibit_post_migrate", False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            try:
                import_module(".management", app_config.name)
            except ImportError:
                pass

        sql_list = sql_flush(
            self.style,
            connection,
            only_django=True,
            reset_sequences=reset_sequences,
            allow_cascade=allow_cascade,
        )

        if interactive:
            confirm = input(
                """You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the "%s" database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """
                % connection.settings_dict["NAME"]
            )
        else:
            confirm = "yes"

        if confirm == "yes":
            try:
                connection.ops.execute_sql_flush(sql_list)
            except Exception as exc:
                raise CommandError(
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin sqlflush'. "
                    "That's the SQL this command wasn't able to run."
                    % (connection.settings_dict["NAME"],)
                ) from exc

            # Empty sql_list may signify an empty database and post_migrate would then crash
            if sql_list and not inhibit_post_migrate:
                # Emit the post migrate signal. This allows individual applications to
                # respond as if the database had been migrated from scratch.
                emit_post_migrate_signal(verbosity, interactive, database)
        else:
            self.stdout.write("Flush cancelled.")
 def handle_noargs(self, **options):
     return '\n'.join(sql_flush(self.style, connections[options.get('database')], only_django=True))
Esempio n. 29
0
    def handle(self, **options):
        database = options.get('database')
        connection = connections[database]
        verbosity = options.get('verbosity')
        interactive = options.get('interactive')
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_migrate = options.get('inhibit_post_migrate', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            try:
                import_module('.management', app_config.name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.atomic(using=database,
                                        savepoint=connection.features.can_rollback_ddl):
                    with connection.cursor() as cursor:
                        for sql in sql_list:
                            cursor.execute(sql)
            except Exception as e:
                new_msg = (
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin sqlflush'. "
                    "That's the SQL this command wasn't able to run.\n"
                    "The full error: %s") % (connection.settings_dict['NAME'], e)
                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])

            if not inhibit_post_migrate:
                self.emit_post_migrate(verbosity, interactive, database)

            # Reinstall the initial_data fixture.
            if options.get('load_initial_data'):
                # Reinstall the initial_data fixture for apps without migrations.
                from django.db.migrations.executor import MigrationExecutor
                executor = MigrationExecutor(connection)
                app_options = options.copy()
                for app_label in executor.loader.unmigrated_apps:
                    app_options['app_label'] = app_label
                    call_command('loaddata', 'initial_data', **app_options)
        else:
            self.stdout.write("Flush cancelled.\n")
Esempio n. 30
0
 def handle_noargs(self, **options):
     return u"\n".join(
         sql_flush(self.style, connections[options.get("database", DEFAULT_DB_ALIAS)], only_django=True)
     ).encode("utf-8")
Esempio n. 31
0
def fast_flush():
    """ All the flushing power, none of the mess. """
    connection = connections[DEFAULT_DB_ALIAS]
    sql_flush(no_style(), connection, only_django=True)
Esempio n. 32
0
 def handle(self, **options):
     return "\n".join(
         sql_flush(self.style,
                   connections[options["database"]],
                   only_django=True))
Esempio n. 33
0
def flush(connection) -> None:
    sql_list = sql_flush(no_style(),
                         connection,
                         reset_sequences=True,
                         allow_cascade=False)
    connection.ops.execute_sql_flush(DEFAULT_DB_ALIAS, sql_list)
Esempio n. 34
0
	def handle_noargs(self, **options):
		return u'\n'.join(sql_flush(self.style, connections[options.get('database', DEFAULT_DB_ALIAS)], only_django=True)).encode('utf-8')
Esempio n. 35
0
 def handle(self, **options):
     return '\n'.join(sql_flush(self.style, connections[options['database']], only_django=True))
Esempio n. 36
0
from __future__ import unicode_literals
 def handle_noargs(self, **options):
     from django.core.management.sql import sql_flush
     return '\n'.join(sql_flush(self.style,
                                only_django=True)).encode('utf-8')
Esempio n. 38
0
 def handle_noargs(self, **options):
     return '\n'.join(
         sql_flush(self.style,
                   connections[options.get('database')],
                   only_django=True))