blob: 87be3d19f9641f85e98f0c2bc787275577a33f58 [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:
Collin Wintera65e94c2007-08-22 21:45:20 +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
Gregory P. Smith5c5f1702007-10-12 19:13:19 +000080class DBShelveError(db.DBError): pass
81
82
Raymond Hettinger30a634e2003-02-05 04:12:41 +000083class DBShelf(DictMixin):
Barry Warsaw99142272003-02-08 03:18:58 +000084 """A shelf to hold pickled objects, built upon a bsddb DB object. It
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000085 automatically pickles/unpickles data objects going to/from the DB.
86 """
87 def __init__(self, dbenv=None):
88 self.db = db.DB(dbenv)
Gregory P. Smith659e7f42007-10-13 23:23:58 +000089 self._closed = True
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000090 self.binary = 1
91
92
93 def __del__(self):
94 self.close()
95
96
97 def __getattr__(self, name):
Barry Warsaw99142272003-02-08 03:18:58 +000098 """Many methods we can just pass through to the DB object.
99 (See below)
100 """
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000101 return getattr(self.db, name)
102
103
104 #-----------------------------------
105 # Dictionary access methods
106
107 def __len__(self):
108 return len(self.db)
109
110
111 def __getitem__(self, key):
112 data = self.db[key]
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000113 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000114
115
116 def __setitem__(self, key, value):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000117 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000118 self.db[key] = data
119
120
121 def __delitem__(self, key):
122 del self.db[key]
123
124
125 def keys(self, txn=None):
126 if txn != None:
127 return self.db.keys(txn)
128 else:
129 return self.db.keys()
130
131
Gregory P. Smith659e7f42007-10-13 23:23:58 +0000132 def open(self, *args, **kwargs):
133 self.db.open(*args, **kwargs)
134 self._closed = False
135
136
137 def close(self, *args, **kwargs):
138 self.db.close(*args, **kwargs)
139 self._closed = True
140
141
142 def __repr__(self):
143 if self._closed:
144 return '<DBShelf @ 0x%x - closed>' % (id(self))
145 else:
146 return repr(dict(self.iteritems()))
147
148
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000149 def items(self, txn=None):
150 if txn != None:
151 items = self.db.items(txn)
152 else:
153 items = self.db.items()
154 newitems = []
155
156 for k, v in items:
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000157 newitems.append( (k, pickle.loads(v)) )
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000158 return newitems
159
160 def values(self, txn=None):
161 if txn != None:
162 values = self.db.values(txn)
163 else:
164 values = self.db.values()
165
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000166 return map(pickle.loads, values)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000167
168 #-----------------------------------
169 # Other methods
170
Gregory P. Smith1281f762004-03-16 18:50:26 +0000171 def __append(self, value, txn=None):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000172 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000173 return self.db.append(data, txn)
174
Gregory P. Smith1281f762004-03-16 18:50:26 +0000175 def append(self, value, txn=None):
Gregory P. Smith5c5f1702007-10-12 19:13:19 +0000176 if self.get_type() == db.DB_RECNO:
Gregory P. Smith659e7f42007-10-13 23:23:58 +0000177 return self.__append(value, txn=txn)
Gregory P. Smith5c5f1702007-10-12 19:13:19 +0000178 raise DBShelveError("append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO")
Gregory P. Smith1281f762004-03-16 18:50:26 +0000179
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000180
181 def associate(self, secondaryDB, callback, flags=0):
182 def _shelf_callback(priKey, priData, realCallback=callback):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000183 data = pickle.loads(priData)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000184 return realCallback(priKey, data)
185 return self.db.associate(secondaryDB, _shelf_callback, flags)
186
187
Martin v. Löwiscccc58d2007-08-10 08:36:56 +0000188 def get(self, key, default=_unspecified, txn=None, flags=0):
189 # If no default is given, we must not pass one to the
190 # extension module, so that an exception can be raised if
191 # set_get_returns_none is turned off.
192 if default is _unspecified:
193 data = self.db.get(key, txn=txn, flags=flags)
194 # if this returns, the default value would be None
195 default = None
196 else:
197 data = self.db.get(key, default, txn=txn, flags=flags)
198 if data is default:
199 return data
200 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000201
202 def get_both(self, key, value, txn=None, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000203 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000204 data = self.db.get(key, data, txn, flags)
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000205 return pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000206
207
208 def cursor(self, txn=None, flags=0):
209 c = DBShelfCursor(self.db.cursor(txn, flags))
210 c.binary = self.binary
211 return c
212
213
214 def put(self, key, value, txn=None, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000215 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000216 return self.db.put(key, data, txn, flags)
217
218
219 def join(self, cursorList, flags=0):
220 raise NotImplementedError
221
222
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000223 def __contains__(self, key):
Guido van Rossum20435132006-08-21 00:21:47 +0000224 return self.db.has_key(key)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000225
226
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000227 #----------------------------------------------
228 # Methods allowed to pass-through to self.db
229 #
230 # close, delete, fd, get_byteswapped, get_type, has_key,
231 # key_range, open, remove, rename, stat, sync,
232 # upgrade, verify, and all set_* methods.
233
234
235#---------------------------------------------------------------------------
236
237class DBShelfCursor:
238 """
239 """
240 def __init__(self, cursor):
241 self.dbc = cursor
242
243 def __del__(self):
244 self.close()
245
246
247 def __getattr__(self, name):
248 """Some methods we can just pass through to the cursor object. (See below)"""
249 return getattr(self.dbc, name)
250
251
252 #----------------------------------------------
253
254 def dup(self, flags=0):
255 return DBShelfCursor(self.dbc.dup(flags))
256
257
258 def put(self, key, value, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000259 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000260 return self.dbc.put(key, data, flags)
261
262
263 def get(self, *args):
264 count = len(args) # a method overloading hack
265 method = getattr(self, 'get_%d' % count)
Neal Norwitzd9108552006-03-17 08:00:19 +0000266 method(*args)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000267
268 def get_1(self, flags):
269 rec = self.dbc.get(flags)
270 return self._extract(rec)
271
272 def get_2(self, key, flags):
273 rec = self.dbc.get(key, flags)
274 return self._extract(rec)
275
276 def get_3(self, key, value, flags):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000277 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000278 rec = self.dbc.get(key, flags)
279 return self._extract(rec)
280
281
282 def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
283 def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
284 def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
285 def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
286 def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
287 def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
288 def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
289 def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
290 def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)
291
292
293 def get_both(self, key, value, flags=0):
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000294 data = pickle.dumps(value, self.binary)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000295 rec = self.dbc.get_both(key, flags)
296 return self._extract(rec)
297
298
299 def set(self, key, flags=0):
300 rec = self.dbc.set(key, flags)
301 return self._extract(rec)
302
303 def set_range(self, key, flags=0):
304 rec = self.dbc.set_range(key, flags)
305 return self._extract(rec)
306
307 def set_recno(self, recno, flags=0):
308 rec = self.dbc.set_recno(recno, flags)
309 return self._extract(rec)
310
311 set_both = get_both
312
313 def _extract(self, rec):
314 if rec is None:
315 return None
316 else:
317 key, data = rec
Martin v. Löwis918f49e2007-08-08 22:08:30 +0000318 return key, pickle.loads(data)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000319
320 #----------------------------------------------
321 # Methods allowed to pass-through to self.dbc
322 #
323 # close, count, delete, get_recno, join_item
324
325
326#---------------------------------------------------------------------------