blob: 82e914d05a431b21daf5bb3466fe79d87a8f1563 [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
Barry Warsaw99142272003-02-08 03:18:58 +000033try:
34 from UserDict import DictMixin
35except ImportError:
36 # DictMixin is new in Python 2.3
37 class DictMixin: pass
Gregory P. Smith41631e82003-09-21 00:08:14 +000038import db
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000039
40#------------------------------------------------------------------------
41
42
43def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH,
44 dbenv=None, dbname=None):
45 """
46 A simple factory function for compatibility with the standard
47 shleve.py module. It can be used like this, where key is a string
48 and data is a pickleable object:
49
Barry Warsaw9a0d7792002-12-30 20:53:52 +000050 from bsddb import dbshelve
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000051 db = dbshelve.open(filename)
52
53 db[key] = data
54
55 db.close()
56 """
57 if type(flags) == type(''):
58 sflag = flags
59 if sflag == 'r':
60 flags = db.DB_RDONLY
61 elif sflag == 'rw':
62 flags = 0
63 elif sflag == 'w':
64 flags = db.DB_CREATE
65 elif sflag == 'c':
66 flags = db.DB_CREATE
67 elif sflag == 'n':
68 flags = db.DB_TRUNCATE | db.DB_CREATE
69 else:
Gregory P. Smith1281f762004-03-16 18:50:26 +000070 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 +000071
72 d = DBShelf(dbenv)
73 d.open(filename, dbname, filetype, flags, mode)
74 return d
75
76#---------------------------------------------------------------------------
77
Gregory P. Smith137bdfa2007-10-12 18:49:36 +000078class DBShelveError(db.DBError): pass
79
80
Raymond Hettinger30a634e2003-02-05 04:12:41 +000081class DBShelf(DictMixin):
Barry Warsaw99142272003-02-08 03:18:58 +000082 """A shelf to hold pickled objects, built upon a bsddb DB object. It
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000083 automatically pickles/unpickles data objects going to/from the DB.
84 """
85 def __init__(self, dbenv=None):
86 self.db = db.DB(dbenv)
87 self.binary = 1
88
89
90 def __del__(self):
91 self.close()
92
93
94 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +000095 """Many methods we can just pass through to the DB object.
96 (See below)
97 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000098 return getattr(self.db, name)
99
100
101 #-----------------------------------
102 # Dictionary access methods
103
104 def __len__(self):
105 return len(self.db)
106
107
108 def __getitem__(self, key):
109 data = self.db[key]
110 return cPickle.loads(data)
111
112
113 def __setitem__(self, key, value):
114 data = cPickle.dumps(value, self.binary)
115 self.db[key] = data
116
117
118 def __delitem__(self, key):
119 del self.db[key]
120
121
122 def keys(self, txn=None):
123 if txn != None:
124 return self.db.keys(txn)
125 else:
126 return self.db.keys()
127
128
129 def items(self, txn=None):
130 if txn != None:
131 items = self.db.items(txn)
132 else:
133 items = self.db.items()
134 newitems = []
135
136 for k, v in items:
137 newitems.append( (k, cPickle.loads(v)) )
138 return newitems
139
140 def values(self, txn=None):
141 if txn != None:
142 values = self.db.values(txn)
143 else:
144 values = self.db.values()
145
146 return map(cPickle.loads, values)
147
148 #-----------------------------------
149 # Other methods
150
Gregory P. Smith1281f762004-03-16 18:50:26 +0000151 def __append(self, value, txn=None):
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000152 data = cPickle.dumps(value, self.binary)
153 return self.db.append(data, txn)
154
Gregory P. Smith1281f762004-03-16 18:50:26 +0000155 def append(self, value, txn=None):
Gregory P. Smith137bdfa2007-10-12 18:49:36 +0000156 if self.get_type() == db.DB_RECNO:
Gregory P. Smith1281f762004-03-16 18:50:26 +0000157 self.append = self.__append
158 return self.append(value, txn=txn)
Gregory P. Smith137bdfa2007-10-12 18:49:36 +0000159 raise DBShelveError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"
Gregory P. Smith1281f762004-03-16 18:50:26 +0000160
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000161
162 def associate(self, secondaryDB, callback, flags=0):
163 def _shelf_callback(priKey, priData, realCallback=callback):
164 data = cPickle.loads(priData)
165 return realCallback(priKey, data)
166 return self.db.associate(secondaryDB, _shelf_callback, flags)
167
168
169 #def get(self, key, default=None, txn=None, flags=0):
170 def get(self, *args, **kw):
171 # We do it with *args and **kw so if the default value wasn't
172 # given nothing is passed to the extension module. That way
173 # an exception can be raised if set_get_returns_none is turned
174 # off.
175 data = apply(self.db.get, args, kw)
176 try:
177 return cPickle.loads(data)
178 except (TypeError, cPickle.UnpicklingError):
179 return data # we may be getting the default value, or None,
180 # so it doesn't need unpickled.
181
182 def get_both(self, key, value, txn=None, flags=0):
183 data = cPickle.dumps(value, self.binary)
184 data = self.db.get(key, data, txn, flags)
185 return cPickle.loads(data)
186
187
188 def cursor(self, txn=None, flags=0):
189 c = DBShelfCursor(self.db.cursor(txn, flags))
190 c.binary = self.binary
191 return c
192
193
194 def put(self, key, value, txn=None, flags=0):
195 data = cPickle.dumps(value, self.binary)
196 return self.db.put(key, data, txn, flags)
197
198
199 def join(self, cursorList, flags=0):
200 raise NotImplementedError
201
202
203 #----------------------------------------------
204 # Methods allowed to pass-through to self.db
205 #
206 # close, delete, fd, get_byteswapped, get_type, has_key,
207 # key_range, open, remove, rename, stat, sync,
208 # upgrade, verify, and all set_* methods.
209
210
211#---------------------------------------------------------------------------
212
213class DBShelfCursor:
214 """
215 """
216 def __init__(self, cursor):
217 self.dbc = cursor
218
219 def __del__(self):
220 self.close()
221
222
223 def __getattr__(self, name):
224 """Some methods we can just pass through to the cursor object. (See below)"""
225 return getattr(self.dbc, name)
226
227
228 #----------------------------------------------
229
230 def dup(self, flags=0):
231 return DBShelfCursor(self.dbc.dup(flags))
232
233
234 def put(self, key, value, flags=0):
235 data = cPickle.dumps(value, self.binary)
236 return self.dbc.put(key, data, flags)
237
238
239 def get(self, *args):
240 count = len(args) # a method overloading hack
241 method = getattr(self, 'get_%d' % count)
242 apply(method, args)
243
244 def get_1(self, flags):
245 rec = self.dbc.get(flags)
246 return self._extract(rec)
247
248 def get_2(self, key, flags):
249 rec = self.dbc.get(key, flags)
250 return self._extract(rec)
251
252 def get_3(self, key, value, flags):
253 data = cPickle.dumps(value, self.binary)
254 rec = self.dbc.get(key, flags)
255 return self._extract(rec)
256
257
258 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
259 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
260 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
261 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
262 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
263 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
264 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
265 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
266 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
267
268
269 def get_both(self, key, value, flags=0):
270 data = cPickle.dumps(value, self.binary)
271 rec = self.dbc.get_both(key, flags)
272 return self._extract(rec)
273
274
275 def set(self, key, flags=0):
276 rec = self.dbc.set(key, flags)
277 return self._extract(rec)
278
279 def set_range(self, key, flags=0):
280 rec = self.dbc.set_range(key, flags)
281 return self._extract(rec)
282
283 def set_recno(self, recno, flags=0):
284 rec = self.dbc.set_recno(recno, flags)
285 return self._extract(rec)
286
287 set_both = get_both
288
289 def _extract(self, rec):
290 if rec is None:
291 return None
292 else:
293 key, data = rec
294 return key, cPickle.loads(data)
295
296 #----------------------------------------------
297 # Methods allowed to pass-through to self.dbc
298 #
299 # close, count, delete, get_recno, join_item
300
301
302#---------------------------------------------------------------------------