@@ -89,6 +89,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
8989 "endswith" : "LIKE '%%' || {}" ,
9090 "iendswith" : "LIKE '%%' || UPPER({})" ,
9191 }
92+ _connection_pools = {}
9293
9394 def _isnull_operator (a , b ):
9495 is_null = {
@@ -176,7 +177,12 @@ def get_connection_params(self):
176177
177178 @async_unsafe
178179 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 ]
180186
181187 def _driver_info (self ):
182188 if not os .environ .get ("RUNNING_DJANGOS_TEST_SUITE" ):
@@ -192,11 +198,28 @@ def _rollback(self):
192198 def set_autocommit (self , autocommit , force_begin_transaction_with_broken_autocommit = False ):
193199 self .autocommit = autocommit
194200
201+ def _close (self ):
202+ # Normally called by close(), this method is also called by some tests.
203+ pass
204+
195205 @async_unsafe
196206 def close (self ):
197- super ().close ()
207+ self .validate_thread_sharing ()
208+ # MongoClient is a connection pool and, unlike database drivers that
209+ # implement PEP 249, shouldn't be closed by connection.close().
210+
211+ def close_pool (self ):
212+ """Close the MongoClient."""
213+ connection = self .connection
214+ if connection is None :
215+ return
216+ # Remove all references to the connection.
217+ self .connection = None
198218 with contextlib .suppress (AttributeError ):
199219 del self .database
220+ del self ._connection_pools [self .alias ]
221+ # Then close it.
222+ connection .close ()
200223
201224 @async_unsafe
202225 def cursor (self ):
0 commit comments