forked from PySimpleSQL/pysimplesql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pysimplesql.py
1290 lines (1104 loc) · 137 KB
/
pysimplesql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
try:
import PySimpleGUI as sg
except ImportError:
assert 'This module is designed to be used with PySimpleGUI. Try installing with pip3 install pysimplegui'
import logging
import sqlite3
import functools
import os.path
from os import path
logger = logging.getLogger(__name__)
def escape(query_string):
"""
Safely escape characters in strings needed for queries
Parameters:
query_string (str):
Returns:
str: escaped (safe) version of the query_string
"""
# I'm not sure we will need this, but it's here in the case that we do
query_string = str(query_string)
return query_string
class Row:
"""
@Row class. This is a convenience class used by listboxes and comboboxes to display values
while keeping them linked to a primary key.
You may have to cast this to a str() to get the value. Of course, there are methods to get the
value or primary key either way.
"""
def __init__(self, pk, val):
self.pk = pk
self.val = val
def __repr__(self):
return self.val
def __str__(self):
# This override is so that comboboxes can display the value
return self.val
def get_pk(self):
"""Return the primary key portion of the row"""
return self.pk
def get_val(self):
"""Return the value portion of the row"""
return self.val
def get_instance(self):
"""Return this instance of @Row"""
return self
class Relationship:
"""
@Relationship class is used to track primary/foreign key relationships in the database. See the following
for more information: @Database.add_relationship and @Database.auto_add_relationships
Note that this class offers little to the end user, and the above Database functions are all that is needed
by the user.
"""
def __init__(self, join, child, fk, parent, pk, requery_table):
self.join = join
self.child = child
self.fk = fk
self.parent = parent
self.pk = pk
self.requery_table = requery_table
def __str__(self):
return f'{self.join} {self.parent} ON {self.child}.{self.fk}={self.parent}.{self.pk}'
class Table:
"""
@Table class is used for an internal representation of database tables. These are added by the following:
@Database.add_table @Database.auto_add_tables
"""
def __init__(self, db_reference, con, table, pk_field, description_field, query='', order=''):
"""
:param db_reference: This is a reference to the @ Database object, for convenience
:param con: This is a reference to the sqlie connection, also for convience
:param table: Name (string) of the table
:param pk_field: The name of the field containing the primary key for this table
:param description_field: The name of the field used for display to users (normally in a combobox or listbox)
:param query: You can optionally set an inital query here. If none is provided, it will default to "SELECT * FROM {table}"
:param order: The sort order of the returned query
"""
# todo finish the order processing!
# No query was passed in, so we will generate a generic one
if query == '':
query = f'SELECT * FROM {table}'
# No order was passed in, so we will generate generic one
if order == '':
order = f' ORDER BY {description_field} ASC'
self.db = db_reference #type: Database
self._current_index = 0
self.table = table # type: str
self.pk_field = pk_field
self.description_field = description_field
self.query = query
self.order = order
self.join = ''
self.where='' # In addition to generated where!
self.con = con
self.dependents = []
self.field_names = []
self.rows = []
self.search_order=[]
self.selector = None
self.callbacks={}
# self.requery(True)
# Override the [] operator to retrieve fields by key
def __getitem__(self, key):
return self.get_current(key)
# Make current_index a property so that bounds can be respected
@property
def current_index(self):
return self._current_index
@current_index.setter
def current_index(self, val):
if val > len(self.rows)-1:
self._current_index = len(self.rows)-1
elif val < 0:
self._current_index = 0
else:
self._current_index = val
def set_search_order(self,order):
"""
Set the search order when using the search box.
This is a list of fields to be searched, in order.
:param order: A list of field names to search
:return: None
"""
self.search_order=order
def set_callback(self,callback,fctn):
"""
Set table callbacks. A runtime error will be thrown if the callback is not supported.
The following callbacks are supported:
before_save called before a record is saved. The save will continue if the callback returns true, or the record will rollback if the callback returns false.
after_save called after a record is saved. The save will commit to the database if the callback returns true, else it will rollback the transaction
before_update Alias for before_save
after_update Alias for after_save
before_delete called before a record is deleted. The delete will move forward if the callback returns true, else the transaction will rollback
after_delete called after a record is deleted. The delete will commit to the database if the callback returns true, else it will rollback the transaction
before_search called before searching. The search will continue if the callback returns True
after_search called after a search has been performed. The record change will undo if the callback returns False
:param callback: The name of the callback, from the list above
:param fctn: The function to call. Note, the function must take in two parameters, a @Database instance, and a @PySimpleGUI.Window instance, and return True or False
:return: None
"""
callback=callback.lower()
supported=[
'before_save', 'after_save', 'before_delete', 'after_delete',
'before_update', 'after_update', # Aliases for before/after_save
'before_search', 'after_search'
]
if callback in supported:
# handle our convenience aliases
callback='before_save' if callback=='before_update' else callback
callback='after_save' if callback=='after_update' else callback
self.callbacks[callback]=fctn
else:
raise RuntimeError( f'Callback "{callback}" not supported.')
def set_query(self,q):
"""
Set the tables query string. This is more for advanced users. It defautls to "SELECT * FROM {Table};
:param q: The query string you would like to associate with the table
:return: None
"""
self.query=q
def set_join_clause(self,clause):
"""
Set the table's join string. This is more for advanced users, as it will automatically generate from the
Relationships that have been set otherwise.
:param clause: The join clause, such as "LEFT JOIN That on This.pk=That.fk"
:return: None
"""
self.join=clause
def set_where_clause(self,clause):
"""
Set the table's where clause. This is added to the auto-generated where clause from Relationship data!
:param clause: The where clause, such as "WHERE pkThis=100"
:return: None
"""
self.where=clause
def set_order_clause(self,clause):
"""
Set the table's order string. This is more for advanced users, as it will automatically generate from the
Relationships that have been set otherwise.
:param clause: The order clause, such as "Order by name ASC"
:return: None
"""
self.order=clause
def prompt_save(self):
"""
Prompts the user if they want to save when saving a record that has been changed.
:return: True or False on whether the user intends to save the record
"""
# TODO: children too?
if self.current_index is None or self.rows == []: return
return # hack this in for now
# handle dependents first
for rel in self.db.relationships:
if rel.parent == self.table and rel.requery_table:
self.db[rel.child].prompt_save()
dirty = False
for c in self.db.control_map:
# Compare the control version to the GUI version
if c['table'].table == self.table:
control_val = c['control'].Get()
table_val = self[c['field']]
# Sanitize things a bit due to empty values being slightly different in the two cases
if table_val is None: table_val = ''
if control_val != table_val:
print(f'{c["control"].Key}:{c["control"].Get()} != {c["field"]}:{self[c["field"]]}')
dirty = True
if dirty:
save_changes = sg.popup_yes_no('You have unsaved changes! Would you like to save them first?')
if save_changes == 'Yes':
print(save_changes + 'SAVING')
# self.save_record(True) # TODO
# self.requery(False)
def generate_join_clause(self):
"""
Automatically generates a join clause from the Relationships that have been set
:return: A join string to be used in a sqlite3 query
"""
join = ''
for r in self.db.relationships:
if self.table == r.child:
join += f' {r.join} {r.parent} ON {r.child}.{r.fk} = {r.parent}.{r.pk}'
return join if self.join=='' else self.join
def generate_where_clause(self):
"""
Generates a where clause from the Relationships that have been set, as well as the Table's where clause
:return: A where clause string to be used in a sqlite3 query
"""
where = ''
for r in self.db.relationships:
if self.table == r.child:
if r.requery_table:
where += f' WHERE {self.table}.{r.fk}={str(self.db[r.parent].get_current(r.pk, 0))}'
if where == '':
# There was no where clause from Relationships..
where = self.where
else:
# There was an auto-generated portion of the where clause. We will add the table's where clause to it
where = where + ' ' + self.where.replace('WHERE', 'AND')
return where
def generate_query(self,join=True, where=True, order=True):
"""
Generate a query string using the relationships that have been set
:param join: True if you want the join clause auto-generated, False if not
:param where: True if you want the where clause auto-generated, False if not
:param order: True if you want the order by clause auto-generated, False if not
:return: a query string for use with sqlite3
"""
q=self.query
q += f' {self.join if join else ""}'
q += f' {self.where if where else ""}'
q += f' {self.order if order else ""}'
return q
def requery(self, select_first=True, filtered=True):
"""
Requeries the table
The @Table object maintains an internal representation of the actual database table.
The requery method will requery the actual database and sync the @Table objects to it
:param select_first: If true, the first record will be selected after the requery
:param filtered: If true, the relationships will be considered and an appropriate WHERE clause will be generated
:return: None
"""
if filtered:
join=self.generate_join_clause()
where=self.generate_where_clause()
query = self.query+' '+join+' '+where+' '+self.order
logger.info('Running query: '+query)
cur = self.con.execute(query)
self.rows = cur.fetchall()
if select_first:
self.first()
def requery_dependents(self):
"""
Requery parent tables as defined by the relationships of the table
:return: None
"""
for rel in self.db.relationships:
if rel.parent == self.table and rel.requery_table:
self.db[rel.child].requery()
def first(self):
"""
Move to the first record of the table
Only one entry in the table is ever considered "Selected" This is one of several functions that influences
which record is currently selected. See @Table.first, @Table.previous, @Table.next, @Table.last, @Table.search,
@Table.set_by_pk
:return: None
"""
self.prompt_save()
self.current_index = 0
self.requery_dependents()
self.db.update_controls()
def last(self):
"""
Move to the last record of the table
Only one entry in the table is ever considered "Selected" This is one of several functions that influences
which record is currently selected. See @Table.first, @Table.previous, @Table.next, @Table.last, @Table.search,
@Table.set_by_pk
:return: None
"""
self.prompt_save()
self.current_index = len(self.rows)-1
self.requery_dependents()
self.db.update_controls()
def next(self):
"""
Move to the next record of the table
Only one entry in the table is ever considered "Selected" This is one of several functions that influences
which record is currently selected. See @Table.first, @Table.previous, @Table.next, @Table.last, @Table.search,
@Table.set_by_pk
:return: None
"""
self.prompt_save()
if self.current_index < len(self.rows)-1:
self.current_index += 1
self.requery_dependents()
self.db.update_controls()
def previous(self):
"""
Move to the previous record of the table
Only one entry in the table is ever considered "Selected" This is one of several functions that influences
which record is currently selected. See @Table.first, @Table.previous, @Table.next, @Table.last, @Table.search,
@Table.set_by_pk
:return: None
"""
self.prompt_save()
if self.current_index > 0:
self.current_index -= 1
self.requery_dependents()
self.db.update_controls()
def search(self, string):
"""
Move to the next record in the search table that contains @string.
Successive calls will search from the current position, and wrap around back to the beginning.
The search order from @Table.set_search_order() will be used. If the search order is not set by the user,
it will default to the 'name' field, or the 2nd column of the table.
Only one entry in the table is ever considered "Selected" This is one of several functions that influences
which record is currently selected. See @Table.first, @Table.previous, @Table.next, @Table.last, @Table.search,
@Table.set_by_pk
:param string: The search string
:return: None
"""
# callback
if 'before_search' in self.callbacks.keys():
if not self.callbacks['before_search'](self.db, self.db.window):
return
# See if the string is a control name
if string in self.db.window.AllKeysDict.keys():
string=self.db.window[string].get()
if string == '':
return
self.prompt_save()
# First lets make a search order.. TODO: remove this hard coded garbage
for o in self.search_order:
# Perform a search for str, from the current position to the end and back
for i in list(range(self.current_index+1, len(self.rows))) + list(range(0, self.current_index)):
if o in self.rows[i].keys():
if self.rows[i][o]:
if string.lower() in self.rows[i][o].lower():
old_index=self.current_index
self.current_index = i
self.requery_dependents()
self.db.update_controls()
# callback
if 'after_search' in self.callbacks.keys():
if not self.callbacks['after_search'](self.db, self.db.window):
self.current_index=old_index
self.requery_dependents()
self.db.update_controls(self.table)
return
return False
# If we have made it here, then it was not found!
# sg.Popup('Search term "'+str+'" not found!')
# TODO: Play sound?
def set_by_pk(self,pk):
"""
Move to the record with this primary key
This is useful when modifying a record (such as renaming). The primary key can be stored, the record re-named,
and then the current record selection updated regardless of the new sort order.
Only one entry in the table is ever considered "Selected" This is one of several functions that influences
which record is currently selected. See @Table.first, @Table.previous, @Table.next, @Table.last, @Table.search,
@Table.set_by_pk
:param pk: The primary key to move to
:return: None
"""
i = 0
for r in self.rows:
if r[self.pk_field] == pk:
self.current_index = i
break
else:
i += 1
self.db.update_controls(self.table)
def get_current(self, field, default=""):
"""
Get the current value pointed to for @field
You can also use indexing of the @Database object to get the current value of a field
I.e. db["{Table}].[{field'}]
:param field: The field you want the value of
:param default: A value to return if the record is blank
:return: The value of the field requested
"""
if self.rows:
if self.get_current_row()[field] != '':
return self.get_current_row()[field]
else:
return default
else:
return default
def get_current_pk(self):
"""
Get the primary key of the currently selected record
:return: the primary key
"""
return self.get_current(self.pk_field)
def get_max_pk(self):
"""
The the highest primary key for this table.
This can give some insight on what the next inserted primary key will be
:return: The maximum primary key value currently in the table
"""
# TODO: Maybe get this right from the table object instead of running a query?
q = f'SELECT MAX({self.pk_field}) AS highest FROM {self.table};'
cur = self.con.execute(q)
records = cur.fetchone()
return records['highest']
def get_current_row(self):
"""
Get the sqlite3 row for the currently selected record of this table
:return: @sqlite3.row
"""
if self.rows:
return self.rows[self.current_index]
def add_selector(self, control): # _listBox,_pk,_field):
"""
Use a control such as a listbox as a selector item for this table.
This can be done via this method, or via auto_map_controls by naming the control key "selector.{Table}"
:param control: the @PySinpleGUI element used as a selector control
:return: None
"""
# Associate a listbox with this query object. This will be used to select the appropriate record
# self.selector={'control':_listBox,'pk':_pk,'field':_field}
# TODO: any other controls?? Maybe a slider, combobox, etc?
if type(control) != sg.PySimpleGUI.Listbox:
raise RuntimeError(f'AddSelector error: Not a supported Listbox control.')
logger.info(f'Adding {control.Key} as a selector for the {self.table} table.')
self.selector = control
def insert_record(self, field='', value=''):
"""
Insert a new record. If field and value are passed, it will initially set that field to the value
(I.e. {Table}.name='New Record). If none are provided, the default values for the field are used, as set in the
database.
:param field: The field to set
:param value: The value to set (I.e "New record")
:return:
"""
# todo: you don't add a record if there isn't a parent!!!
# todo: this is currently filtered out by enabling of the control, but it should be filtered here too!
# todo: bring back the values parameter
fields=[]
values=[]
if field != '' and value != '':
fields.append(field)
values.append(value)
# Make sure we take into account the foreign key relationships...
for r in self.db.relationships:
if self.table==r.child:
if r.requery_table:
fields.append(r.fk)
values.append(self.db[r.parent].get_current_pk())
fields=",".join([str(x) for x in fields])
values = ",".join([str(x) for x in values])
# We will make a blank record and insert it
#q = f'INSERT INTO {self.table} ({fields}) VALUES ({q_marks});'
q = f'INSERT INTO {self.table} '
if fields != '':
q += f'({fields}) VALUES ({values});'
else:
q += 'DEFAULT VALUES'
cur=self.con.execute(q)
self.con.commit()
# Now we save the new pk
pk = cur.lastrowid
# and move to it
self.requery() # Don't move to the first record
self.set_by_pk(pk)
self.requery_dependents()
self.db.update_controls()
self.db.window.refresh()
def save_record(self, display_message=True):
"""
Save the currently selected record
Saves any changes made via the GUI back to the database. The before_save and after_save @callbacks will call
your own functions for error checking if needed!
:param display_message: Displays a message "Updates saved successfully", otherwise is silent on success
:return: None
"""
# Ensure that there is actually something to delete
if not len(self.rows):
return
# callback
if 'before_save' in self.callbacks.keys():
if not self.callbacks['before_save'](self.db,self.db.window):
self.db.update_controls(self.table)
return
values = []
# We are updating a record
q = f'UPDATE {self.table} SET'
for v in self.db.control_map:
if v['table'] == self:
q += f' {v["control"].Key.split(".",1)[1]}=?,'
values.append(escape(v['control'].Get()))
if values:
# there was something to update
# Remove the trailing comma
q = q[:-1]
# Add the where clause
q += f' WHERE {self.pk_field}={self.get_current(self.pk_field)};'
self.con.execute(q, tuple(values))
# callback
if 'after_save' in self.callbacks.keys():
if not self.callbacks['after_save'](self.db,self.db.window):
self.con.rollback()
else:
self.con.commit()
else:
self.con.commit()
# Lets refresh our data
pk = self.get_current_pk()
self.requery(False)
self.set_by_pk(pk)
#self.requery_dependents()
self.db.update_controls(self.table)
logger.info(f'Record Saved: {q} {str(values)}')
if display_message:
sg.popup('Updates saved successfully!',keep_on_top=True)
def delete_record(self, children=False):
"""
Delete the currently selected record
The before_delete and after_delete callbacks are run during this process to give some control over the process
:param children: Delete child records (as defined by @Relationship that were set up) before deleting this record
:return: None
"""
# Ensure that there is actually something to delete
if not len(self.rows):
return
# callback
if 'before_delete' in self.callbacks.keys():
if not self.callbacks['before_delete'](self.db,self.db.window):
return
if children:
msg = 'Are you sure you want to delete this record? Keep in mind that all children will be deleted as well!'
else:
msg = 'Are you sure you want to delete this record?'
answer = sg.popup_yes_no(msg,keep_on_top=True)
if answer == 'No':
return True
# Delete child records first!
if children:
for qry in self.db.tables:
for r in self.db[qry].relationships:
if r['dbParent'] == self:
q = f'DELETE FROM {self.db[qry].table} WHERE {r["fk"]}={self.get_current(self.pk_field)}'
self.con.execute(q)
logger.info(f'Delete query executed: {q}')
q = f'DELETE FROM {self.table} WHERE {self.pk_field}={self.get_current(self.pk_field)};'
self.con.execute(q)
# callback
if 'after_delete' in self.callbacks.keys():
if not self.callbacks['after_delete'](self.db,self.db.window):
self.con.rollback()
else:
self.con.commit()
else:
self.con.commit()
self.requery(False) # Don't move to the first record
self.current_index=self.current_index # force the current_index to be in bounds! todo should this be done in requery?
self.requery_dependents()
logger.info(f'Delete query executed: {q}')
self.requery(select_first=False)
self.db.update_controls()
class Database:
"""
@Database class
Maintains an internal version of the actual database
Tables can be accessed by key, I.e. db['Table_name"] to return a @Table instance
"""
def __init__(self, db_path='', sqlite3_database=None, win=None, sql_commands=None, sql_file=None):
"""
Initialize a new @Database instance
:param db_path: the name of the database file. It will be created if it doesn't exist.
:param sqlite3_database: A sqlite3 database object
:param win: @PySimpleGUI window instance
:param sql_commands: (str) SQL commands to run if @sqlite3_database is not present
:param sql_file: (file) SQL commands to run if @sqlite3_database is not present
"""
if db_path != '' :
logger.info(f'Importing database {sqlite3_database}')
new_database = not os.path.isfile(sqlite3_database)
con = sqlite3.connect(db_path) # Open our database
if sqlite3_database is not None :
con=sqlite3_database
new_database = False
self.path = db_path # type: str
self.window=None
self.tables = {}
self.control_map = []
self.event_map = []
self.relationships = []
self.callbacks={}
self.con = con
self.con.row_factory = sqlite3.Row
if sql_commands is not None and new_database:
# run SQL script if the database does not yet exist
self.con.executescript(sql_commands)
if sql_file is not None and new_database:
# run SQL script from the file if the database does not yet exist
with open(sql_file, 'r') as file:
logger.info('Loading database into memory')
self.con.executescript(file.read())
if win is not None:
self.auto_bind(win)
def __del__(self):
# optimize the database for long-term benefits
if self.path!=':memory:':
q='PRAGMA optimize;'
self.con.execute(q)
# Close the connection
self.con.close()
# Override the [] operator to retrieve queries by key
def __getitem__(self, key):
return self.tables[key]
def execute(self,q):
"""
Convenience function to pass along to sqlite3.execute()
:param q: The query to execute
:return: sqlite3.cursor
"""
return self.con.execute(q)
def commit(self):
"""
Convience function to pass along to sqlite3.commit()
:return: None
"""
self.con.commit()
def set_callback(self, callback, fctn):
"""
Set @Database callbacks. A runtime error will be raised if the callback is not supported.
The following callbacks are supported:
update_controls Called after controls are updated via @Database.update_controls. This allows for other GUI manipulation on each update of the GUI
edit_enable Called before editing mode is enabled. This can be useful for asking for a password for example
edit_disable Called after the editing mode is disabled
{control_name} Called while updating MAPPED controls. This overrides the default control update implementation.
Note that the {control_name} callback function needs to return a value to pass to Win[control].update()
:param callback: The name of the callback, from the list above
:param fctn: The function to call. Note, the function must take in two parameters, a @Database instance, and a @PySimpleGUI.Window instance
:return: None
"""
callback = callback.lower()
supported = [
'update_controls', 'edit_enable', 'edit_disable'
]
# Add in support fow Window keys
for control in self.control_map:
supported.append(control['control'].Key.lower())
if callback in supported:
self.callbacks[callback] = fctn
else:
raise RuntimeError( f'Callback "{callback}" not supported.')
def auto_bind(self, win):
"""
Auto-bind the window to the database, for the purpose of control, event and relationship mapping
This can happen automatically on @Database creation with a parameter.
This function literally just groups all of the auto_* methods. See" @Database.auto_add_tables,
@Database.auto_add_relationships, @Database.auto_map_controls, @Database.auto_map_events
:param win: The @PySimpleGUI window
:return: None
"""
self.window=win # TODO: provide another way to set this manually...
self.auto_add_tables()
self.auto_add_relationships()
self.auto_map_controls(win)
self.auto_map_events(win)
self.requery_all()
self.update_controls()
# Add a Table object
def add_table(self, table, pk_field, description_field, query='', order=''):
"""
Manually add a table to the @Database
When you attach to an sqlite database, PySimpleSQL isn't aware of what it contains until this command is run
Note that @Database.auto_add_tables will do this automatically, which is also called from @Database.auto_bind
and even from the @Database.__init__ with a parameter
:param table: The name of the table (must match sqlite)
:param pk_field: The primary key field
:param description_field: The field to be used to display to users
:param query: The initial query for the table. Set to "SELECT * FROM {Table}" if none is passed
:param order: The initial sort order for the query
:return: None
"""
self.tables.update({table: Table(self, self.con, table, pk_field, description_field, query, order)})
self[table].set_search_order([description_field]) # set a default sort order
def add_relationship(self, join, child, fk, parent, pk, requery_table):
"""
Add a foreign key relationship between two tables of the database
When you attach an sqlite database, PySimpleSQL isn't aware of the relationships contained until tables are
added via @Database.add_table, and the relationship of various tables is set with this function.
Note that @Database.auto_add_relationships will do this automatically from the schema of the sqlite database,
which also happens automatically with @Database.auto_bind and even from the @Database.__init__ with a parameter
:param join: The join type of the relationship ('LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN')
:param child: The child table containing the foreign key
:param fk: The foreign key field of the child table
:param parent: The parent table containing the primary key
:param pk: The primary key field of the parent table
:param requery_table: Automatically requery the child table if the parent table changes (ON UPDATE CASCADE in sql)
:return: None
"""
self.relationships.append(Relationship(join, child, fk, parent, pk, requery_table))
def get_relationships_for_table(self, table):
"""
Return the relationships for the passed-in table
:param table: The table to get relationships for
:return: A list of @Relationship objects
"""
rel = []
for r in self.relationships:
if r.child == table.table:
rel.append(r)
return rel
def get_cascaded_relationships(self):
rel = []
for r in self.relationships:
if r.requery_table:
rel.append(r.parent)
rel.append(r.child)
# make unique
rel = list(set(rel))
return rel
def get_parent(self, table):
for r in self.relationships:
if r.child == table and r.requery_table:
return r.parent
return ''
def auto_add_tables(self):
logger.info('Automatically adding tables from the sqlite database...')
q = 'SELECT name FROM sqlite_master WHERE type="table" AND name NOT like "sqlite%";'
cur = self.con.execute(q)
records = cur.fetchall() # TODO: new version of this w/o cur
for t in records:
# Now lets get the pk
# TODO: should we capture on_update, on_delete and match from PRAGMA?
q2 = f'PRAGMA table_info({t["name"]})'
cur2 = self.con.execute(q2)
records2 = cur2.fetchall()
names = []
# auto generate description field. Default it to the 2md column,
# but can be overwritten below
description_field = records2[1]['name']
pk_field = None
for t2 in records2:
names.append(t2['name'])
if t2['pk']:
pk_field = t2['name']
if t2['name'] == 'name':
description_field = t2['name']
logger.debug(f'Adding table {t["name"]} to schema with primary key {pk_field} and description of {description_field}')
self.add_table(t['name'], pk_field, description_field)
self.tables[t['name']].field_names = names
# Make sure to send a list of table names to requery if you want
# dependent tables to requery automatically
# TODO: clear relationships first so that successive calls don't add multiple entries.
def auto_add_relationships(self):
for table in self.tables:
rows = self.con.execute(f"PRAGMA foreign_key_list({table})")
rows = rows.fetchall()
for row in rows:
# Add the relationship if it's in the requery list
if row['on_update'] == 'CASCADE':
logger.info(f'Setting table {table} to auto requery with table {row["table"]}')
requery_table = True
else:
requery_table = False
logger.debug(f'Adding relationship {table}.{row["from"]} = {row["table"]}.{row["to"]}')
self.add_relationship('LEFT JOIN', table, row['from'], row['table'], row['to'], requery_table)
def auto_map_controls(self, win):
# TODO: Should controls to be mapped start with C. to match events, and selectors?
logger.info('Automapping controls...')
for control in win.AllKeysDict.keys():
# See if this control has table.field information
# Start by seeing if there is a '.'
if '.' in str(control):
lhs = control.split('.')[0]
rhs = control.split('.')[1]
# If these are valid tables and fields, we can map the control!
if lhs == 'SELECTOR':
self[rhs].add_selector(win[control])
elif lhs in self.tables:
if rhs in self[lhs].field_names:
# Map this control to table.field
self.map_control(win[control], self[lhs], rhs)
# Map a control.
# Optionally supply an FQ (Foreign Query Object), Primary Key and Foreign Key, and Foreign Feild
# TV=True Valeu, FV=False Value
def map_control(self, control, table, field):
dic = {
'control': control,
'table': table,
'field': field,
}
logger.info(f'Mapping control {control.Key}')
self.control_map.append(dic)
def auto_map_events(self, win):
# TODO: Change Event to E?
# TODO: Can we dynamically map a string representation of function instead of using the event_map approach below?
logger.info(f'Auto mapping events...')
for control in win.AllKeysDict.keys():
control=str(control) # sometimes I end up with an integer control 0? TODO: Research
# See if this control has Event.table.func information
# Start by seeing if there is an 'Event.' and two '.' in the name
if 'Event.' in str(control) and str(control).count('.') == 2:
sub_str = control.split('.', 1)[1]
table = sub_str.split('.')[0]
fctn = sub_str.split('.')[1]
event_map = {
'Insert': self[table].insert_record, 'Save': self[table].save_record,
'Delete': self[table].delete_record, 'First': self[table].first, 'Previous': self[table].previous,
'Last': self[table].last, 'Search': functools.partial(self[table].search,f'txtSearch.{table}'),
'Next': self[table].next
}
if fctn in event_map:
self.map_event(control, event_map[fctn])
elif control == 'btnEditProtect':
self.map_event(control, self.edit_protect)
elif 'btnSaveRecord' in control: # also covers btnSaveRecord0,1,2 et
# all save buttons essentially save everything (I.e. not table related, but database wide)
self.map_event(control,self.save_records)
def map_event(self, event, fctn):
dic = {
'event': event,
'function': fctn
}
logger.info(f'Mapping event {event} to function {fctn}')
self.event_map.append(dic)
def edit_protect(self):
if self.window['btnEditProtect'].metadata:
if 'edit_enable' in self.callbacks.keys():
if not self.callbacks['edit_enable'](self,self.window):
return
else:
if 'edit_disable' in self.callbacks.keys():
if not self.callbacks['edit_disable'](self,self.window):
return
self.window['btnEditProtect'].metadata = not self.window['btnEditProtect'].metadata
self.update_controls()
def save_records(self,cascade_only=True):
self.window.refresh() # todo remove?
i=0
tables=self.get_cascaded_relationships() if cascade_only else self.tables
last_index=len(self.tables)-1
msg=False
for t in tables:
if i==last_index:
msg=True