2006-05-02 09:31:56 +08:00
|
|
|
from django.core import signals
|
2015-06-16 02:07:31 +08:00
|
|
|
from django.db.utils import (
|
|
|
|
DEFAULT_DB_ALIAS,
|
|
|
|
DJANGO_VERSION_PICKLE_KEY,
|
|
|
|
ConnectionHandler,
|
|
|
|
ConnectionRouter,
|
|
|
|
DatabaseError,
|
|
|
|
DataError,
|
|
|
|
Error,
|
|
|
|
IntegrityError,
|
|
|
|
InterfaceError,
|
|
|
|
InternalError,
|
|
|
|
NotSupportedError,
|
|
|
|
OperationalError,
|
|
|
|
ProgrammingError,
|
|
|
|
)
|
2017-10-22 23:30:42 +08:00
|
|
|
from django.utils.connection import ConnectionProxy
|
2013-07-08 08:39:54 +08:00
|
|
|
|
|
|
|
__all__ = [
|
2016-09-27 07:04:18 +08:00
|
|
|
"connection",
|
|
|
|
"connections",
|
|
|
|
"router",
|
|
|
|
"DatabaseError",
|
|
|
|
"IntegrityError",
|
|
|
|
"InternalError",
|
|
|
|
"ProgrammingError",
|
|
|
|
"DataError",
|
|
|
|
"NotSupportedError",
|
|
|
|
"Error",
|
|
|
|
"InterfaceError",
|
|
|
|
"OperationalError",
|
|
|
|
"DEFAULT_DB_ALIAS",
|
|
|
|
"DJANGO_VERSION_PICKLE_KEY",
|
2013-07-08 08:39:54 +08:00
|
|
|
]
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-05-21 17:35:05 +08:00
|
|
|
connections = ConnectionHandler()
|
2009-03-13 12:41:45 +08:00
|
|
|
|
2013-05-21 18:21:31 +08:00
|
|
|
router = ConnectionRouter()
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2019-02-21 00:30:51 +08:00
|
|
|
# For backwards compatibility. Prefer connections['default'] instead.
|
2017-10-22 23:30:42 +08:00
|
|
|
connection = ConnectionProxy(connections, DEFAULT_DB_ALIAS)
|
2013-05-21 17:11:05 +08:00
|
|
|
|
2013-07-08 08:32:04 +08:00
|
|
|
|
2013-02-18 18:37:26 +08:00
|
|
|
# Register an event to reset saved queries when a Django request is started.
|
2008-08-06 23:32:46 +08:00
|
|
|
def reset_queries(**kwargs):
|
2022-03-08 18:48:56 +08:00
|
|
|
for conn in connections.all(initialized_only=True):
|
2014-06-07 20:09:27 +08:00
|
|
|
conn.queries_log.clear()
|
2016-11-13 01:11:23 +08:00
|
|
|
|
|
|
|
|
2008-08-06 23:32:46 +08:00
|
|
|
signals.request_started.connect(reset_queries)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2013-02-18 18:37:26 +08:00
|
|
|
# Register an event to reset transaction state and close connections past
|
2014-03-21 21:21:43 +08:00
|
|
|
# their lifetime.
|
2013-02-18 18:37:26 +08:00
|
|
|
def close_old_connections(**kwargs):
|
2022-03-08 18:48:56 +08:00
|
|
|
for conn in connections.all(initialized_only=True):
|
2013-02-18 18:37:26 +08:00
|
|
|
conn.close_if_unusable_or_obsolete()
|
2016-11-13 01:11:23 +08:00
|
|
|
|
|
|
|
|
2013-02-18 18:37:26 +08:00
|
|
|
signals.request_started.connect(close_old_connections)
|
|
|
|
signals.request_finished.connect(close_old_connections)
|