@@ -89,6 +89,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
89
89
"endswith" : "LIKE '%%' || {}" ,
90
90
"iendswith" : "LIKE '%%' || UPPER({})" ,
91
91
}
92
+ _connection_pools = {}
92
93
93
94
def _isnull_operator (a , b ):
94
95
is_null = {
@@ -176,7 +177,12 @@ def get_connection_params(self):
176
177
177
178
@async_unsafe
178
179
def get_new_connection (self , conn_params ):
179
- return MongoClient (** conn_params , driver = self ._driver_info ())
180
+ if self .alias not in self ._connection_pools :
181
+ conn = MongoClient (** conn_params , driver = self ._driver_info ())
182
+ # setdefault() ensures that multiple threads don't set this in
183
+ # parallel.
184
+ self ._connection_pools .setdefault (self .alias , conn )
185
+ return self ._connection_pools [self .alias ]
180
186
181
187
def _driver_info (self ):
182
188
if not os .environ .get ("RUNNING_DJANGOS_TEST_SUITE" ):
@@ -189,14 +195,23 @@ def _commit(self):
189
195
def _rollback (self ):
190
196
pass
191
197
192
- def set_autocommit (self , autocommit , force_begin_transaction_with_broken_autocommit = False ):
193
- self .autocommit = autocommit
198
+ def _close (self ):
199
+ # MongoClient is a connection pool and, unlike database drivers that
200
+ # implement PEP 249, shouldn't be closed by connection.close().
201
+ pass
194
202
195
- @async_unsafe
196
- def close (self ):
197
- super ().close ()
203
+ def close_pool (self ):
204
+ connection = self .connection
205
+ # Remove any reference to the connection.
206
+ self .connection = None
198
207
with contextlib .suppress (AttributeError ):
199
208
del self .database
209
+ del self ._connection_pools [self .alias ]
210
+ # Then close it.
211
+ connection .close ()
212
+
213
+ def set_autocommit (self , autocommit , force_begin_transaction_with_broken_autocommit = False ):
214
+ self .autocommit = autocommit
200
215
201
216
@async_unsafe
202
217
def cursor (self ):
0 commit comments