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