Skip to content

Commit 75cee1b

Browse files
committed
Add close method to SqliteAccountInfo, explicitly close temporary connections
1 parent e8cf1e6 commit 75cee1b

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

b2sdk/_internal/account_info/sqlite_account_info.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import stat
1818
import sys
1919
import threading
20+
from contextlib import contextmanager
2021

2122
from .exception import CorruptAccountInfo, MissingAccountData
2223
from .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.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix `SqliteAccountInfo` to explicitly close temporary sqlite connections used during setup, add a `close()` method for cached connection.

0 commit comments

Comments
 (0)