blob: 6d7414ed9cd3174ba8de753f3106b65140fa244c [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
Jesus Cea18eb1fa2008-05-13 20:57:59 +000040# In python 2.3.*, "cPickle.dumps" accepts no
41# named parameters. "pickle.dumps" accepts them,
42# so this seems a bug.
43 if sys.version_info[:3] < (2, 4, 0):
44 def _dumps(object, protocol):
45 return cPickle.dumps(object, protocol)
46 else :
47 def _dumps(object, protocol):
48 return cPickle.dumps(object, protocol=protocol)
49
Gregory P. Smithb7de61b2007-10-09 07:19:11 +000050 from UserDict import DictMixin
Jesus Cea18eb1fa2008-05-13 20:57:59 +000051
Gregory P. Smithb7de61b2007-10-09 07:19:11 +000052else:
53 HIGHEST_PROTOCOL = None
54 def _dumps(object, protocol):
55 return cPickle.dumps(object, bin=protocol)
56 class DictMixin: pass
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000057
58#------------------------------------------------------------------------
59
60
61def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH,
62 dbenv=None, dbname=None):
63 """
64 A simple factory function for compatibility with the standard
65 shleve.py module. It can be used like this, where key is a string
66 and data is a pickleable object:
67
Barry Warsaw9a0d7792002-12-30 20:53:52 +000068 from bsddb import dbshelve
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000069 db = dbshelve.open(filename)
70
71 db[key] = data
72
73 db.close()
74 """
75 if type(flags) == type(''):
76 sflag = flags
77 if sflag == 'r':
78 flags = db.DB_RDONLY
79 elif sflag == 'rw':
80 flags = 0
81 elif sflag == 'w':
82 flags = db.DB_CREATE
83 elif sflag == 'c':
84 flags = db.DB_CREATE
85 elif sflag == 'n':
86 flags = db.DB_TRUNCATE | db.DB_CREATE
87 else:
Gregory P. Smith1281f762004-03-16 18:50:26 +000088 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 +000089
90 d = DBShelf(dbenv)
91 d.open(filename, dbname, filetype, flags, mode)
92 return d
93
94#---------------------------------------------------------------------------
95
Gregory P. Smithd40f1262007-10-12 18:44:06 +000096class DBShelveError(db.DBError): pass
97
98
Raymond Hettinger30a634e2003-02-05 04:12:41 +000099class DBShelf(DictMixin):
Barry Warsaw99142272003-02-08 03:18:58 +0000100 """A shelf to hold pickled objects, built upon a bsddb DB object. It
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000101 automatically pickles/unpickles data objects going to/from the DB.
102 """
103 def __init__(self, dbenv=None):
104 self.db = db.DB(dbenv)
Gregory P. Smith5d743fd2007-10-13 23:02:05 +0000105 self._closed = True
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000106 if HIGHEST_PROTOCOL:
107 self.protocol = HIGHEST_PROTOCOL
108 else:
109 self.protocol = 1
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000110
111
112 def __del__(self):
113 self.close()
114
115
116 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +0000117 """Many methods we can just pass through to the DB object.
118 (See below)
119 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000120 return getattr(self.db, name)
121
122
123 #-----------------------------------
124 # Dictionary access methods
125
126 def __len__(self):
127 return len(self.db)
128
129
130 def __getitem__(self, key):
131 data = self.db[key]
132 return cPickle.loads(data)
133
134
135 def __setitem__(self, key, value):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000136 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000137 self.db[key] = data
138
139
140 def __delitem__(self, key):
141 del self.db[key]
142
143
144 def keys(self, txn=None):
Jesus Cea18eb1fa2008-05-13 20:57:59 +0000145 if txn != None:
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000146 return self.db.keys(txn)
147 else:
148 return self.db.keys()
149
150
Gregory P. Smith5d743fd2007-10-13 23:02:05 +0000151 def open(self, *args, **kwargs):
152 self.db.open(*args, **kwargs)
153 self._closed = False
154
155
156 def close(self, *args, **kwargs):
157 self.db.close(*args, **kwargs)
158 self._closed = True
159
160
161 def __repr__(self):
162 if self._closed:
163 return '<DBShelf @ 0x%x - closed>' % (id(self))
164 else:
165 return repr(dict(self.iteritems()))
166
167
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000168 def items(self, txn=None):
Jesus Cea18eb1fa2008-05-13 20:57:59 +0000169 if txn != None:
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000170 items = self.db.items(txn)
171 else:
172 items = self.db.items()
173 newitems = []
174
175 for k, v in items:
176 newitems.append( (k, cPickle.loads(v)) )
177 return newitems
178
179 def values(self, txn=None):
Jesus Cea18eb1fa2008-05-13 20:57:59 +0000180 if txn != None:
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000181 values = self.db.values(txn)
182 else:
183 values = self.db.values()
184
185 return map(cPickle.loads, values)
186
187 #-----------------------------------
188 # Other methods
189
Gregory P. Smith1281f762004-03-16 18:50:26 +0000190 def __append(self, value, txn=None):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000191 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000192 return self.db.append(data, txn)
193
Gregory P. Smith1281f762004-03-16 18:50:26 +0000194 def append(self, value, txn=None):
Gregory P. Smithd40f1262007-10-12 18:44:06 +0000195 if self.get_type() == db.DB_RECNO:
Gregory P. Smith5d743fd2007-10-13 23:02:05 +0000196 return self.__append(value, txn=txn)
Gregory P. Smithd40f1262007-10-12 18:44:06 +0000197 raise DBShelveError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"
Gregory P. Smith1281f762004-03-16 18:50:26 +0000198
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000199
200 def associate(self, secondaryDB, callback, flags=0):
201 def _shelf_callback(priKey, priData, realCallback=callback):
202 data = cPickle.loads(priData)
203 return realCallback(priKey, data)
204 return self.db.associate(secondaryDB, _shelf_callback, flags)
205
206
207 #def get(self, key, default=None, txn=None, flags=0):
208 def get(self, *args, **kw):
209 # We do it with *args and **kw so if the default value wasn't
210 # given nothing is passed to the extension module. That way
211 # an exception can be raised if set_get_returns_none is turned
212 # off.
213 data = apply(self.db.get, args, kw)
214 try:
215 return cPickle.loads(data)
216 except (TypeError, cPickle.UnpicklingError):
217 return data # we may be getting the default value, or None,
218 # so it doesn't need unpickled.
219
220 def get_both(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000221 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000222 data = self.db.get(key, data, txn, flags)
223 return cPickle.loads(data)
224
225
226 def cursor(self, txn=None, flags=0):
227 c = DBShelfCursor(self.db.cursor(txn, flags))
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000228 c.protocol = self.protocol
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000229 return c
230
231
232 def put(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000233 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000234 return self.db.put(key, data, txn, flags)
235
236
237 def join(self, cursorList, flags=0):
238 raise NotImplementedError
239
240
241 #----------------------------------------------
242 # Methods allowed to pass-through to self.db
243 #
244 # close, delete, fd, get_byteswapped, get_type, has_key,
245 # key_range, open, remove, rename, stat, sync,
246 # upgrade, verify, and all set_* methods.
247
248
249#---------------------------------------------------------------------------
250
251class DBShelfCursor:
252 """
253 """
254 def __init__(self, cursor):
255 self.dbc = cursor
256
257 def __del__(self):
258 self.close()
259
260
261 def __getattr__(self, name):
262 """Some methods we can just pass through to the cursor object. (See below)"""
263 return getattr(self.dbc, name)
264
265
266 #----------------------------------------------
267
268 def dup(self, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000269 c = DBShelfCursor(self.dbc.dup(flags))
270 c.protocol = self.protocol
271 return c
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000272
273
274 def put(self, key, value, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000275 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000276 return self.dbc.put(key, data, flags)
277
278
279 def get(self, *args):
280 count = len(args) # a method overloading hack
281 method = getattr(self, 'get_%d' % count)
282 apply(method, args)
283
284 def get_1(self, flags):
285 rec = self.dbc.get(flags)
286 return self._extract(rec)
287
288 def get_2(self, key, flags):
289 rec = self.dbc.get(key, flags)
290 return self._extract(rec)
291
292 def get_3(self, key, value, flags):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000293 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000294 rec = self.dbc.get(key, flags)
295 return self._extract(rec)
296
297
298 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
299 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
300 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
301 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
302 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
303 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
304 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
305 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
306 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
307
308
309 def get_both(self, key, value, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000310 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000311 rec = self.dbc.get_both(key, flags)
312 return self._extract(rec)
313
314
315 def set(self, key, flags=0):
316 rec = self.dbc.set(key, flags)
317 return self._extract(rec)
318
319 def set_range(self, key, flags=0):
320 rec = self.dbc.set_range(key, flags)
321 return self._extract(rec)
322
323 def set_recno(self, recno, flags=0):
324 rec = self.dbc.set_recno(recno, flags)
325 return self._extract(rec)
326
327 set_both = get_both
328
329 def _extract(self, rec):
330 if rec is None:
331 return None
332 else:
333 key, data = rec
334 return key, cPickle.loads(data)
335
336 #----------------------------------------------
337 # Methods allowed to pass-through to self.dbc
338 #
339 # close, count, delete, get_recno, join_item
340
341
342#---------------------------------------------------------------------------