-
Notifications
You must be signed in to change notification settings - Fork 399
/
generic.py
2655 lines (2264 loc) · 87.5 KB
/
generic.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
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2015-2016 Gramps Development Team
# Copyright (C) 2016 Nick Hall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# ------------------------------------------------------------------------
#
# Python Modules
#
# ------------------------------------------------------------------------
import random
import pickle
import time
import re
import os
import logging
import bisect
import ast
import sys
import datetime
import glob
from pathlib import Path
# ------------------------------------------------------------------------
#
# Gramps Modules
#
# ------------------------------------------------------------------------
from . import (
DbReadBase,
DbWriteBase,
DbUndo,
DBLOGNAME,
DBUNDOFN,
REFERENCE_KEY,
PERSON_KEY,
FAMILY_KEY,
CITATION_KEY,
SOURCE_KEY,
EVENT_KEY,
MEDIA_KEY,
PLACE_KEY,
REPOSITORY_KEY,
NOTE_KEY,
TAG_KEY,
TXNADD,
TXNUPD,
TXNDEL,
KEY_TO_NAME_MAP,
DBMODE_R,
DBMODE_W,
)
from .utils import write_lock_file, clear_lock_file
from .exceptions import DbVersionError, DbUpgradeRequiredError
from ..errors import HandleError
from ..utils.callback import Callback
from ..updatecallback import UpdateCallback
from .bookmarks import DbBookmarks
from ..utils.id import create_id
from ..lib.researcher import Researcher
from ..lib import (
Tag,
Media,
Person,
Family,
Source,
Citation,
Event,
Place,
Repository,
Note,
NameOriginType,
)
from ..lib.genderstats import GenderStats
from ..config import config
from ..const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
LOG = logging.getLogger(DBLOGNAME)
SIGBASE = (
"person",
"family",
"source",
"event",
"media",
"place",
"repository",
"reference",
"note",
"tag",
"citation",
)
class DbGenericUndo(DbUndo):
def __init__(self, grampsdb, path):
super(DbGenericUndo, self).__init__(grampsdb)
self.undodb = []
def open(self, value=None):
"""
Open the backing storage. Needs to be overridden in the derived
class.
"""
pass
def close(self):
"""
Close the backing storage. Needs to be overridden in the derived
class.
"""
pass
def append(self, value):
"""
Add a new entry on the end. Needs to be overridden in the derived
class.
"""
self.undodb.append(value)
def __getitem__(self, index):
"""
Returns an entry by index number. Needs to be overridden in the
derived class.
"""
return self.undodb[index]
def __setitem__(self, index, value):
"""
Set an entry to a value. Needs to be overridden in the derived class.
"""
self.undodb[index] = value
def __len__(self):
"""
Returns the number of entries. Needs to be overridden in the derived
class.
"""
return len(self.undodb)
def _redo(self, update_history):
"""
Access the last undone transaction, and revert the data to the state
before the transaction was undone.
"""
txn = self.redoq.pop()
self.undoq.append(txn)
transaction = txn
db = self.db
subitems = transaction.get_recnos()
# sigs[obj_type][trans_type]
sigs = [[[] for trans_type in range(3)] for key in range(11)]
# Process all records in the transaction
try:
self.db._txn_begin()
for record_id in subitems:
(key, trans_type, handle, old_data, new_data) = pickle.loads(
self.undodb[record_id]
)
if key == REFERENCE_KEY:
self.db.undo_reference(new_data, handle)
else:
self.db.undo_data(new_data, handle, key)
sigs[key][trans_type].append(handle)
# now emit the signals
self.undo_sigs(sigs, False)
self.db._txn_commit()
except:
self.db._txn_abort()
raise
# Notify listeners
if db.undo_callback:
db.undo_callback(_("_Undo %s") % transaction.get_description())
if db.redo_callback:
if self.redo_count > 1:
new_transaction = self.redoq[-2]
db.redo_callback(_("_Redo %s") % new_transaction.get_description())
else:
db.redo_callback(None)
if update_history and db.undo_history_callback:
db.undo_history_callback()
return True
def _undo(self, update_history):
"""
Access the last committed transaction, and revert the data to the
state before the transaction was committed.
"""
txn = self.undoq.pop()
self.redoq.append(txn)
transaction = txn
db = self.db
subitems = transaction.get_recnos(reverse=True)
# sigs[obj_type][trans_type]
sigs = [[[] for trans_type in range(3)] for key in range(11)]
# Process all records in the transaction
try:
self.db._txn_begin()
for record_id in subitems:
(key, trans_type, handle, old_data, new_data) = pickle.loads(
self.undodb[record_id]
)
if key == REFERENCE_KEY:
self.db.undo_reference(old_data, handle)
else:
self.db.undo_data(old_data, handle, key)
sigs[key][trans_type].append(handle)
# now emit the signals
self.undo_sigs(sigs, True)
self.db._txn_commit()
except:
self.db._txn_abort()
raise
# Notify listeners
if db.undo_callback:
if self.undo_count > 0:
db.undo_callback(_("_Undo %s") % self.undoq[-1].get_description())
else:
db.undo_callback(None)
if db.redo_callback:
db.redo_callback(_("_Redo %s") % transaction.get_description())
if update_history and db.undo_history_callback:
db.undo_history_callback()
return True
def undo_sigs(self, sigs, undo):
"""
Helper method to undo/redo the signals for changes made
We want to do deletes and adds first
Note that if 'undo' we swap emits
"""
for trans_type in [TXNDEL, TXNADD, TXNUPD]:
for obj_type in range(11):
handles = sigs[obj_type][trans_type]
if handles:
if (
not undo
and trans_type == TXNDEL
or undo
and trans_type == TXNADD
):
typ = "-delete"
else:
# don't update a handle if its been deleted, and note
# that 'deleted' handles are in the 'add' list if we
# are undoing
handles = [
handle
for handle in handles
if handle not in sigs[obj_type][TXNADD if undo else TXNDEL]
]
if ((not undo) and trans_type == TXNADD) or (
undo and trans_type == TXNDEL
):
typ = "-add"
else: # TXNUPD
typ = "-update"
if handles:
self.db.emit(KEY_TO_NAME_MAP[obj_type] + typ, (handles,))
class Cursor:
def __init__(self, iterator):
self.iterator = iterator
self._iter = self.__iter__()
def __enter__(self):
return self
def __iter__(self):
for handle, data in self.iterator():
yield (handle, data)
def __next__(self):
try:
return self._iter.__next__()
except StopIteration:
return None
def __exit__(self, *args, **kwargs):
pass
def iter(self):
for handle, data in self.iterator():
yield (handle, data)
def first(self):
self._iter = self.__iter__()
try:
return next(self._iter)
except:
return
def next(self):
try:
return next(self._iter)
except:
return
def close(self):
pass
class DbGeneric(DbWriteBase, DbReadBase, UpdateCallback, Callback):
"""
A Gramps Database Backend. This replicates the grampsdb functions.
"""
__signals__ = dict(
(obj + "-" + op, signal)
for obj in [
"person",
"family",
"event",
"place",
"repository",
"source",
"citation",
"media",
"note",
"tag",
]
for op, signal in zip(
["add", "update", "delete", "rebuild"], [(list,), (list,), (list,), None]
)
)
# 2. Signals for long operations
__signals__.update(
("long-op-" + op, signal)
for op, signal in zip(["start", "heartbeat", "end"], [(object,), None, None])
)
# 3. Special signal for change in home person
__signals__["home-person-changed"] = None
# 4. Signal for change in person group name, parameters are
__signals__["person-groupname-rebuild"] = (str, str)
__callback_map = {}
VERSION = (20, 0, 0)
def __init__(self, directory=None):
DbReadBase.__init__(self)
DbWriteBase.__init__(self)
Callback.__init__(self)
self.__tables = {
"Person": {
"handle_func": self.get_person_from_handle,
"gramps_id_func": self.get_person_from_gramps_id,
"class_func": Person,
"cursor_func": self.get_person_cursor,
"handles_func": self.get_person_handles,
"add_func": self.add_person,
"commit_func": self.commit_person,
"iter_func": self.iter_people,
"ids_func": self.get_person_gramps_ids,
"has_handle_func": self.has_person_handle,
"has_gramps_id_func": self.has_person_gramps_id,
"count_func": self.get_number_of_people,
"raw_func": self.get_raw_person_data,
"raw_id_func": self._get_raw_person_from_id_data,
"del_func": self.remove_person,
},
"Family": {
"handle_func": self.get_family_from_handle,
"gramps_id_func": self.get_family_from_gramps_id,
"class_func": Family,
"cursor_func": self.get_family_cursor,
"handles_func": self.get_family_handles,
"add_func": self.add_family,
"commit_func": self.commit_family,
"iter_func": self.iter_families,
"ids_func": self.get_family_gramps_ids,
"has_handle_func": self.has_family_handle,
"has_gramps_id_func": self.has_family_gramps_id,
"count_func": self.get_number_of_families,
"raw_func": self.get_raw_family_data,
"raw_id_func": self._get_raw_family_from_id_data,
"del_func": self.remove_family,
},
"Source": {
"handle_func": self.get_source_from_handle,
"gramps_id_func": self.get_source_from_gramps_id,
"class_func": Source,
"cursor_func": self.get_source_cursor,
"handles_func": self.get_source_handles,
"add_func": self.add_source,
"commit_func": self.commit_source,
"iter_func": self.iter_sources,
"ids_func": self.get_source_gramps_ids,
"has_handle_func": self.has_source_handle,
"has_gramps_id_func": self.has_source_gramps_id,
"count_func": self.get_number_of_sources,
"raw_func": self.get_raw_source_data,
"raw_id_func": self._get_raw_source_from_id_data,
"del_func": self.remove_source,
},
"Citation": {
"handle_func": self.get_citation_from_handle,
"gramps_id_func": self.get_citation_from_gramps_id,
"class_func": Citation,
"cursor_func": self.get_citation_cursor,
"handles_func": self.get_citation_handles,
"add_func": self.add_citation,
"commit_func": self.commit_citation,
"iter_func": self.iter_citations,
"ids_func": self.get_citation_gramps_ids,
"has_handle_func": self.has_citation_handle,
"has_gramps_id_func": self.has_citation_gramps_id,
"count_func": self.get_number_of_citations,
"raw_func": self.get_raw_citation_data,
"raw_id_func": self._get_raw_citation_from_id_data,
"del_func": self.remove_citation,
},
"Event": {
"handle_func": self.get_event_from_handle,
"gramps_id_func": self.get_event_from_gramps_id,
"class_func": Event,
"cursor_func": self.get_event_cursor,
"handles_func": self.get_event_handles,
"add_func": self.add_event,
"commit_func": self.commit_event,
"iter_func": self.iter_events,
"ids_func": self.get_event_gramps_ids,
"has_handle_func": self.has_event_handle,
"has_gramps_id_func": self.has_event_gramps_id,
"count_func": self.get_number_of_events,
"raw_func": self.get_raw_event_data,
"raw_id_func": self._get_raw_event_from_id_data,
"del_func": self.remove_event,
},
"Media": {
"handle_func": self.get_media_from_handle,
"gramps_id_func": self.get_media_from_gramps_id,
"class_func": Media,
"cursor_func": self.get_media_cursor,
"handles_func": self.get_media_handles,
"add_func": self.add_media,
"commit_func": self.commit_media,
"iter_func": self.iter_media,
"ids_func": self.get_media_gramps_ids,
"has_handle_func": self.has_media_handle,
"has_gramps_id_func": self.has_media_gramps_id,
"count_func": self.get_number_of_media,
"raw_func": self.get_raw_media_data,
"raw_id_func": self._get_raw_media_from_id_data,
"del_func": self.remove_media,
},
"Place": {
"handle_func": self.get_place_from_handle,
"gramps_id_func": self.get_place_from_gramps_id,
"class_func": Place,
"cursor_func": self.get_place_cursor,
"handles_func": self.get_place_handles,
"add_func": self.add_place,
"commit_func": self.commit_place,
"iter_func": self.iter_places,
"ids_func": self.get_place_gramps_ids,
"has_handle_func": self.has_place_handle,
"has_gramps_id_func": self.has_place_gramps_id,
"count_func": self.get_number_of_places,
"raw_func": self.get_raw_place_data,
"raw_id_func": self._get_raw_place_from_id_data,
"del_func": self.remove_place,
},
"Repository": {
"handle_func": self.get_repository_from_handle,
"gramps_id_func": self.get_repository_from_gramps_id,
"class_func": Repository,
"cursor_func": self.get_repository_cursor,
"handles_func": self.get_repository_handles,
"add_func": self.add_repository,
"commit_func": self.commit_repository,
"iter_func": self.iter_repositories,
"ids_func": self.get_repository_gramps_ids,
"has_handle_func": self.has_repository_handle,
"has_gramps_id_func": self.has_repository_gramps_id,
"count_func": self.get_number_of_repositories,
"raw_func": self.get_raw_repository_data,
"raw_id_func": self._get_raw_repository_from_id_data,
"del_func": self.remove_repository,
},
"Note": {
"handle_func": self.get_note_from_handle,
"gramps_id_func": self.get_note_from_gramps_id,
"class_func": Note,
"cursor_func": self.get_note_cursor,
"handles_func": self.get_note_handles,
"add_func": self.add_note,
"commit_func": self.commit_note,
"iter_func": self.iter_notes,
"ids_func": self.get_note_gramps_ids,
"has_handle_func": self.has_note_handle,
"has_gramps_id_func": self.has_note_gramps_id,
"count_func": self.get_number_of_notes,
"raw_func": self.get_raw_note_data,
"raw_id_func": self._get_raw_note_from_id_data,
"del_func": self.remove_note,
},
"Tag": {
"handle_func": self.get_tag_from_handle,
"gramps_id_func": None,
"class_func": Tag,
"cursor_func": self.get_tag_cursor,
"handles_func": self.get_tag_handles,
"add_func": self.add_tag,
"commit_func": self.commit_tag,
"has_handle_func": self.has_tag_handle,
"iter_func": self.iter_tags,
"count_func": self.get_number_of_tags,
"raw_func": self.get_raw_tag_data,
"del_func": self.remove_tag,
},
}
self.readonly = False
self.db_is_open = False
self.name_formats = []
# Bookmarks:
self.bookmarks = DbBookmarks()
self.family_bookmarks = DbBookmarks()
self.event_bookmarks = DbBookmarks()
self.place_bookmarks = DbBookmarks()
self.citation_bookmarks = DbBookmarks()
self.source_bookmarks = DbBookmarks()
self.repo_bookmarks = DbBookmarks()
self.media_bookmarks = DbBookmarks()
self.note_bookmarks = DbBookmarks()
self.set_person_id_prefix("I%04d")
self.set_media_id_prefix("O%04d")
self.set_family_id_prefix("F%04d")
self.set_citation_id_prefix("C%04d")
self.set_source_id_prefix("S%04d")
self.set_place_id_prefix("P%04d")
self.set_event_id_prefix("E%04d")
self.set_repository_id_prefix("R%04d")
self.set_note_id_prefix("N%04d")
# ----------------------------------
self.undodb = None
self.cmap_index = 0
self.smap_index = 0
self.emap_index = 0
self.pmap_index = 0
self.fmap_index = 0
self.lmap_index = 0
self.omap_index = 0
self.rmap_index = 0
self.nmap_index = 0
self.undo_callback = None
self.redo_callback = None
self.undo_history_callback = None
self.modified = 0
self.transaction = None
self.abort_possible = True
self._bm_changes = 0
self.has_changed = 0 # Also gives commits since startup
self.surname_list = []
self.genderStats = GenderStats() # can pass in loaded stats as dict
self.owner = Researcher()
if directory:
self.load(directory)
def _initialize(self, directory, username, password):
"""
Initialize database backend.
"""
raise NotImplementedError
def __check_readonly(self, name):
"""
Return True if we don't have read/write access to the database,
otherwise return False (that is, we DO have read/write access)
"""
# In-memory databases always allow write access.
if name == ":memory:":
return False
# See if we write to the target directory at all?
if not os.access(name, os.W_OK):
return True
# See if we lack write access to the database file
path = os.path.join(name, "sqlite.db")
if os.path.isfile(path) and not os.access(path, os.W_OK):
return True
# All tests passed. Inform caller that we are NOT read only
return False
def load(
self,
directory,
callback=None,
mode=DBMODE_W,
force_schema_upgrade=False,
force_bsddb_upgrade=False,
force_bsddb_downgrade=False,
force_python_upgrade=False,
update=True,
username=None,
password=None,
):
"""
If update is False: then don't update any files
"""
if self.__check_readonly(directory):
mode = DBMODE_R
self.readonly = mode == DBMODE_R
if not self.readonly and directory != ":memory:":
write_lock_file(directory)
# run backend-specific code:
self._initialize(directory, username, password)
if not self._schema_exists():
self._create_schema()
self._set_metadata("version", str(self.VERSION[0]))
# Load metadata
self.name_formats = self._get_metadata("name_formats")
self.owner = self._get_metadata("researcher", default=Researcher())
# Load bookmarks
self.bookmarks.load(self._get_metadata("bookmarks"))
self.family_bookmarks.load(self._get_metadata("family_bookmarks"))
self.event_bookmarks.load(self._get_metadata("event_bookmarks"))
self.source_bookmarks.load(self._get_metadata("source_bookmarks"))
self.citation_bookmarks.load(self._get_metadata("citation_bookmarks"))
self.repo_bookmarks.load(self._get_metadata("repo_bookmarks"))
self.media_bookmarks.load(self._get_metadata("media_bookmarks"))
self.place_bookmarks.load(self._get_metadata("place_bookmarks"))
self.note_bookmarks.load(self._get_metadata("note_bookmarks"))
# Custom type values
self.event_names = self._get_metadata("event_names", set())
self.family_attributes = self._get_metadata("fattr_names", set())
self.individual_attributes = self._get_metadata("pattr_names", set())
self.source_attributes = self._get_metadata("sattr_names", set())
self.marker_names = self._get_metadata("marker_names", set())
self.child_ref_types = self._get_metadata("child_refs", set())
self.family_rel_types = self._get_metadata("family_rels", set())
self.event_role_names = self._get_metadata("event_roles", set())
self.name_types = self._get_metadata("name_types", set())
self.origin_types = self._get_metadata("origin_types", set())
self.repository_types = self._get_metadata("repo_types", set())
self.note_types = self._get_metadata("note_types", set())
self.source_media_types = self._get_metadata("sm_types", set())
self.url_types = self._get_metadata("url_types", set())
self.media_attributes = self._get_metadata("mattr_names", set())
self.event_attributes = self._get_metadata("eattr_names", set())
self.place_types = self._get_metadata("place_types", set())
# surname list
self.surname_list = self.get_surname_list()
self._set_save_path(directory)
if self._directory and self._directory != ":memory:":
self.undolog = os.path.join(self._directory, DBUNDOFN)
else:
self.undolog = None
self.undodb = self._create_undo_manager()
self.undodb.open()
# Other items to load
gstats = self.get_gender_stats()
self.genderStats = GenderStats(gstats)
# Indexes:
self.cmap_index = self._get_metadata("cmap_index", 0)
self.smap_index = self._get_metadata("smap_index", 0)
self.emap_index = self._get_metadata("emap_index", 0)
self.pmap_index = self._get_metadata("pmap_index", 0)
self.fmap_index = self._get_metadata("fmap_index", 0)
self.lmap_index = self._get_metadata("lmap_index", 0)
self.omap_index = self._get_metadata("omap_index", 0)
self.rmap_index = self._get_metadata("rmap_index", 0)
self.nmap_index = self._get_metadata("nmap_index", 0)
self.db_is_open = True
# Check on db version to see if we need upgrade or too new
dbversion = int(self._get_metadata("version", default="0"))
if dbversion > self.VERSION[0]:
self.close()
raise DbVersionError(dbversion, 18, self.VERSION[0])
if not self.readonly and dbversion < self.VERSION[0]:
LOG.debug(
"Schema upgrade required from %s to %s", dbversion, self.VERSION[0]
)
if force_schema_upgrade:
self._gramps_upgrade(dbversion, directory, callback)
else:
self.close()
raise DbUpgradeRequiredError(dbversion, self.VERSION[0])
def _create_undo_manager(self):
"""
Create the undo manager.
"""
return DbGenericUndo(self, self.undolog)
def _close(self):
"""
Close database backend.
"""
raise NotImplementedError
def close(self, update=True, user=None):
"""
Close the database.
if update is False, don't change access times, etc.
"""
if self._directory != ":memory:":
if update and not self.readonly:
# This is just a dummy file to indicate last modified time of
# the database for gramps.cli.clidbman:
filename = os.path.join(self._directory, "meta_data.db")
Path(filename).touch()
# Save metadata
self._set_metadata("name_formats", self.name_formats)
self._set_metadata("researcher", self.owner)
# Bookmarks
self._set_metadata("bookmarks", self.bookmarks.get())
self._set_metadata("family_bookmarks", self.family_bookmarks.get())
self._set_metadata("event_bookmarks", self.event_bookmarks.get())
self._set_metadata("place_bookmarks", self.place_bookmarks.get())
self._set_metadata("repo_bookmarks", self.repo_bookmarks.get())
self._set_metadata("source_bookmarks", self.source_bookmarks.get())
self._set_metadata("citation_bookmarks", self.citation_bookmarks.get())
self._set_metadata("media_bookmarks", self.media_bookmarks.get())
self._set_metadata("note_bookmarks", self.note_bookmarks.get())
# Custom type values, sets
self._set_metadata("event_names", self.event_names)
self._set_metadata("fattr_names", self.family_attributes)
self._set_metadata("pattr_names", self.individual_attributes)
self._set_metadata("sattr_names", self.source_attributes)
self._set_metadata("marker_names", self.marker_names)
self._set_metadata("child_refs", self.child_ref_types)
self._set_metadata("family_rels", self.family_rel_types)
self._set_metadata("event_roles", self.event_role_names)
self._set_metadata("name_types", self.name_types)
self._set_metadata("origin_types", self.origin_types)
self._set_metadata("repo_types", self.repository_types)
self._set_metadata("note_types", self.note_types)
self._set_metadata("sm_types", self.source_media_types)
self._set_metadata("url_types", self.url_types)
self._set_metadata("mattr_names", self.media_attributes)
self._set_metadata("eattr_names", self.event_attributes)
self._set_metadata("place_types", self.place_types)
# Save misc items:
if self.has_changed:
self.save_gender_stats(self.genderStats)
# Indexes:
self._set_metadata("cmap_index", self.cmap_index)
self._set_metadata("smap_index", self.smap_index)
self._set_metadata("emap_index", self.emap_index)
self._set_metadata("pmap_index", self.pmap_index)
self._set_metadata("fmap_index", self.fmap_index)
self._set_metadata("lmap_index", self.lmap_index)
self._set_metadata("omap_index", self.omap_index)
self._set_metadata("rmap_index", self.rmap_index)
self._set_metadata("nmap_index", self.nmap_index)
self._close()
try:
clear_lock_file(self.get_save_path())
except IOError:
pass
self.db_is_open = False
self._directory = None
def is_open(self):
return self.db_is_open
def get_dbid(self):
"""
We use the file directory name as the unique ID for
this database on this computer.
"""
return self.brief_name
def get_dbname(self):
"""
In DbGeneric, the database is in a text file at the path
"""
name = None
if self._directory:
filepath = os.path.join(self._directory, "name.txt")
try:
with open(filepath, "r", encoding="utf8") as name_file:
name = name_file.readline().strip()
except (OSError, IOError) as msg:
LOG.error(str(msg))
return name
def version_supported(self):
"""Return True when the file has a supported version."""
return True
def _get_table_func(self, table=None, func=None):
"""
Private implementation of get_table_func.
"""
if table is None:
return list(self.__tables.keys())
elif func is None:
return self.__tables[table] # dict of functions
elif func in self.__tables[table].keys():
return self.__tables[table][func]
else:
return None
def _txn_begin(self):
"""
Lowlevel interface to the backend transaction.
Executes a db BEGIN;
"""
pass
def _txn_commit(self):
"""
Lowlevel interface to the backend transaction.
Executes a db END;
"""
pass
def _txn_abort(self):
"""
Lowlevel interface to the backend transaction.
Executes a db ROLLBACK;
"""
pass
def transaction_begin(self, transaction):
"""
Transactions are handled automatically by the db layer.
"""
self.transaction = transaction
return transaction
def _get_metadata(self, key, default=[]):
"""
Get an item from the database.
Default is an empty list, which is a mutable and
thus a bad default (pylint will complain).
However, it is just used as a value, and not altered, so
its use here is ok.
"""
raise NotImplementedError
def _set_metadata(self, key, value):
"""
key: string
value: item, will be serialized here
"""
raise NotImplementedError
################################################################
#
# set_*_id_prefix methods
#
################################################################
@staticmethod
def _validated_id_prefix(val, default):
if isinstance(val, str) and val:
try:
str_ = val % 1
except TypeError: # missing conversion specifier
prefix_var = val + "%d"
except ValueError: # incomplete format
prefix_var = default + "%04d"
else:
prefix_var = val # OK as given
else:
prefix_var = default + "%04d" # not a string or empty string
return prefix_var
@staticmethod
def __id2user_format(id_pattern):
"""
Return a method that accepts a Gramps ID and adjusts it to the users
format.
"""
pattern_match = re.match(r"(.*)%[0 ](\d+)[diu]$", id_pattern)
if pattern_match:
str_prefix = pattern_match.group(1)
# nr_width = int(pattern_match.group(2))
def closure_func(gramps_id):
if gramps_id and gramps_id.startswith(str_prefix):
id_number = gramps_id[len(str_prefix) :]
if id_number.isdigit():
id_value = int(id_number, 10)
# if len(str(id_value)) > nr_width:
# # The ID to be imported is too large to fit in the
# # users format. For now just create a new ID,
# # because that is also what happens with IDs that
# # are identical to IDs already in the database. If
# # the problem of colliding import and already
# # present IDs is solved the code here also needs
# # some solution.
# gramps_id = id_pattern % 1
# else:
gramps_id = id_pattern % id_value
return gramps_id
else:
def closure_func(gramps_id):
return gramps_id
return closure_func
def set_person_id_prefix(self, val):
"""
Set the naming template for Gramps Person ID values.
The string is expected to be in the form of a simple text string, or
in a format that contains a C/Python style format string using %d,
such as I%d or I%04d.
"""
self.person_prefix = self._validated_id_prefix(val, "I")
self.id2user_format = self.__id2user_format(self.person_prefix)
def set_citation_id_prefix(self, val):
"""
Set the naming template for Gramps Citation ID values.
The string is expected to be in the form of a simple text string, or
in a format that contains a C/Python style format string using %d,
such as C%d or C%04d.
"""
self.citation_prefix = self._validated_id_prefix(val, "C")
self.cid2user_format = self.__id2user_format(self.citation_prefix)
def set_source_id_prefix(self, val):
"""
Set the naming template for Gramps Source ID values.
The string is expected to be in the form of a simple text string, or
in a format that contains a C/Python style format string using %d,
such as S%d or S%04d.
"""
self.source_prefix = self._validated_id_prefix(val, "S")
self.sid2user_format = self.__id2user_format(self.source_prefix)
def set_media_id_prefix(self, val):
"""
Set the naming template for Gramps Media ID values.
The string is expected to be in the form of a simple text string, or
in a format that contains a C/Python style format string using %d,
such as O%d or O%04d.
"""