__init__.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """Generic interface to all dbm clones.
  2. Use
  3. import dbm
  4. d = dbm.open(file, 'w', 0o666)
  5. The returned object is a dbm.gnu, dbm.ndbm or dbm.dumb object, dependent on the
  6. type of database being opened (determined by the whichdb function) in the case
  7. of an existing dbm. If the dbm does not exist and the create or new flag ('c'
  8. or 'n') was specified, the dbm type will be determined by the availability of
  9. the modules (tested in the above order).
  10. It has the following interface (key and data are strings):
  11. d[key] = data # store data at key (may override data at
  12. # existing key)
  13. data = d[key] # retrieve data at key (raise KeyError if no
  14. # such key)
  15. del d[key] # delete data stored at key (raises KeyError
  16. # if no such key)
  17. flag = key in d # true if the key exists
  18. list = d.keys() # return a list of all existing keys (slow!)
  19. Future versions may change the order in which implementations are
  20. tested for existence, and add interfaces to other dbm-like
  21. implementations.
  22. """
  23. __all__ = ['open', 'whichdb', 'error']
  24. import io
  25. import os
  26. import struct
  27. import sys
  28. class error(Exception):
  29. pass
  30. _names = ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb']
  31. _defaultmod = None
  32. _modules = {}
  33. error = (error, OSError)
  34. try:
  35. from dbm import ndbm
  36. except ImportError:
  37. ndbm = None
  38. def open(file, flag='r', mode=0o666):
  39. """Open or create database at path given by *file*.
  40. Optional argument *flag* can be 'r' (default) for read-only access, 'w'
  41. for read-write access of an existing database, 'c' for read-write access
  42. to a new or existing database, and 'n' for read-write access to a new
  43. database.
  44. Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
  45. only if it doesn't exist; and 'n' always creates a new database.
  46. """
  47. global _defaultmod
  48. if _defaultmod is None:
  49. for name in _names:
  50. try:
  51. mod = __import__(name, fromlist=['open'])
  52. except ImportError:
  53. continue
  54. if not _defaultmod:
  55. _defaultmod = mod
  56. _modules[name] = mod
  57. if not _defaultmod:
  58. raise ImportError("no dbm clone found; tried %s" % _names)
  59. # guess the type of an existing database, if not creating a new one
  60. result = whichdb(file) if 'n' not in flag else None
  61. if result is None:
  62. # db doesn't exist or 'n' flag was specified to create a new db
  63. if 'c' in flag or 'n' in flag:
  64. # file doesn't exist and the new flag was used so use default type
  65. mod = _defaultmod
  66. else:
  67. raise error[0]("need 'c' or 'n' flag to open new db")
  68. elif result == "":
  69. # db type cannot be determined
  70. raise error[0]("db type could not be determined")
  71. elif result not in _modules:
  72. raise error[0]("db type is {0}, but the module is not "
  73. "available".format(result))
  74. else:
  75. mod = _modules[result]
  76. return mod.open(file, flag, mode)
  77. def whichdb(filename):
  78. """Guess which db package to use to open a db file.
  79. Return values:
  80. - None if the database file can't be read;
  81. - empty string if the file can be read but can't be recognized
  82. - the name of the dbm submodule (e.g. "ndbm" or "gnu") if recognized.
  83. Importing the given module may still fail, and opening the
  84. database using that module may still fail.
  85. """
  86. # Check for ndbm first -- this has a .pag and a .dir file
  87. try:
  88. f = io.open(filename + ".pag", "rb")
  89. f.close()
  90. f = io.open(filename + ".dir", "rb")
  91. f.close()
  92. return "dbm.ndbm"
  93. except OSError:
  94. # some dbm emulations based on Berkeley DB generate a .db file
  95. # some do not, but they should be caught by the bsd checks
  96. try:
  97. f = io.open(filename + ".db", "rb")
  98. f.close()
  99. # guarantee we can actually open the file using dbm
  100. # kind of overkill, but since we are dealing with emulations
  101. # it seems like a prudent step
  102. if ndbm is not None:
  103. d = ndbm.open(filename)
  104. d.close()
  105. return "dbm.ndbm"
  106. except OSError:
  107. pass
  108. # Check for dumbdbm next -- this has a .dir and a .dat file
  109. try:
  110. # First check for presence of files
  111. os.stat(filename + ".dat")
  112. size = os.stat(filename + ".dir").st_size
  113. # dumbdbm files with no keys are empty
  114. if size == 0:
  115. return "dbm.dumb"
  116. f = io.open(filename + ".dir", "rb")
  117. try:
  118. if f.read(1) in (b"'", b'"'):
  119. return "dbm.dumb"
  120. finally:
  121. f.close()
  122. except OSError:
  123. pass
  124. # See if the file exists, return None if not
  125. try:
  126. f = io.open(filename, "rb")
  127. except OSError:
  128. return None
  129. with f:
  130. # Read the start of the file -- the magic number
  131. s16 = f.read(16)
  132. s = s16[0:4]
  133. # Return "" if not at least 4 bytes
  134. if len(s) != 4:
  135. return ""
  136. # Convert to 4-byte int in native byte order -- return "" if impossible
  137. try:
  138. (magic,) = struct.unpack("=l", s)
  139. except struct.error:
  140. return ""
  141. # Check for GNU dbm
  142. if magic in (0x13579ace, 0x13579acd, 0x13579acf):
  143. return "dbm.gnu"
  144. # Later versions of Berkeley db hash file have a 12-byte pad in
  145. # front of the file type
  146. try:
  147. (magic,) = struct.unpack("=l", s16[-4:])
  148. except struct.error:
  149. return ""
  150. # Unknown
  151. return ""
  152. if __name__ == "__main__":
  153. for filename in sys.argv[1:]:
  154. print(whichdb(filename) or "UNKNOWN", filename)