示例#1
0
 def runner():
     from djmodels.db import connections
     for conn in connections.all():
         # Allow thread sharing so the connection can be closed by the
         # main thread.
         conn.allow_thread_sharing = True
         connections_dict[id(conn)] = conn
示例#2
0
文件: apps.py 项目: iMerica/dj-models
 def ready(self):
     # Connections may already exist before we are called.
     for conn in connections.all():
         if conn.vendor == 'postgresql':
             conn.introspection.data_types_reverse.update({
                 3802:
                 'djmodels.contrib.postgres.fields.JSONField',
                 3904:
                 'djmodels.contrib.postgres.fields.IntegerRangeField',
                 3906:
                 'djmodels.contrib.postgres.fields.FloatRangeField',
                 3910:
                 'djmodels.contrib.postgres.fields.DateTimeRangeField',
                 3912:
                 'djmodels.contrib.postgres.fields.DateRangeField',
                 3926:
                 'djmodels.contrib.postgres.fields.BigIntegerRangeField',
             })
             if conn.connection is not None:
                 register_type_handlers(conn)
     connection_created.connect(register_type_handlers)
     CharField.register_lookup(Unaccent)
     TextField.register_lookup(Unaccent)
     CharField.register_lookup(SearchLookup)
     TextField.register_lookup(SearchLookup)
     CharField.register_lookup(TrigramSimilar)
     TextField.register_lookup(TrigramSimilar)
示例#3
0
    def test_connections_thread_local(self):
        """
        The connections are different for each thread (#17258).
        """
        # Map connections by id because connections with identical aliases
        # have the same hash.
        connections_dict = {}
        for conn in connections.all():
            connections_dict[id(conn)] = conn

        def runner():
            from djmodels.db import connections
            for conn in connections.all():
                # Allow thread sharing so the connection can be closed by the
                # main thread.
                conn.allow_thread_sharing = True
                connections_dict[id(conn)] = conn
        for x in range(2):
            t = threading.Thread(target=runner)
            t.start()
            t.join()
        self.assertEqual(len(connections_dict), 6)
        # Finish by closing the connections opened by the other threads (the
        # connection opened in the main thread will automatically be closed on
        # teardown).
        for conn in connections_dict.values():
            if conn is not connection:
                conn.close()
示例#4
0
 def _post_teardown(self):
     """
     Perform post-test things:
     * Flush the contents of the database to leave a clean slate. If the
       class has an 'available_apps' attribute, don't fire post_migrate.
     * Force-close the connection so the next test gets a clean cursor.
     """
     try:
         self._fixture_teardown()
         super()._post_teardown()
         if self._should_reload_connections():
             # Some DB cursors include SQL statements as part of cursor
             # creation. If you have a test that does a rollback, the effect
             # of these statements is lost, which can affect the operation of
             # tests (e.g., losing a timezone setting causing objects to be
             # created with the wrong time). To make sure this doesn't
             # happen, get a clean connection at the start of every test.
             for conn in connections.all():
                 conn.close()
     finally:
         if self.available_apps is not None:
             apps.unset_available_apps()
             setting_changed.send(sender=settings._wrapped.__class__,
                                  setting='INSTALLED_APPS',
                                  value=settings.INSTALLED_APPS,
                                  enter=False)
示例#5
0
def update_connections_time_zone(**kwargs):
    if kwargs['setting'] == 'TIME_ZONE':
        # Reset process time zone
        if hasattr(time, 'tzset'):
            if kwargs['value']:
                os.environ['TZ'] = kwargs['value']
            else:
                os.environ.pop('TZ', None)
            time.tzset()

        # Reset local time zone cache
        timezone.get_default_timezone.cache_clear()

    # Reset the database connections' time zone
    if kwargs['setting'] in {'TIME_ZONE', 'USE_TZ'}:
        for conn in connections.all():
            try:
                del conn.timezone
            except AttributeError:
                pass
            try:
                del conn.timezone_name
            except AttributeError:
                pass
            conn.ensure_timezone()
示例#6
0
def actual_test_processes(parallel):
    if parallel == 0:
        # This doesn't work before djmodels.setup() on some databases.
        if all(conn.features.can_clone_databases
               for conn in connections.all()):
            return default_test_processes()
        else:
            return 1
    else:
        return parallel
示例#7
0
 def _nodb_connection(self):
     nodb_connection = super()._nodb_connection
     try:
         nodb_connection.ensure_connection()
     except (Database.DatabaseError, WrappedDatabaseError):
         warnings.warn(
             "Normally Django will use a connection to the 'postgres' database "
             "to avoid running initialization queries against the production "
             "database when it's not needed (for example, when running tests). "
             "Django was unable to create a connection to the 'postgres' database "
             "and will use the first PostgreSQL database instead.",
             RuntimeWarning)
         for connection in connections.all():
             if connection.vendor == 'postgresql' and connection.settings_dict[
                     'NAME'] != 'postgres':
                 return self.__class__(
                     {
                         **self.settings_dict, 'NAME':
                         connection.settings_dict['NAME']
                     },
                     alias=self.alias,
                     allow_thread_sharing=False,
                 )
     return nodb_connection
示例#8
0
def check_database_backends(*args, **kwargs):
    issues = []
    for conn in connections.all():
        issues.extend(conn.validation.check(**kwargs))
    return issues
示例#9
0
 def tearDownClass(cls):
     if connections_support_transactions():
         cls._rollback_atomics(cls.cls_atomics)
         for conn in connections.all():
             conn.close()
     super().tearDownClass()
示例#10
0
def connections_support_transactions():
    """Return True if all connections support transactions."""
    return all(conn.features.supports_transactions
               for conn in connections.all())