def destroy_test_db(self, old_database_name, verbosity=1): """ Destroy a test database, prompting the user for confirmation if the database already exists. """ self.connection.close() test_database_name = self.connection.settings_dict['NAME'] if verbosity >= 1: test_db_repr = '' if verbosity >= 2: test_db_repr = " ('%s')" % test_database_name print("Destroying test database for alias '%s'%s..." % ( self.connection.alias, test_db_repr)) # Temporarily use a new connection and a copy of the settings dict. # This prevents the production database from being exposed to potential # child threads while (or after) the test database is destroyed. # Refs #10868 and #17786. settings_dict = self.connection.settings_dict.copy() settings_dict['NAME'] = old_database_name backend = load_backend(settings_dict['ENGINE']) new_connection = backend.DatabaseWrapper( settings_dict, alias='__destroy_test_db__', allow_thread_sharing=False) new_connection.creation._destroy_test_db(test_database_name, verbosity)
# We load all these up for backwards compatibility, you should use # connections['default'] instead. class DefaultConnectionProxy(object): """ Proxy for accessing the default DatabaseWrapper object's attributes. If you need to access the DatabaseWrapper object itself, use connections[DEFAULT_DB_ALIAS] instead. """ def __getattr__(self, item): return getattr(connections[DEFAULT_DB_ALIAS], item) def __setattr__(self, name, value): return setattr(connections[DEFAULT_DB_ALIAS], name, value) connection = DefaultConnectionProxy() backend = load_backend(connection.settings_dict['ENGINE']) # Register an event that closes the database connection # when a Django request is finished. def close_connection(**kwargs): for conn in connections.all(): conn.close() signals.request_finished.connect(close_connection) # Register an event that resets connection.queries # when a Django request is started. def reset_queries(**kwargs): for conn in connections.all(): conn.queries = [] signals.request_started.connect(reset_queries)