1- # pylint: disable=protected-access, too-many-locals, too-many-branches, too-many-statements
2-
31"""
4- sqlThread is defined here
2+ SQLThread is defined here
53"""
64
75import logging
@@ -38,87 +36,80 @@ def __init__(self):
3836 self .conn = None
3937 self .cur = None
4038 self ._connection_build ()
41- self .root_path = os .path .dirname (os .path .dirname (__file__ ))
4239
4340 def _connection_build (self ):
4441 self ._connection_build_internal ('messages.dat' , False )
4542
46- def _connection_build_internal (self , file_name = "messages.dat" , memory = False ):
47- """
48- Stablish SQL connection
49- """
50- if memory :
51- self .conn = sqlite3 .connect (':memory:' )
52- else :
53- self .conn = sqlite3 .connect (os .path .join (state .appdata + file_name ))
43+ def _connection_build_internal (
44+ self , file_name = "messages.dat" , memory = False
45+ ):
46+ """Establish SQL connection"""
47+ self .conn = sqlite3 .connect (
48+ ':memory:' if memory else os .path .join (state .appdata , file_name ))
5449 self .conn .text_factory = str
5550 self .cur = self .conn .cursor ()
56- self .cur .execute (' PRAGMA secure_delete = true' )
51+ self .cur .execute (" PRAGMA secure_delete = true" )
5752
5853 def __get_current_settings_version (self ):
59- """
60- Get current setting Version
61- """
62- query = "SELECT value FROM settings WHERE key='version'"
63- parameters = ()
64- self .cur .execute (query , parameters )
54+ """Get current setting Version"""
55+ self .cur .execute (
56+ "SELECT value FROM settings WHERE key='version'" )
6557 try :
6658 return int (self .cur .fetchall ()[0 ][0 ])
6759 except (ValueError , IndexError ):
6860 return 0
6961
7062 def _upgrade_one_level_sql_statement (self , file_name ):
71- """
72- Upgrade database versions with applying sql scripts
73- """
63+ """Upgrade database versions with applying sql scripts"""
7464 self .initialize_sql ("init_version_{}" .format (file_name ))
7565
7666 def initialize_sql (self , file_name ):
77- """
78- Initializing sql
79- """
67+ """Initializing sql"""
8068 try :
81- with open (os .path .join (self .root_path , "pybitmessage/sql/{}.sql" .format (file_name ))) as sql_file :
69+ with open (os .path .join (
70+ paths .codePath (), 'sql' , '{}.sql' .format (file_name ))
71+ ) as sql_file :
8272 sql_as_string = sql_file .read ()
8373 self .cur .executescript (sql_as_string )
8474 return True
8575 except OSError as err :
86- logger .debug ('The file is missing. Error message: %s\n ' , str (err ))
76+ logger .debug ('The file is missing. Error message: %s\n ' ,
77+ str (err ))
8778 except IOError as err :
8879 logger .debug (
89- 'ERROR trying to initialize database. Error message: %s\n ' , str (err ))
80+ 'ERROR trying to initialize database. Error message: %s\n ' ,
81+ str (err ))
9082 except sqlite3 .Error as err :
9183 logger .error (err )
9284 except Exception as err :
9385 logger .debug (
94- 'ERROR trying to initialize database. Error message: %s\n ' , str (err ))
86+ 'ERROR trying to initialize database. Error message: %s\n ' ,
87+ str (err ))
9588 return False
9689
9790 @property
9891 def sql_schema_version (self ):
99- """
100- Getter for get current schema version
101- """
92+ """Getter for get current schema version"""
10293 return self .__get_current_settings_version ()
10394
10495 def upgrade_to_latest (self ):
105- """
106- Initialize upgrade level
107- """
108-
109- query = "SELECT name FROM sqlite_master WHERE type='table' AND name='settings'"
110- parameters = ()
111- self .cur .execute (query , parameters )
112- if self .cur .fetchall () == []:
96+ """Initialize upgrade level"""
97+ self .cur .execute (
98+ "SELECT name FROM sqlite_master WHERE type='table' AND name='settings'" )
99+ if not self .cur .fetchall ():
113100 # The settings table doesn't exist. We need to make it.
114101 logger .debug (
115102 "In messages.dat database, creating new 'settings' table." )
116103 self .cur .execute (
117- '''CREATE TABLE settings (key text, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' )
118- self .cur .execute ('''INSERT INTO settings VALUES('version','1')''' )
119- self .cur .execute ('''INSERT INTO settings VALUES('lastvacuumtime',?)''' , (
120- int (time .time ()),))
121- logger .debug ('In messages.dat database, removing an obsolete field from the pubkeys table.' )
104+ "CREATE TABLE settings (key text, value blob, UNIQUE(key)"
105+ " ON CONFLICT REPLACE)" )
106+ self .cur .execute ("INSERT INTO settings VALUES('version','1')" )
107+ self .cur .execute (
108+ "INSERT INTO settings VALUES('lastvacuumtime',?)" ,
109+ (int (time .time ()),))
110+ logger .debug (
111+ 'In messages.dat database, removing an obsolete field'
112+ 'from the pubkeys table.' )
122113
123114 # initiate sql file
124115 self .initialize_sql ("upg_sc_if_old_ver_1" )
@@ -133,71 +124,65 @@ def upgrade_to_latest(self):
133124 self .conn .commit ()
134125
135126 def check_columns_can_store_binary_null (self ):
136- """
137- Check if sqlite can store binary zeros.
138- """
127+ """Check if sqlite can store binary zeros."""
139128 try :
140129 testpayload = '\x00 \x00 '
141130 t = ('1234' , 1 , testpayload , '12345678' , 'no' )
142- self .cur .execute (''' INSERT INTO pubkeys VALUES(?,?,?,?,?)''' , t )
131+ self .cur .execute (" INSERT INTO pubkeys VALUES(?,?,?,?,?)" , t )
143132 self .conn .commit ()
144133 self .cur .execute (
145- '''SELECT transmitdata FROM pubkeys WHERE address='1234' ''' )
146- queryreturn = self .cur .fetchall ()
147- for row in queryreturn :
148- transmitdata , = row
149- self .cur .execute ('''DELETE FROM pubkeys WHERE address='1234' ''' )
134+ "SELECT transmitdata FROM pubkeys WHERE address='1234' " )
135+ transmitdata = self .cur .fetchall ()[- 1 ][0 ]
136+ self .cur .execute ("DELETE FROM pubkeys WHERE address='1234' " )
150137 self .conn .commit ()
151- if transmitdata == '' :
138+ if transmitdata != testpayload :
152139 logger .fatal (
153- 'Problem: The version of SQLite you have cannot store Null values.'
154- ' Please download and install the latest revision of your version of Python'
155- ' (for example, the latest Python 2.7 revision) and try again.\n ' )
140+ 'Problem: The version of SQLite you have cannot store Null'
141+ 'values. Please download and install the latest revision'
142+ 'of your version of Python (for example, the latest '
143+ 'Python 2.7 revision) and try again.\n ' )
156144 logger .fatal (
157145 'PyBitmessage will now exit very abruptly.'
158- ' You may now see threading errors related to this abrupt exit'
159- ' but the problem you need to solve is related to SQLite.\n \n ' )
160- os ._exit (0 )
146+ ' You may now see threading errors related to this abrupt'
147+ 'exit but the problem you need to solve is related to'
148+ 'SQLite.\n \n ' )
149+ os ._exit (1 )
161150 except Exception as err :
162- sqlThread () .error_handler (err , 'null value test' )
151+ sqlThread .error_handler (err , 'null value test' )
163152
164- def check_vacuum (self ): # pylint: disable=too-many-locals, too-many-branches, too-many-statements,
165- # Redefinition-of-parameters-type-from-tuple-to-str, R0204, line-too-long, E501
153+ def check_vacuum (self ):
166154 """
167- Check vacuum and apply sql queries for different different conditions.
168- Let us check to see the last time we vaccumed the messages.dat file.
169- If it has been more than a month let's do it now.
155+ Check vacuum and apply sql queries for different conditions.
156+ Let us check to see the last time we vaccumed the messages.dat file.
157+ If it has been more than a month let's do it now.
170158 """
171-
172- query = "SELECT value FROM settings WHERE key='lastvacuumtime'"
173- parameters = ()
174- self .cur .execute (query , parameters )
175- queryreturn = self .cur .fetchall ()
176- for row in queryreturn :
177- value , = row
178- if int (value ) < int (time .time ()) - 86400 :
179- logger .info ('It has been a long time since the messages.dat file has been vacuumed. Vacuuming now...' )
180- try :
181- self .cur .execute (''' VACUUM ''' )
182- except Exception as err :
183- sqlThread ().error_handler (err , 'VACUUM' )
184- query = "update settings set value=? WHERE key='lastvacuumtime'"
185- parameters = (int (time .time ()),)
186- self .cur .execute (query , parameters )
159+ self .cur .execute (
160+ "SELECT value FROM settings WHERE key='lastvacuumtime'" )
161+ try :
162+ date = self .cur .fetchall ()[- 1 ][0 ]
163+ except IndexError :
164+ return
165+ if int (date ) < int (time .time ()) - 86400 :
166+ logger .info (
167+ 'It has been a long time since the messages.dat file'
168+ ' has been vacuumed. Vacuuming now...' )
169+ try :
170+ self .cur .execute (''' VACUUM ''' )
171+ except Exception as err :
172+ sqlThread .error_handler (err , 'VACUUM' )
173+ self .cur .execute (
174+ "UPDATE settings SET value=? WHERE key='lastvacuumtime'" ,
175+ (int (time .time ()),))
187176
188177 def upgrade_config_parser_setting_version (self , settingsversion ):
189- """
190- Upgrade schema with respect setting version
191- """
178+ """Upgrade schema with respect setting version"""
192179
193180 self .initialize_sql ("config_setting_ver_{}" .format (settingsversion ))
194181
195182 def initialize_schema (self ):
196- """
197- Initialize DB schema
198- """
183+ """Initialize DB schema"""
199184 try :
200- inbox_exists = list (self .cur .execute (' PRAGMA table_info(inbox)' ))
185+ inbox_exists = list (self .cur .execute (" PRAGMA table_info(inbox)" ))
201186 if not inbox_exists :
202187 self .initialize_sql ("initialize_schema" )
203188 self .conn .commit ()
@@ -206,13 +191,13 @@ def initialize_schema(self):
206191 if str (err ) == 'table inbox already exists' :
207192 logger .debug ('Database file already exists.' )
208193 else :
209- os ._exit (
210- 'ERROR trying to create database file (message.dat). Error message: %s\n ' % str (err ))
194+ logger .fatal (
195+ 'Error trying to create database file (message.dat).'
196+ ' Error message: %s\n ' , str (err ))
197+ os ._exit (1 )
211198
212199 def create_sql_function (self ):
213- """
214- Apply create_function to DB
215- """
200+ """Apply create_function to DB"""
216201 try :
217202 self .conn .create_function ("enaddr" , 3 , func = encodeAddress , deterministic = True )
218203 except (TypeError , sqlite3 .NotSupportedError ) as err :
@@ -248,20 +233,18 @@ def sql_config_settings_version(self, settingsversion): # pylint: disable=R0201
248233
249234 def upgrade_config_setting_version (self ):
250235 """
251- upgrade config parser setting version.
252- If the settings version is equal to 2 or 3 then the
253- sqlThread will modify the pubkeys table and change
254- the settings version to 4.
236+ upgrade config parser setting version.
237+ If the settings version is equal to 2 or 3 then the
238+ sqlThread will modify the pubkeys table and change
239+ the settings version to 4.
255240 """
256241 while self .sql_config_settings_version < self .max_setting_level :
257242 self .db .upgrade_config_parser_setting_version (self .sql_config_settings_version )
258243 self .sql_config_settings_version = self .sql_config_settings_version
259244
260245 @staticmethod
261246 def error_handler (err , command , query = None , parameters = None ):
262- """
263- Common error handler
264- """
247+ """Common error handler"""
265248 if str (err ) == 'database or disk is full' :
266249 logger .fatal (
267250 "(While %s) Alert: Your disk or data storage volume is full. sqlThread will now exit." , command
@@ -290,18 +273,14 @@ def error_handler(err, command, query=None, parameters=None):
290273 os ._exit (0 )
291274
292275 def is_query_commit (self ):
293- """
294- When query == 'commit'
295- """
276+ """When query == 'commit'"""
296277 try :
297278 self .db .conn .commit ()
298279 except Exception as err :
299280 self .error_handler (err , 'committing' )
300281
301282 def is_query_movemessagstoprog (self ):
302- """
303- When query == 'movemessagstoprogs'
304- """
283+ """When query == 'movemessagstoprogs'"""
305284 logger .debug ('the sqlThread is moving the messages.dat file to the local program directory.' )
306285 try :
307286 self .db .conn .commit ()
@@ -315,9 +294,7 @@ def is_query_movemessagstoprog(self):
315294 self .db .cur = self .db .conn .cursor ()
316295
317296 def is_query_deleteandvacuume (self ):
318- """
319- When query == 'deleteandvacuume'
320- """
297+ """When query == 'deleteandvacuume'"""
321298 try :
322299 self .db .cur .execute (''' VACUUM ''' )
323300 except Exception as err :
@@ -327,9 +304,7 @@ def is_query_deleteandvacuume(self):
327304 self .db .conn .commit ()
328305
329306 def is_query_other (self , query ):
330- """
331- When the query can be default or other '
332- """
307+ """When the query can be default or other '"""
333308 parameters = helper_sql .sqlSubmitQueue .get ()
334309 try :
335310 self .db .cur .execute (query , parameters )
@@ -339,9 +314,7 @@ def is_query_other(self, query):
339314 self .error_handler (err , 'cur.execute' , query , parameters )
340315
341316 def is_query_movemessagestoappdata (self ):
342- """
343- When query == 'movemessagestoappdata'
344- """
317+ """When query == 'movemessagestoappdata'"""
345318 logger .debug ('the sqlThread is moving the messages.dat file to the Appdata folder.' )
346319 try :
347320 self .db .conn .commit ()
@@ -355,16 +328,12 @@ def is_query_movemessagestoappdata(self):
355328 self .db .cur = self .db .conn .cursor ()
356329
357330 def is_query_exit (self ):
358- """
359- When query == 'exit'
360- """
331+ """When query == 'exit'"""
361332 self .db .conn .close ()
362333 logger .info ('sqlThread exiting gracefully.' )
363334
364335 def loop_queue (self ):
365- """
366- Looping queue and process them
367- """
336+ """Looping queue and process them"""
368337 query = helper_sql .sqlSubmitQueue .get ()
369338 if query == 'commit' :
370339 self .is_query_commit ()
@@ -416,9 +385,8 @@ def run(self): # pylint: disable=R0204, E501
416385
417386
418387class TestDB (BitmessageDB ):
419- """
420- Database connection build for test e
421- """
388+ """Database connection build for test e"""
389+
422390 def _connection_build (self ):
423391 self ._connection_build_internal ("memory" , True )
424392 return self .conn , self .cur
0 commit comments