[8fd8d8]: gramps / gen / db / write.py Maximize Restore History

Download this file

write.py    2328 lines (2002 with data), 90.3 kB

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2008 Donald N. Allingham
# Copyright (C) 2010 Nick Hall
# Copyright (C) 2011 Tim G L Lyons
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
"""
Provide the Berkeley DB (DbBsddb) database backend for GRAMPS.
This is used since GRAMPS version 3.0
"""
#-------------------------------------------------------------------------
#
# Standard python modules
#
#-------------------------------------------------------------------------
from __future__ import print_function, with_statement, unicode_literals
import sys
if sys.version_info[0] < 3:
import cPickle as pickle
else:
import pickle
import os
import time
import bisect
import io
from functools import wraps
import logging
from sys import maxsize, getfilesystemencoding, version_info
from ..config import config
if config.get('preferences.use-bsddb3') or sys.version_info[0] >= 3:
from bsddb3 import dbshelve, db
else:
from bsddb import dbshelve, db
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from ..lib.person import Person
from ..lib.family import Family
from ..lib.src import Source
from ..lib.citation import Citation
from ..lib.event import Event
from ..lib.place import Place
from ..lib.repo import Repository
from ..lib.mediaobj import MediaObject
from ..lib.note import Note
from ..lib.tag import Tag
from ..lib.genderstats import GenderStats
from ..lib.researcher import Researcher
from . import (DbBsddbRead, DbWriteBase, BSDDBTxn,
DbTxn, BsddbBaseCursor, BsddbDowngradeError, DbVersionError,
DbEnvironmentError, DbUpgradeRequiredError, find_surname,
find_byte_surname, find_surname_name, DbUndoBSDDB as DbUndo,
exceptions)
from .dbconst import *
from ..utils.callback import Callback
from ..utils.cast import conv_dbstr_to_unicode
from ..updatecallback import UpdateCallback
from ..errors import DbError
from ..constfunc import (win, conv_to_unicode, cuni, UNITYPE, handle2internal,
get_env_var)
from ..const import HOME_DIR, GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
_LOG = logging.getLogger(DBLOGNAME)
LOG = logging.getLogger(".citation")
#_LOG.setLevel(logging.DEBUG)
#_hdlr = logging.StreamHandler()
#_hdlr.setFormatter(logging.Formatter(fmt="%(name)s.%(levelname)s: %(message)s"))
#_LOG.addHandler(_hdlr)
_MINVERSION = 9
_DBVERSION = 16
IDTRANS = "person_id"
FIDTRANS = "family_id"
PIDTRANS = "place_id"
OIDTRANS = "media_id"
EIDTRANS = "event_id"
RIDTRANS = "repo_id"
NIDTRANS = "note_id"
SIDTRANS = "source_id"
CIDTRANS = "citation_id"
TAGTRANS = "tag_name"
SURNAMES = "surnames"
NAME_GROUP = "name_group"
META = "meta_data"
FAMILY_TBL = "family"
PLACES_TBL = "place"
SOURCES_TBL = "source"
CITATIONS_TBL = "citation"
MEDIA_TBL = "media"
EVENTS_TBL = "event"
PERSON_TBL = "person"
REPO_TBL = "repo"
NOTE_TBL = "note"
TAG_TBL = "tag"
REF_MAP = "reference_map"
REF_PRI = "primary_map"
REF_REF = "referenced_map"
DBERRS = (db.DBRunRecoveryError, db.DBAccessError,
db.DBPageNotFoundError, db.DBInvalidArgError)
# The following two dictionaries provide fast translation
# between the primary class names and the keys used to reference
# these classes in the database tables. Beware that changing
# these maps or modifying the values of the keys will break
# existing databases.
CLASS_TO_KEY_MAP = {Person.__name__: PERSON_KEY,
Family.__name__: FAMILY_KEY,
Source.__name__: SOURCE_KEY,
Citation.__name__: CITATION_KEY,
Event.__name__: EVENT_KEY,
MediaObject.__name__: MEDIA_KEY,
Place.__name__: PLACE_KEY,
Repository.__name__:REPOSITORY_KEY,
Note.__name__: NOTE_KEY,
Tag.__name__: TAG_KEY}
KEY_TO_CLASS_MAP = {PERSON_KEY: Person.__name__,
FAMILY_KEY: Family.__name__,
SOURCE_KEY: Source.__name__,
CITATION_KEY: Citation.__name__,
EVENT_KEY: Event.__name__,
MEDIA_KEY: MediaObject.__name__,
PLACE_KEY: Place.__name__,
REPOSITORY_KEY: Repository.__name__,
NOTE_KEY: Note.__name__,
TAG_KEY: Tag.__name__}
KEY_TO_NAME_MAP = {PERSON_KEY: 'person',
FAMILY_KEY: 'family',
EVENT_KEY: 'event',
SOURCE_KEY: 'source',
CITATION_KEY: 'citation',
PLACE_KEY: 'place',
MEDIA_KEY: 'media',
REPOSITORY_KEY: 'repository',
#REFERENCE_KEY: 'reference',
NOTE_KEY: 'note',
TAG_KEY: 'tag'}
#-------------------------------------------------------------------------
#
# Helper functions
#
#-------------------------------------------------------------------------
def find_idmap(key, data):
""" return id for association of secondary index.
returns a byte string
"""
val = data[1]
if isinstance(val, UNITYPE):
val = val.encode('utf-8')
return val
# Secondary database key lookups for reference_map table
# reference_map data values are of the form:
# ((primary_object_class_name, primary_object_handle),
# (referenced_object_class_name, referenced_object_handle))
def find_primary_handle(key, data):
""" return handle for association of indexes
returns byte string
"""
val = (data)[0][1]
if isinstance(val, UNITYPE):
val = val.encode('utf-8')
return val
def find_referenced_handle(key, data):
""" return handle for association of indexes
returns byte string
"""
val = (data)[1][1]
if isinstance(val, UNITYPE):
val = val.encode('utf-8')
return val
def _encode(path):
"""
Conditionally return the unicode string encoded to sys.filesystem.encoding
"""
if not (isinstance(path, UNITYPE) and sys.version_info[0] < 3):
_LOG.debug("Didn't Encode %s", repr(path))
return path
_LOG.debug("Encoding %s", repr(path))
return path.encode(sys.getfilesystemencoding())
#-------------------------------------------------------------------------
#
# BsddbWriteCursor
#
#-------------------------------------------------------------------------
class BsddbWriteCursor(BsddbBaseCursor):
def __init__(self, source, txn=None, **kwargs):
BsddbBaseCursor.__init__(self, txn=txn, **kwargs)
self.cursor = source.db.cursor(txn)
self.source = source
#-------------------------------------------------------------------------
#
# DbBsddbAssocCursor
#
#-------------------------------------------------------------------------
class DbBsddbAssocCursor(BsddbBaseCursor):
def __init__(self, source, txn=None, **kwargs):
BsddbBaseCursor.__init__(self, txn=txn, **kwargs)
self.cursor = source.cursor(txn)
self.source = source
#-------------------------------------------------------------------------
#
# DbBsddb
#
#-------------------------------------------------------------------------
class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
"""
GRAMPS database write access object.
"""
# Set up dictionary for callback signal handler
# ---------------------------------------------
# 1. Signals for primary objects
__signals__ = dict((obj+'-'+op, signal)
for obj in
['person', 'family', 'event', 'place',
'source', 'citation', 'media', 'note', 'repository', '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
if sys.version_info[0] < 3:
__signals__['person-groupname-rebuild'] = (unicode, unicode)
else:
__signals__['person-groupname-rebuild'] = (str, str)
def __init__(self):
"""Create a new GrampsDB."""
self.txn = None
DbBsddbRead.__init__(self)
DbWriteBase.__init__(self)
#UpdateCallback.__init__(self)
self.secondary_connected = False
self.has_changed = False
self.brief_name = None
self.update_env_version = False
self.update_python_version = False
def catch_db_error(func):
"""
Decorator function for catching database errors. If *func* throws
one of the exceptions in DBERRS, the error is logged and a DbError
exception is raised.
"""
@wraps(func)
def try_(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except DBERRS as msg:
self.__log_error()
raise DbError(msg)
return try_
def __open_db(self, file_name, table_name, dbtype=db.DB_HASH, flags=0):
dbmap = db.DB(self.env)
dbmap.set_flags(flags)
fname = os.path.join(file_name, table_name + DBEXT)
if self.readonly:
dbmap.open(fname, table_name, dbtype, DBFLAGS_R)
else:
dbmap.open(fname, table_name, dbtype, DBFLAGS_O, DBMODE)
return dbmap
def __open_shelf(self, file_name, table_name, dbtype=db.DB_HASH):
dbmap = dbshelve.DBShelf(self.env)
fname = os.path.join(file_name, table_name + DBEXT)
if self.readonly:
dbmap.open(fname, table_name, dbtype, DBFLAGS_R)
else:
dbmap.open(fname, table_name, dbtype, DBFLAGS_O, DBMODE)
return dbmap
def __all_handles(self, table):
return table.keys(self.txn)
def __log_error(self):
mypath = os.path.join(self.get_save_path(),DBRECOVFN)
ofile = open(mypath, "w")
ofile.close()
try:
clear_lock_file(self.get_save_path())
except:
pass
_log_error = __log_error
# Override get_cursor method from the superclass to add udpate
# capability
@catch_db_error
def get_cursor(self, table, txn=None, update=False, commit=False):
""" Helper function to return a cursor over a table """
if update and not txn:
txn = self.env.txn_begin(self.txn)
return BsddbWriteCursor(table, txn=txn or self.txn,
update=update, commit=commit)
# cursors for lookups in the reference_map for back reference
# lookups. The reference_map has three indexes:
# the main index: a tuple of (primary_handle, referenced_handle)
# the primary_handle index: the primary_handle
# the referenced_handle index: the referenced_handle
# the main index is unique, the others allow duplicate entries.
@catch_db_error
def get_reference_map_cursor(self):
"""
Returns a reference to a cursor over the reference map
"""
return DbBsddbAssocCursor(self.reference_map, self.txn)
@catch_db_error
def get_reference_map_primary_cursor(self):
"""
Returns a reference to a cursor over the reference map primary map
"""
return DbBsddbAssocCursor(self.reference_map_primary_map,
self.txn)
@catch_db_error
def get_reference_map_referenced_cursor(self):
"""
Returns a reference to a cursor over the reference map referenced map
"""
return DbBsddbAssocCursor(self.reference_map_referenced_map,
self.txn)
# These are overriding the DbBsddbRead's methods of saving metadata
# because we now have txn-capable metadata table
@catch_db_error
def set_default_person_handle(self, handle):
"""Set the default Person to the passed instance."""
#we store a byte string!
if isinstance(handle, UNITYPE):
handle = handle.encode('utf-8')
if not self.readonly:
# Start transaction
with BSDDBTxn(self.env, self.metadata) as txn:
txn.put(b'default', handle)
self.emit('home-person-changed')
@catch_db_error
def get_default_person(self):
"""Return the default Person of the database."""
person = self.get_person_from_handle(self.get_default_handle())
if person:
return person
elif (self.metadata) and (not self.readonly):
# Start transaction
with BSDDBTxn(self.env, self.metadata) as txn:
txn.put(b'default', None)
return None
def set_mediapath(self, path):
"""Set the default media path for database, path should be utf-8."""
if self.metadata and not self.readonly:
# Start transaction
with BSDDBTxn(self.env, self.metadata) as txn:
txn.put(b'mediapath', path)
def __make_zip_backup(self, dirname):
import zipfile
title = self.get_dbname()
if not os.access(dirname, os.W_OK):
_LOG.warning("Can't write technical DB backup for %s" % title)
return
(grampsdb_path, db_code) = os.path.split(dirname)
dotgramps_path = os.path.dirname(grampsdb_path)
zipname = title + time.strftime("_%Y-%m-%d_%H-%M-%S") + ".zip"
zippath = os.path.join(dotgramps_path, zipname)
myzip = zipfile.ZipFile(zippath, 'w')
for filename in os.listdir(dirname):
pathname = os.path.join(dirname, filename)
myzip.write(pathname, os.path.join(db_code, filename))
myzip.close()
_LOG.warning("If upgrade and loading the Family Tree works, you can "
"delete the zip file at %s" %
zippath)
def __check_bdb_version(self, name, force_bsddb_upgrade=False,
force_bsddb_downgrade=False):
"""Older version of Berkeley DB can't read data created by a newer
version."""
bdb_version = db.version()
versionpath = os.path.join(self.path, cuni(BDBVERSFN))
# Compare the current version of the database (bsddb_version) with the
# version of the database code (env_version). If it is a downgrade,
# raise an exception because we can't do anything. If they are the same,
# return. If it is an upgrade, raise an exception unless the user has
# already told us we can upgrade.
if os.path.isfile(versionpath):
with open(versionpath, "r") as version_file:
bsddb_version = version_file.read().strip()
env_version = tuple(map(int, bsddb_version[1:-1].split(', ')))
else:
# bsddb version is unknown
bsddb_version = "Unknown"
env_version = "Unknown"
# _LOG.debug("db version %s, program version %s" % (bsddb_version, bdb_version))
if env_version == "Unknown" or \
(env_version[0] < bdb_version[0]) or \
(env_version[0] == bdb_version[0] and
env_version[1] < bdb_version[1]) or \
(env_version[0] == bdb_version[0] and
env_version[1] == bdb_version[1] and
env_version[2] < bdb_version[2]):
# an upgrade is needed
if not force_bsddb_upgrade:
_LOG.debug("Bsddb upgrade required from %s to %s" %
(bsddb_version, str(bdb_version)))
clear_lock_file(name)
raise exceptions.BsddbUpgradeRequiredError(bsddb_version,
str(bdb_version))
if not self.readonly:
_LOG.warning("Bsddb upgrade requested from %s to %s" %
(bsddb_version, str(bdb_version)))
self.update_env_version = True
# Make a backup of the database files anyway
self.__make_zip_backup(name)
elif (env_version[0] > bdb_version[0]) or \
(env_version[0] == bdb_version[0] and
env_version[1] > bdb_version[1]):
clear_lock_file(name)
raise BsddbDowngradeError(env_version, bdb_version)
elif (env_version[0] == bdb_version[0] and
env_version[1] == bdb_version[1] and
env_version[2] > bdb_version[2]):
# A down-grade may be possible
if not force_bsddb_downgrade:
_LOG.debug("Bsddb downgrade required from %s to %s" %
(bsddb_version, str(bdb_version)))
clear_lock_file(name)
raise exceptions.BsddbDowngradeRequiredError(bsddb_version,
str(bdb_version))
# Try to do a down-grade
if not self.readonly:
_LOG.warning("Bsddb downgrade requested from %s to %s" %
(bsddb_version, str(bdb_version)))
self.update_env_version = True
# Make a backup of the database files anyway
self.__make_zip_backup(name)
elif env_version == bdb_version:
# Bsddb version is OK
pass
else:
# This can't happen
raise "Comparison between Bsddb version failed"
def __check_python_version(self, name, force_python_upgrade=False):
"""
The 'pickle' format (may) change with each Python version, see
http://docs.python.org/3.2/library/pickle.html#pickle. Code commits
21777 and 21778 ensure that when going from python2 to python3, the old
format can be read. However, once the data has been written in the
python3 format, it will not be possible to go back to pyton2. This check
test whether we are changing python versions. If going from 2 to 3 it
warns the user, and allows it if he confirms. When going from 3 to 3, an
error is raised. Because code for python2 did not write the Python
version file, if the file is absent, python2 is assumed.
"""
current_python_version = version_info[0]
versionpath = os.path.join(self.path, "pythonversion.txt")
if os.path.isfile(versionpath):
with open(versionpath, "r") as version_file:
db_python_version = int(version_file.read().strip())
else:
db_python_version = 2
if db_python_version == 3 and current_python_version == 2:
clear_lock_file(name)
raise exceptions.PythonDowngradeError(db_python_version,
current_python_version)
elif db_python_version == 2 and current_python_version > 2:
if not force_python_upgrade:
_LOG.debug("Python upgrade required from %s to %s" %
(db_python_version, current_python_version))
clear_lock_file(name)
raise exceptions.PythonUpgradeRequiredError(db_python_version,
current_python_version)
# Try to do an upgrade
if not self.readonly:
_LOG.warning("Python upgrade requested from %s to %s" %
(db_python_version, current_python_version))
self.update_python_version = True
# Make a backup of the database files anyway
self.__make_zip_backup(name)
elif db_python_version == 2 and current_python_version == 2:
pass
@catch_db_error
def version_supported(self):
dbversion = self.metadata.get(b'version', default=0)
return ((dbversion <= _DBVERSION) and (dbversion >= _MINVERSION))
@catch_db_error
def need_schema_upgrade(self):
dbversion = self.metadata.get(b'version', default=0)
return not self.readonly and dbversion < _DBVERSION
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)
"""
# 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 any files in the directory
for base in [FAMILY_TBL, PLACES_TBL, SOURCES_TBL, CITATIONS_TBL,
MEDIA_TBL, EVENTS_TBL, PERSON_TBL, REPO_TBL,
NOTE_TBL, REF_MAP, META]:
path = os.path.join(name, base + DBEXT)
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
@catch_db_error
def load(self, name, callback, mode=DBMODE_W, force_schema_upgrade=False,
force_bsddb_upgrade=False, force_bsddb_downgrade=False,
force_python_upgrade=False):
if self.__check_readonly(name):
mode = DBMODE_R
else:
write_lock_file(name)
if self.db_is_open:
self.close()
self.readonly = mode == DBMODE_R
#super(DbBsddbRead, self).load(name, callback, mode)
if callback:
callback(12)
# Save full path and base file name
self.full_name = os.path.abspath(name)
self.path = self.full_name
self.brief_name = os.path.basename(name)
# If we re-enter load with force_python_upgrade True, then we have
# already checked the bsddb version, and then checked python version,
# and are agreeing on the upgrade
if not force_python_upgrade:
self.__check_bdb_version(name, force_bsddb_upgrade,
force_bsddb_downgrade)
self.__check_python_version(name, force_python_upgrade)
# Set up database environment
self.env = db.DBEnv()
self.env.set_cachesize(0, DBCACHE)
# These env settings are only needed for Txn environment
self.env.set_lk_max_locks(DBLOCKS)
self.env.set_lk_max_objects(DBOBJECTS)
# Set to auto remove stale logs
self.set_auto_remove()
# Set not to flush to disk synchronous, this greatly speeds up
# database changes, but comes at the cause of loss of durability, so
# power loss might cause a need to run db recovery, see BSDDB manual
## NOTE: due to pre 4.8 bsddb bug it is needed to set this flag before
## open of env, #16492 - http://download.oracle.com/docs/cd/E17076_02/html/installation/changelog_4_8.html
self.env.set_flags(db.DB_TXN_WRITE_NOSYNC, 1)
# The DB_PRIVATE flag must go if we ever move to multi-user setup
env_flags = db.DB_CREATE | db.DB_PRIVATE |\
db.DB_INIT_MPOOL |\
db.DB_INIT_LOG | db.DB_INIT_TXN
# As opposed to before, we always try recovery on databases
env_flags |= db.DB_RECOVER
# Environment name is now based on the filename
env_name = name
try:
self.env.open(env_name, env_flags)
except Exception as msg:
_LOG.warning("Error opening db environment: " + str(msg))
try:
self.__close_early()
except:
pass
raise DbEnvironmentError(msg)
self.env.txn_checkpoint()
if callback:
callback(25)
# Process metadata
self.metadata = self.__open_shelf(self.full_name, META)
# If we cannot work with this DB version,
# it makes no sense to go further
if not self.version_supported():
tree_vers = self.metadata.get(b'version', default=0)
self.__close_early()
raise DbVersionError(tree_vers, _MINVERSION, _DBVERSION)
self.__load_metadata()
gstats = self.metadata.get(b'gender_stats', default=None)
# Ensure version info in metadata
if not self.readonly:
# Start transaction
with BSDDBTxn(self.env, self.metadata) as txn:
if gstats is None:
# New database. Set up the current version.
#self.metadata.put(b'version', _DBVERSION, txn=the_txn)
txn.put(b'version', _DBVERSION)
elif b'version' not in self.metadata:
# Not new database, but the version is missing.
# Use 0, but it is likely to fail anyway.
txn.put(b'version', 0)
self.genderStats = GenderStats(gstats)
# Open main tables in gramps database
db_maps = [
("family_map", FAMILY_TBL, db.DB_HASH),
("place_map", PLACES_TBL, db.DB_HASH),
("source_map", SOURCES_TBL, db.DB_HASH),
("citation_map", CITATIONS_TBL, db.DB_HASH),
("media_map", MEDIA_TBL, db.DB_HASH),
("event_map", EVENTS_TBL, db.DB_HASH),
("person_map", PERSON_TBL, db.DB_HASH),
("repository_map", REPO_TBL, db.DB_HASH),
("note_map", NOTE_TBL, db.DB_HASH),
("tag_map", TAG_TBL, db.DB_HASH),
("reference_map", REF_MAP, db.DB_BTREE),
]
dbflags = DBFLAGS_R if self.readonly else DBFLAGS_O
for (dbmap, dbname, dbtype) in db_maps:
_db = self.__open_shelf(self.full_name, dbname, dbtype)
setattr(self, dbmap, _db)
if callback:
callback(37)
# Open name grouping database
self.name_group = self.__open_db(self.full_name, NAME_GROUP,
db.DB_HASH, db.DB_DUP)
# We have now successfully opened the database, so if the BSDDB version
# has changed, we update the DBSDB version file.
if self.update_env_version:
versionpath = os.path.join(name, BDBVERSFN)
with open(versionpath, "w") as version_file:
version = str(db.version())
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
version_file.write(version)
_LOG.debug("Updated BDBVERSFN file to %s" % str(db.version()))
if self.update_python_version:
versionpath = os.path.join(name, "pythonversion.txt")
version = str(version_info[0])
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
_LOG.debug("Updated python version file to %s" % version)
with open(versionpath, "w") as version_file:
version_file.write(version)
# Here we take care of any changes in the tables related to new code.
# If secondary indices change, then they should removed
# or rebuilt by upgrade as well. In any case, the
# self.secondary_connected flag should be set accordingly.
if self.need_schema_upgrade():
oldschema = self.metadata.get(b'version', default=0)
newschema = _DBVERSION
_LOG.debug("Schema upgrade required from %s to %s" %
(oldschema, newschema))
if force_schema_upgrade == True:
self.gramps_upgrade(callback)
else:
self.__close_early()
clear_lock_file(name)
raise DbUpgradeRequiredError(oldschema, newschema)
if callback:
callback(50)
# Connect secondary indices
if not self.secondary_connected:
self.__connect_secondary()
if callback:
callback(75)
# Open undo database
self.__open_undodb()
self.db_is_open = True
if callback:
callback(87)
self.abort_possible = True
return 1
def __open_undodb(self):
"""
Open the undo database
"""
if not self.readonly:
self.undolog = os.path.join(self.full_name, DBUNDOFN)
self.undodb = DbUndo(self, self.undolog)
self.undodb.open()
def __close_undodb(self):
if not self.readonly:
try:
self.undodb.close()
except db.DBNoSuchFileError:
pass
def get_undodb(self):
"""
Return the database that keeps track of Undo/Redo operations.
"""
return self.undodb
def __load_metadata(self):
# name display formats
self.name_formats = self.metadata.get(b'name_formats', default=[])
# upgrade formats if they were saved in the old way
for format_ix in range(len(self.name_formats)):
format = self.name_formats[format_ix]
if len(format) == 3:
format = format + (True,)
self.name_formats[format_ix] = format
# database owner
try:
owner_data = self.metadata.get(b'researcher')
if owner_data:
if len(owner_data[0]) == 7: # Pre-3.3 format
owner_data = upgrade_researcher(owner_data)
self.owner.unserialize(owner_data)
except ImportError: #handle problems with pre-alpha 3.0
pass
# bookmarks
def meta(key):
try:
return self.metadata.get(key, default=[])
except UnicodeDecodeError:
#we need to assume we opened data in python3 saved in python2
raw = self.metadata.db.get(key, default=[])
return pickle.loads(raw, encoding='utf-8') if raw else raw
self.bookmarks.set(meta(b'bookmarks'))
self.family_bookmarks.set(meta(b'family_bookmarks'))
self.event_bookmarks.set(meta(b'event_bookmarks'))
self.source_bookmarks.set(meta(b'source_bookmarks'))
self.citation_bookmarks.set(meta(b'citation_bookmarks'))
self.repo_bookmarks.set(meta(b'repo_bookmarks'))
self.media_bookmarks.set(meta(b'media_bookmarks'))
self.place_bookmarks.set(meta(b'place_bookmarks'))
self.note_bookmarks.set(meta(b'note_bookmarks'))
# Custom type values
self.family_event_names = set(meta(b'fevent_names'))
self.individual_event_names = set(meta(b'pevent_names'))
self.family_attributes = set(meta(b'fattr_names'))
self.individual_attributes = set(meta(b'pattr_names'))
self.marker_names = set(meta(b'marker_names'))
self.child_ref_types = set(meta(b'child_refs'))
self.family_rel_types = set(meta(b'family_rels'))
self.event_role_names = set(meta(b'event_roles'))
self.name_types = set(meta(b'name_types'))
self.origin_types = set(meta(b'origin_types'))
self.repository_types = set(meta(b'repo_types'))
self.note_types = set(meta(b'note_types'))
self.source_media_types = set(meta(b'sm_types'))
self.url_types = set(meta(b'url_types'))
self.media_attributes = set(meta(b'mattr_names'))
# surname list
self.surname_list = meta(b'surname_list')
def __connect_secondary(self):
"""
Connect or creates secondary index tables.
It assumes that the tables either exist and are in the right
format or do not exist (in which case they get created).
It is the responsibility of upgrade code to either create
or remove invalid secondary index tables.
"""
# index tables used just for speeding up searches
self.surnames = self.__open_db(self.full_name, SURNAMES, db.DB_BTREE,
db.DB_DUP | db.DB_DUPSORT)
db_maps = [
("id_trans", IDTRANS, db.DB_HASH, 0),
("fid_trans", FIDTRANS, db.DB_HASH, 0),
("eid_trans", EIDTRANS, db.DB_HASH, 0),
("pid_trans", PIDTRANS, db.DB_HASH, 0),
("sid_trans", SIDTRANS, db.DB_HASH, 0),
("cid_trans", CIDTRANS, db.DB_HASH, 0),
("oid_trans", OIDTRANS, db.DB_HASH, 0),
("rid_trans", RIDTRANS, db.DB_HASH, 0),
("nid_trans", NIDTRANS, db.DB_HASH, 0),
("tag_trans", TAGTRANS, db.DB_HASH, 0),
("reference_map_primary_map", REF_PRI, db.DB_BTREE, 0),
("reference_map_referenced_map", REF_REF, db.DB_BTREE, db.DB_DUPSORT),
]
for (dbmap, dbname, dbtype, dbflags) in db_maps:
_db = self.__open_db(self.full_name, dbname, dbtype,
db.DB_DUP | dbflags)
setattr(self, dbmap, _db)
if not self.readonly:
assoc = [
(self.person_map, self.surnames, find_byte_surname),
(self.person_map, self.id_trans, find_idmap),
(self.family_map, self.fid_trans, find_idmap),
(self.event_map, self.eid_trans, find_idmap),
(self.place_map, self.pid_trans, find_idmap),
(self.source_map, self.sid_trans, find_idmap),
(self.citation_map, self.cid_trans, find_idmap),
(self.media_map, self.oid_trans, find_idmap),
(self.repository_map, self.rid_trans, find_idmap),
(self.note_map, self.nid_trans, find_idmap),
(self.tag_map, self.tag_trans, find_idmap),
(self.reference_map, self.reference_map_primary_map,
find_primary_handle),
(self.reference_map, self.reference_map_referenced_map,
find_referenced_handle),
]
flags = DBFLAGS_R if self.readonly else DBFLAGS_O
for (dbmap, a_map, a_find) in assoc:
dbmap.associate(a_map, a_find, flags=flags)
self.secondary_connected = True
self.smap_index = len(self.source_map)
self.cmap_index = len(self.citation_map)
self.emap_index = len(self.event_map)
self.pmap_index = len(self.person_map)
self.fmap_index = len(self.family_map)
self.lmap_index = len(self.place_map)
self.omap_index = len(self.media_map)
self.rmap_index = len(self.repository_map)
self.nmap_index = len(self.note_map)
@catch_db_error
def rebuild_secondary(self, callback=None):
if self.readonly:
return
table_flags = DBFLAGS_O
# remove existing secondary indices
items = [
( self.id_trans, IDTRANS ),
( self.surnames, SURNAMES ),
( self.fid_trans, FIDTRANS ),
( self.pid_trans, PIDTRANS ),
( self.oid_trans, OIDTRANS ),
( self.eid_trans, EIDTRANS ),
( self.rid_trans, RIDTRANS ),
( self.nid_trans, NIDTRANS ),
( self.cid_trans, CIDTRANS ),
( self.tag_trans, TAGTRANS ),
( self.reference_map_primary_map, REF_PRI),
( self.reference_map_referenced_map, REF_REF),
]
index = 1
for (database, name) in items:
database.close()
_db = db.DB(self.env)
try:
_db.remove(_mkname(self.full_name, name), name)
except db.DBNoSuchFileError:
pass
if callback:
callback(index)
index += 1
if callback:
callback(11)
# Set flag saying that we have removed secondary indices
# and then call the creating routine
self.secondary_connected = False
self.__connect_secondary()
if callback:
callback(12)
@catch_db_error
def find_backlink_handles(self, handle, include_classes=None):
"""
Find all objects that hold a reference to the object handle.
Returns an interator over a list of (class_name, handle) tuples.
:param handle: handle of the object to search for.
:type handle: database handle
:param include_classes: list of class names to include in the results.
Default: None means include all classes.
:type include_classes: list of class names
Note that this is a generator function, it returns a iterator for
use in loops. If you want a list of the results use::
result_list = list(find_backlink_handles(handle))
"""
if isinstance(handle, UNITYPE):
handle = handle.encode('utf-8')
# Use the secondary index to locate all the reference_map entries
# that include a reference to the object we are looking for.
referenced_cur = self.get_reference_map_referenced_cursor()
try:
ret = referenced_cur.set(handle)
except:
ret = None
while (ret is not None):
(key, data) = ret
# data values are of the form:
# ((primary_object_class_name, primary_object_handle),
# (referenced_object_class_name, referenced_object_handle))
# so we need the first tuple to give us the type to compare
### FIXME: this is a dirty hack that works without no
### sensible explanation. For some reason, for a readonly
### database, secondary index returns a primary table key
### corresponding to the data, not the data.
if self.readonly:
data = self.reference_map.get(data)
else:
data = pickle.loads(data)
key, handle = data[0][:2]
name = KEY_TO_CLASS_MAP[key]
assert name == KEY_TO_CLASS_MAP[data[0][0]]
assert handle == data[0][1]
if (include_classes is None or
name in include_classes):
yield (name, handle)
ret = referenced_cur.next_dup()
referenced_cur.close()
def delete_primary_from_reference_map(self, handle, transaction, txn=None):
"""
Remove all references to the primary object from the reference_map.
handle should be utf-8
"""
primary_cur = self.get_reference_map_primary_cursor()
try:
ret = primary_cur.set(handle)
except:
ret = None
remove_list = set()
while (ret is not None):
(key, data) = ret
# data values are of the form:
# ((primary_object_class_name, primary_object_handle),
# (referenced_object_class_name, referenced_object_handle))
# so we need the second tuple give us a reference that we can
# combine with the primary_handle to get the main key.
if sys.version_info[0] < 3:
#handle should be in python 2 str
main_key = (handle, pickle.loads(data)[1][1])
else:
#python 3 work internally with unicode
main_key = (handle.decode('utf-8'), pickle.loads(data)[1][1])
# The trick is not to remove while inside the cursor,
# but collect them all and remove after the cursor is closed
remove_list.add(main_key)
ret = primary_cur.next_dup()
primary_cur.close()
# Now that the cursor is closed, we can remove things
for main_key in remove_list:
self.__remove_reference(main_key, transaction, txn)
def update_reference_map(self, obj, transaction, txn=None):
"""
If txn is given, then changes are written right away using txn.
"""
# Add references to the reference_map for all primary object referenced
# from the primary object 'obj' or any of its secondary objects.
handle = obj.handle
existing_references = set()
primary_cur = self.get_reference_map_primary_cursor()
try:
ret = primary_cur.set(handle)
except:
ret = None
while (ret is not None):
(key, data) = ret
# data values are of the form:
# ((primary_object_class_name, primary_object_handle),
# (referenced_object_class_name, referenced_object_handle))
# so we need the second tuple give us a reference that we can
# compare with what is returned from
# get_referenced_handles_recursively
# secondary DBs are not DBShelf's, so we need to do pickling
# and unpickling ourselves here
existing_reference = pickle.loads(data)[1]
existing_references.add((KEY_TO_CLASS_MAP[existing_reference[0]],
existing_reference[1]))
ret = primary_cur.next_dup()
primary_cur.close()
# Once we have the list of rows that already have a reference
# we need to compare it with the list of objects that are
# still references from the primary object.
current_references = set(obj.get_referenced_handles_recursively())
no_longer_required_references = existing_references.difference(
current_references)
new_references = current_references.difference(existing_references)
# handle addition of new references
for (ref_class_name, ref_handle) in new_references:
data = ((CLASS_TO_KEY_MAP[obj.__class__.__name__], handle),
(CLASS_TO_KEY_MAP[ref_class_name], ref_handle),)
self.__add_reference((handle, ref_handle), data, transaction, txn)
# handle deletion of old references
for (ref_class_name, ref_handle) in no_longer_required_references:
try:
self.__remove_reference((handle, ref_handle), transaction, txn)
except:
# ignore missing old reference
pass
def __remove_reference(self, key, transaction, txn):
"""
Remove the reference specified by the key, preserving the change in
the passed transaction.
"""
if isinstance(key, tuple):
#create a byte string key, first validity check in python 3!
for val in key:
if sys.version_info[0] >= 3 and isinstance(val, bytes):
raise DbError(_('An attempt is made to safe a reference key '
'which is partly bytecode, this is not allowed.\n'
'Key is %s') % str(key))
if sys.version_info[0] >= 3:
key= str(key)
else:
key = str(tuple(k.encode('utf-8') for k in key))
if isinstance(key, UNITYPE):
key = key.encode('utf-8')
if not self.readonly:
if not transaction.batch:
old_data = self.reference_map.get(key, txn=txn)
transaction.add(REFERENCE_KEY, TXNDEL, key, old_data, None)
self.reference_map.delete(key, txn=txn)
def __add_reference(self, key, data, transaction, txn):
"""
Add the reference specified by the key and the data, preserving the
change in the passed transaction.
"""
if isinstance(key, tuple):
#create a string key
key = str(key)
if isinstance(key, UNITYPE):
key = key.encode('utf-8')
if self.readonly or not key:
return
self.reference_map.put(key, data, txn=txn)
if not transaction.batch:
transaction.add(REFERENCE_KEY, TXNADD, key, None, data)
#transaction.reference_add.append((str(key), data))
@catch_db_error
def reindex_reference_map(self, callback):
"""
Reindex all primary records in the database.
This will be a slow process for large databases.
"""
# First, remove the reference map and related tables
db_maps = [
("reference_map_referenced_map", REF_REF),
("reference_map_primary_map", REF_PRI),
("reference_map", REF_MAP),
]
for index, (dbmap, dbname) in enumerate(db_maps):
getattr(self, dbmap).close()
_db = db.DB(self.env)
try:
_db.remove(_mkname(self.full_name, dbname), dbname)
except db.DBNoSuchFileError:
pass
callback(index+1)
# Open reference_map and primary map
self.reference_map = self.__open_shelf(self.full_name, REF_MAP,
dbtype=db.DB_BTREE)
self.reference_map_primary_map = self.__open_db(self.full_name,
REF_PRI, db.DB_BTREE, db.DB_DUP)
self.reference_map.associate(self.reference_map_primary_map,
find_primary_handle, DBFLAGS_O)
# Make a tuple of the functions and classes that we need for
# each of the primary object tables.
with DbTxn(_("Rebuild reference map"), self, batch=True,
no_magic=True) as transaction:
callback(4)
primary_table = (
(self.get_person_cursor, Person),
(self.get_family_cursor, Family),
(self.get_event_cursor, Event),
(self.get_place_cursor, Place),
(self.get_source_cursor, Source),
(self.get_citation_cursor, Citation),
(self.get_media_cursor, MediaObject),
(self.get_repository_cursor, Repository),
(self.get_note_cursor, Note),
(self.get_tag_cursor, Tag),
)
# Now we use the functions and classes defined above
# to loop through each of the primary object tables.
for cursor_func, class_func in primary_table:
logging.info("Rebuilding %s reference map" %
class_func.__name__)
with cursor_func() as cursor:
for found_handle, val in cursor:
obj = class_func()
obj.unserialize(val)
with BSDDBTxn(self.env) as txn:
self.update_reference_map(obj, transaction, txn.txn)
callback(5)
self.reference_map_referenced_map = self.__open_db(self.full_name,
REF_REF, db.DB_BTREE, db.DB_DUP|db.DB_DUPSORT)
flags = DBFLAGS_R if self.readonly else DBFLAGS_O
self.reference_map.associate(self.reference_map_referenced_map,
find_referenced_handle, flags=flags)
callback(6)
def __close_metadata(self):
if not self.readonly:
# Start transaction
with BSDDBTxn(self.env, self.metadata) as txn:
# name display formats
txn.put(b'name_formats', self.name_formats)
# database owner
owner_data = self.owner.serialize()
txn.put(b'researcher', owner_data)
# bookmarks
txn.put(b'bookmarks', self.bookmarks.get())
txn.put(b'family_bookmarks', self.family_bookmarks.get())
txn.put(b'event_bookmarks', self.event_bookmarks.get())
txn.put(b'source_bookmarks', self.source_bookmarks.get())
txn.put(b'citation_bookmarks', self.citation_bookmarks.get())
txn.put(b'place_bookmarks', self.place_bookmarks.get())
txn.put(b'repo_bookmarks', self.repo_bookmarks.get())
txn.put(b'media_bookmarks', self.media_bookmarks.get())
txn.put(b'note_bookmarks', self.note_bookmarks.get())
# gender stats
txn.put(b'gender_stats', self.genderStats.save_stats())
# Custom type values
txn.put(b'fevent_names', list(self.family_event_names))
txn.put(b'pevent_names', list(self.individual_event_names))
txn.put(b'fattr_names', list(self.family_attributes))
txn.put(b'pattr_names', list(self.individual_attributes))
txn.put(b'marker_names', list(self.marker_names))
txn.put(b'child_refs', list(self.child_ref_types))
txn.put(b'family_rels', list(self.family_rel_types))
txn.put(b'event_roles', list(self.event_role_names))
txn.put(b'name_types', list(self.name_types))
txn.put(b'origin_types', list(self.origin_types))
txn.put(b'repo_types', list(self.repository_types))
txn.put(b'note_types', list(self.note_types))
txn.put(b'sm_types', list(self.source_media_types))
txn.put(b'url_types', list(self.url_types))
txn.put(b'mattr_names', list(self.media_attributes))
# name display formats
txn.put(b'surname_list', self.surname_list)
self.metadata.close()
def __close_early(self):
"""
Bail out if the incompatible version is discovered:
* close cleanly to not damage data/env
"""
if hasattr(self, 'metadata') and self.metadata:
self.metadata.close()
self.env.close()
self.metadata = None
self.env = None
self.db_is_open = False
@catch_db_error
def close(self):
if not self.db_is_open:
return
if self.txn:
self.transaction_abort(self.transaction)
self.env.txn_checkpoint()
self.__close_metadata()
self.name_group.close()
self.surnames.close()
self.id_trans.close()
self.fid_trans.close()
self.eid_trans.close()
self.rid_trans.close()
self.nid_trans.close()
self.oid_trans.close()
self.sid_trans.close()
self.cid_trans.close()
self.pid_trans.close()
self.tag_trans.close()
self.reference_map_primary_map.close()
self.reference_map_referenced_map.close()
self.reference_map.close()
self.secondary_connected = False
# primary databases must be closed after secondary indexes, or
# we run into problems with any active cursors.
self.person_map.close()
self.family_map.close()
self.repository_map.close()
self.note_map.close()
self.place_map.close()
self.source_map.close()
self.citation_map.close()
self.media_map.close()
self.event_map.close()
self.tag_map.close()
self.env.close()
self.__close_undodb()
self.person_map = None
self.family_map = None
self.repository_map = None
self.note_map = None
self.place_map = None
self.source_map = None
self.citation_map = None
self.media_map = None
self.event_map = None
self.tag_map = None
self.surnames = None
self.env = None
self.metadata = None
self.db_is_open = False
self.surname_list = None
DbBsddbRead.close(self)
self.person_map = None
self.family_map = None
self.repository_map = None
self.note_map = None
self.place_map = None
self.source_map = None
self.citation_map = None
self.media_map = None
self.event_map = None
self.tag_map = None
self.reference_map_primary_map = None
self.reference_map_referenced_map = None
self.reference_map = None
self.undo_callback = None
self.redo_callback = None
self.undo_history_callback = None
self.undodb = None
try:
clear_lock_file(self.get_save_path())
except IOError:
pass
def create_id(self):
return "%08x%08x" % ( int(time.time()*10000),
self.rand.randint(0, maxsize))
def __add_object(self, obj, transaction, find_next_func, commit_func):
if find_next_func and not obj.gramps_id:
obj.gramps_id = find_next_func()
if not obj.handle:
obj.handle = self.create_id()
commit_func(obj, transaction)
return obj.handle
def add_person(self, person, transaction, set_gid=True):
"""
Add a Person to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
handle = self.__add_object(person, transaction,
self.find_next_person_gramps_id if set_gid else None,
self.commit_person)
self.genderStats.count_person(person)
return handle
def add_family(self, family, transaction, set_gid=True):
"""
Add a Family to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(family, transaction,
self.find_next_family_gramps_id if set_gid else None,
self.commit_family)
def add_source(self, source, transaction, set_gid=True):
"""
Add a Source to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(source, transaction,
self.find_next_source_gramps_id if set_gid else None,
self.commit_source)
def add_citation(self, citation, transaction, set_gid=True):
"""
Add a Citation to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(citation, transaction,
self.find_next_citation_gramps_id if set_gid else None,
self.commit_citation)
def add_event(self, event, transaction, set_gid=True):
"""
Add an Event to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(event, transaction,
self.find_next_event_gramps_id if set_gid else None,
self.commit_event)
def add_person_event(self, event, transaction):
"""
Add an Event to the database, assigning internal IDs if they have
not already been defined.
"""
if event.type.is_custom():
self.individual_event_names.add(str(event.type))
return self.add_event(event, transaction)
def add_family_event(self, event, transaction):
"""
Add an Event to the database, assigning internal IDs if they have
not already been defined.
"""
if event.type.is_custom():
self.family_event_names.add(str(event.type))
return self.add_event(event, transaction)
def add_place(self, place, transaction, set_gid=True):
"""
Add a Place to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(place, transaction,
self.find_next_place_gramps_id if set_gid else None,
self.commit_place)
def add_object(self, obj, transaction, set_gid=True):
"""
Add a MediaObject to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(obj, transaction,
self.find_next_object_gramps_id if set_gid else None,
self.commit_media_object)
def add_repository(self, obj, transaction, set_gid=True):
"""
Add a Repository to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(obj, transaction,
self.find_next_repository_gramps_id if set_gid else None,
self.commit_repository)
def add_note(self, obj, transaction, set_gid=True):
"""
Add a Note to the database, assigning internal IDs if they have
not already been defined.
If not set_gid, then gramps_id is not set.
"""
return self.__add_object(obj, transaction,
self.find_next_note_gramps_id if set_gid else None,
self.commit_note)
def add_tag(self, obj, transaction):
"""
Add a Tag to the database, assigning a handle if it has not already
been defined.
"""
return self.__add_object(obj, transaction, None, self.commit_tag)
def __do_remove(self, handle, transaction, data_map, key):
if self.readonly or not handle:
return
if isinstance(handle, UNITYPE):
handle = handle.encode('utf-8')
if transaction.batch:
with BSDDBTxn(self.env, data_map) as txn:
self.delete_primary_from_reference_map(handle, transaction,
txn=txn.txn)
txn.delete(handle)
else:
self.delete_primary_from_reference_map(handle, transaction,
txn=self.txn)
old_data = data_map.get(handle, txn=self.txn)
data_map.delete(handle, txn=self.txn)
transaction.add(key, TXNDEL, handle, old_data, None)
def remove_person(self, handle, transaction):
"""
Remove the Person specified by the database handle from the database,
preserving the change in the passed transaction.
"""
if self.readonly or not handle:
return
person = self.get_person_from_handle(handle)
self.genderStats.uncount_person (person)
self.remove_from_surname_list(person)
if isinstance(handle, UNITYPE):
handle = handle.encode('utf-8')
if transaction.batch:
with BSDDBTxn(self.env, self.person_map) as txn:
self.delete_primary_from_reference_map(handle, transaction,
txn=txn.txn)
txn.delete(handle)
else:
self.delete_primary_from_reference_map(handle, transaction,
txn=self.txn)
self.person_map.delete(handle, txn=self.txn)
transaction.add(PERSON_KEY, TXNDEL, handle, person.serialize(), None)
def remove_source(self, handle, transaction):
"""
Remove the Source specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.source_map,
SOURCE_KEY)
def remove_citation(self, handle, transaction):
"""
Remove the Citation specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.citation_map,
CITATION_KEY)
def remove_event(self, handle, transaction):
"""
Remove the Event specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.event_map,
EVENT_KEY)
def remove_object(self, handle, transaction):
"""
Remove the MediaObjectPerson specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.media_map,
MEDIA_KEY)
def remove_place(self, handle, transaction):
"""
Remove the Place specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.place_map,
PLACE_KEY)
def remove_family(self, handle, transaction):
"""
Remove the Family specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.family_map,
FAMILY_KEY)
def remove_repository(self, handle, transaction):
"""
Remove the Repository specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.repository_map,
REPOSITORY_KEY)
def remove_note(self, handle, transaction):
"""
Remove the Note specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.note_map,
NOTE_KEY)
def remove_tag(self, handle, transaction):
"""
Remove the Tag specified by the database handle from the
database, preserving the change in the passed transaction.
"""
self.__do_remove(handle, transaction, self.tag_map,
TAG_KEY)
@catch_db_error
def set_name_group_mapping(self, name, group):
if not self.readonly:
# Start transaction
with BSDDBTxn(self.env, self.name_group) as txn:
sname = name.encode('utf-8')
data = txn.get(sname)
if data is not None:
txn.delete(sname)
if group is not None:
txn.put(sname, group)
if group == None:
grouppar = ''
else:
grouppar = group
self.emit('person-groupname-rebuild', (name, grouppar))
def sort_surname_list(self):
self.surname_list.sort(key=glocale.sort_key)
@catch_db_error
def build_surname_list(self):
"""
Build surname list for use in autocompletion
This is a list of unicode objects, which are decoded from the utf-8 in
bsddb
"""
#TODO GTK3: Why double conversion? Convert to a list of str objects!
self.surname_list = sorted(
map(conv_dbstr_to_unicode, set(self.surnames.keys())),
key=glocale.sort_key)
def add_to_surname_list(self, person, batch_transaction):
"""
Add surname to surname list
"""
if batch_transaction:
return
name = conv_to_unicode(find_surname_name(person.handle,
person.get_primary_name().serialize()), 'utf-8')
i = bisect.bisect(self.surname_list, name)
if 0 < i <= len(self.surname_list):
if self.surname_list[i-1] != name:
self.surname_list.insert(i, name)
else:
self.surname_list.insert(i, name)
@catch_db_error
def remove_from_surname_list(self, person):
"""
Check whether there are persons with the same surname left in
the database.
If not then we need to remove the name from the list.
The function must be overridden in the derived class.
"""
name = find_surname_name(person.handle,
person.get_primary_name().serialize())
if sys.version_info[0] < 3:
if isinstance(name, unicode):
uname = name
name = str(name)
else:
uname = unicode(name, 'utf-8')
else:
if isinstance(name, str):
uname = name
name = name.encode('utf-8')
else:
uname = str(name)
try:
cursor = self.surnames.cursor(txn=self.txn)
cursor_position = cursor.set(name)
if cursor_position is not None and cursor.count() == 1:
#surname list contains unicode objects
i = bisect.bisect(self.surname_list, uname)
if 0 <= i-1 < len(self.surname_list):
del self.surname_list[i-1]
except db.DBError as err:
if str(err) == "(0, 'DB object has been closed')":
pass # A batch transaction closes the surnames db table.
else:
raise
finally:
if 'cursor' in locals():
cursor.close()
def commit_base(self, obj, data_map, key, transaction, change_time):
"""
Commit the specified object to the database, storing the changes as
part of the transaction.
"""
if self.readonly or not obj or not obj.handle:
return
obj.change = int(change_time or time.time())
handle = obj.handle
if isinstance(handle, UNITYPE):
handle = handle.encode('utf-8')
self.update_reference_map(obj, transaction, self.txn)
new_data = obj.serialize()
old_data = None
if not transaction.batch:
old_data = data_map.get(handle, txn=self.txn)
op = TXNUPD if old_data else TXNADD
transaction.add(key, op, handle, old_data, new_data)
data_map.put(handle, new_data, txn=self.txn)
return old_data
def commit_person(self, person, transaction, change_time=None):
"""
Commit the specified Person to the database, storing the changes as
part of the transaction.
"""
old_data = self.commit_base(
person, self.person_map, PERSON_KEY, transaction, change_time)
if old_data:
old_person = Person(old_data)
# Update gender statistics if necessary
if (old_person.gender != person.gender or
old_person.primary_name.first_name !=
person.primary_name.first_name):
self.genderStats.uncount_person(old_person)
self.genderStats.count_person(person)
# Update surname list if necessary
if (find_surname_name(old_person.handle,
old_person.primary_name.serialize()) !=
find_surname_name(person.handle,
person.primary_name.serialize())):
self.remove_from_surname_list(old_person)
self.add_to_surname_list(person, transaction.batch)
else:
self.genderStats.count_person(person)
self.add_to_surname_list(person, transaction.batch)
self.individual_attributes.update(
[str(attr.type) for attr in person.attribute_list
if attr.type.is_custom() and str(attr.type)])
self.event_role_names.update([str(eref.role)
for eref in person.event_ref_list
if eref.role.is_custom()])
self.name_types.update([str(name.type)
for name in ([person.primary_name]
+ person.alternate_names)
if name.type.is_custom()])
all_surn = [] # new list we will use for storage
all_surn += person.primary_name.get_surname_list()
for asurname in person.alternate_names:
all_surn += asurname.get_surname_list()
self.origin_types.update([str(surn.origintype) for surn in all_surn
if surn.origintype.is_custom()])
all_surn = None
self.url_types.update([str(url.type) for url in person.urls
if url.type.is_custom()])
attr_list = []
for mref in person.media_list:
attr_list += [str(attr.type) for attr in mref.attribute_list
if attr.type.is_custom() and str(attr.type)]
self.media_attributes.update(attr_list)
def commit_media_object(self, obj, transaction, change_time=None):
"""
Commit the specified MediaObject to the database, storing the changes
as part of the transaction.
"""
self.commit_base(obj, self.media_map, MEDIA_KEY,
transaction, change_time)
self.media_attributes.update(
[str(attr.type) for attr in obj.attribute_list
if attr.type.is_custom() and str(attr.type)])
def commit_source(self, source, transaction, change_time=None):
"""
Commit the specified Source to the database, storing the changes as
part of the transaction.
"""
self.commit_base(source, self.source_map, SOURCE_KEY,
transaction, change_time)
self.source_media_types.update(
[str(ref.media_type) for ref in source.reporef_list
if ref.media_type.is_custom()])
attr_list = []
for mref in source.media_list:
attr_list += [str(attr.type) for attr in mref.attribute_list
if attr.type.is_custom() and str(attr.type)]
self.media_attributes.update(attr_list)
def commit_citation(self, citation, transaction, change_time=None):
"""
Commit the specified Citation to the database, storing the changes as
part of the transaction.
"""
self.commit_base(citation, self.citation_map, CITATION_KEY,
transaction, change_time)
attr_list = []
for mref in citation.media_list:
attr_list += [str(attr.type) for attr in mref.attribute_list
if attr.type.is_custom() and str(attr.type)]
self.media_attributes.update(attr_list)
def commit_place(self, place, transaction, change_time=None):
"""
Commit the specified Place to the database, storing the changes as
part of the transaction.
"""
self.commit_base(place, self.place_map, PLACE_KEY,
transaction, change_time)
self.url_types.update([str(url.type) for url in place.urls
if url.type.is_custom()])
attr_list = []
for mref in place.media_list:
attr_list += [str(attr.type) for attr in mref.attribute_list
if attr.type.is_custom() and str(attr.type)]
self.media_attributes.update(attr_list)
def commit_personal_event(self, event, transaction, change_time=None):
if event.type.is_custom():
self.individual_event_names.add(str(event.type))
self.commit_event(event, transaction, change_time)
def commit_family_event(self, event, transaction, change_time=None):
if event.type.is_custom():
self.family_event_names.add(str(event.type))
self.commit_event(event, transaction, change_time)
def commit_event(self, event, transaction, change_time=None):
"""
Commit the specified Event to the database, storing the changes as
part of the transaction.
"""
self.commit_base(event, self.event_map, EVENT_KEY,
transaction, change_time)
attr_list = []
for mref in event.media_list:
attr_list += [str(attr.type) for attr in mref.attribute_list
if attr.type.is_custom() and str(attr.type)]
self.media_attributes.update(attr_list)
def commit_family(self, family, transaction, change_time=None):
"""
Commit the specified Family to the database, storing the changes as
part of the transaction.
"""
self.commit_base(family, self.family_map, FAMILY_KEY,
transaction, change_time)
self.family_attributes.update(
[str(attr.type) for attr in family.attribute_list
if attr.type.is_custom() and str(attr.type)])
rel_list = []
for ref in family.child_ref_list:
if ref.frel.is_custom():
rel_list.append(str(ref.frel))
if ref.mrel.is_custom():
rel_list.append(str(ref.mrel))
self.child_ref_types.update(rel_list)
self.event_role_names.update(
[str(eref.role) for eref in family.event_ref_list
if eref.role.is_custom()])
if family.type.is_custom():
self.family_rel_types.add(str(family.type))
attr_list = []
for mref in family.media_list:
attr_list += [str(attr.type) for attr in mref.attribute_list
if attr.type.is_custom() and str(attr.type)]
self.media_attributes.update(attr_list)
def commit_repository(self, repository, transaction, change_time=None):
"""
Commit the specified Repository to the database, storing the changes
as part of the transaction.
"""
self.commit_base(repository, self.repository_map, REPOSITORY_KEY,
transaction, change_time)
if repository.type.is_custom():
self.repository_types.add(str(repository.type))
self.url_types.update([str(url.type) for url in repository.urls
if url.type.is_custom()])
def commit_note(self, note, transaction, change_time=None):
"""
Commit the specified Note to the database, storing the changes as part
of the transaction.
"""
self.commit_base(note, self.note_map, NOTE_KEY,
transaction, change_time)
if note.type.is_custom():
self.note_types.add(str(note.type))
def commit_tag(self, tag, transaction, change_time=None):
"""
Commit the specified Tag to the database, storing the changes as part
of the transaction.
"""
self.commit_base(tag, self.tag_map, TAG_KEY,
transaction, change_time)
def get_from_handle(self, handle, class_type, data_map):
if isinstance(handle, UNITYPE):
handle = handle.encode('utf-8')
try:
data = data_map.get(handle, txn=self.txn)
except UnicodeDecodeError:
#we need to assume we opened data in python3 saved in python2
raw = data_map.db.get(handle, txn=self.txn)
data = pickle.loads(raw, encoding='utf-8')
except:
data = None
# under certain circumstances during a database reload,
# data_map can be none. If so, then don't report an error
if data_map:
_LOG.error("Failed to get from handle", exc_info=True)
if data:
newobj = class_type()
newobj.unserialize(data)
return newobj
return None
@catch_db_error
def transaction_begin(self, transaction):
"""
Prepare the database for the start of a new Transaction.
Supported transaction parameters:
no_magic: Boolean, defaults to False, indicating if secondary indices
should be disconnected.
"""
if self.txn is not None:
msg = self.transaction.get_description()
self.transaction_abort(self.transaction)
raise DbError(_('A second transaction is started while there'
' is still a transaction, "%s", active in the database.') % msg)
if not isinstance(transaction, DbTxn) or len(transaction) != 0:
raise TypeError("transaction_begin must be called with an empty "
"instance of DbTxn which typically happens by using the "
"DbTxn instance as a context manager.")
self.transaction = transaction
if transaction.batch:
# A batch transaction does not store the commits
# Aborting the session completely will become impossible.
self.abort_possible = False
# Undo is also impossible after batch transaction
self.undodb.clear()
self.env.txn_checkpoint()
if (self.secondary_connected and
not getattr(transaction, 'no_magic', False)):
# Disconnect unneeded secondary indices
self.surnames.close()
_db = db.DB(self.env)
try:
_db.remove(_mkname(self.full_name, SURNAMES), SURNAMES)
except db.DBNoSuchFileError:
pass
self.reference_map_referenced_map.close()
_db = db.DB(self.env)
try:
_db.remove(_mkname(self.full_name, REF_REF), REF_REF)
except db.DBNoSuchFileError:
pass
else:
self.bsddbtxn = BSDDBTxn(self.env)
self.txn = self.bsddbtxn.begin()
return transaction
@catch_db_error
def transaction_commit(self, transaction):
"""
Make the changes to the database final and add the content of the
transaction to the undo database.
"""
msg = transaction.get_description()
if self._LOG_ALL:
_LOG.debug("%s: Transaction commit '%s'\n"
% (self.__class__.__name__, msg))
if self.readonly:
return
if self.txn is not None:
assert msg != ''
self.bsddbtxn.commit()
self.bsddbtxn = None
self.txn = None
self.env.log_flush()
if not transaction.batch:
emit = self.__emit
for obj_type, obj_name in KEY_TO_NAME_MAP.items():
emit(transaction, obj_type, TXNADD, obj_name, '-add')
emit(transaction, obj_type, TXNUPD, obj_name, '-update')
emit(transaction, obj_type, TXNDEL, obj_name, '-delete')
self.transaction = None
transaction.clear()
self.undodb.commit(transaction, msg)
self.__after_commit(transaction)
self.has_changed = True
def __emit(self, transaction, obj_type, trans_type, obj, suffix):
"""
Define helper function to do the actual emits
"""
if (obj_type, trans_type) in transaction:
if trans_type == TXNDEL:
handles = [handle2internal(handle) for handle, data in
transaction[(obj_type, trans_type)]]
else:
handles = [handle2internal(handle) for handle, data in
transaction[(obj_type, trans_type)]
if (handle, None) not in transaction[(obj_type,
TXNDEL)]]
if handles:
self.emit(obj + suffix, (handles, ))
def transaction_abort(self, transaction):
"""
Revert the changes made to the database so far during the transaction.
"""
if self._LOG_ALL:
_LOG.debug("%s: Transaction abort '%s'\n" %
(self.__class__.__name__, transaction.get_description()))
if self.readonly:
return
if self.txn is not None:
self.bsddbtxn.abort()
self.bsddbtxn = None
self.txn = None
if not transaction.batch:
# It can occur that the listview is already updated because of
# the "model-treeview automatic update" combined with a
# "while Gtk.events_pending(): Gtk.main_iteration() loop"
# (typically used in a progress bar), so emit rebuild signals
# to correct that.
object_types = set([x[0] for x in list(transaction.keys())])
for object_type in object_types:
if object_type == REFERENCE_KEY:
continue
self.emit('%s-rebuild' % KEY_TO_NAME_MAP[object_type], ())
self.transaction = None
transaction.clear()
transaction.first = None
transaction.last = None
self.__after_commit(transaction)
def __after_commit(self, transaction):
"""
Post-transaction commit processing
"""
if transaction.batch:
self.env.txn_checkpoint()
if not getattr(transaction, 'no_magic', False):
# create new secondary indices to replace the ones removed
self.surnames = self.__open_db(self.full_name, SURNAMES,
db.DB_BTREE, db.DB_DUP | db.DB_DUPSORT)
self.person_map.associate(self.surnames, find_byte_surname,
DBFLAGS_O)
self.reference_map_referenced_map = self.__open_db(self.full_name,
REF_REF, db.DB_BTREE, db.DB_DUP|db.DB_DUPSORT)
self.reference_map.associate(self.reference_map_referenced_map,
find_referenced_handle, DBFLAGS_O)
# Only build surname list after surname index is surely back
self.build_surname_list()
# Reset callbacks if necessary
if transaction.batch or not len(transaction):
return
if self.undo_callback:
self.undo_callback(_("_Undo %s") % transaction.get_description())
if self.redo_callback:
self.redo_callback(None)
if self.undo_history_callback:
self.undo_history_callback()
def undo(self, update_history=True):
return self.undodb.undo(update_history)
def redo(self, update_history=True):
return self.undodb.redo(update_history)
def gramps_upgrade(self, callback=None):
UpdateCallback.__init__(self, callback)
version = self.metadata.get(b'version', default=_MINVERSION)
t = time.time()
from . import upgrade
if version < 14:
upgrade.gramps_upgrade_14(self)
if version < 15:
upgrade.gramps_upgrade_15(self)
if version < 16:
upgrade.gramps_upgrade_16(self)
self.reset()
self.set_total(6)
self.__connect_secondary()
# Open undo database
self.__open_undodb()
self.db_is_open = True
self.reindex_reference_map(self.update)
self.reset()
# Close undo database
self.__close_undodb()
self.db_is_open = False
_LOG.debug("Upgrade time: %d seconds" % int(time.time()-t))
def set_auto_remove(self):
"""
BSDDB change log settings using new method with renamed attributes
"""
autoremove_flag = None
autoremove_method = None
for flag in ["DB_LOG_AUTO_REMOVE", "DB_LOG_AUTOREMOVE"]:
if hasattr(db, flag):
autoremove_flag = getattr(db, flag)
break
for method in ["log_set_config", "set_flags"]:
if hasattr(self.env, method):
autoremove_method = getattr(self.env, method)
break
if autoremove_method and autoremove_flag:
autoremove_method(autoremove_flag, 1)
else:
_LOG.debug("Failed to set autoremove flag")
def write_version(self, name):
"""Write version number for a newly created DB."""
full_name = os.path.abspath(name)
self.env = db.DBEnv()
self.env.set_cachesize(0, DBCACHE)
# These env settings are only needed for Txn environment
self.env.set_lk_max_locks(DBLOCKS)
self.env.set_lk_max_objects(DBOBJECTS)
# clean up unused logs
self.set_auto_remove()
# The DB_PRIVATE flag must go if we ever move to multi-user setup
env_flags = db.DB_CREATE | db.DB_PRIVATE |\
db.DB_INIT_MPOOL |\
db.DB_INIT_LOG | db.DB_INIT_TXN
# As opposed to before, we always try recovery on databases
env_flags |= db.DB_RECOVER
# Environment name is now based on the filename
env_name = name
self.env.open(env_name, env_flags)
self.env.txn_checkpoint()
self.metadata = self.__open_shelf(full_name, META)
_LOG.debug("Write schema version %s" % _DBVERSION)
with BSDDBTxn(self.env, self.metadata) as txn:
txn.put(b'version', _DBVERSION)
versionpath = os.path.join(name, BDBVERSFN)
version = str(db.version())
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
_LOG.debug("Write bsddb version %s" % version)
with open(versionpath, "w") as version_file:
version_file.write(version)
versionpath = os.path.join(name, "pythonversion.txt")
version = str(version_info[0])
if sys.version_info[0] < 3:
if isinstance(version, UNITYPE):
version = version.encode('utf-8')
_LOG.debug("Write python version file to %s" % version)
with open(versionpath, "w") as version_file:
version_file.write(version)
self.metadata.close()
self.env.close()
def get_dbid(self):
"""
In BSDDB, we use the file directory name as the unique ID for
this database on this computer.
"""
return self.brief_name
def _mkname(path, name):
return os.path.join(path, name + DBEXT)
def clear_lock_file(name):
try:
os.unlink(os.path.join(name, DBLOCKFN))
except OSError:
return
def write_lock_file(name):
if not os.path.isdir(name):
os.mkdir(name)
f = io.open(os.path.join(name, DBLOCKFN), "w", encoding='utf8')
if win():
user = get_env_var('USERNAME')
host = get_env_var('USERDOMAIN')
if host == None:
host = ""
else:
host = os.uname()[1]
# An ugly workaround for os.getlogin() issue with Konsole
try:
user = os.getlogin()
except:
user = os.environ['USER'] #not win, don't need get_env_var
if host:
text = "%s@%s" % (user, host)
else:
text = user
# Save only the username and host, so the massage can be
# printed with correct locale in DbManager.py when a lock is found
f.write(text)
f.close()
def upgrade_researcher(owner_data):
"""
Upgrade researcher data to include a locality field in the address.
This should be called for databases prior to Gramps 3.3.
"""
addr = tuple([owner_data[0][0], ''] + list(owner_data[0][1:]))
return (addr, owner_data[1], owner_data[2], owner_data[3])
if __name__ == "__main__":
import os, sys, pdb
d = DbBsddb()
if len(sys.argv) > 1:
db_name = sys.argv[1]
else:
db_home = os.path.join(HOME_DIR,'grampsdb')
for dir in os.listdir(db_home):
db_path = os.path.join(db_home, dir)
db_fn = os.path.join(db_path, 'name.txt')
if os.stat(db_fn):
f = open(db_fn)
db_name = f.read()
if db_name == 'Small Example':
break
print("loading", db_path)
d.load(db_path, lambda x: x)
print(d.get_default_person())
out = ''
with d.get_person_cursor() as c:
for key, data in c:
person = Person(data)
out += key + person.get_primary_name().get_name()
print(out, list(d.surnames.keys()))