blob: 3186edf1a78dfa707a0171d37dc6a26eef738f40 [file] [log] [blame]
Guido van Rossum8d12a1b1996-07-30 16:30:15 +00001"""Guess which db package to use to open a db file."""
2
3import struct
4
5def whichdb(filename):
6 """Guess which db package to use to open a db file.
7
8 Return values:
9
10 - None if the database file can't be read;
11 - empty string if the file can be read but can't be recognized
12 - the module name (e.g. "dbm" or "gdbm") if recognized.
13
14 Importing the given module may still fail, and opening the
15 database using that module may still fail.
16 """
17
18 # Check for dbm first -- this has a .pag and a .dir file
19 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000020 f = open(filename + ".pag", "rb")
21 f.close()
22 f = open(filename + ".dir", "rb")
23 f.close()
24 return "dbm"
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000025 except IOError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000026 pass
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000027
28 # See if the file exists, return None if not
29 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000030 f = open(filename, "rb")
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000031 except IOError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000032 return None
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000033
34 # Read the first 4 bytes of the file -- the magic number
35 s = f.read(4)
36 f.close()
37
38 # Return "" if not at least 4 bytes
39 if len(s) != 4:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000040 return ""
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000041
42 # Convert to 4-byte int in native byte order -- return "" if impossible
43 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000044 (magic,) = struct.unpack("=l", s)
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000045 except struct.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000046 return ""
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000047
48 # Check for GNU dbm
49 if magic == 0x13579ace:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000050 return "gdbm"
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000051
52 # Check for BSD hash
53 if magic == 0x061561:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000054 return "dbhash"
Guido van Rossum8d12a1b1996-07-30 16:30:15 +000055
56 # Unknown
57 return ""