blob: 1f7fdc1cfe897b379dcfa93ab1b83ae509508fb1 [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
Martin v. Löwis918f49e2007-08-08 22:08:30 +000032import pickle
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
Guido van Rossume2b70bc2006-08-18 22:13:04 +000038from . import db
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000039
Martin v. Löwiscccc58d2007-08-10 08:36:56 +000040_unspecified = object()
41
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000042#------------------------------------------------------------------------
43
44
Guido van Rossumcd16bf62007-06-13 18:07:49 +000045def open(filename, flags=db.DB_CREATE, mode=0o660, filetype=db.DB_HASH,
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000046 dbenv=None, dbname=None):
47 """
48 A simple factory function for compatibility with the standard
49 shleve.py module. It can be used like this, where key is a string
50 and data is a pickleable object:
51
Barry Warsaw9a0d7792002-12-30 20:53:52 +000052 from bsddb import dbshelve
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000053 db = dbshelve.open(filename)
54
55 db[key] = data
56
57 db.close()
58 """
59 if type(flags) == type(''):
60 sflag = flags
61 if sflag == 'r':
62 flags = db.DB_RDONLY
63 elif sflag == 'rw':
64 flags = 0
65 elif sflag == 'w':
66 flags = db.DB_CREATE
67 elif sflag == 'c':
68 flags = db.DB_CREATE
69 elif sflag == 'n':
70 flags = db.DB_TRUNCATE | db.DB_CREATE
71 else:
Gregory P. Smith1281f762004-03-16 18:50:26 +000072 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 +000073
74 d = DBShelf(dbenv)
75 d.open(filename, dbname, filetype, flags, mode)
76 return d
77
78#---------------------------------------------------------------------------
79
Raymond Hettinger30a634e2003-02-05 04:12:41 +000080class DBShelf(DictMixin):
Barry Warsaw99142272003-02-08 03:18:58 +000081 """A shelf to hold pickled objects, built upon a bsddb DB object. It
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000082 automatically pickles/unpickles data objects going to/from the DB.
83 """
84 def __init__(self, dbenv=None):
85 self.db = db.DB(dbenv)
86 self.binary = 1
87
88
89 def __del__(self):
90 self.close()
91
92
93 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +000094 """Many methods we can just pass through to the DB object.
95 (See below)
96 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000097 return getattr(self.db, name)
98
99
100 #-----------------------------------
101 # Dictionary access methods
102
103 def __len__(self):
104 return len(self.db)
105
106
107 def __getitem__(self, key):
108 data = self.db[key]
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000109 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000110
111
112 def __setitem__(self, key, value):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000113 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000114 self.db[key] = data
115
116
117 def __delitem__(self, key):
118 del self.db[key]
119
120
121 def keys(self, txn=None):
122 if txn != None:
123 return self.db.keys(txn)
124 else:
125 return self.db.keys()
126
127
128 def items(self, txn=None):
129 if txn != None:
130 items = self.db.items(txn)
131 else:
132 items = self.db.items()
133 newitems = []
134
135 for k, v in items:
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000136 newitems.append( (k, pickle.loads(v)) )
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000137 return newitems
138
139 def values(self, txn=None):
140 if txn != None:
141 values = self.db.values(txn)
142 else:
143 values = self.db.values()
144
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000145 return map(pickle.loads, values)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000146
147 #-----------------------------------
148 # Other methods
149
Gregory P. Smith1281f762004-03-16 18:50:26 +0000150 def __append(self, value, txn=None):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000151 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000152 return self.db.append(data, txn)
153
Gregory P. Smith1281f762004-03-16 18:50:26 +0000154 def append(self, value, txn=None):
155 if self.get_type() != db.DB_RECNO:
156 self.append = self.__append
157 return self.append(value, txn=txn)
158 raise db.DBError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"
159
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000160
161 def associate(self, secondaryDB, callback, flags=0):
162 def _shelf_callback(priKey, priData, realCallback=callback):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000163 data = pickle.loads(priData)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000164 return realCallback(priKey, data)
165 return self.db.associate(secondaryDB, _shelf_callback, flags)
166
167
Martin v. Löwiscccc58d2007-08-10 08:36:56 +0000168 def get(self, key, default=_unspecified, txn=None, flags=0):
169 # If no default is given, we must not pass one to the
170 # extension module, so that an exception can be raised if
171 # set_get_returns_none is turned off.
172 if default is _unspecified:
173 data = self.db.get(key, txn=txn, flags=flags)
174 # if this returns, the default value would be None
175 default = None
176 else:
177 data = self.db.get(key, default, txn=txn, flags=flags)
178 if data is default:
179 return data
180 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000181
182 def get_both(self, key, value, txn=None, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000183 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000184 data = self.db.get(key, data, txn, flags)
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000185 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000186
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):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000195 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000196 return self.db.put(key, data, txn, flags)
197
198
199 def join(self, cursorList, flags=0):
200 raise NotImplementedError
201
202
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000203 def __contains__(self, key):
Guido van Rossum20435132006-08-21 00:21:47 +0000204 return self.db.has_key(key)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000205
206
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000207 #----------------------------------------------
208 # Methods allowed to pass-through to self.db
209 #
210 # close, delete, fd, get_byteswapped, get_type, has_key,
211 # key_range, open, remove, rename, stat, sync,
212 # upgrade, verify, and all set_* methods.
213
214
215#---------------------------------------------------------------------------
216
217class DBShelfCursor:
218 """
219 """
220 def __init__(self, cursor):
221 self.dbc = cursor
222
223 def __del__(self):
224 self.close()
225
226
227 def __getattr__(self, name):
228 """Some methods we can just pass through to the cursor object. (See below)"""
229 return getattr(self.dbc, name)
230
231
232 #----------------------------------------------
233
234 def dup(self, flags=0):
235 return DBShelfCursor(self.dbc.dup(flags))
236
237
238 def put(self, key, value, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000239 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000240 return self.dbc.put(key, data, flags)
241
242
243 def get(self, *args):
244 count = len(args) # a method overloading hack
245 method = getattr(self, 'get_%d' % count)
Neal Norwitzd9108552006-03-17 08:00:19 +0000246 method(*args)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000247
248 def get_1(self, flags):
249 rec = self.dbc.get(flags)
250 return self._extract(rec)
251
252 def get_2(self, key, flags):
253 rec = self.dbc.get(key, flags)
254 return self._extract(rec)
255
256 def get_3(self, key, value, flags):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000257 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000258 rec = self.dbc.get(key, flags)
259 return self._extract(rec)
260
261
262 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
263 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
264 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
265 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
266 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
267 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
268 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
269 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
270 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
271
272
273 def get_both(self, key, value, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000274 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000275 rec = self.dbc.get_both(key, flags)
276 return self._extract(rec)
277
278
279 def set(self, key, flags=0):
280 rec = self.dbc.set(key, flags)
281 return self._extract(rec)
282
283 def set_range(self, key, flags=0):
284 rec = self.dbc.set_range(key, flags)
285 return self._extract(rec)
286
287 def set_recno(self, recno, flags=0):
288 rec = self.dbc.set_recno(recno, flags)
289 return self._extract(rec)
290
291 set_both = get_both
292
293 def _extract(self, rec):
294 if rec is None:
295 return None
296 else:
297 key, data = rec
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000298 return key, pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000299
300 #----------------------------------------------
301 # Methods allowed to pass-through to self.dbc
302 #
303 # close, count, delete, get_recno, join_item
304
305
306#---------------------------------------------------------------------------