1313# limitations under the License.
1414
1515import logging
16+ import threading
1617import apsw
1718
1819
@@ -29,6 +30,8 @@ class DbException(Exception):
2930
3031
3132class DB :
33+ _lock = threading .Lock ()
34+
3235 def __init__ (self , dbfile ):
3336 """
3437 Create a connection to sqlite database
@@ -41,7 +44,7 @@ def __init__(self, dbfile):
4144 self .__dbfile = dbfile
4245 try :
4346 log .debug ("Database file: %s" % self .__dbfile )
44- self .__cursor = DB .__create_connection (dbfile ). cursor ( )
47+ self .__conn = DB .__create_connection (dbfile )
4548 except apsw .Error as err :
4649 log .exception ("Database error during init: %s" % err )
4750 raise DbException ("Database error during init" )
@@ -67,24 +70,27 @@ def __create_connection(db_file):
6770
6871 def __create_table (self , query ):
6972 try :
70- self .__cursor .execute (query )
73+ cursor = self .__conn .cursor ()
74+ with cursor :
75+ cursor .execute (query )
7176 except apsw .Error as err :
7277 log .exception ("Database Error: %s" % err )
7378 return 0
7479
7580 @staticmethod
7681 def __log_and_execute (cursor , sql , args ):
77- log .debug ("SQL command: " + sql .replace ('?' , '%s' ) % args )
78- cursor .execute (sql , args )
82+ with DB ._lock :
83+ log .debug ("SQL command: " + sql .replace ('?' , '%s' ) % args )
84+ cursor .execute (sql , args )
7985
8086 def __insert_or_delete (self , query , params , login = False ):
8187 try :
8288 if login :
8389 cursor = DB .__create_connection (self .__dbfile ).cursor ()
8490 else :
85- cursor = self .__cursor
86-
87- DB .__log_and_execute (cursor , query , params )
91+ cursor = self .__conn . cursor ()
92+ with cursor :
93+ DB .__log_and_execute (cursor , query , params )
8894 return 1
8995 except apsw .Error as err :
9096 log .exception ("Database Error: %s" % err )
@@ -95,10 +101,10 @@ def __select(self, query, params, login=False):
95101 if login :
96102 cursor = DB .__create_connection (self .__dbfile ).cursor ()
97103 else :
98- cursor = self .__cursor
99-
100- DB .__log_and_execute (cursor , query , params )
101- return cursor .fetchall ()
104+ cursor = self .__conn . cursor ()
105+ with cursor :
106+ DB .__log_and_execute (cursor , query , params )
107+ return cursor .fetchall ()
102108 except apsw .Error as err :
103109 log .exception ("Database Error: %s" % err )
104110 return None
0 commit comments