1 # dblite.py module contributed by Ralf W. Grosse-Kunstleve.
2 # Extended for Unicode by Steven Knight.
11 keep_all_files = 00000
12 ignore_corrupt_dbfiles = 0
14 def corruption_warning(filename):
15 print "Warning: Discarding corrupt database:", filename
17 if hasattr(types, 'UnicodeType'):
20 return t is types.StringType or t is types.UnicodeType
23 return type(s) is types.StringType
28 def unicode(s): return s
30 dblite_suffix = '.dblite'
35 # Squirrel away references to the functions in various modules
36 # that we'll use when our __del__() method calls our sync() method
37 # during shutdown. We might get destroyed when Python is in the midst
38 # of tearing down the different modules we import in an essentially
39 # arbitrary order, and some of the various modules's global attributes
40 # may already be wiped out from under us.
42 # See the discussion at:
43 # http://mail.python.org/pipermail/python-bugs-list/2003-March/016877.html
45 _open = __builtin__.open
46 _cPickle_dump = cPickle.dump
50 except AttributeError:
52 _os_rename = os.rename
53 _os_unlink = os.unlink
54 _shutil_copyfile = shutil.copyfile
55 _time_time = time.time
57 def __init__(self, file_base_name, flag, mode):
58 assert flag in (None, "r", "w", "c", "n")
59 if (flag is None): flag = "r"
60 base, ext = os.path.splitext(file_base_name)
61 if ext == dblite_suffix:
62 # There's already a suffix on the file name, don't add one.
63 self._file_name = file_base_name
64 self._tmp_name = base + tmp_suffix
66 self._file_name = file_base_name + dblite_suffix
67 self._tmp_name = file_base_name + tmp_suffix
71 self._needs_sync = 00000
72 if self._os_chown is not None and (os.geteuid()==0 or os.getuid()==0):
73 # running as root; chown back to current owner/group when done
75 statinfo = os.stat(self._file_name)
76 self._chown_to = statinfo.st_uid
77 self._chgrp_to = statinfo.st_gid
79 # db file doesn't exist yet.
80 # Check os.environ for SUDO_UID, use if set
81 self._chown_to = int(os.environ.get('SUDO_UID', -1))
82 self._chgrp_to = int(os.environ.get('SUDO_GID', -1))
84 self._chown_to = -1 # don't chown
85 self._chgrp_to = -1 # don't chgrp
86 if (self._flag == "n"):
87 self._open(self._file_name, "wb", self._mode)
90 f = self._open(self._file_name, "rb")
92 if (self._flag != "c"):
94 self._open(self._file_name, "wb", self._mode)
99 self._dict = cPickle.loads(p)
100 except (cPickle.UnpicklingError, EOFError):
101 if (ignore_corrupt_dbfiles == 0): raise
102 if (ignore_corrupt_dbfiles == 1):
103 corruption_warning(self._file_name)
106 if (self._needs_sync):
110 self._check_writable()
111 f = self._open(self._tmp_name, "wb", self._mode)
112 self._cPickle_dump(self._dict, f, 1)
114 # Windows doesn't allow renaming if the file exists, so unlink
115 # it first, chmod'ing it to make sure we can do so. On UNIX, we
116 # may not be able to chmod the file if it's owned by someone else
117 # (e.g. from a previous run as root). We should still be able to
118 # unlink() the file if the directory's writable, though, so ignore
119 # any OSError exception thrown by the chmod() call.
120 try: self._os_chmod(self._file_name, 0777)
122 self._os_unlink(self._file_name)
123 self._os_rename(self._tmp_name, self._file_name)
124 if self._os_chown is not None and self._chown_to > 0: # don't chown to root or -1
126 self._os_chown(self._file_name, self._chown_to, self._chgrp_to)
129 self._needs_sync = 00000
131 self._shutil_copyfile(
133 self._file_name + "_" + str(int(self._time_time())))
135 def _check_writable(self):
136 if (self._flag == "r"):
137 raise IOError("Read-only database: %s" % self._file_name)
139 def __getitem__(self, key):
140 return self._dict[key]
142 def __setitem__(self, key, value):
143 self._check_writable()
144 if (not is_string(key)):
145 raise TypeError, "key `%s' must be a string but is %s" % (key, type(key))
146 if (not is_string(value)):
147 raise TypeError, "value `%s' must be a string but is %s" % (value, type(value))
148 self._dict[key] = value
149 self._needs_sync = 0001
152 return self._dict.keys()
154 def has_key(self, key):
155 return key in self._dict
157 def __contains__(self, key):
158 return key in self._dict
161 return self._dict.iterkeys()
166 return len(self._dict)
168 def open(file, flag=None, mode=0666):
169 return dblite(file, flag, mode)
172 db = open("tmp", "n")
175 assert db["foo"] == "bar"
176 db[unicode("ufoo")] = unicode("ubar")
177 assert db[unicode("ufoo")] == unicode("ubar")
179 db = open("tmp", "c")
180 assert len(db) == 2, len(db)
181 assert db["foo"] == "bar"
183 assert db["bar"] == "foo"
184 db[unicode("ubar")] = unicode("ufoo")
185 assert db[unicode("ubar")] == unicode("ufoo")
187 db = open("tmp", "r")
188 assert len(db) == 4, len(db)
189 assert db["foo"] == "bar"
190 assert db["bar"] == "foo"
191 assert db[unicode("ufoo")] == unicode("ubar")
192 assert db[unicode("ubar")] == unicode("ufoo")
196 assert str(e) == "Read-only database: tmp.dblite"
198 raise RuntimeError, "IOError expected."
199 db = open("tmp", "w")
206 assert str(e) == "key `(1, 2)' must be a string but is <type 'tuple'>", str(e)
208 raise RuntimeError, "TypeError exception expected"
212 assert str(e) == "value `[1, 2]' must be a string but is <type 'list'>", str(e)
214 raise RuntimeError, "TypeError exception expected"
215 db = open("tmp", "r")
217 db = open("tmp", "n")
219 _open("tmp.dblite", "w")
220 db = open("tmp", "r")
221 _open("tmp.dblite", "w").write("x")
223 db = open("tmp", "r")
224 except cPickle.UnpicklingError:
227 raise RuntimeError, "cPickle exception expected."
228 global ignore_corrupt_dbfiles
229 ignore_corrupt_dbfiles = 2
230 db = open("tmp", "r")
232 os.unlink("tmp.dblite")
234 db = open("tmp", "w")
236 assert str(e) == "[Errno 2] No such file or directory: 'tmp.dblite'", str(e)
238 raise RuntimeError, "IOError expected."
241 if (__name__ == "__main__"):
246 # indent-tabs-mode:nil
248 # vim: set expandtab tabstop=4 shiftwidth=4: