1 """Guess which db package to use to open a db file."""
11 # just some sort of valid exception which might be raised in the
15 def whichdb(filename
):
16 """Guess which db package to use to open a db file.
20 - None if the database file can't be read;
21 - empty string if the file can be read but can't be recognized
22 - the module name (e.g. "dbm" or "gdbm") if recognized.
24 Importing the given module may still fail, and opening the
25 database using that module may still fail.
28 # Check for dbm first -- this has a .pag and a .dir file
30 f
= open(filename
+ os
.extsep
+ "pag", "rb")
32 f
= open(filename
+ os
.extsep
+ "dir", "rb")
36 # some dbm emulations based on Berkeley DB generate a .db file
37 # some do not, but they should be caught by the dbhash checks
39 f
= open(filename
+ os
.extsep
+ "db", "rb")
41 # guarantee we can actually open the file using dbm
42 # kind of overkill, but since we are dealing with emulations
43 # it seems like a prudent step
45 d
= dbm
.open(filename
)
48 except (IOError, _dbmerror
):
51 # Check for dumbdbm next -- this has a .dir and and a .dat file
53 # First check for presence of files
54 os
.stat(filename
+ os
.extsep
+ "dat")
55 size
= os
.stat(filename
+ os
.extsep
+ "dir").st_size
56 # dumbdbm files with no keys are empty
59 f
= open(filename
+ os
.extsep
+ "dir", "rb")
61 if f
.read(1) in ["'", '"']:
65 except (OSError, IOError):
68 # See if the file exists, return None if not
70 f
= open(filename
, "rb")
74 # Read the start of the file -- the magic number
79 # Return "" if not at least 4 bytes
83 # Convert to 4-byte int in native byte order -- return "" if impossible
85 (magic
,) = struct
.unpack("=l", s
)
90 if magic
== 0x13579ace:
93 # Check for old Berkeley db hash file format v2
94 if magic
in (0x00061561, 0x61150600):
97 # Later versions of Berkeley db hash file have a 12-byte pad in
98 # front of the file type
100 (magic
,) = struct
.unpack("=l", s16
[-4:])
105 if magic
in (0x00061561, 0x61150600):