1717import stat
1818import sys
1919import threading
20+ from contextlib import contextmanager
2021
2122from .exception import CorruptAccountInfo , MissingAccountData
2223from .upload_url_pool import UrlPoolAccountInfo
@@ -152,7 +153,7 @@ def _validate_database(self, last_upgrade_to_run=None):
152153
153154 # If we can connect to the database, and do anything, then all is good.
154155 try :
155- with self ._connect () as conn :
156+ with self ._temp_connection () as conn :
156157 self ._create_tables (conn , last_upgrade_to_run )
157158 return
158159 except sqlite3 .DatabaseError :
@@ -178,7 +179,7 @@ def _validate_database(self, last_upgrade_to_run=None):
178179 # create a database
179180 self ._create_database (last_upgrade_to_run )
180181 # add the data from the JSON file
181- with self ._connect () as conn :
182+ with self ._temp_connection () as conn :
182183 self ._create_tables (conn , last_upgrade_to_run )
183184 insert_statement = """
184185 INSERT INTO account
@@ -214,6 +215,24 @@ def _get_connection(self):
214215 def _connect (self ):
215216 return sqlite3 .connect (self .filename , isolation_level = 'EXCLUSIVE' )
216217
218+ @contextmanager
219+ def _temp_connection (self ):
220+ """A one-off sqlite connection for setup purposes, that is not cached in thread_local."""
221+ conn = self ._connect ()
222+ try :
223+ with conn :
224+ yield conn
225+ finally :
226+ conn .close ()
227+
228+ def close (self ):
229+ connection = getattr (self .thread_local , 'connection' , None )
230+ if connection is None :
231+ return
232+
233+ connection .close ()
234+ del self .thread_local .connection
235+
217236 def _create_database (self , last_upgrade_to_run ):
218237 """
219238 Make sure that the database is created and has appropriate file permissions.
0 commit comments