blob: f5f8b9a5cb894dac813283579b7c44ef04eba2c1 [file] [log] [blame]
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +00001#!/bin/env python
2#------------------------------------------------------------------------
3# Copyright (c) 1997-2001 by Total Control Software
4# All Rights Reserved
5#------------------------------------------------------------------------
6#
7# Module Name: dbShelve.py
8#
9# Description: A reimplementation of the standard shelve.py that
10# forces the use of cPickle, and DB.
11#
12# Creation Date: 11/3/97 3:39:04PM
13#
14# License: This is free software. You may use this software for any
15# purpose including modification/redistribution, so long as
16# this header remains intact and that you do not claim any
17# rights of ownership or authorship of this software. This
18# software has been tested, but no warranty is expressed or
19# implied.
20#
21# 13-Dec-2000: Updated to be used with the new bsddb3 package.
22# Added DBShelfCursor class.
23#
24#------------------------------------------------------------------------
25
Barry Warsaw9a0d7792002-12-30 20:53:52 +000026"""Manage shelves of pickled objects using bsddb database files for the
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000027storage.
28"""
29
30#------------------------------------------------------------------------
31
32import cPickle
Gregory P. Smith41631e82003-09-21 00:08:14 +000033import db
Gregory P. Smithb7de61b2007-10-09 07:19:11 +000034import sys
35
36#At version 2.3 cPickle switched to using protocol instead of bin and
37#DictMixin was added
38if sys.version_info[:3] >= (2, 3, 0):
39 HIGHEST_PROTOCOL = cPickle.HIGHEST_PROTOCOL
40 def _dumps(object, protocol):
41 return cPickle.dumps(object, protocol=protocol)
42 from UserDict import DictMixin
43else:
44 HIGHEST_PROTOCOL = None
45 def _dumps(object, protocol):
46 return cPickle.dumps(object, bin=protocol)
47 class DictMixin: pass
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000048
49#------------------------------------------------------------------------
50
51
52def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH,
53 dbenv=None, dbname=None):
54 """
55 A simple factory function for compatibility with the standard
56 shleve.py module. It can be used like this, where key is a string
57 and data is a pickleable object:
58
Barry Warsaw9a0d7792002-12-30 20:53:52 +000059 from bsddb import dbshelve
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000060 db = dbshelve.open(filename)
61
62 db[key] = data
63
64 db.close()
65 """
66 if type(flags) == type(''):
67 sflag = flags
68 if sflag == 'r':
69 flags = db.DB_RDONLY
70 elif sflag == 'rw':
71 flags = 0
72 elif sflag == 'w':
73 flags = db.DB_CREATE
74 elif sflag == 'c':
75 flags = db.DB_CREATE
76 elif sflag == 'n':
77 flags = db.DB_TRUNCATE | db.DB_CREATE
78 else:
Gregory P. Smith1281f762004-03-16 18:50:26 +000079 raise db.DBError, "flags should be one of 'r', 'w', 'c' or 'n' or use the bsddb.db.DB_* flags"
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000080
81 d = DBShelf(dbenv)
82 d.open(filename, dbname, filetype, flags, mode)
83 return d
84
85#---------------------------------------------------------------------------
86
Gregory P. Smithd40f1262007-10-12 18:44:06 +000087class DBShelveError(db.DBError): pass
88
89
Raymond Hettinger30a634e2003-02-05 04:12:41 +000090class DBShelf(DictMixin):
Barry Warsaw99142272003-02-08 03:18:58 +000091 """A shelf to hold pickled objects, built upon a bsddb DB object. It
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000092 automatically pickles/unpickles data objects going to/from the DB.
93 """
94 def __init__(self, dbenv=None):
95 self.db = db.DB(dbenv)
Gregory P. Smith5d743fd2007-10-13 23:02:05 +000096 self._closed = True
Gregory P. Smithb7de61b2007-10-09 07:19:11 +000097 if HIGHEST_PROTOCOL:
98 self.protocol = HIGHEST_PROTOCOL
99 else:
100 self.protocol = 1
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000101
102
103 def __del__(self):
104 self.close()
105
106
107 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +0000108 """Many methods we can just pass through to the DB object.
109 (See below)
110 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000111 return getattr(self.db, name)
112
113
114 #-----------------------------------
115 # Dictionary access methods
116
117 def __len__(self):
118 return len(self.db)
119
120
121 def __getitem__(self, key):
122 data = self.db[key]
123 return cPickle.loads(data)
124
125
126 def __setitem__(self, key, value):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000127 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000128 self.db[key] = data
129
130
131 def __delitem__(self, key):
132 del self.db[key]
133
134
135 def keys(self, txn=None):
136 if txn != None:
137 return self.db.keys(txn)
138 else:
139 return self.db.keys()
140
141
Gregory P. Smith5d743fd2007-10-13 23:02:05 +0000142 def open(self, *args, **kwargs):
143 self.db.open(*args, **kwargs)
144 self._closed = False
145
146
147 def close(self, *args, **kwargs):
148 self.db.close(*args, **kwargs)
149 self._closed = True
150
151
152 def __repr__(self):
153 if self._closed:
154 return '<DBShelf @ 0x%x - closed>' % (id(self))
155 else:
156 return repr(dict(self.iteritems()))
157
158
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000159 def items(self, txn=None):
160 if txn != None:
161 items = self.db.items(txn)
162 else:
163 items = self.db.items()
164 newitems = []
165
166 for k, v in items:
167 newitems.append( (k, cPickle.loads(v)) )
168 return newitems
169
170 def values(self, txn=None):
171 if txn != None:
172 values = self.db.values(txn)
173 else:
174 values = self.db.values()
175
176 return map(cPickle.loads, values)
177
178 #-----------------------------------
179 # Other methods
180
Gregory P. Smith1281f762004-03-16 18:50:26 +0000181 def __append(self, value, txn=None):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000182 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000183 return self.db.append(data, txn)
184
Gregory P. Smith1281f762004-03-16 18:50:26 +0000185 def append(self, value, txn=None):
Gregory P. Smithd40f1262007-10-12 18:44:06 +0000186 if self.get_type() == db.DB_RECNO:
Gregory P. Smith5d743fd2007-10-13 23:02:05 +0000187 return self.__append(value, txn=txn)
Gregory P. Smithd40f1262007-10-12 18:44:06 +0000188 raise DBShelveError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"
Gregory P. Smith1281f762004-03-16 18:50:26 +0000189
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000190
191 def associate(self, secondaryDB, callback, flags=0):
192 def _shelf_callback(priKey, priData, realCallback=callback):
193 data = cPickle.loads(priData)
194 return realCallback(priKey, data)
195 return self.db.associate(secondaryDB, _shelf_callback, flags)
196
197
198 #def get(self, key, default=None, txn=None, flags=0):
199 def get(self, *args, **kw):
200 # We do it with *args and **kw so if the default value wasn't
201 # given nothing is passed to the extension module. That way
202 # an exception can be raised if set_get_returns_none is turned
203 # off.
204 data = apply(self.db.get, args, kw)
205 try:
206 return cPickle.loads(data)
207 except (TypeError, cPickle.UnpicklingError):
208 return data # we may be getting the default value, or None,
209 # so it doesn't need unpickled.
210
211 def get_both(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000212 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000213 data = self.db.get(key, data, txn, flags)
214 return cPickle.loads(data)
215
216
217 def cursor(self, txn=None, flags=0):
218 c = DBShelfCursor(self.db.cursor(txn, flags))
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000219 c.protocol = self.protocol
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000220 return c
221
222
223 def put(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000224 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000225 return self.db.put(key, data, txn, flags)
226
227
228 def join(self, cursorList, flags=0):
229 raise NotImplementedError
230
231
232 #----------------------------------------------
233 # Methods allowed to pass-through to self.db
234 #
235 # close, delete, fd, get_byteswapped, get_type, has_key,
236 # key_range, open, remove, rename, stat, sync,
237 # upgrade, verify, and all set_* methods.
238
239
240#---------------------------------------------------------------------------
241
242class DBShelfCursor:
243 """
244 """
245 def __init__(self, cursor):
246 self.dbc = cursor
247
248 def __del__(self):
249 self.close()
250
251
252 def __getattr__(self, name):
253 """Some methods we can just pass through to the cursor object. (See below)"""
254 return getattr(self.dbc, name)
255
256
257 #----------------------------------------------
258
259 def dup(self, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000260 c = DBShelfCursor(self.dbc.dup(flags))
261 c.protocol = self.protocol
262 return c
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000263
264
265 def put(self, key, value, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000266 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000267 return self.dbc.put(key, data, flags)
268
269
270 def get(self, *args):
271 count = len(args) # a method overloading hack
272 method = getattr(self, 'get_%d' % count)
273 apply(method, args)
274
275 def get_1(self, flags):
276 rec = self.dbc.get(flags)
277 return self._extract(rec)
278
279 def get_2(self, key, flags):
280 rec = self.dbc.get(key, flags)
281 return self._extract(rec)
282
283 def get_3(self, key, value, flags):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000284 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000285 rec = self.dbc.get(key, flags)
286 return self._extract(rec)
287
288
289 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
290 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
291 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
292 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
293 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
294 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
295 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
296 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
297 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
298
299
300 def get_both(self, key, value, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000301 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000302 rec = self.dbc.get_both(key, flags)
303 return self._extract(rec)
304
305
306 def set(self, key, flags=0):
307 rec = self.dbc.set(key, flags)
308 return self._extract(rec)
309
310 def set_range(self, key, flags=0):
311 rec = self.dbc.set_range(key, flags)
312 return self._extract(rec)
313
314 def set_recno(self, recno, flags=0):
315 rec = self.dbc.set_recno(recno, flags)
316 return self._extract(rec)
317
318 set_both = get_both
319
320 def _extract(self, rec):
321 if rec is None:
322 return None
323 else:
324 key, data = rec
325 return key, cPickle.loads(data)
326
327 #----------------------------------------------
328 # Methods allowed to pass-through to self.dbc
329 #
330 # close, count, delete, get_recno, join_item
331
332
333#---------------------------------------------------------------------------