blob: 077f9c7a9fc9b6f80313526cd14cf842735d1542 [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
Raymond Hettinger30a634e2003-02-05 04:12:41 +000087class DBShelf(DictMixin):
Barry Warsaw99142272003-02-08 03:18:58 +000088 """A shelf to hold pickled objects, built upon a bsddb DB object. It
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000089 automatically pickles/unpickles data objects going to/from the DB.
90 """
91 def __init__(self, dbenv=None):
92 self.db = db.DB(dbenv)
Gregory P. Smithb7de61b2007-10-09 07:19:11 +000093 if HIGHEST_PROTOCOL:
94 self.protocol = HIGHEST_PROTOCOL
95 else:
96 self.protocol = 1
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000097
98
99 def __del__(self):
100 self.close()
101
102
103 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +0000104 """Many methods we can just pass through to the DB object.
105 (See below)
106 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000107 return getattr(self.db, name)
108
109
110 #-----------------------------------
111 # Dictionary access methods
112
113 def __len__(self):
114 return len(self.db)
115
116
117 def __getitem__(self, key):
118 data = self.db[key]
119 return cPickle.loads(data)
120
121
122 def __setitem__(self, key, value):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000123 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000124 self.db[key] = data
125
126
127 def __delitem__(self, key):
128 del self.db[key]
129
130
131 def keys(self, txn=None):
132 if txn != None:
133 return self.db.keys(txn)
134 else:
135 return self.db.keys()
136
137
138 def items(self, txn=None):
139 if txn != None:
140 items = self.db.items(txn)
141 else:
142 items = self.db.items()
143 newitems = []
144
145 for k, v in items:
146 newitems.append( (k, cPickle.loads(v)) )
147 return newitems
148
149 def values(self, txn=None):
150 if txn != None:
151 values = self.db.values(txn)
152 else:
153 values = self.db.values()
154
155 return map(cPickle.loads, values)
156
157 #-----------------------------------
158 # Other methods
159
Gregory P. Smith1281f762004-03-16 18:50:26 +0000160 def __append(self, value, txn=None):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000161 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000162 return self.db.append(data, txn)
163
Gregory P. Smith1281f762004-03-16 18:50:26 +0000164 def append(self, value, txn=None):
165 if self.get_type() != db.DB_RECNO:
166 self.append = self.__append
167 return self.append(value, txn=txn)
168 raise db.DBError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"
169
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000170
171 def associate(self, secondaryDB, callback, flags=0):
172 def _shelf_callback(priKey, priData, realCallback=callback):
173 data = cPickle.loads(priData)
174 return realCallback(priKey, data)
175 return self.db.associate(secondaryDB, _shelf_callback, flags)
176
177
178 #def get(self, key, default=None, txn=None, flags=0):
179 def get(self, *args, **kw):
180 # We do it with *args and **kw so if the default value wasn't
181 # given nothing is passed to the extension module. That way
182 # an exception can be raised if set_get_returns_none is turned
183 # off.
184 data = apply(self.db.get, args, kw)
185 try:
186 return cPickle.loads(data)
187 except (TypeError, cPickle.UnpicklingError):
188 return data # we may be getting the default value, or None,
189 # so it doesn't need unpickled.
190
191 def get_both(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000192 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000193 data = self.db.get(key, data, txn, flags)
194 return cPickle.loads(data)
195
196
197 def cursor(self, txn=None, flags=0):
198 c = DBShelfCursor(self.db.cursor(txn, flags))
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000199 c.protocol = self.protocol
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000200 return c
201
202
203 def put(self, key, value, txn=None, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000204 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000205 return self.db.put(key, data, txn, flags)
206
207
208 def join(self, cursorList, flags=0):
209 raise NotImplementedError
210
211
212 #----------------------------------------------
213 # Methods allowed to pass-through to self.db
214 #
215 # close, delete, fd, get_byteswapped, get_type, has_key,
216 # key_range, open, remove, rename, stat, sync,
217 # upgrade, verify, and all set_* methods.
218
219
220#---------------------------------------------------------------------------
221
222class DBShelfCursor:
223 """
224 """
225 def __init__(self, cursor):
226 self.dbc = cursor
227
228 def __del__(self):
229 self.close()
230
231
232 def __getattr__(self, name):
233 """Some methods we can just pass through to the cursor object. (See below)"""
234 return getattr(self.dbc, name)
235
236
237 #----------------------------------------------
238
239 def dup(self, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000240 c = DBShelfCursor(self.dbc.dup(flags))
241 c.protocol = self.protocol
242 return c
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000243
244
245 def put(self, key, value, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000246 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000247 return self.dbc.put(key, data, flags)
248
249
250 def get(self, *args):
251 count = len(args) # a method overloading hack
252 method = getattr(self, 'get_%d' % count)
253 apply(method, args)
254
255 def get_1(self, flags):
256 rec = self.dbc.get(flags)
257 return self._extract(rec)
258
259 def get_2(self, key, flags):
260 rec = self.dbc.get(key, flags)
261 return self._extract(rec)
262
263 def get_3(self, key, value, flags):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000264 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000265 rec = self.dbc.get(key, flags)
266 return self._extract(rec)
267
268
269 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
270 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
271 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
272 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
273 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
274 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
275 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
276 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
277 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
278
279
280 def get_both(self, key, value, flags=0):
Gregory P. Smithb7de61b2007-10-09 07:19:11 +0000281 data = _dumps(value, self.protocol)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000282 rec = self.dbc.get_both(key, flags)
283 return self._extract(rec)
284
285
286 def set(self, key, flags=0):
287 rec = self.dbc.set(key, flags)
288 return self._extract(rec)
289
290 def set_range(self, key, flags=0):
291 rec = self.dbc.set_range(key, flags)
292 return self._extract(rec)
293
294 def set_recno(self, recno, flags=0):
295 rec = self.dbc.set_recno(recno, flags)
296 return self._extract(rec)
297
298 set_both = get_both
299
300 def _extract(self, rec):
301 if rec is None:
302 return None
303 else:
304 key, data = rec
305 return key, cPickle.loads(data)
306
307 #----------------------------------------------
308 # Methods allowed to pass-through to self.dbc
309 #
310 # close, count, delete, get_recno, join_item
311
312
313#---------------------------------------------------------------------------