blob: 33668f44ae469b50d77006d9462ac5db453d8421 [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. Smithb7de61b2007-10-09 07:19:11 +000096 if HIGHEST_PROTOCOL:
97 self.protocol = HIGHEST_PROTOCOL
98 else:
99 self.protocol = 1
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000100
101
102 def __del__(self):
103 self.close()
104
105
106 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +0000107 """Many methods we can just pass through to the DB object.
108 (See below)
109 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000110 return getattr(self.db, name)
111
112
113 #-----------------------------------
114 # Dictionary access methods
115
116 def __len__(self):
117 return len(self.db)
118
119
120 def __getitem__(self, key):
121 data = self.db[key]
122 return cPickle.loads(data)
123
124
125 def __setitem__(self, key, value):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000126 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000127 self.db[key] = data
128
129
130 def __delitem__(self, key):
131 del self.db[key]
132
133
134 def keys(self, txn=None):
135 if txn != None:
136 return self.db.keys(txn)
137 else:
138 return self.db.keys()
139
140
141 def items(self, txn=None):
142 if txn != None:
143 items = self.db.items(txn)
144 else:
145 items = self.db.items()
146 newitems = []
147
148 for k, v in items:
149 newitems.append( (k, cPickle.loads(v)) )
150 return newitems
151
152 def values(self, txn=None):
153 if txn != None:
154 values = self.db.values(txn)
155 else:
156 values = self.db.values()
157
158 return map(cPickle.loads, values)
159
160 #-----------------------------------
161 # Other methods
162
Gregory P. Smith1281f762004-03-16 18:50:26 +0000163 def __append(self, value, txn=None):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000164 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000165 return self.db.append(data, txn)
166
Gregory P. Smith1281f762004-03-16 18:50:26 +0000167 def append(self, value, txn=None):
Gregory P. Smithd40f1262007-10-12 18:44:06 +0000168 if self.get_type() == db.DB_RECNO:
Gregory P. Smith1281f762004-03-16 18:50:26 +0000169 self.append = self.__append
170 return self.append(value, txn=txn)
Gregory P. Smithd40f1262007-10-12 18:44:06 +0000171 raise DBShelveError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"
Gregory P. Smith1281f762004-03-16 18:50:26 +0000172
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000173
174 def associate(self, secondaryDB, callback, flags=0):
175 def _shelf_callback(priKey, priData, realCallback=callback):
176 data = cPickle.loads(priData)
177 return realCallback(priKey, data)
178 return self.db.associate(secondaryDB, _shelf_callback, flags)
179
180
181 #def get(self, key, default=None, txn=None, flags=0):
182 def get(self, *args, **kw):
183 # We do it with *args and **kw so if the default value wasn't
184 # given nothing is passed to the extension module. That way
185 # an exception can be raised if set_get_returns_none is turned
186 # off.
187 data = apply(self.db.get, args, kw)
188 try:
189 return cPickle.loads(data)
190 except (TypeError, cPickle.UnpicklingError):
191 return data # we may be getting the default value, or None,
192 # so it doesn't need unpickled.
193
194 def get_both(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000195 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000196 data = self.db.get(key, data, txn, flags)
197 return cPickle.loads(data)
198
199
200 def cursor(self, txn=None, flags=0):
201 c = DBShelfCursor(self.db.cursor(txn, flags))
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000202 c.protocol = self.protocol
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000203 return c
204
205
206 def put(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000207 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000208 return self.db.put(key, data, txn, flags)
209
210
211 def join(self, cursorList, flags=0):
212 raise NotImplementedError
213
214
215 #----------------------------------------------
216 # Methods allowed to pass-through to self.db
217 #
218 # close, delete, fd, get_byteswapped, get_type, has_key,
219 # key_range, open, remove, rename, stat, sync,
220 # upgrade, verify, and all set_* methods.
221
222
223#---------------------------------------------------------------------------
224
225class DBShelfCursor:
226 """
227 """
228 def __init__(self, cursor):
229 self.dbc = cursor
230
231 def __del__(self):
232 self.close()
233
234
235 def __getattr__(self, name):
236 """Some methods we can just pass through to the cursor object. (See below)"""
237 return getattr(self.dbc, name)
238
239
240 #----------------------------------------------
241
242 def dup(self, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000243 c = DBShelfCursor(self.dbc.dup(flags))
244 c.protocol = self.protocol
245 return c
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000246
247
248 def put(self, key, value, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000249 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000250 return self.dbc.put(key, data, flags)
251
252
253 def get(self, *args):
254 count = len(args) # a method overloading hack
255 method = getattr(self, 'get_%d' % count)
256 apply(method, args)
257
258 def get_1(self, flags):
259 rec = self.dbc.get(flags)
260 return self._extract(rec)
261
262 def get_2(self, key, flags):
263 rec = self.dbc.get(key, flags)
264 return self._extract(rec)
265
266 def get_3(self, key, value, flags):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000267 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000268 rec = self.dbc.get(key, flags)
269 return self._extract(rec)
270
271
272 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
273 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
274 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
275 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
276 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
277 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
278 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
279 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
280 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
281
282
283 def get_both(self, key, value, flags=0):
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_both(key, flags)
286 return self._extract(rec)
287
288
289 def set(self, key, flags=0):
290 rec = self.dbc.set(key, flags)
291 return self._extract(rec)
292
293 def set_range(self, key, flags=0):
294 rec = self.dbc.set_range(key, flags)
295 return self._extract(rec)
296
297 def set_recno(self, recno, flags=0):
298 rec = self.dbc.set_recno(recno, flags)
299 return self._extract(rec)
300
301 set_both = get_both
302
303 def _extract(self, rec):
304 if rec is None:
305 return None
306 else:
307 key, data = rec
308 return key, cPickle.loads(data)
309
310 #----------------------------------------------
311 # Methods allowed to pass-through to self.dbc
312 #
313 # close, count, delete, get_recno, join_item
314
315
316#---------------------------------------------------------------------------