/usr/share/pyshared/mx/BeeBase/BeeDict.py is in python-egenix-mxbeebase 3.2.1-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | """ BeeDict - On-disk dictionary like databases
"""
import exceptions, os
import BeeIndex,BeeStorage
from mx import Tools
freeze = Tools.freeze
from mx.Log import *
#import TraceCalls; TraceCalls.install()
#log.setup(ignore_level=SYSTEM_LOG_EVERYTHING)
### Globals
# Write debug info
_debug = 0
### Constants
# Special keys
FirstKey = BeeIndex.FirstKey
LastKey = BeeIndex.LastKey
# Maximal cache size default value ( == size of transaction log; kept in memory !)
MAXCACHESIZE = 1000
### Errors
class Error(exceptions.StandardError):
pass
class IndexError(Error):
""" This error is raised for index related errors.
"""
pass
class RecreateIndexError(IndexError):
""" This error is raised in case the index for a dictionary was
not found and/or needs to be recreated by running recovery.
"""
pass
class RecoverError(Error):
""" This error is raised in case the storage for a dictionary was
found to be in an inconsistent state.
"""
pass
### Base classes
# State constants
READ = 0
MODIFIED = 1
DELETED = 2
READKEYONLY = 3 # XXX Currently not used.
class BeeBaseDict:
""" Base class that collects some method that all dicts can usually
share without modification.
The base class implements a transaction based caching
mechanism. The cache stores data in the form
key:(state,value) where state is:
* READ for read but not yet modified
* MODIFIED for added/modified
* DELETED for deleted
* READKEYONLY for key read, value still on disk
The .commit method has to implement the needed disk mechanism
to write the cache data to disk storage.
"""
# Name of the dictionary
name = 'NoName'
# Name of the storage file; set in .__init__()
storage_name = name + '.dat'
# Name of the index file; set in .__init__()
index_name = name + '.idx'
# Bee*Index object
index = None
# Bee*Storage object
storage = None
# Is the dictionary closed ?
closed = 0
# Cache dictionary
cache = None
# Is the dictionary read-only ?
readonly = 0
# Run in auto-commit mode ? This will perform a commit whenever
# the cache gets to full.
autocommit = 0
# Max. cache size in number of items to store in the in-memory
# transaction cache
maxcachesize = MAXCACHESIZE
# Special keys that can be used for .cursor()
FirstKey = FirstKey
LastKey = LastKey
def __init__(self, name, keysize=8, min_recordsize=0, readonly=0,
recover=0, autocommit=0, validate=0,
index=BeeIndex.BeeIntegerIndex, maxcachesize=None):
""" Create an instance using name as basename for the
data and index files.
Two files will be created: <name>.dat and <name>.idx.
keysize gives the maximal size of the key strings used as
index keys. This is only useful for string based keys.
min_recordsize is passed to the BeeStorage as indicator of
the minimum size for data records.
readonly can be set to true to open the files in read-only
mode, preventing any disk modifications.
To open the dictionary in recovery mode, pass a keyword
recover=1. Then run .recover() and reopen using the normal
settings.
If autocommit is true the cache control will do an
automatic .commit() whenever the transaction log
overflows.
If validate is true, the dictionary will run a validation
check after having successfully opened storage and index.
RecreateIndexError or RecoverError exceptions could be
raised in case inconsistencies are found.
index gives the constructor to use for the .index. The
constructors BeeIntegerIndex and BeeStringIndex from the
BeeIndex module are supported.
maxcachesize defines the maximum size of the in-memory
transaction cache. It defaults to MAXCACHESIZE if not
given.
"""
# Init instance vars
self.name = name
self.storage_name = name + '.dat'
self.index_name = name + '.idx'
self.cache = {}
if maxcachesize is not None:
self.maxcachesize = maxcachesize
else:
self.maxcachesize = self.maxcachesize
# Open storage
self.storage = BeeStorage.BeeKeyValueStorage(
self.storage_name,
lock= not readonly,
cache=0,
min_recordsize=min_recordsize,
readonly=readonly,
recover=recover)
# Determine the filemode for the index
if readonly:
# Readonly mode
filemode = 1
else:
if self.storage.is_new or recover:
# Create a new file (overwriting a possibly existing one)
filemode = 2
else:
# Open an existing file, recreate if non-existing
filemode = 0
# Open the index
try:
# Special argument treatment for the indexes; we check
# depending on the used constructor function
if (index is BeeIndex.BeeStringIndex or
index is BeeIndex.BeeFixedLengthStringIndex):
# Calculate the right sectorsize
if keysize <= 30:
sectorsize = 256
elif keysize <= 73:
sectorsize = 512
elif keysize <= 158:
sectorsize = 1024
else:
raise IndexError, 'keysize %i is too large' % keysize
self.index = index(self.index_name,
keysize,
dupkeys=0,
filemode=filemode,
sectorsize=sectorsize)
elif index is BeeIndex.BeeIntegerIndex:
# keysize is sizeof(long)
self.index = index(self.index_name,
dupkeys=1,
filemode=filemode,
sectorsize=256)
elif index is BeeIndex.BeeFloatIndex:
# keysize is sizeof(double)
self.index = index(self.index_name,
dupkeys=1,
filemode=filemode,
sectorsize=256)
else:
raise IndexError, 'unknown index type: %s' % repr(index)
except IOError, why:
# Make sure the storage lock is freed
self.close()
raise RecreateIndexError,\
'Index for %s "%s" could not be opened' % \
(index.__name__, name)
self.readonly = readonly
self.autocommit = autocommit
if validate:
self.validate_index()
self.validate_storage()
def _calc_sectorsize(self, keysize):
""" Calculate the sectorsize given the keysize.
"""
if keysize <= 30:
return 256
elif keysize <= 73:
return 512
elif keysize <= 158:
return 1024
else:
raise IndexError, 'keysize %i is too large' % keysize
def remove_files(self):
""" Deletes the storage and index files used for the instance.
Closes the on-disk dictionary before proceeding with the
removal.
USE WITH CARE !
"""
self.close()
os.remove(self.storage_name)
os.remove(self.index_name)
def __len__(self):
""" This only gives correct results if no modifications
are pending.
"""
# Check for uncommitted changes
if self.cache and self.changed():
raise Error, 'uncommitted data exists; can\'t calculate length'
return len(self.index)
def close(self):
""" Flush buffers and close.
This issues a .rollback(), so the current transaction is
rolled back. It also frees the lock on the used index.
"""
if not self.closed:
self.rollback()
for obj in (self.index, self.storage):
if obj is not None:
# .rollback will have flushed the buffers
obj.close()
self.closed = 1
def __del__(self,
AttributeError=AttributeError):
""" Make sure the object is closed and locks are freed.
"""
#print '__del__ %s' % repr(self)
if not self.closed:
try:
self.close()
except AttributeError:
# Could occur during interpreter cleanup
pass
def flush(self):
""" Flush buffers to disk.
"""
if self.closed:
# Nothing much to do
return
if self.storage is not None:
self.storage.flush()
if self.index is not None:
self.index.flush()
def __repr__(self):
return '<%s instance for "%s" at 0x%x>' % (self.__class__.__name__,
self.name,
id(self))
def commit(self):
""" Commit all changes and start a new transaction.
This method does not implement any write operation, but
takes care of managing the cache and flushing the storage
and index buffers.
You must override this method to have commit have any
writing effect. The base method must be called after the
cache has been processed.
"""
# Clear cache
if self.cache is not None:
self.cache.clear()
# Flush storage and index
self.flush()
def rollback(self):
""" Take back all changes and start a new transaction.
Overriding is normally not needed. This method only takes
care of managing the cache and flushing the storage and
index buffers.
"""
# Clear cache
if self.cache is not None:
self.cache.clear()
# Flush storage and index
self.flush()
def changed(self,
modified=(MODIFIED,DELETED)):
""" Return true in case the current transaction includes changes
to the database, false otherwise.
"""
if self.cache:
for key,(state,value) in self.cache.items():
if state in modified:
return 1
return 0
def free_cache(self,
len=len,unmodified=(READ,READKEYONLY)):
""" Remove all unmodified entries from the cache.
If self.autocommit and the cache cleanup did not reduce
the size below the .maxcachesize limit, a .commit() will be
executed automatically.
Otherwise the processing continues. If the cache size hits
2 * .maxcachesize, a forced .rollback() is done and an
error raised.
"""
cache = self.cache
for key,(state,value) in cache.items():
if state in unmodified:
del cache[key]
size = len(cache)
if size > self.maxcachesize:
if self.autocommit:
self.commit()
return
log(SYSTEM_ERROR,
'Cache overflow: %i modified items in cache',size)
if size > 2 * self.maxcachesize:
# Force .rollback() and raise an error
log(SYSTEM_ERROR,
'Cache overflow: forced a .rollback()')
self.rollback()
raise Error,'cache overflow; last transaction rolled back'
def read(self,key,checkonly=0):
""" Read and return the value corresponding to key.
If checkonly is true, only the availability of a value
has to be checked.
Override this method with an implementation that accesses
the disk.
"""
raise KeyError,'key not found'
def __setitem__(self,key,value,
MODIFIED=MODIFIED):
""" Save the item in the dictionary.
Note that it is written to the cache first. Use .commit()
to make sure it is written to disk.
"""
self.cache[key] = (MODIFIED, value)
def __getitem__(self,key,
validstates=(READ,MODIFIED),len=len,KeyError=KeyError,
DELETED=DELETED,READ=READ):
""" Get an item from the dictionary.
This first tries to read the item from cache and reverts
to the disk storage if it is not found.
"""
try:
cache = self.cache
state,value = cache[key]
if state in validstates:
return value
except KeyError:
pass
else:
if state == DELETED:
raise KeyError,'key deleted'
# Read from disk
value = self.read(key)
# Cache the item
if len(cache) > self.maxcachesize:
self.free_cache()
cache[key] = (READ, value)
return value
def __delitem__(self, key,
DELETED=DELETED):
""" Delete an item.
The item is only marked for deletion. The next .commit()
will make the action permanent.
"""
cache = self.cache
if not cache.has_key(key):
self.read(key, 1)
cache[key] = (DELETED, None)
def has_key(self,key,
len=len,KeyError=KeyError,DELETED=DELETED,READ=READ):
""" Check if the dictionary has an item indexed by key.
Successfully found items are put in the cache for fast
subsequent access.
"""
try:
cache = self.cache
state,value = cache[key]
if state == DELETED:
return 0
return 1
except KeyError:
pass
# Read from disk
try:
value = self.read(key)
except KeyError:
return 0
# Cache the item
if len(cache) > self.maxcachesize:
self.free_cache()
cache[key] = (READ, value)
return 1
def get(self,key,default=None,
len=len,KeyError=KeyError,DELETED=DELETED,READ=READ):
""" Get item indexed by key from the dictionary or default if
no such item exists.
This first tries to read the item from cache and reverts
to the disk storage if it is not found.
"""
try:
cache = self.cache
state,value = cache[key]
if state == DELETED:
return default
return value
except KeyError:
pass
# Read from disk
try:
value = self.read(key)
except KeyError:
return default
# Cache the item
if len(cache) > self.maxcachesize:
self.free_cache()
cache[key] = (READ, value)
return value
def cursor(self, key=FirstKey, default=None):
""" Return a cursor instance for this kind of dictionary.
If key is given, the cursor is positioned on that key in
the dictionary. Otherwise, the first entry in the
dictionary is used which guarantees that all entries are
scanned.
In case the key is not found, default is returned instead.
Note that cursors operate with the data on disk meaning
that any uncommitted changes will not be seen by the
cursor.
Has to be overridden to return a suitable cursor object.
"""
# Check for uncommitted changes
if self.cache and self.changed():
raise Error,'uncommitted data exists'
# Get the index cursor and create a dict cursor from it
cursor = self.index.cursor(key,None)
if cursor is None:
return default
return BeeBaseDictCursor(self,cursor)
def garbage(self):
""" Determine the amount of garbage in bytes that has accumulated
in the storage file.
This amount would be freed if .collect() were run.
"""
valid,old,invalid = self.storage.statistics()
return old + invalid
def collect(self):
""" Run the storage garbage collector.
Storage collection can only be done for writeable
dictionaries and then only if the current transaction does
not contain any pending changes.
This can take a while depending on the size of the
dictionary.
"""
if self.readonly:
raise Error,'dict is read-only'
# Check for uncommitted changes
if self.cache and self.changed():
raise Error,'uncommitted data exists'
self.flush()
log(SYSTEM_INFO,'Collecting %s',self)
# Run collector
self.storage.collect(self.collect_callback)
# End the storage transaction
self.storage.end_transaction()
def collect_callback(self,old_position,new_position,raw_data):
""" Internal callback used to update the index when
the storage garbage collector moves a record.
This method must be overridden to account for the
different indexing schemes.
"""
raise Error,'.collect_callback() not implemented'
def recover(self):
""" Recover all valid records and recreate the index.
"""
log(SYSTEM_INFO,'Recovering %s',self)
# Clear the index
self.index.clear()
# Run recovery and recreate the index through the callback
self.storage.recover(self.recover_callback)
# End the storage transaction
self.storage.end_transaction()
def recover_callback(self,old_position,new_position,raw_data):
""" Internal callback used to update the index when
the storage recovery collector finds a record.
old_position is only given as additional information,
new_position contains the position of the found record.
This method must be overridden to account for the
different indexing schemes.
"""
raise Error,'.recover_callback() not implemented'
def validate_index(self):
""" Checks the consistency of the index and raises an
RecreateIndexError in case the index is found to be
inconsistent.
Validation takes places for the data on disk. The in
memory data is not checked.
"""
log(SYSTEM_INFO,'Validating index for %s',self)
if not self.index.validate():
raise RecreateIndexError,'index is inconsistent'
def validate_storage(self):
""" Checks the consistency of the storage and raises an
RecoverError in case it is found to be
inconsistent.
Validation takes places for the data on disk. The in
memory data is not checked.
XXX This currently does nothing since storages don't
support validation yet.
"""
log(SYSTEM_INFO,'Validating storage for %s',self)
return
def backup(self,archive=None):
""" Issues a backup request to the storage using archive
which defaults to the storage filename + '.backup'.
This causes an implicit .rollback() to be done.
"""
self.rollback()
self.storage.backup(archive)
def restore(self,archive):
""" Restores the storage from an archive file.
XXX Currently does NOT work.
"""
raise SystemError,'.restore() not implemented !'
### Iterator interface
def __iter__(self, method='items'):
""" Iterator interface.
Creates an iterator which iterates over the items of the
complete dictionary.
Note that this only works if there are no uncommitted
changes.
"""
cursor = self.cursor(FirstKey)
if cursor is None:
return EmptyIterator()
if method == 'items':
return BeeBaseIterator(cursor)
elif method == 'keys':
return BeeBaseIterator(cursor, cursor.read_key)
elif method == 'values':
return BeeBaseIterator(cursor, cursor.read_value)
else:
raise ValueError, 'unknown iterator method: %s' % method
def iteritems(self):
""" Returns an iterator to iterate over the items of the dictionary.
"""
return self.__iter__()
def iterkeys(self):
""" Returns an iterator to iterate over the keys of the dictionary.
"""
return self.__iter__('keys')
def itervalues(self):
""" Returns an iterator to iterate over the values of the dictionary.
"""
return self.__iter__('values')
### BeeBase iterators
# To make iterators work in Python 2.1 and below
try:
StopIteration
except NameError:
class StopIteration(exceptions.IndexError):
pass
class EmptyIterator:
""" Empty iterator.
"""
def next(self):
raise StopIteration
def __getitem__(self, index):
raise StopIteration
class BeeBaseIterator:
""" Iterator for BeeBaseDict subclasses.
"""
def __init__(self, cursor, read_method=None):
""" Iterate over cursor and return the values which the read_method
function returns when called without arguments.
If read_method is None, cursor.read_item is used.
"""
self.cursor = cursor
if read_method is None:
self.read_method = cursor.read_item
else:
self.read_method = read_method
self.stop = 0
def next(self):
if self.stop:
raise StopIteration
x = self.read_method()
self.stop = not self.cursor.next()
return x
def __getitem__(self, index):
return self.next()
### Cursor base class
class BeeBaseDictCursor:
""" Cursor for BeeBaseDict subclasses.
The read/read_key/write methods assume that the dictionary
uses a BeeKeyValueStorage instances as storage facility.
Note that modifying the targetted dictionary while using a
cursor can cause the cursor to skip new entries or fail due to
deleted items. Especially deleting the key to which the cursor
currently points can cause errors to be raised. In all other
cases, the cursor will be repositioned.
"""
cursor = None
def __init__(self,dict,cursor):
self.dict = dict
self.cursor = cursor
self.key = cursor.key
self.value = cursor.value
# Alias
self.read_value = self.read
def position(self, key, value=None):
""" Position the index cursor to index[key]. If value is given,
index[key] == value is assured.
key may also be FirstKey or LastKey (in which case value
has to be None).
"""
# Create and position the cursor
self.cursor = cursor = self.dict.index.cursor(key)
if value and cursor.value != value:
# assure that the cursor points to key,value
while cursor.next():
if cursor.value == value:
break
if cursor.key != key:
raise KeyError,'key not found'
else:
raise KeyError,'key not found'
self.key = key
self.value = value
def next(self):
""" Moves to the next entry in the dictionary.
Returns true on success, false if the end-of-data has been
reached.
"""
cursor = self.cursor
if not cursor.valid:
self.position(self.key,self.value)
cursor = self.cursor
rc = cursor.next()
self.key = cursor.key
self.value = cursor.value
return rc
def prev(self):
""" Moves to the previous entry in the dictionary.
Returns true on success, false if the end-of-data has been
reached.
"""
cursor = self.cursor
if not cursor.valid:
self.position(self.key,self.value)
cursor = self.cursor
rc = cursor.prev()
self.key = cursor.key
self.value = cursor.value
return rc
def read(self):
""" Reads the value object from the dict to which the cursor
currently points.
This method assumes a BeeKeyValueStorage instance in
self.storage and an index that holds copies of the key
objects. Override if this is not the case.
"""
return self.dict[self.key]
def read_key(self):
""" Reads the key object from the dict to which the cursor
currently points.
This method is intended for dictionaries that store hash
values in the index. Normally, accessing the instance
variable .key would give the current key object.
This method assumes a BeeKeyValueStorage instance in
self.storage. Override if this is not the case.
"""
return self.dict.storage.read_key(self.value)
def read_item(self):
""" Reads the (key, value) item object from the dict to which
the cursor currently points.
This method is intended for dictionaries that store hash
values in the index.
This method assumes a BeeKeyValueStorage instance in
self.storage. Override if this is not the case.
"""
keyobj = self.dict.storage.read_key(self.value)
return keyobj, self.dict[keyobj]
def write(self,object):
""" Writes the value object to the dict under the key to which
the cursor currently points.
The new data is not written to disk until the dictionaries
current transaction is committed.
This method assumes a BeeKeyValueStorage instance in
self.storage and an index that holds copies of the key
objects. Override if this is not the case.
"""
self.dict[self.key] = object
### Actual implementations
class BeeDict(BeeBaseDict):
""" On-disk dictionary that uses a "hash to address" index.
Both Keys and values must be pickleable. Keys also have to be
hashable. Both can have arbitrary size (keys shouldn't be too
long though).
Hash collisions are treated by sequential reads of all records
with the same hash value and testing for equality of keys. This
can be expensive !
"""
# Count the number of hash collisions in writes
collisions = 0
def __init__(self,name,min_recordsize=0,readonly=0,recover=0,
autocommit=0,validate=0, maxcachesize=None,
basemethod=BeeBaseDict.__init__):
""" Create an instance using name as basename for the
data and index files.
Two files will be created: <name>.dat and <name>.idx.
min_recordsize is passed to the BeeStorage as indicator of
the minimum size for data records. readonly can be set to
true to open the files in read-only mode, preventing any
disk modifications.
To open the dictionary in recovery mode, pass a keyword
recover=1. Then run .recover() and reopen using the normal
settings.
If autocommit is true the cache control will do an
automatic .commit() whenever the transaction log
overflows.
If validate is true, the dictionary will run a validation
check after having successfully opened storage and index.
RecreateIndexError or RecoverError exceptions could be
raised in case inconsistencies are found.
maxcachesize defines the maximum size of the in-memory
transaction cache. It defaults to MAXCACHESIZE if not
given.
"""
basemethod(self, name, min_recordsize=min_recordsize,
readonly=readonly, recover=recover,
autocommit=autocommit, validate=validate,
index=BeeIndex.BeeIntegerIndex,
maxcachesize=maxcachesize)
def find_address(self,cursor,hashvalue,key):
""" Find the address of a key by scanning the hash value
set pointed to by the cursor.
Returns the address of the found key or None.
"""
while cursor.next():
if cursor.key != hashvalue:
# Left set of identical keys in index: not found
return None
if key == self.storage.read_key(cursor.value):
# Found
return cursor.value
# EOF reached index: not found
return None
def index_cursor(self, key=FirstKey, default=None):
""" Return an index cursor pointing to key.
If key is not given, it defaults to FirstKey. In case the
key is not found, default is returned.
XXX Should use this method in more places...
"""
if key is FirstKey or key is LastKey:
return self.index.cursor(key, default)
hashvalue = hash(key)
cursor = self.index.cursor(hashvalue,None)
if cursor is None:
return default
# Check that we have really found the key
address = cursor.value
if key != self.storage.read_key(address):
# Ah, a collision
address = self.find_address(cursor,hashvalue,key)
if address is None:
return default
return cursor
def commit(self,
basemethod=BeeBaseDict.commit,MODIFIED=MODIFIED,DELETED=DELETED):
""" Commit all changes and start a new transaction.
"""
# Write all changed entries in the cache to disk
index = self.index
index_cursor = index.cursor
index_update = index.update
index_delete = index.delete
storage = self.storage
storage_read_key = storage.read_key
storage_write = storage.write
storage_delete = storage.delete
readonly = self.readonly
NotFound = None
debug = _debug
if debug:
log(SYSTEM_DEBUG,'Committing all changes for "%s"...',self.name)
for key,(state,value) in self.cache.items():
if state == MODIFIED:
if debug:
log.object(SYSTEM_DEBUG,' writing key %r:' % repr(key), value)
if readonly:
raise Error,'dict is read-only'
hashvalue = hash(key)
cursor = index_cursor(hashvalue, NotFound)
if cursor is not NotFound:
# Update an existing entry (or maybe add a new one if there
# was a hash collision)
address = cursor.value
if key != storage_read_key(address):
self.collisions = self.collisions + 1
address = self.find_address(cursor, hashvalue, key)
# address may be None (== NotFound)... meaning
# that we have to add a new record
new_address = storage_write(key, value, address)
if new_address == address:
continue
# Update index
if address is not NotFound:
index_update(hashvalue, new_address, address)
else:
index[hashvalue] = new_address
else:
# Add a new entry
address = storage_write(key, value)
# Update index
index[hashvalue] = address
elif state == DELETED:
if debug:
log(SYSTEM_DEBUG,' deleting key %r', repr(key))
if readonly:
raise Error,'dict is read-only'
hashvalue = hash(key)
cursor = index_cursor(hashvalue)
# Check that we have really found the key
address = cursor.value
if key != storage_read_key(address):
# Ah, a collision
address = self.find_address(cursor, hashvalue, key)
if address is NotFound:
raise KeyError,'key not found'
storage_delete(address)
# Update index
index_delete(hashvalue, address)
# End the storage transaction
storage.end_transaction()
# Call basemethod
basemethod(self)
def read(self,key,checkonly=0):
# Load from disk
hashvalue = hash(key)
cursor = self.index.cursor(hashvalue)
# Check that we have really found the key
address = cursor.value
if key != self.storage.read_key(address):
# Ah, a collision
address = self.find_address(cursor,hashvalue,key)
if address is None:
raise KeyError,'key not found'
if checkonly:
return
else:
return self.storage.read(address)[1]
def keys(self,
DELETED=DELETED):
""" Return a list of keys.
The method does not load any data into the cache, but does
take notice of uncommitted changes.
"""
l = []
read_key = self.storage.read_key
# First the cache entries that are not yet committed
for key,(state,value) in self.cache.items():
if state != DELETED:
l.append(key)
# Next the remaining entries read from disk
key_added = self.cache.has_key
for address in self.index.values():
key = read_key(address)
if not key_added(key):
l.append(key)
return l
def values(self,
DELETED=DELETED):
""" Return a list of values.
The method does not load any data into the cache, but does
take notice of uncommitted changes.
"""
l = []
read = self.storage.read
# First the cache entries that are not yet committed
for key,(state,value) in self.cache.items():
if state != DELETED:
l.append(value)
# Next the remaining entries read from disk
key_added = self.cache.has_key
for address in self.index.values():
key,value = read(address)
if not key_added(key):
l.append(value)
return l
def items(self,
DELETED=DELETED):
""" Return a list of items.
The method does not load any data into the cache, but does
take notice of uncommitted changes.
"""
l = []
read = self.storage.read
# First the cache entries that are not yet committed
for key,(state,value) in self.cache.items():
if state != DELETED:
l.append((key,value))
# Next the remaining entries read from disk
key_added = self.cache.has_key
for address in self.index.values():
key,value = read(address)
if not key_added(key):
l.append((key,value))
return l
def cursor(self, key=FirstKey, default=None):
""" Return a cursor instance for this kind of dictionary.
If key is given, the cursor is positioned on that key in
the dictionary. Otherwise, the first entry in the
dictionary is used which guarantees that all entries are
scanned.
Note that cursors operate with the data on disk. The
method will raise an error in case there are uncommitted
changes pending.
In case the key is not found, default is returned instead.
"""
# Check for uncommitted changes
if self.cache and self.changed():
raise Error,'uncommitted data exists'
# Get the index cursor and create a dict cursor from it
cursor = self.index_cursor(key,None)
if cursor is None:
return default
return BeeDictCursor(self,cursor)
def collect_callback(self, old_position, new_position, raw_data):
""" Internal callback used to update the index when
the storage garbage collector moves a record.
"""
key = hash(self.storage.decode_key(raw_data))
try:
self.index.update(key,new_position,old_position)
except KeyError:
# Ok, then we'll add the key as new entry
log(SYSTEM_WARNING,
'Collect callback detected a missing key in '
'index: %i; restoring it',old_position)
self.index[key] = new_position
def recover_callback(self, old_position, new_position, raw_data):
""" Internal callback used to update the index when
the storage recovery collector finds a record.
old_position is only given as additional information.
new_position contains the position of the found record.
"""
self.index[hash(self.storage.decode_key(raw_data))] = new_position
###
class BeeDictCursor(BeeBaseDictCursor):
""" Cursor for BeeDict instances.
Since the keys are not kept directly in the index, .read_key()
must be used to obtain the real key objects instead of
querying the instance variable .key.
"""
def read(self):
""" Reads the value object from the dict to which the cursor
currently points.
"""
keyobj = self.dict.storage.read_key(self.value)
return self.dict[keyobj]
def read_key(self):
""" Reads the key object from the dict to which the cursor
currently points.
"""
return self.dict.storage.read_key(self.value)
def read_item(self):
""" Reads the (key, value) item object from the dict to which
the cursor currently points.
"""
keyobj = self.dict.storage.read_key(self.value)
return keyobj, self.dict[keyobj]
def write(self,object):
""" Writes the value object to the dict under the key to which
the cursor currently points.
The new data is not written to disk until the dictionary's
current transaction is committed.
"""
keyobj = self.dict.storage.read_key(self.value)
self.dict[keyobj] = object
freeze(BeeDictCursor)
###
class BeeStringDict(BeeBaseDict):
""" A dictionary that is indexed by limited size strings.
The key strings may *not* contain embedded \0 characters.
Though the keys must be strings of limited size, the values
can be any pickleable object.
"""
def __init__(self,name,keysize=10,min_recordsize=0,readonly=0,recover=0,
autocommit=0,validate=0, maxcachesize=None,
basemethod=BeeBaseDict.__init__):
""" Create an instance using name as dictionary name.
Two files will be created: <name>.dat and <name>.idx.
keysize gives the maximal size of the strings used as
index keys.
min_recordsize gives a hint to the expected typical size
of (key,value) pickles: all records will have at least
this size.
To open the dictionary in recovery mode, pass a keyword
recover=1. Then run .recover() and reopen using the normal
settings.
If autocommit is true the cache control will do an
automatic .commit() whenever the transaction log
overflows.
If validate is true, the dictionary will run a validation
check after having successfully opened storage and index.
RecreateIndexError or RecoverError exceptions could be
raised in case inconsistencies are found.
maxcachesize defines the maximum size of the in-memory
transaction cache. It defaults to MAXCACHESIZE if not
given.
XXX Save keysize in storage file header.
"""
basemethod(self, name, keysize=keysize, min_recordsize=min_recordsize,
readonly=readonly, recover=recover,
autocommit=autocommit, validate=validate,
index=BeeIndex.BeeStringIndex,
maxcachesize=maxcachesize)
def commit(self,
basemethod=BeeBaseDict.commit,DELETED=DELETED,MODIFIED=MODIFIED):
""" Commit all changes and start a new transaction.
"""
# Write all changed entries in the cache to disk
index = self.index
index_get = index.get
storage = self.storage
storage_write = storage.write
storage_delete = storage.delete
readonly = self.readonly
NotFound = None
debug = _debug
if debug:
log(SYSTEM_DEBUG,'Committing all changes for "%s"...',self.name)
for key,(state,value) in self.cache.items():
if state == MODIFIED:
if debug:
log.object(SYSTEM_DEBUG,' writing key %s:' % repr(key), value)
address = index_get(key,NotFound)
if address is not NotFound:
# Update storage
new_addr = storage_write(key,value,address)
if new_addr == address:
continue
# Update index
index[key] = new_addr
else:
# Add to storage
address = storage_write(key,value)
# Add to the index
index[key] = address
elif state == DELETED:
if debug:
log(SYSTEM_DEBUG,' deleting key %s', repr(key))
if readonly:
raise Error,'dict is read-only'
address = index_get(key,NotFound)
if address is not NotFound:
# Delete record
storage_delete(address)
# Update Index
del index[key]
else:
raise KeyError,'key not found'
# End the storage transaction
storage.end_transaction()
# Call basemethod
basemethod(self)
def read(self,key,checkonly=0):
address = self.index[key]
if checkonly:
return
else:
return self.storage.read(address)[1]
def keys(self):
""" Return a list of keys.
The method will raise an error if there are uncommitted
changes pending. Output is sorted ascending according to
keys.
"""
if self.cache and self.changed():
raise Error,'uncommitted data exists'
return self.index.keys()
def values(self):
""" Return a list of values.
The method will raise an error if there are uncommitted
changes pending. Output is sorted ascending according to
keys.
"""
if self.cache and self.changed():
raise Error,'uncommitted data exists'
l = []
read = self.storage.read
for address in self.index.values():
l.append(read(address)[1])
return l
def items(self):
""" Return a list of items.
The method will raise an error if there are uncommitted
changes pending. Output is sorted ascending according to
keys.
"""
if self.cache and self.changed():
raise Error,'uncommitted data exists'
l = []
read = self.storage.read
for address in self.index.values():
l.append(read(address))
return l
def cursor(self, key=FirstKey, default=None):
""" Return a cursor instance for this kind of dictionary.
If key is given, the cursor is positioned on that key in
the dictionary. Otherwise, the first entry in the
dictionary is used which guarantees that all entries are
scanned.
Note that cursors operate with the data on disk meaning
that any uncommitted changes will not be seen by the
cursor.
In case the key is not found, default is returned instead.
"""
# Check for uncommitted changes
if self.cache and self.changed():
raise Error,'uncommitted data exists'
# Get the index cursor and create a dict cursor from it
cursor = self.index.cursor(key,None)
if cursor is None:
return default
return BeeStringDictCursor(self,cursor)
def collect_callback(self,old_position,new_position,raw_data):
""" Internal callback used to update the index when
the storage garbage collector moves a record.
"""
key = self.storage.decode_key(raw_data)
try:
self.index.update(key,new_position,old_position)
except KeyError:
# Ok, then we'll add the key as new entry
log(SYSTEM_WARNING,
'Collect callback detected a missing key in '
'index: %i; restoring it',old_position)
self.index[key] = new_position
def recover_callback(self,old_position,new_position,raw_data):
""" Internal callback used to update the index when
the storage recovery collector finds a record.
old_position is only given as additional information.
new_position contains the position of the found record.
XXX What if the recovery collector find two records
with the same key ?
"""
self.index[self.storage.decode_key(raw_data)] = new_position
freeze(BeeStringDict)
###
class BeeFixedLengthStringDict(BeeStringDict):
""" A dictionary that is indexed by fixed length strings.
The key strings may contain embedded \0 characters.
Though the keys must be strings of limited size, the values
can be any pickleable object.
"""
def __init__(self,name,keysize=10,min_recordsize=0,readonly=0,recover=0,
autocommit=0,validate=0, maxcachesize=None,
basemethod=BeeBaseDict.__init__):
""" Create an instance using name as dictionary name.
Two files will be created: <name>.dat and <name>.idx.
keysize gives the maximal size of the strings used as
index keys.
min_recordsize gives a hint to the expected typical size
of (key,value) pickles: all records will have at least
this size.
To open the dictionary in recovery mode, pass a keyword
recover=1. Then run .recover() and reopen using the normal
settings.
If autocommit is true the cache control will do an
automatic .commit() whenever the transaction log
overflows.
If validate is true, the dictionary will run a validation
check after having successfully opened storage and index.
RecreateIndexError or RecoverError exceptions could be
raised in case inconsistencies are found.
maxcachesize defines the maximum size of the in-memory
transaction cache. It defaults to MAXCACHESIZE if not
given.
XXX Save keysize in storage file header.
"""
basemethod(self, name, keysize=keysize, min_recordsize=min_recordsize,
readonly=readonly, recover=recover,
autocommit=autocommit, validate=validate,
index=BeeIndex.BeeFixedLengthStringIndex,
maxcachesize=maxcachesize)
freeze(BeeFixedLengthStringDict)
###
class BeeStringDictCursor(BeeBaseDictCursor):
""" Cursor for BeeStringDict and BeeFixedLengthStringDict instances.
"""
def read_key(self):
""" Reads the key object from the dict to which the cursor
currently points.
"""
return self.key
def read_item(self):
""" Reads the (key, value) item object from the dict to which
the cursor currently points.
"""
return self.key, self.dict[self.key]
freeze(BeeStringDictCursor)
###
def AutoRecover(Class,*args,**kws):
""" Wrapper that runs recovery whenever needed.
This can still fail, but at least many "normal" failures can
be handled this way automatically.
"""
try:
d = apply(Class,args,kws)
return d
except BeeStorage.RunRecoveryError:
pass
except RecreateIndexError:
pass
except RecoverError:
pass
# Open in recovery mode
log(SYSTEM_ERROR,
'Database "%s" is corrupt; trying recovery...',args[0])
new_kws = kws.copy()
new_kws['readonly'] = 0
new_kws['validate'] = 0
#new_kws['lock'] = 1
new_kws['recover'] = 1
d = apply(Class,args,new_kws)
# Run recover & close
d.recover()
del d
# Reopen in original mode
d = apply(Class,args,kws)
log(SYSTEM_WARNING,
'Successfully recovered the database "%s"',args[0])
return d
###
if __name__ == '__main__':
import sys
print 'Testing BeeStringDict...'
s = BeeStringDict('test-BeeStringDict')
s['Marc'] = 'Sveta'
s['Thorsten'] = 'Petra'
s['Christian'] = 'Leesa'
s.commit()
print 'Testing BeeDict...'
d = BeeDict('test-BeeDict')
d['Marc'] = 'Sveta'
d['Thorsten'] = 'Petra'
d['Christian'] = 'Leesa'
d.commit()
d['Marc'] = 'Sveta' * 100
d.commit()
del d,s
print 'Testing iteration...'
d = BeeDict('test-BeeDict')
d['Marc'] = 'Sveta'
d['Thorsten'] = 'Petra'
d['Christian'] = 'Leesa'
d.commit()
i = 0
for k,v in d.iteritems():
print '%s: %s' % (k,v)
i = i + 1
assert i == 3
if sys.version[:3] >= '2.2':
i = 0
for k,v in d:
print '%s: %s' % (k,v)
i = i + 1
assert i == 3
del d
print 'Works.'
|