6
6
import json
7
7
import argparse
8
8
from datetime import datetime
9
+ from logger_cfg import logger , enable_file_logging
9
10
10
11
parser = argparse .ArgumentParser (description = "MS Access to SQL Export Tool" )
11
12
@@ -14,7 +15,7 @@ class GetWidgetsFrame(WidgetsRender, ttk.Frame):
14
15
The main class of the program is responsible for constructing the form and interaction of elements
15
16
"""
16
17
17
- def __init__ (self , render_params = None , * args , ** options ):
18
+ def __init__ (self , render_params = None , mode = "" , * args , ** options ):
18
19
"""
19
20
Initialization of the Frame, description of the main elements
20
21
:param render_params: General parameters for the arrangement of elements can be set externally
@@ -36,6 +37,7 @@ def __init__(self, render_params=None, *args, **options):
36
37
11 : "Binary" ,
37
38
12 : "Text"
38
39
}}
40
+ self .mode = tk .StringVar (self , mode )
39
41
self .db_path = tk .StringVar (self , "" )
40
42
self .sql_path = tk .StringVar (self , "" )
41
43
self .log_path = tk .StringVar (self , "" )
@@ -221,15 +223,23 @@ def load_config(self, fpath='config.json', loadbyinit=False):
221
223
self .sql_path .set (config ["sql_path" ])
222
224
if "log_path" in config :
223
225
self .log_path .set (config ["log_path" ])
226
+ if self .mode .get () == "cmd" :
227
+ enable_file_logging (self .log_path .get ())
228
+ logger .info (f"Logging in file { self .log_path .get ()} enabled" )
224
229
self .update_widgets ()
225
230
self .tree .df = self .tree .df .from_dict (config ["tree" ])
226
231
self .tree .rebuild_tree ()
227
232
self .tree .all_checked_update ()
233
+ if self .mode .get () == "cmd" :
234
+ logger .info (f"Configuration`s uploaded: { fpath } " )
228
235
else :
229
236
raise
230
237
except :
231
238
if loadbyinit :
232
239
return
240
+ if self .mode .get () == "cmd" :
241
+ logger .error (f"Configuration upload fail: { self .config_path .get ()} " )
242
+ return
233
243
fpath = filedialog .askopenfilename (filetypes = [("JSON files" , "*.json" )])
234
244
if fpath :
235
245
self .load_config (fpath )
@@ -289,7 +299,13 @@ def db_connect(self):
289
299
if not db_path :
290
300
return None
291
301
engine = win32com .client .Dispatch ("DAO.DBEngine.120" )
292
- self .db = engine .OpenDatabase (db_path )
302
+ try :
303
+ self .db = engine .OpenDatabase (db_path )
304
+ if self .mode .get () == "cmd" :
305
+ logger .info (f"DB connected: { db_path } " )
306
+ except Exception as e :
307
+ if self .mode .get () == "cmd" :
308
+ logger .error (f"OpenDatabase({ db_path } ) failed: { e } " )
293
309
294
310
def check_permissions (self ):
295
311
try :
@@ -349,13 +365,13 @@ def resolve_dependencies(self, export_list):
349
365
350
366
return list (export_set ), list (added_tables )
351
367
352
- def export_prepare (self , output_sql_path = "" , mode = "" ):
368
+ def export_prepare (self , output_sql_path = "" ):
353
369
df = self .tree .df
354
370
export_list = df [df .iloc [:, 1 ] == "✔" ]["table" ].to_list ()
355
371
upload_list = df [df .iloc [:, 2 ] == "✔" ]["table" ].to_list ()
356
372
final_list , added_tables = self .resolve_dependencies (export_list )
357
373
358
- if added_tables and mode != "cmd" :
374
+ if added_tables and self . mode . get () != "cmd" :
359
375
added_tables_str = "\n " .join (added_tables )
360
376
message = (
361
377
"The following tables were added to ensure database integrity:\n \n "
@@ -364,18 +380,23 @@ def export_prepare(self, output_sql_path="", mode=""):
364
380
)
365
381
if not messagebox .askyesno ("Integrity Check" , message ):
366
382
return False
383
+ elif self .mode .get () == "cmd" :
384
+ logger .info (f"Depended tables were added: { ', ' .join (added_tables )} " )
385
+
367
386
if not output_sql_path :
368
387
output_sql_path = self .get_output_sql_name ()
369
388
370
389
return final_list , upload_list , output_sql_path
371
390
372
- def export (self , mode = "" ):
373
- export_lists = self .export_prepare (self .sql_path .get (), mode = mode )
391
+ def export (self ):
392
+ export_lists = self .export_prepare (self .sql_path .get ())
374
393
if not export_lists :
375
394
return
376
395
377
396
with (open (export_lists [2 ], "w" , encoding = "utf-8" ) as sql_file ):
378
397
for tab_name in export_lists [0 ]:
398
+ if self .mode .get () == "cmd" :
399
+ logger .info (f"Export table structure: { tab_name } ." )
379
400
table = self .db .TableDefs (tab_name )
380
401
sql_file .write (f"-- Table: { table .Name } \n " )
381
402
sql_file .write (f"CREATE TABLE '{ table .Name } ' (\n " )
@@ -419,6 +440,8 @@ def export(self, mode=""):
419
440
sql_file .write ("\n );\n \n " )
420
441
421
442
if table .Name in export_lists [1 ]:
443
+ if self .mode .get () == "cmd" :
444
+ logger .info (f"Export data from: { tab_name } ." )
422
445
ref_columns = [field .Name for field in table .Fields ]
423
446
sql_file .write (f"-- Filling data for { table .Name } \n " )
424
447
sql_file .write (f"INSERT INTO '{ table .Name } ' ({ ', ' .join (ref_columns )} ) VALUES\n " )
@@ -440,31 +463,24 @@ def export(self, mode=""):
440
463
recordset .MoveNext ()
441
464
recordset .Close ()
442
465
sql_file .write ("\n );\n \n " )
443
- if mode == "cmd" :
444
- print (f"{ datetime .now ().strftime ('%Y-%m-%d %H:%M:%S' )} - SQL export completed!" , f"File saved as { export_lists [2 ]} " , sep = "\n " )
466
+ if self .mode .get () == "cmd" :
467
+ logger .info (f"Table { tab_name } export complete." )
468
+ if self .mode .get () == "cmd" :
469
+ logger .info (f"SQL export completed!" )
445
470
else :
446
471
messagebox .showinfo ("SQL export completed!" , f"File saved as { export_lists [2 ]} " )
447
472
473
+
448
474
def main ():
449
475
parser .add_argument ("-c" ,"--config" , type = str , help = "Path to config file" )
450
476
args = parser .parse_args ()
451
-
452
477
if args .config :
453
- log_list = []
454
478
conf = args .config
455
- log_list .append (f"{ datetime .now ().strftime ('%Y-%m-%d %H:%M:%S' )} - Configuration`s accepted: { conf } " )
456
479
root .withdraw ()
457
- app = GetWidgetsFrame (master = root )
458
- log_list .append (f"{ datetime .now ().strftime ('%Y-%m-%d %H:%M:%S' )} - App started: { app .master .title ()} " )
480
+ app = GetWidgetsFrame (master = root , mode = "cmd" )
459
481
app .load_config (conf )
460
- log_list .append (f"{ datetime .now ().strftime ('%Y-%m-%d %H:%M:%S' )} - Configuration`s uploaded:" )
461
- log_list .append (f"\t db path: { app .db_path .get ()} " )
462
- log_list .append (f"\t sql path: { app .sql_path .get ()} " )
463
- log_list .append (f"{ datetime .now ().strftime ('%Y-%m-%d %H:%M:%S' )} - Export execution..." )
464
- print ("\n " .join (log_list ))
465
- app .export (mode = "cmd" )
482
+ app .export ()
466
483
app .btn_exit ()
467
-
468
484
else :
469
485
app = GetWidgetsFrame (master = root , padding = (2 , 2 ))
470
486
app .mainloop ()
0 commit comments