1 # dblite.py module contributed by Ralf W. Grosse-Kunstleve.
2 # Extended for Unicode by Steven Knight.
8 # compat layer imports "cPickle" for us if it's available.
13 keep_all_files = 00000
14 ignore_corrupt_dbfiles = 0
16 def corruption_warning(filename):
17 print "Warning: Discarding corrupt database:", filename
22 return isinstance(s, str)
25 return type(s) in (str, unicode)
30 def unicode(s): return s
32 dblite_suffix = '.dblite'
37 # Squirrel away references to the functions in various modules
38 # that we'll use when our __del__() method calls our sync() method
39 # during shutdown. We might get destroyed when Python is in the midst
40 # of tearing down the different modules we import in an essentially
41 # arbitrary order, and some of the various modules's global attributes
42 # may already be wiped out from under us.
44 # See the discussion at:
45 # http://mail.python.org/pipermail/python-bugs-list/2003-March/016877.html
48 _pickle_dump = staticmethod(pickle.dump)
52 except AttributeError:
54 _os_rename = os.rename
55 _os_unlink = os.unlink
56 _shutil_copyfile = shutil.copyfile
57 _time_time = time.time
59 def __init__(self, file_base_name, flag, mode):
60 assert flag in (None, "r", "w", "c", "n")
61 if (flag is None): flag = "r"
62 base, ext = os.path.splitext(file_base_name)
63 if ext == dblite_suffix:
64 # There's already a suffix on the file name, don't add one.
65 self._file_name = file_base_name
66 self._tmp_name = base + tmp_suffix
68 self._file_name = file_base_name + dblite_suffix
69 self._tmp_name = file_base_name + tmp_suffix
73 self._needs_sync = 00000
74 if self._os_chown is not None and (os.geteuid()==0 or os.getuid()==0):
75 # running as root; chown back to current owner/group when done
77 statinfo = os.stat(self._file_name)
78 self._chown_to = statinfo.st_uid
79 self._chgrp_to = statinfo.st_gid
81 # db file doesn't exist yet.
82 # Check os.environ for SUDO_UID, use if set
83 self._chown_to = int(os.environ.get('SUDO_UID', -1))
84 self._chgrp_to = int(os.environ.get('SUDO_GID', -1))
86 self._chown_to = -1 # don't chown
87 self._chgrp_to = -1 # don't chgrp
88 if (self._flag == "n"):
89 self._open(self._file_name, "wb", self._mode)
92 f = self._open(self._file_name, "rb")
94 if (self._flag != "c"):
96 self._open(self._file_name, "wb", self._mode)
101 self._dict = pickle.loads(p)
102 except (pickle.UnpicklingError, EOFError):
103 if (ignore_corrupt_dbfiles == 0): raise
104 if (ignore_corrupt_dbfiles == 1):
105 corruption_warning(self._file_name)
108 if (self._needs_sync):
112 self._check_writable()
113 f = self._open(self._tmp_name, "wb", self._mode)
114 self._pickle_dump(self._dict, f, 1)
116 # Windows doesn't allow renaming if the file exists, so unlink
117 # it first, chmod'ing it to make sure we can do so. On UNIX, we
118 # may not be able to chmod the file if it's owned by someone else
119 # (e.g. from a previous run as root). We should still be able to
120 # unlink() the file if the directory's writable, though, so ignore
121 # any OSError exception thrown by the chmod() call.
122 try: self._os_chmod(self._file_name, 0777)
124 self._os_unlink(self._file_name)
125 self._os_rename(self._tmp_name, self._file_name)
126 if self._os_chown is not None and self._chown_to > 0: # don't chown to root or -1
128 self._os_chown(self._file_name, self._chown_to, self._chgrp_to)
131 self._needs_sync = 00000
133 self._shutil_copyfile(
135 self._file_name + "_" + str(int(self._time_time())))
137 def _check_writable(self):
138 if (self._flag == "r"):
139 raise IOError("Read-only database: %s" % self._file_name)
141 def __getitem__(self, key):
142 return self._dict[key]
144 def __setitem__(self, key, value):
145 self._check_writable()
146 if (not is_string(key)):
147 raise TypeError("key `%s' must be a string but is %s" % (key, type(key)))
148 if (not is_string(value)):
149 raise TypeError("value `%s' must be a string but is %s" % (value, type(value)))
150 self._dict[key] = value
151 self._needs_sync = 0001
154 return list(self._dict.keys())
156 def has_key(self, key):
157 return key in self._dict
159 def __contains__(self, key):
160 return key in self._dict
163 # Wrapping name in () prevents fixer from "fixing" this
164 return (self._dict.iterkeys)()
169 return len(self._dict)
171 def open(file, flag=None, mode=0666):
172 return dblite(file, flag, mode)
175 db = open("tmp", "n")
178 assert db["foo"] == "bar"
179 db[unicode("ufoo")] = unicode("ubar")
180 assert db[unicode("ufoo")] == unicode("ubar")
182 db = open("tmp", "c")
183 assert len(db) == 2, len(db)
184 assert db["foo"] == "bar"
186 assert db["bar"] == "foo"
187 db[unicode("ubar")] = unicode("ufoo")
188 assert db[unicode("ubar")] == unicode("ufoo")
190 db = open("tmp", "r")
191 assert len(db) == 4, len(db)
192 assert db["foo"] == "bar"
193 assert db["bar"] == "foo"
194 assert db[unicode("ufoo")] == unicode("ubar")
195 assert db[unicode("ubar")] == unicode("ufoo")
199 assert str(e) == "Read-only database: tmp.dblite"
201 raise RuntimeError("IOError expected.")
202 db = open("tmp", "w")
209 assert str(e) == "key `(1, 2)' must be a string but is <type 'tuple'>", str(e)
211 raise RuntimeError("TypeError exception expected")
215 assert str(e) == "value `[1, 2]' must be a string but is <type 'list'>", str(e)
217 raise RuntimeError("TypeError exception expected")
218 db = open("tmp", "r")
220 db = open("tmp", "n")
222 dblite._open("tmp.dblite", "w")
223 db = open("tmp", "r")
224 dblite._open("tmp.dblite", "w").write("x")
226 db = open("tmp", "r")
227 except pickle.UnpicklingError:
230 raise RuntimeError("pickle exception expected.")
231 global ignore_corrupt_dbfiles
232 ignore_corrupt_dbfiles = 2
233 db = open("tmp", "r")
235 os.unlink("tmp.dblite")
237 db = open("tmp", "w")
239 assert str(e) == "[Errno 2] No such file or directory: 'tmp.dblite'", str(e)
241 raise RuntimeError("IOError expected.")
244 if (__name__ == "__main__"):
249 # indent-tabs-mode:nil
251 # vim: set expandtab tabstop=4 shiftwidth=4: